answer stringlengths 17 10.2M |
|---|
package com.almasb.fxgl.scene;
import com.almasb.fxgl.app.GameApplication;
import com.almasb.fxgl.event.MenuDataEvent;
import com.almasb.fxgl.event.MenuEvent;
import com.almasb.fxgl.gameplay.Achievement;
import com.almasb.fxgl.input.InputBinding;
import com.almasb.fxgl.settings.SceneDimension;
import com.almasb.fxgl.ui.UIFactory;
import com.almasb.fxgl.util.FXGLLogger;
import com.almasb.fxgl.util.Version;
import javafx.beans.binding.Bindings;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.event.Event;
import javafx.geometry.HPos;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.ScrollPane.ScrollBarPolicy;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Line;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Text;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Logger;
import java.util.stream.Collectors;
/**
* This is a base class for main/game menus. It provides several
* convenience methods for those who just want to extend an existing menu.
* It also allows for implementors to build menus from scratch. Freshly
* build menus can interact with FXGL by calling fire* methods.
*
* @author Almas Baimagambetov (AlmasB) (almaslvl@gmail.com)
*/
public abstract class FXGLMenu extends FXGLScene {
/**
* The logger
*/
protected static final Logger log = FXGLLogger.getLogger("FXGL.Menu");
protected final GameApplication app;
private List<String> credits = new ArrayList<>();
public FXGLMenu(GameApplication app) {
this.app = app;
populateCredits();
}
private void populateCredits() {
addCredit("Powered by FXGL " + Version.getAsString());
addCredit("Graphics Framework: JavaFX " + Version.getJavaFXAsString());
addCredit("Physics Engine: JBox2d (jbox2d.org) " + Version.getJBox2DAsString());
addCredit("FXGL Author: Almas Baimagambetov (AlmasB)");
addCredit("https://github.com/AlmasB/FXGL");
}
/**
*
* @return menu content containing list of save files and load/delete buttons
*/
protected final MenuContent createContentLoad() {
ListView<String> list = new ListView<>();
app.getSaveLoadManager().loadSaveFileNames().ifPresent(names -> list.getItems().setAll(names));
list.prefHeightProperty().bind(Bindings.size(list.getItems()).multiply(36));
if (list.getItems().size() > 0) {
list.getSelectionModel().selectFirst();
}
Button btnLoad = UIFactory.newButton("LOAD");
btnLoad.setOnAction(e -> {
String fileName = list.getSelectionModel().getSelectedItem();
if (fileName == null)
return;
fireLoad(fileName);
});
Button btnDelete = UIFactory.newButton("DELETE");
btnDelete.setOnAction(e -> {
String fileName = list.getSelectionModel().getSelectedItem();
if (fileName == null)
return;
fireDelete(fileName);
list.getItems().remove(fileName);
});
HBox hbox = new HBox(50, btnLoad, btnDelete);
hbox.setAlignment(Pos.CENTER);
return new MenuContent(list, hbox);
}
/**
*
* @return menu content containing input mappings (action -> key/mouse)
*/
protected final MenuContent createContentControls() {
GridPane grid = new GridPane();
grid.setAlignment(Pos.CENTER);
grid.setHgap(50);
grid.setUserData(0);
// add listener for new ones
app.getInput().getBindings().addListener((ListChangeListener.Change<? extends InputBinding> c) -> {
while (c.next()) {
if (c.wasAdded()) {
c.getAddedSubList().forEach(binding -> addNewInputBinding(binding, grid));
}
}
});
// register current ones
app.getInput().getBindings().forEach(binding -> addNewInputBinding(binding, grid));
ScrollPane scroll = new ScrollPane(grid);
scroll.setVbarPolicy(ScrollBarPolicy.ALWAYS);
scroll.setMaxHeight(app.getHeight() / 2);
scroll.setStyle("-fx-background: black;");
HBox hbox = new HBox(scroll);
hbox.setAlignment(Pos.CENTER);
return new MenuContent(hbox);
}
private void addNewInputBinding(InputBinding binding, GridPane grid) {
Text actionName = UIFactory.newText(binding.getAction().getName());
Button triggerName = UIFactory.newButton("");
triggerName.textProperty().bind(binding.triggerNameProperty());
triggerName.setOnMouseClicked(event -> {
Rectangle rect = new Rectangle(250, 100);
rect.setStroke(Color.AZURE);
Text text = UIFactory.newText("PRESS ANY KEY", 24);
Stage stage = new Stage(StageStyle.TRANSPARENT);
stage.initModality(Modality.WINDOW_MODAL);
stage.initOwner(getRoot().getScene().getWindow());
Scene scene = new Scene(new StackPane(rect, text));
scene.setOnKeyPressed(e -> {
app.getInput().rebind(binding.getAction(), e.getCode());
stage.close();
});
scene.setOnMouseClicked(e -> {
app.getInput().rebind(binding.getAction(), e.getButton());
stage.close();
});
stage.setScene(scene);
stage.show();
});
int controlsRow = (int) grid.getUserData();
grid.addRow(controlsRow++, actionName, triggerName);
grid.setUserData(controlsRow);
GridPane.setHalignment(actionName, HPos.RIGHT);
GridPane.setHalignment(triggerName, HPos.LEFT);
}
/**
*
* @return menu content with video settings
*/
protected final MenuContent createContentVideo() {
Spinner<SceneDimension> spinner =
new Spinner<>(FXCollections.observableArrayList(app.getDisplay().getSceneDimensions()));
Button btnApply = UIFactory.newButton("Apply");
btnApply.setOnAction(e -> {
SceneDimension dimension = spinner.getValue();
app.getDisplay().setSceneDimension(dimension);
});
return new MenuContent(new HBox(50, UIFactory.newText("Resolution"), spinner), btnApply);
}
/**
*
* @return menu content containing music and sound volume sliders
*/
protected final MenuContent createContentAudio() {
Slider sliderMusic = new Slider(0, 1, 1);
sliderMusic.valueProperty().bindBidirectional(app.getAudioPlayer().globalMusicVolumeProperty());
Text textMusic = UIFactory.newText("Music Volume: ");
Text percentMusic = UIFactory.newText("");
percentMusic.textProperty().bind(sliderMusic.valueProperty().multiply(100).asString("%.0f"));
Slider sliderSound = new Slider(0, 1, 1);
sliderSound.valueProperty().bindBidirectional(app.getAudioPlayer().globalSoundVolumeProperty());
Text textSound = UIFactory.newText("Sound Volume: ");
Text percentSound = UIFactory.newText("");
percentSound.textProperty().bind(sliderSound.valueProperty().multiply(100).asString("%.0f"));
HBox hboxMusic = new HBox(15, textMusic, sliderMusic, percentMusic);
HBox hboxSound = new HBox(15, textSound, sliderSound, percentSound);
hboxMusic.setAlignment(Pos.CENTER_RIGHT);
hboxSound.setAlignment(Pos.CENTER_RIGHT);
return new MenuContent(hboxMusic, hboxSound);
}
/**
* Add a single line of credit text.
*
* @param text the text to append to credits list
*/
protected final void addCredit(String text) {
credits.add(text);
}
/**
*
* @return menu content containing a list of credits
*/
protected final MenuContent createContentCredits() {
return new MenuContent(credits.stream()
.map(UIFactory::newText)
.collect(Collectors.toList())
.toArray(new Text[0]));
}
/**
*
* @return menu content containing a list of achievements
*/
protected final MenuContent createContentAchievements() {
MenuContent content = new MenuContent();
for (Achievement a : app.getAchievementManager().getAchievements()) {
CheckBox checkBox = new CheckBox();
checkBox.setDisable(true);
checkBox.selectedProperty().bind(a.achievedProperty());
Text text = UIFactory.newText(a.getName());
Tooltip.install(text, new Tooltip(a.getDescription()));
HBox box = new HBox(25, text, checkBox);
box.setAlignment(Pos.CENTER_RIGHT);
content.getChildren().add(box);
}
return content;
}
/**
* A generic vertical box container for menu content
* where each element is followed by a separator
*/
protected class MenuContent extends VBox {
public MenuContent(Node... items) {
int maxW = Arrays.asList(items)
.stream()
.mapToInt(n -> (int)n.getLayoutBounds().getWidth())
.max()
.orElse(0);
getChildren().add(createSeparator(maxW));
for (Node item : items) {
getChildren().addAll(item, createSeparator(maxW));
}
}
private Line createSeparator(int width) {
Line sep = new Line();
sep.setEndX(width);
sep.setStroke(Color.DARKGREY);
return sep;
}
}
/**
* Adds a UI node.
*
* @param node the node to add
*/
protected final void addUINode(Node node) {
getRoot().getChildren().add(node);
}
private void fireMenuEvent(Event event) {
app.getEventBus().fireEvent(event);
}
/**
* Fires {@link MenuEvent#NEW_GAME} event.
* Can only be fired from main menu.
* Starts new game.
*/
protected final void fireNewGame() {
fireMenuEvent(new MenuEvent(MenuEvent.NEW_GAME));
}
/**
* Fires {@link MenuEvent#CONTINUE} event.
* Lads the game state from last modified save file.
*/
protected final void fireContinue() {
fireMenuEvent(new MenuEvent(MenuEvent.CONTINUE));
}
/**
* Fires {@link MenuDataEvent#LOAD} event.
* Loads the game state from previously saved file.
*
* @param fileName name of the saved file
*/
protected final void fireLoad(String fileName) {
fireMenuEvent(new MenuDataEvent(MenuDataEvent.LOAD, fileName));
}
/**
* Fires {@link MenuEvent#SAVE} event.
* Can only be fired from game menu. Saves current state of the game with given file name.
*/
protected final void fireSave() {
fireMenuEvent(new MenuEvent(MenuEvent.SAVE));
}
/**
* Fires {@link MenuDataEvent#DELETE} event.
*
* @param fileName name of the save file
*/
protected final void fireDelete(String fileName) {
fireMenuEvent(new MenuDataEvent(MenuDataEvent.DELETE, fileName));
}
/**
* Fires {@link MenuEvent#RESUME} event.
* Can only be fired from game menu. Will close the menu and unpause the game.
*/
protected final void fireResume() {
fireMenuEvent(new MenuEvent(MenuEvent.RESUME));
}
/**
* Fire {@link MenuEvent#EXIT} event.
* App will clean up the world/the scene and exit.
*/
protected final void fireExit() {
fireMenuEvent(new MenuEvent(MenuEvent.EXIT));
}
/**
* Fire {@link MenuEvent#EXIT_TO_MAIN_MENU} event.
* App will clean up the world/the scene and enter main menu.
*/
protected final void fireExitToMainMenu() {
fireMenuEvent(new MenuEvent(MenuEvent.EXIT_TO_MAIN_MENU));
}
} |
package app.lsgui.gui;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import app.lsgui.gui.channelinfopanel.ChannelInfoPanel;
import app.lsgui.gui.channellist.ChannelList;
import app.lsgui.gui.settings.SettingsWindow;
import app.lsgui.model.Channel;
import app.lsgui.model.Service;
import app.lsgui.service.Settings;
import app.lsgui.service.twitch.TwitchAPIClient;
import de.jensd.fx.glyphs.GlyphsDude;
import de.jensd.fx.glyphs.fontawesome.FontAwesomeIcon;
import javafx.collections.FXCollections;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonBar.ButtonData;
import javafx.scene.control.ButtonType;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Dialog;
import javafx.scene.control.TextField;
import javafx.scene.control.ToolBar;
import javafx.scene.image.Image;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.stage.Stage;
import javafx.util.StringConverter;
public class MainController {
private static final Logger LOGGER = LoggerFactory.getLogger(MainController.class);
private static final String OFFLINEQUALITY = "Channel is offline";
private ChannelList channelList;
private ChannelInfoPanel channelInfoPanel;
@FXML
private ComboBox<String> qualityComboBox;
@FXML
private ComboBox<Service> serviceComboBox;
@FXML
private BorderPane contentBorderPane;
@FXML
private ToolBar toolBarLeft;
@FXML
public void initialize() {
LOGGER.debug("INIT MainController");
setupServiceComboBox();
setupChannelList();
setupQualityComboBox();
setupChannelInfoPanel();
setupToolbar();
}
private void setupQualityComboBox() {
qualityComboBox.getSelectionModel().selectedItemProperty().addListener((obs, oldValue, newValue) -> {
if (newValue != null && !newValue.equals(OFFLINEQUALITY)) {
Settings.instance().setQuality(newValue);
}
});
}
private void setupServiceComboBox() {
if (Settings.instance().getStreamServices().isEmpty()) {
Settings.instance().getStreamServices().add(new Service("Twitch.tv", "http://twitch.tv/"));
}
serviceComboBox.getItems().addAll(Settings.instance().getStreamServices());
serviceComboBox.setCellFactory(listView -> new ServiceCell());
serviceComboBox.setConverter(new StringConverter<Service>() {
@Override
public String toString(Service service) {
if (service == null) {
return null;
}
return service.getName().get();
}
@Override
public Service fromString(String string) {
return null;
}
});
serviceComboBox.getSelectionModel().select(0);
serviceComboBox.valueProperty().addListener((observable, oldValue, newValue) -> changeService(newValue));
}
private void setupChannelList() {
channelList = new ChannelList();
channelList.getListView().getSelectionModel().selectedItemProperty()
.addListener((observable, oldValue, newValue) -> {
Channel value = newValue == null ? oldValue : newValue;
qualityComboBox.setItems(FXCollections.observableArrayList(value.getAvailableQualities()));
if (qualityComboBox.getItems().size() > 1) {
final String quality = Settings.instance().getQuality();
if (qualityComboBox.getItems().contains(quality)) {
qualityComboBox.getSelectionModel().select(quality);
} else {
qualityComboBox.getSelectionModel().select("Best");
}
} else {
qualityComboBox.getSelectionModel().select(0);
}
});
channelList.getStreams().bind(serviceComboBox.getSelectionModel().getSelectedItem().getChannels());
contentBorderPane.setLeft(channelList);
}
private void setupChannelInfoPanel() {
channelInfoPanel = new ChannelInfoPanel(serviceComboBox, qualityComboBox);
channelInfoPanel.getModelProperty().bind(channelList.getModelProperty());
contentBorderPane.setCenter(channelInfoPanel);
}
private void setupToolbar() {
Button addButton = GlyphsDude.createIconButton(FontAwesomeIcon.PLUS);
addButton.setOnAction(event -> addAction());
Button removeButton = GlyphsDude.createIconButton(FontAwesomeIcon.MINUS);
removeButton.setOnAction(event -> removeAction());
Button importButton = GlyphsDude.createIconButton(FontAwesomeIcon.USERS);
importButton.setOnAction(event -> importFollowedChannels());
toolBarLeft.getItems().add(toolBarLeft.getItems().size() - 1, addButton);
toolBarLeft.getItems().add(toolBarLeft.getItems().size() - 1, removeButton);
toolBarLeft.getItems().add(toolBarLeft.getItems().size() - 1, importButton);
Region spacer = new Region();
HBox.setHgrow(spacer, Priority.ALWAYS);
spacer.setMinWidth(Region.USE_PREF_SIZE);
toolBarLeft.getItems().add(toolBarLeft.getItems().size() - 1, spacer);
Button settingsButton = GlyphsDude.createIconButton(FontAwesomeIcon.COG);
settingsButton.setOnAction(event -> openSettings());
toolBarLeft.getItems().add(toolBarLeft.getItems().size(), settingsButton);
}
private void changeService(final Service newService) {
LOGGER.debug("Change Service to {}", newService.getName().get());
channelList.getStreams().bind(newService.getChannels());
}
private void openSettings() {
SettingsWindow sw = new SettingsWindow(contentBorderPane.getScene().getWindow());
sw.showAndWait();
}
private void addAction() {
final Dialog<Boolean> dialog = new Dialog<>();
dialog.setTitle("Add Channel to current Service");
Stage dialogStage = (Stage) dialog.getDialogPane().getScene().getWindow();
dialogStage.getIcons().add(new Image(getClass().getResourceAsStream("/icon.jpg")));
final ButtonType bt = new ButtonType("Submit", ButtonData.OK_DONE);
dialog.getDialogPane().getButtonTypes().addAll(bt, ButtonType.CANCEL);
final BorderPane ap = new BorderPane();
final TextField tf = new TextField();
ap.setCenter(tf);
dialog.getDialogPane().setContent(ap);
final Node submitButton = dialog.getDialogPane().lookupButton(bt);
submitButton.setDisable(true);
tf.textProperty()
.addListener((observable, oldValue, newValue) -> submitButton.setDisable(newValue.trim().isEmpty()));
dialog.setResultConverter(button -> {
if ("".equals(tf.getText().trim()) || button.equals(ButtonType.CANCEL)) {
return false;
}
if (TwitchAPIClient.instance().channelExists(tf.getText().trim())) {
return true;
}
return false;
});
tf.requestFocus();
final Optional<Boolean> result = dialog.showAndWait();
if (result.isPresent() && result.get()) {
addChannelToCurrentService(tf.getText().trim());
}
}
private void removeAction() {
final Channel toRemove = channelList.getListView().getSelectionModel().getSelectedItem();
removeChannelFromCurrentService(toRemove);
}
private void importFollowedChannels() {
final Dialog<Boolean> dialog = new Dialog<>();
Stage dialogStage = (Stage) dialog.getDialogPane().getScene().getWindow();
dialogStage.getIcons().add(new Image(getClass().getResourceAsStream("/icon.jpg")));
dialog.setTitle("Import Twitch.tv followed Channels");
dialog.setContentText("Please enter your Twitch.tv Username:");
final ButtonType bt = new ButtonType("Import", ButtonData.OK_DONE);
dialog.getDialogPane().getButtonTypes().addAll(bt, ButtonType.CANCEL);
final BorderPane ap = new BorderPane();
final TextField tf = new TextField();
ap.setCenter(tf);
dialog.getDialogPane().setContent(ap);
final Node submitButton = dialog.getDialogPane().lookupButton(bt);
submitButton.setDisable(true);
tf.textProperty()
.addListener((observable, oldValue, newValue) -> submitButton.setDisable(newValue.trim().isEmpty()));
dialog.setResultConverter(button -> {
if ("".equals(tf.getText().trim()) || button.equals(ButtonType.CANCEL)) {
return false;
}
if (TwitchAPIClient.instance().channelExists(tf.getText().trim())) {
return true;
}
return false;
});
tf.requestFocus();
final Optional<Boolean> result = dialog.showAndWait();
if (result.isPresent() && result.get()) {
addFollowedChannelsToCurrentService(tf.getText().trim());
}
}
private void addChannelToCurrentService(final String channel) {
serviceComboBox.getSelectionModel().getSelectedItem().addChannel(channel);
}
private void addFollowedChannelsToCurrentService(final String channel) {
serviceComboBox.getSelectionModel().getSelectedItem().addFollowedChannels(channel);
}
private void removeChannelFromCurrentService(final Channel channel) {
serviceComboBox.getSelectionModel().getSelectedItem().removeSelectedChannel(channel);
}
} |
package be.isach.samaritan;
import be.isach.samaritan.birthday.BirthdayTask;
import be.isach.samaritan.brainfuck.BrainfuckInterpreter;
import be.isach.samaritan.chat.PrivateMessageChatThread;
import be.isach.samaritan.colorfulrank.ColorfulRankChanger;
import be.isach.samaritan.command.console.ConsoleListenerThread;
import be.isach.samaritan.history.MessageHistoryPrinter;
import be.isach.samaritan.level.AccessLevelManager;
import be.isach.samaritan.listener.CleverBotListener;
import be.isach.samaritan.listener.CommandListener;
import be.isach.samaritan.listener.PrivateMessageListener;
import be.isach.samaritan.listener.QuoteHandler;
import be.isach.samaritan.log.SmartLogger;
import be.isach.samaritan.music.SongPlayer;
import be.isach.samaritan.pokemongo.LoginData;
import be.isach.samaritan.runtime.ShutdownThread;
import be.isach.samaritan.stream.BeamModule;
import be.isach.samaritan.stream.StreamData;
import be.isach.samaritan.stream.TwitchModule;
import be.isach.samaritan.stream.TwitchData;
import be.isach.samaritan.util.GifFactory;
import be.isach.samaritan.util.SamaritanStatus;
import be.isach.samaritan.websocket.SamaritanWebsocketServer;
import com.google.maps.GeoApiContext;
import com.pokegoapi.api.PokemonGo;
import net.dv8tion.jda.JDA;
import net.dv8tion.jda.JDABuilder;
import net.dv8tion.jda.entities.Guild;
import net.dv8tion.jda.entities.PrivateChannel;
import net.dv8tion.jda.entities.User;
import org.joda.time.Instant;
import javax.security.auth.login.LoginException;
import java.io.File;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.*;
public class Samaritan {
/**
* Song Players map with their corresponding guilds.
*/
private Map<Guild, SongPlayer> songPlayers;
/**
* Samaritan Status.
*/
private SamaritanStatus status;
/**
* The Jda of this Samaritan Instance.
*/
private JDA jda;
/**
* Message History Printer Util.
*/
private MessageHistoryPrinter messageHistoryPrinter;
/**
* The Smart Logger of this Samaritan Instance.
*/
private SmartLogger logger;
/**
* Absolute File!
*/
private File workingDirectory;
/**
* Brainfuck Code Interpreter
*/
private BrainfuckInterpreter brainfuckInterpreter;
/**
* Stream Module.
*/
private TwitchModule twitchModule;
/**
* Stream Module.
*/
private BeamModule beamModule;
/**
* UI WebSocket Server.
*/
private SamaritanWebsocketServer samaritanWebsocketServer;
/**
* Private Message Listener.
*/
private PrivateMessageListener pmListener;
/**
* Private Message Listener.
*/
private CleverBotListener cleverBotListener;
/**
* Bot Token.
*/
private String botToken;
/**
* Main Admin. Owner. As Discord User ID.
*/
private String ownerId;
/**
* WEB Interface using WebSockets?
*/
private boolean webUi;
/**
* Web Interface WebSocket Server Port.
*/
private int uiWebSocketPort;
/**
* Gif Factory.
*/
private GifFactory gifFactory;
/**
* Birthday task
*/
private BirthdayTask birthdayTask;
/**
* Colorful rank color changer task
*/
private ColorfulRankChanger colorfulRankChanger;
/**
* Timer.
*/
private Timer timer;
/**
* Users Acess Level Manager.
*/
private AccessLevelManager accessLevelManager;
/**
* Manages quotes.
*/
private QuoteHandler quoteHandler;
private PokemonGo pokemonGo;
private GeoApiContext geoApiContext;
private LoginData loginData;
/**
* Samaritan Constructor.
*
* @param args Program Arguments.
* Given when program is started
* @param botToken Bot Token.
* From samaritan.properties
* @param webUi Use Web UI or not.
* From samaritan.properties.
* @param uiWebSocketPort Web UI Port.
* From <samaritan.properties.
*/
public Samaritan(String[] args, String botToken, boolean webUi, int uiWebSocketPort, long ownerId, File workingDirectory, String googleMapsApiKey, LoginData loginData) {
this.botToken = botToken;
this.logger = new SmartLogger();
this.status = new SamaritanStatus();
this.songPlayers = new HashMap<>();
this.gifFactory = new GifFactory();
this.ownerId = String.valueOf(ownerId);
this.workingDirectory = workingDirectory;
this.brainfuckInterpreter = new BrainfuckInterpreter();
this.messageHistoryPrinter = new MessageHistoryPrinter();
this.accessLevelManager = new AccessLevelManager(this);
this.webUi = webUi;
this.loginData = loginData;
status.setBootInstant(new Instant());
logger.write("
logger.write();
logger.write("Hello.");
logger.write();
logger.write("I am Samaritan.");
logger.write();
logger.write("Starting...");
logger.write();
logger.write("Boot Instant: " + new Instant().toString());
logger.write();
if (!initJda()) {
logger.write("Invalid token! Please change it in samaritan.properties");
System.exit(1);
return;
}
this.quoteHandler = new QuoteHandler(jda);
this.birthdayTask = new BirthdayTask(this);
this.colorfulRankChanger = new ColorfulRankChanger(this);
this.timer = new Timer();
quoteHandler.start();
timer.schedule(birthdayTask, 0L, 1000L * 60L);
timer.schedule(colorfulRankChanger, 0L, 500L);
this.accessLevelManager.loadUsers();
Runtime.getRuntime().addShutdownHook(new ShutdownThread(this));
startSongPlayers();
setUpListeners();
if (webUi) startWebSocketServer();
new ConsoleListenerThread(this).start();
}
/**
* Starts JDA.
*
* @return {@code true} if everything went well, {@code false} otherwise.
*/
private boolean initJda() {
try {
jda = new JDABuilder().setBotToken(botToken).buildBlocking();
jda.getAccountManager().setGame("Beta 2.0.1");
jda.getAccountManager().update();
} catch (LoginException | InterruptedException e) {
logger.write("Couldn't connect!");
return false;
}
return true;
}
/**
* Shuts Samaritan down.
*
* @param exitSystem If true, will execute a 'System.exit(0);'
*/
public final void shutdown(boolean exitSystem) {
for (PrivateMessageChatThread chatThread : getPrivateMessageListener().getChatThreads().values()) {
PrivateChannel privateChannel = (PrivateChannel) chatThread.getMessageChannel();
privateChannel.sendMessage("I must go, a reboot is in the queue!\nYou can try speaking to me again in a few moments.\nGood bye, my dear " + privateChannel.getUser().getUsername() + ".");
}
try {
jda.getAccountManager().setUsername("Samaritan");
jda.getAccountManager().update();
} catch (Exception exc) {
}
jda.shutdown();
if (exitSystem)
System.exit(0);
}
/**
* Starts WebSocket Server (for UI).
*/
private void startWebSocketServer() {
try {
samaritanWebsocketServer = new SamaritanWebsocketServer(new InetSocketAddress(11350));
samaritanWebsocketServer.start();
System.out.println("WS Server started.");
} catch (UnknownHostException e) {
System.out.println("WS Server couldn't start.");
e.printStackTrace();
}
}
/**
* Set up Listeners.
*/
private void setUpListeners() {
this.pmListener = new PrivateMessageListener();
this.cleverBotListener = new CleverBotListener(getJda());
jda.addEventListener(new CommandListener(this));
jda.addEventListener(pmListener);
}
/**
* Start Song Players.
*/
private void startSongPlayers() {
for (Guild guild : jda.getGuilds()) {
SongPlayer songPlayer = new SongPlayer(guild, this);
songPlayers.put(guild, songPlayer);
}
}
/**
* @param guild The Guild.
* @return A song Player by Guild.
*/
public SongPlayer getSongPlayer(Guild guild) {
return songPlayers.get(guild);
}
/**
* @return The SongPlayers map.
*/
public Map<Guild, SongPlayer> getSongPlayers() {
return songPlayers;
}
/**
* @return The UI WebSocket Server.
*/
public SamaritanWebsocketServer getWebSocketServer() {
return samaritanWebsocketServer;
}
/**
* @return The JDA of this Samaritan Instance.
*/
public JDA getJda() {
return jda;
}
/**
* @return The Smart Logger.
*/
public SmartLogger getLogger() {
return logger;
}
/**
* @return The Private Message Listener
*/
public PrivateMessageListener getPrivateMessageListener() {
return pmListener;
}
/**
* @return Samaritan's status.
*/
public SamaritanStatus getStatus() {
return status;
}
/**
* @return The Gif Factory.
*/
public GifFactory getGifFactory() {
return gifFactory;
}
/**
* @return webUi value.
*/
public boolean useWebUi() {
return webUi;
}
/**
* @return Access Level Manager.
*/
public AccessLevelManager getAccessLevelManager() {
return accessLevelManager;
}
/**
* @return Brainfuck code Interpreter.
*/
public BrainfuckInterpreter getBrainfuckInterpreter() {
return brainfuckInterpreter;
}
/**
* @return Message History Printer Util.
*/
public MessageHistoryPrinter getMessageHistoryPrinter() {
return messageHistoryPrinter;
}
/**
* @return Directory where Samaritan is currently running.
*/
public File getWorkingDirectory() {
return workingDirectory;
}
/**
* @return Main Admin ID.
*/
public String getOwnerId() {
return ownerId;
}
/**
* @return Quote Handler.
*/
public QuoteHandler getQuoteHandler() {
return quoteHandler;
}
public PokemonGo getPokemonGo() {
return pokemonGo;
}
public GeoApiContext getGeoApiContext() {
return geoApiContext;
}
public User getOwner() {
return getJda().getUserById(getOwnerId());
}
public Timer getTimer() {
return timer;
}
public LoginData getLoginData() {
return loginData;
}
public void initTwitchModule(TwitchData twitchData) {
this.twitchModule = new TwitchModule(getJda(), twitchData);
this.timer.schedule(twitchModule, 0L, 25000L);
}
public void initBeamModule(StreamData streamData) {
this.beamModule = new BeamModule(getJda(), streamData);
this.timer.schedule(beamModule, 0L, 25000L);
}
public TwitchModule getTwitchModule() {
return twitchModule;
}
public BeamModule getBeamModule() {
return beamModule;
}
} |
package com.celements.menu;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.xwiki.component.annotation.Component;
import org.xwiki.component.annotation.Requirement;
import org.xwiki.context.Execution;
import org.xwiki.model.EntityType;
import org.xwiki.model.reference.DocumentReference;
import org.xwiki.model.reference.EntityReferenceResolver;
import org.xwiki.model.reference.EntityReferenceSerializer;
import org.xwiki.model.reference.WikiReference;
import org.xwiki.query.Query;
import org.xwiki.query.QueryException;
import org.xwiki.query.QueryManager;
import com.celements.web.service.IWebUtilsService;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.objects.BaseObject;
@Component
public class MenuService implements IMenuService {
private static Log LOGGER = LogFactory.getFactory().getInstance(MenuService.class);
@Requirement("default")
EntityReferenceSerializer<String> modelSerializer;
@Requirement
IWebUtilsService webUtilsService;
@Requirement
EntityReferenceResolver<String> referenceResolver;
@Requirement
QueryManager queryManager;
@Requirement
Execution execution;
private XWikiContext getContext() {
return (XWikiContext)execution.getContext().getProperty("xwikicontext");
}
public List<BaseObject> getMenuHeaders() {
LOGGER.trace("getMenuHeaders_internal start");
TreeMap<Integer, BaseObject> menuHeadersMap = new TreeMap<Integer, BaseObject>();
addMenuHeaders(menuHeadersMap);
getContext().setDatabase("celements2web");
addMenuHeaders(menuHeadersMap);
getContext().setDatabase(getContext().getOriginalDatabase());
ArrayList<BaseObject> resultList = new ArrayList<BaseObject>();
resultList.addAll(menuHeadersMap.values());
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("getMenuHeaders_internal returning: "
+ Arrays.deepToString(resultList.toArray()));
}
LOGGER.debug("getMenuHeaders_internal end");
return resultList;
}
boolean hasview(DocumentReference menuBarDocRef) throws XWikiException {
if (modelSerializer.serialize(menuBarDocRef).endsWith("Celements2.AdminMenu")) {
return webUtilsService.isAdvancedAdmin();
}
String database = getContext().getDatabase();
getContext().setDatabase("celements2web");
DocumentReference menuBar2webDocRef = new DocumentReference("celements2web",
menuBarDocRef.getLastSpaceReference().getName(), menuBarDocRef.getName());
String menuBar2webFullName = modelSerializer.serialize(menuBar2webDocRef);
boolean centralView = !getContext().getWiki().exists(menuBar2webDocRef, getContext())
|| getContext().getWiki().getRightService().hasAccessLevel("view",
getContext().getUser(), menuBar2webFullName, getContext());
LOGGER.debug("hasview: centralView [" + menuBar2webFullName + "] for ["
+ getContext().getUser() + "] -> [" + centralView + "] on database ["
+ getContext().getDatabase() + "].");
getContext().setDatabase(getContext().getOriginalDatabase());
DocumentReference menuBarLocalDocRef = new DocumentReference(getContext(
).getOriginalDatabase(), menuBarDocRef.getLastSpaceReference().getName(),
menuBarDocRef.getName());
String menuBarFullName = modelSerializer.serialize(menuBarLocalDocRef);
boolean localView = !getContext().getWiki().exists(menuBarLocalDocRef, getContext())
|| getContext().getWiki().getRightService().hasAccessLevel("view",
getContext().getUser(), menuBarFullName, getContext());
LOGGER.debug("hasview: localView [" + menuBarFullName + "] for ["
+ getContext().getUser() + "] -> [" + localView + "] on database ["
+ getContext().getDatabase() + "].");
getContext().setDatabase(database);
return centralView && localView;
}
void addMenuHeaders(SortedMap<Integer, BaseObject> menuHeadersMap) {
try {
List<String> result = queryManager.createQuery(getHeadersXWQL(), Query.XWQL
).execute();
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("addMenuHeaders received for " + getContext().getDatabase()
+ ": " + Arrays.deepToString(result.toArray()));
}
for(String fullName : new HashSet<String>(result)) {
DocumentReference menuBarDocRef = resolveDocument(fullName);
if (hasview(menuBarDocRef)) {
LOGGER.trace("addMenuHeaders: hasview for [" + modelSerializer.serialize(
menuBarDocRef) + "].");
List<BaseObject> headerObjList = getContext().getWiki().getDocument(
menuBarDocRef, getContext()).getXObjects(getMenuBarHeaderClassRef());
if (headerObjList != null) {
for (BaseObject obj : headerObjList) {
menuHeadersMap.put(obj.getIntValue("pos"), obj);
}
}
} else {
LOGGER.trace("addMenuHeaders: NO hasview for [" + modelSerializer.serialize(
menuBarDocRef) + "].");
}
}
} catch (XWikiException e) {
LOGGER.error(e);
} catch (QueryException e) {
LOGGER.error(e);
}
}
public DocumentReference getMenuBarHeaderClassRef() {
return new DocumentReference(getContext().getDatabase(), "Celements",
"MenuBarHeaderItemClass");
}
public DocumentReference getMenuBarSubItemClassRef() {
return new DocumentReference(getContext().getDatabase(), "Celements",
"MenuBarSubItemClass");
}
String getHeadersXWQL() {
return "from doc.object(Celements.MenuBarHeaderItemClass) as mHeader";
}
private DocumentReference resolveDocument(String docFullName) {
DocumentReference eventRef = new DocumentReference(referenceResolver.resolve(
docFullName, EntityType.DOCUMENT));
eventRef.setWikiReference(new WikiReference(getContext().getDatabase()));
LOGGER.debug("getDocRefFromFullName: for [" + docFullName + "] got reference ["
+ eventRef + "].");
return eventRef;
}
public List<BaseObject> getSubMenuItems(Integer headerId) {
TreeMap<Integer, BaseObject> menuItemsMap = new TreeMap<Integer, BaseObject>();
addMenuItems(menuItemsMap, headerId);
getContext().setDatabase("celements2web");
addMenuItems(menuItemsMap, headerId);
getContext().setDatabase(getContext().getOriginalDatabase());
ArrayList<BaseObject> resultList = new ArrayList<BaseObject>();
resultList.addAll(menuItemsMap.values());
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("getSubMenuItems_internal returning: "
+ Arrays.deepToString(resultList.toArray()));
}
LOGGER.debug("getSubMenuItems_internal end");
return resultList;
}
private void addMenuItems(TreeMap<Integer, BaseObject> menuItemsMap, Integer headerId) {
try {
List<Object[]> result = queryManager.createQuery(getSubItemsXWQL(), Query.XWQL
).bindValue("headerId", headerId).execute();
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("addMenuItems received for " + getContext().getDatabase()
+ ": " + Arrays.deepToString(result.toArray()));
}
for(Object[] resultObj : result) {
String fullName = resultObj[0].toString();
int objectNr = Integer.parseInt(resultObj[1].toString());
DocumentReference menuBarDocRef = resolveDocument(fullName);
BaseObject obj = getContext().getWiki().getDocument(menuBarDocRef, getContext()
).getXObject(getMenuBarSubItemClassRef(), objectNr);
menuItemsMap.put(obj.getIntValue("itempos"), obj);
}
} catch (XWikiException e) {
LOGGER.error(e);
} catch (QueryException e) {
LOGGER.error(e);
}
}
private String getSubItemsXWQL() {
return "select doc.fullName, subItem.number"
+ " from Document as doc, doc.object(Celements.MenuBarSubItemClass) as subItem"
+ " where subItem.header_id = :headerId";
}
} |
package com.chimbori.crux.urls;
import com.chimbori.crux.common.StringUtils;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
/**
* Checks heuristically whether a given URL is likely to be an article, video, image, or other
* types. Can optionally resolve redirects such as when Facebook or Google show an interstitial
* page instead of redirecting the user to the actual URL.
*/
public class CruxURL {
private final String fileName;
private URI uri;
/**
* Static method to validate, initialize, and create a new {@link CruxURL}.
*/
public static CruxURL parse(String url) {
if (url == null || url.isEmpty()) {
return null;
}
URI javaNetUri = null;
try {
javaNetUri = new URI(url);
} catch (URISyntaxException e) {
// used in valid URLs are rejected by it. So, if we encounter a URISyntaxException here, it
// parse.
// have been included in this project.
try {
javaNetUri = LenientURLParser.toURILenient(new URL(url));
} catch (URISyntaxException | MalformedURLException e1) {
}
}
if (javaNetUri != null &&
(javaNetUri.getScheme() == null || javaNetUri.getScheme().isEmpty())) {
try {
url = "http://" + url;
javaNetUri = new URI(url);
} catch (URISyntaxException e) {
// Ignore.
}
}
if (javaNetUri == null) {
return null;
}
return new CruxURL(javaNetUri);
}
/**
* Private constructor, so that the wrapping static method can perform some validation before
* invoking the constructor.
*/
private CruxURL(URI uri) {
this.uri = uri;
String path = uri.getPath();
fileName = path != null && !path.isEmpty()
? path.substring(path.lastIndexOf('/') + 1)
: "";
}
public boolean isAdImage() {
return StringUtils.countMatches(uri.toString(), "ad") >= 2;
}
public boolean isWebScheme() {
String scheme = uri.getScheme().toLowerCase();
return scheme.equals("http") || scheme.equals("https");
}
public boolean isLikelyArticle() {
return !isLikelyBinaryDocument() &&
!isLikelyExecutable() &&
!isLikelyArchive() &&
!isLikelyImage() &&
!isLikelyVideo() &&
!isLikelyAudio();
}
@SuppressWarnings("WeakerAccess")
public boolean isLikelyVideo() {
return fileName.endsWith(".mpeg") || fileName.endsWith(".mpg") || fileName.endsWith(".avi") || fileName.endsWith(".mov")
|| fileName.endsWith(".mpg4") || fileName.endsWith(".mp4") || fileName.endsWith(".flv") || fileName.endsWith(".wmv");
}
@SuppressWarnings("WeakerAccess")
public boolean isLikelyAudio() {
return fileName.endsWith(".mp3") || fileName.endsWith(".ogg") || fileName.endsWith(".m3u") || fileName.endsWith(".wav");
}
@SuppressWarnings("WeakerAccess")
public boolean isLikelyBinaryDocument() {
return fileName.endsWith(".pdf") || fileName.endsWith(".ppt") || fileName.endsWith(".doc")
|| fileName.endsWith(".swf") || fileName.endsWith(".rtf") || fileName.endsWith(".xls");
}
@SuppressWarnings("WeakerAccess")
public boolean isLikelyArchive() {
return fileName.endsWith(".gz") || fileName.endsWith(".tgz") || fileName.endsWith(".zip")
|| fileName.endsWith(".rar") || fileName.endsWith(".deb") || fileName.endsWith(".rpm") || fileName.endsWith(".7z");
}
@SuppressWarnings("WeakerAccess")
public boolean isLikelyExecutable() {
return fileName.endsWith(".exe") || fileName.endsWith(".bin") || fileName.endsWith(".bat") || fileName.endsWith(".dmg");
}
@SuppressWarnings("WeakerAccess")
public boolean isLikelyImage() {
return fileName.endsWith(".png") || fileName.endsWith(".jpeg") || fileName.endsWith(".gif")
|| fileName.endsWith(".jpg") || fileName.endsWith(".bmp") || fileName.endsWith(".ico") || fileName.endsWith(".eps");
}
public CruxURL resolveRedirects() {
for (Redirectors.RedirectPattern redirect : Redirectors.REDIRECT_PATTERNS) {
if (redirect.matches(uri)) {
uri = redirect.resolveHandlingException(uri);
}
}
return this;
}
@Override
public String toString() {
return uri.toString();
}
} |
package br.gov.servicos.cms;
import br.gov.servicos.v3.schema.Servico;
import com.github.slugify.Slugify;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.Value;
import lombok.experimental.Wither;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldIndex;
import static br.gov.servicos.config.PortalDeServicosIndex.IMPORTADOR;
import static lombok.AccessLevel.PRIVATE;
import static org.springframework.data.elasticsearch.annotations.FieldType.String;
@Value
@Wither
@AllArgsConstructor(access = PRIVATE)
@Document(indexName = IMPORTADOR, type = "conteudo")
public class Conteudo {
@Id
String id;
@Field(store = true, type = String)
String nome;
@Field(store = true, type = String)
String conteudo;
@Field(type = String, store = true, index = FieldIndex.not_analyzed)
String conteudoHtml;
@Field(store = true, type = String)
String tipoConteudo;
public Conteudo() {
this(null, null, null, null, null);
}
@SneakyThrows
public static Conteudo fromServico(Servico servico) {
return new Conteudo()
.withId(new Slugify().slugify(servico.getNome()))
.withTipoConteudo("servico")
.withNome(servico.getNome())
.withConteudo(servico.getDescricao());
}
} |
package openblocks.common.block;
import net.minecraft.block.material.Material;
import openblocks.Config;
import openblocks.common.tileentity.TileEntityGoldenEgg;
public class BlockGoldenEgg extends OpenBlock {
public BlockGoldenEgg() {
super(Config.blockGoldenEggId, Material.ground);
setupBlock(this, "goldenegg", TileEntityGoldenEgg.class);
}
@Override
public boolean shouldRenderBlock() {
return false;
}
@Override
public boolean isOpaqueCube() {
return false;
}
} |
package com.continuuity;
import ch.qos.logback.classic.Logger;
import com.continuuity.common.conf.CConfiguration;
import com.continuuity.common.conf.Constants;
import com.continuuity.common.utils.Copyright;
import com.continuuity.common.zookeeper.InMemoryZookeeper;
import com.continuuity.data.runtime.DataFabricModules;
import com.continuuity.flow.manager.server.FARServer;
import com.continuuity.flow.manager.server.FlowManagerServer;
import com.continuuity.flow.runtime.FARModules;
import com.continuuity.flow.runtime.FlowManagerModules;
import com.continuuity.gateway.Gateway;
import com.continuuity.gateway.runtime.GatewayModules;
import com.continuuity.metrics.service.MetricsServer;
import com.continuuity.runtime.MetricsModules;
import com.google.common.base.Preconditions;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
import org.apache.commons.lang.StringUtils;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.net.InetAddress;
/**
* SingleNodeMain is the master main method for the Continuuity single node
* platform. This is where we load all our external configuration and bootstrap
* all the services that comprise the platform.
*/
public class SingleNodeMain {
/**
* This is our Logger instance
*/
private static final Logger logger =
(Logger)LoggerFactory.getLogger(SingleNodeMain.class);
/**
* This is the Zookeeper service.
*
* TODO: Find somewhere to create this so we can inject it
*/
private InMemoryZookeeper zookeeper;
/**
* This is the Gateway service
*/
@Inject
private Gateway theGateway;
/**
* This is the Metrics Monitor service
*/
@Inject
private MetricsServer theOverlord;
/**
* This is the FAR server.
*/
@Inject
private FARServer theFARServer;
/**
* This is the FlowManager server
*/
@Inject
private FlowManagerServer theFlowManager;
/**
* This is the WebApp Service
*/
private WebCloudAppService theWebApp;
/**
* This is our universal configurations object.
*/
private CConfiguration myConfiguration;
/**
* Creates a zookeeper data directory for single node.
*/
private static final String ZOOKEEPER_DATA_DIR = "data/zookeeper";
/**
* Bootstrap is where we initialize all the services that make up the
* SingleNode version.
*
*/
private void bootStrapServices() throws Exception {
// Check all our preconditions (which should have been injected)
Preconditions.checkNotNull(theOverlord);
Preconditions.checkNotNull(theGateway);
Preconditions.checkNotNull(theFARServer);
Preconditions.checkNotNull(theFlowManager);
System.out.println(" Starting Zookeeper Service");
startZookeeper();
System.out.println(" Starting Metrics Service");
theOverlord.start(null, myConfiguration);
System.out.println(" Starting Gateway Service");
theGateway.start(null, myConfiguration);
System.out.println(" Starting FlowArchive Service");
theFARServer.start(null, myConfiguration);
System.out.println(" Starting FlowManager Service");
theFlowManager.start(null, myConfiguration);
System.out.println(" Starting Monitoring Webapp");
theWebApp = new WebCloudAppService();
theWebApp.start(null, myConfiguration);
String hostname = InetAddress.getLocalHost().getHostName();
System.out.println(" Bigflow started successfully. Connect to UI @ http:
+ hostname + ":9999");
} // end of bootStrapServices
/**
* Start Zookeeper attempts to start our single node ZK instance. It requires
* two configuration values to be set somewhere in our config files:
*
* <ul>
* <li>zookeeper.port</li>
* <li>zookeeper.datadir</li>
* </ul>
*
* We also push the ZK ensemble setting back into myConfiguration for
* use by the other services.
*
* @throws InterruptedException
* @throws IOException
*/
private void startZookeeper() throws InterruptedException, IOException {
// Create temporary directory where zookeeper data files will be stored.
File temporaryDir = new File(ZOOKEEPER_DATA_DIR);
temporaryDir.mkdir();
zookeeper = new InMemoryZookeeper(temporaryDir);
// Set the connection string about where ZK server started on */
myConfiguration.set(Constants.CFG_ZOOKEEPER_ENSEMBLE,
zookeeper.getConnectionString());
}
/**
* Load Configuration looks for all of the config xml files in the resources
* directory, and loads all of the properties into those files.
*/
private void loadConfiguration() {
// Create our config object
myConfiguration = CConfiguration.create();
} // end of loadConfiguration
static void usage(boolean error) {
// Which output stream should we use?
PrintStream out = (error ? System.err : System.out);
Copyright.print(out);
// And our requirements and usage
out.println("Requirements: ");
out.println(" Java: JDK 1.6+ must be installed and JAVA_HOME environment variable set to the java executable");
out.println(" Node.js: Node.js must be installed (obtain from http://nodejs.org/#download). ");
out.println(" The \"node\" executable must be in the system $PATH environment variable");
out.println("");
out.println("Usage: ");
out.println(" ./bigFlow [options]");
out.println("");
out.println("Additional options:");
out.println(" --help To print this message");
out.println("");
if (error) {
throw new IllegalArgumentException();
}
}
/**
* The root of all goodness!
*
* @param args Our cmdline arguments
*/
public static void main(String[] args) {
// We only support 'help' command line options currently
if (args.length > 0) {
if ("--help".equals(args[0]) || "-h".equals(args[0])) {
usage(false);
return;
} else {
usage(true);
}
}
// Retrieve all of the modules from each of the components
FARModules farModules = new FARModules();
FlowManagerModules flowManagerModules = new FlowManagerModules();
MetricsModules metricsModules = new MetricsModules();
GatewayModules gatewayModules = new GatewayModules();
DataFabricModules dataFabricModules = new DataFabricModules();
// Set up our Guice injections
Injector injector = Guice.createInjector(
farModules.getSingleNodeModules(),
flowManagerModules.getSingleNodeModules(),
metricsModules.getSingleNodeModules(),
gatewayModules.getSingleNodeModules(),
dataFabricModules.getSingleNodeModules()
);
// Create our server instance
SingleNodeMain continuuity = injector.getInstance(SingleNodeMain.class);
// Load all our config files
continuuity.loadConfiguration();
// Now bootstrap all of the services
try {
Copyright.print();
continuuity.bootStrapServices();
System.out.println(StringUtils.repeat("=", 80));
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
} // end of SingleNodeMain class |
package com.crowdmap.java.sdk;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.crowdmap.java.sdk.json.Date;
import com.crowdmap.java.sdk.json.DateDeserializer;
import com.crowdmap.java.sdk.json.UsersDeserializer;
import com.crowdmap.java.sdk.model.User;
import com.crowdmap.java.sdk.net.ICrowdmapConstants;
import com.crowdmap.java.sdk.net.SignRequestClient;
import com.crowdmap.java.sdk.service.ExternalService;
import com.crowdmap.java.sdk.service.LocationService;
import com.crowdmap.java.sdk.service.MapService;
import com.crowdmap.java.sdk.service.MediaService;
import com.crowdmap.java.sdk.service.PostService;
import com.crowdmap.java.sdk.service.SessionService;
import com.crowdmap.java.sdk.service.UserService;
import com.crowdmap.java.sdk.service.UtilityService;
import java.lang.reflect.Type;
import java.util.List;
import retrofit.Endpoint;
import retrofit.Endpoints;
import retrofit.RestAdapter;
import retrofit.client.Client;
import retrofit.converter.GsonConverter;
import static com.google.gson.FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES;
/**
* Creates the various Crowdmap API resources. Create an object of this class to get to the various
* services supported by the Crowdmap API.
*/
public class Crowdmap {
private static Gson gson;
private RestAdapter restAdapter;
private CrowdmapApiKeys mCrowdmapApiKeys;
static {
Type userListType = new TypeToken<List<User>>() {
}.getType();
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Date.class, new DateDeserializer());
builder.registerTypeAdapter(userListType, new UsersDeserializer());
builder.setFieldNamingPolicy(LOWER_CASE_WITH_UNDERSCORES);
gson = builder.create();
}
public Crowdmap(Endpoint endpoint, Client client, ApiHeaders headers,
CrowdmapApiKeys crowdmapApiKeys) {
if (crowdmapApiKeys == null) {
throw new IllegalArgumentException(
"Crowdmap API Key cannot be public. Please provide a valid api key");
}
this.mCrowdmapApiKeys = crowdmapApiKeys;
this.restAdapter = new RestAdapter.Builder()
.setClient(client)
.setEndpoint(endpoint)
.setRequestInterceptor(headers)
.setConverter(new GsonConverter(gson))
.build();
}
public Crowdmap(CrowdmapApiKeys crowdmapApiKeys) {
this(Endpoints.newFixedEndpoint(ICrowdmapConstants.CROWDMAP_HOST_API),
new SignRequestClient(crowdmapApiKeys), new ApiHeaders(), crowdmapApiKeys);
}
public Crowdmap(RestAdapter adapter, CrowdmapApiKeys crowdmapApiKeys) {
this(crowdmapApiKeys);
this.restAdapter = adapter;
}
public RestAdapter getRestAdapter() {
return this.restAdapter;
}
public UtilityService utilityService() {
return new UtilityService(restAdapter);
}
public ExternalService externalService() {
return new ExternalService(restAdapter);
}
public LocationService locationService() {
return new LocationService(restAdapter);
}
public SessionService sessionService() {
return new SessionService(restAdapter);
}
public UserService userService() {
return new UserService(restAdapter);
}
/**
* Create a new media service instance
*/
public MediaService mediaService() {
return new MediaService(restAdapter);
}
public MapService mapService() {
return new MapService(restAdapter);
}
public PostService postService() {
return new PostService(restAdapter);
}
} |
package hex.schemas;
import hex.glm.GLM;
import hex.glm.GLMModel.GLMParameters;
import hex.glm.GLMModel.GLMParameters.Solver;
import water.api.API;
import water.api.API.Direction;
import water.api.API.Level;
import water.api.FrameV3.ColSpecifierV3;
import water.api.KeyV3.FrameKeyV3;
import water.api.ModelParametersSchema;
public class GLMV3 extends ModelBuilderSchema<GLM,GLMV3,GLMV3.GLMParametersV3> {
public static final class GLMParametersV3 extends ModelParametersSchema<GLMParameters, GLMParametersV3> {
static public String[] own_fields = new String[]{
"response_column",
"offset_column",
"weights_column",
"family",
"solver",
"alpha",
"lambda",
"lambda_search",
"nlambdas",
"standardize",
"max_iterations",
"objective_epsilon",
"beta_epsilon",
"gradient_epsilon",
"link",
// "tweedie_variance_power",
// "tweedie_link_power",
"prior",
"lambda_min_ratio",
"beta_constraints",
"max_active_predictors",
// dead unused args forced here by backwards compatibility, remove in V4
"balance_classes",
"class_sampling_factors",
"max_after_balance_size",
"max_confusion_matrix_size",
"max_hit_ratio_k",
};
@API(help = "Response column", is_member_of_frames = {"training_frame", "validation_frame"}, is_mutually_exclusive_with = {"ignored_columns"}, direction = API.Direction.INOUT)
public ColSpecifierV3 response_column;
// todo move this up in the hierarchy when there is offset support?
@API(help = "Column with observation weights", is_member_of_frames = {"training_frame", "validation_frame"}, is_mutually_exclusive_with = {"ignored_columns","response_column"}, direction = API.Direction.INOUT)
public ColSpecifierV3 weights_column;
// todo move this up in the hierarchy when there is offset support?
@API(help = "Offset column", is_member_of_frames = {"training_frame", "validation_frame"}, is_mutually_exclusive_with = {"ignored_columns","response_column", "weights_column"}, direction = API.Direction.INOUT)
public ColSpecifierV3 offset_column;
// Input fields
@API(help = "Family. Use binomial for classification with logistic regression, others are for regression problems.", values = {"gaussian", "binomial", "poisson", "gamma" /* , "tweedie" */}, level = Level.critical)
// took tweedie out since it's not reliable
public GLMParameters.Family family;
@API(help = "Auto will pick solver better suited for the given dataset, in case of lambda search solvers may be changed during computation. IRLSM is fast on on problems with small number of predictors and for lambda-search with L1 penalty, L_BFGS scales better for datasets with many columns.", values = {"AUTO", "IRLSM", "L_BFGS"}, level = Level.critical)
public Solver solver;
@API(help = "distribution of regularization between L1 and L2.", level = Level.critical)
public double[] alpha;
@API(help = "regularization strength", required = false, level = Level.critical)
public double[] lambda;
@API(help = "use lambda search starting at lambda max, given lambda is then interpreted as lambda min", level = Level.critical)
public boolean lambda_search;
@API(help = "number of lambdas to be used in a search", level = Level.critical)
public int nlambdas;
@API(help = "Standardize numeric columns to have zero mean and unit variance", level = Level.critical)
public boolean standardize;
@API(help = "Maximum number of iterations", level = Level.secondary)
public int max_iterations;
@API(help = "converge if beta changes less (using L-infinity norm) than beta esilon, ONLY applies to IRLSM solver ", level = Level.expert)
public double beta_epsilon;
@API(help = "converge if objective value changes less than this", level = Level.expert)
public double objective_epsilon;
@API(help = "converge if objective changes less (using L-infinity norm) than this, ONLY applies to L-BFGS solver", level = Level.expert)
public double gradient_epsilon;
@API(help = "", level = Level.secondary, values = {"family_default", "identity", "logit", "log", "inverse", "tweedie"})
public GLMParameters.Link link;
@API(help="include constant term in the model", level = Level.expert)
public boolean intercept;
// @API(help = "Tweedie variance power", level = Level.secondary)
// public double tweedie_variance_power;
// @API(help = "Tweedie link power", level = Level.secondary)
// public double tweedie_link_power;
@API(help = "prior probability for y==1. To be used only for logistic regression iff the data has been sampled and the mean of response does not reflect reality.", level = Level.expert)
public double prior;
@API(help = "min lambda used in lambda search, specified as a ratio of lambda_max", level = Level.expert)
public double lambda_min_ratio;
@API(help = "beta constraints", direction = API.Direction.INPUT /* Not required, to allow initial params validation: , required=true */)
public FrameKeyV3 beta_constraints;
@API(help="Maximum number of active predictors during computation. Use as a stopping criterium to prevent expensive model building with many predictors.", direction = Direction.INPUT, level = Level.expert)
public int max_active_predictors = -1;
// dead unused args, formely inherited from supervised model schema
/*Imbalanced Classes*/
/**
* For imbalanced data, balance training data class counts via
* over/under-sampling. This can result in improved predictive accuracy.
*/
@API(help = "Balance training data class counts via over/under-sampling (for imbalanced data).", level = API.Level.secondary, direction = API.Direction.INOUT)
public boolean balance_classes;
/**
* Desired over/under-sampling ratios per class (lexicographic order).
* Only when balance_classes is enabled.
* If not specified, they will be automatically computed to obtain class balance during training.
*/
@API(help = "Desired over/under-sampling ratios per class (in lexicographic order). If not specified, sampling factors will be automatically computed to obtain class balance during training. Requires balance_classes.", level = API.Level.expert, direction = API.Direction.INOUT)
public float[] class_sampling_factors;
/**
* When classes are balanced, limit the resulting dataset size to the
* specified multiple of the original dataset size.
*/
@API(help = "Maximum relative size of the training data after balancing class counts (can be less than 1.0). Requires balance_classes.", /* dmin=1e-3, */ level = API.Level.expert, direction = API.Direction.INOUT)
public float max_after_balance_size;
/** For classification models, the maximum size (in terms of classes) of
* the confusion matrix for it to be printed. This option is meant to
* avoid printing extremely large confusion matrices. */
@API(help = "Maximum size (# classes) for confusion matrices to be printed in the Logs", level = API.Level.secondary, direction = API.Direction.INOUT)
public int max_confusion_matrix_size;
/**
* The maximum number (top K) of predictions to use for hit ratio computation (for multi-class only, 0 to disable)
*/
@API(help = "Max. number (top K) of predictions to use for hit ratio computation (for multi-class only, 0 to disable)", level = API.Level.secondary, direction=API.Direction.INOUT)
public int max_hit_ratio_k;
}
} |
package com.cflint.plugins;
import com.cflint.CFLint;
public interface CFLintSet {
void setCFLint(CFLint cflint);
} |
package ch.ethz.inf.vs.californium.layers;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Timer;
import java.util.TimerTask;
import ch.ethz.inf.vs.californium.coap.EndpointAddress;
import ch.ethz.inf.vs.californium.coap.Message;
import ch.ethz.inf.vs.californium.dtls.ApplicationMessage;
import ch.ethz.inf.vs.californium.dtls.ClientHandshaker;
import ch.ethz.inf.vs.californium.dtls.ClientHello;
import ch.ethz.inf.vs.californium.dtls.ContentType;
import ch.ethz.inf.vs.californium.dtls.DTLSFlight;
import ch.ethz.inf.vs.californium.dtls.DTLSMessage;
import ch.ethz.inf.vs.californium.dtls.DTLSSession;
import ch.ethz.inf.vs.californium.dtls.HandshakeMessage;
import ch.ethz.inf.vs.californium.dtls.Handshaker;
import ch.ethz.inf.vs.californium.dtls.Record;
import ch.ethz.inf.vs.californium.dtls.ResumingClientHandshaker;
import ch.ethz.inf.vs.californium.dtls.ResumingServerHandshaker;
import ch.ethz.inf.vs.californium.dtls.ServerHandshaker;
import ch.ethz.inf.vs.californium.dtls.ServerHello;
import ch.ethz.inf.vs.californium.util.ByteArrayUtils;
import ch.ethz.inf.vs.californium.util.Properties;
public class DTLSLayer extends Layer {
/** The socket to send the datagrams. */
private DatagramSocket socket;
/** The timer daemon to schedule retransmissions. */
private Timer timer = new Timer(true); // run as daemon
private ReceiverThread receiverThread;
/** Storing sessions according to peer-addresses */
private Map<String, DTLSSession> dtlsSessions = new HashMap<String, DTLSSession>();
/** Storing handshakers according to peer-addresses. */
private Map<String, Handshaker> handshakers = new HashMap<String, Handshaker>();
/** Storing flights according to peer-addresses. */
private Map<String, DTLSFlight> flights = new HashMap<String, DTLSFlight>();
/**
* Utility class to handle timeouts.
*/
private class RetransmitTask extends TimerTask {
private DTLSFlight flight;
RetransmitTask(DTLSFlight flight) {
this.flight = flight;
}
@Override
public void run() {
handleTimeout(flight);
}
}
class ReceiverThread extends Thread {
public ReceiverThread() {
super("ReceiverThread");
}
@Override
public void run() {
while (true) {
// allocate buffer
byte[] buffer = new byte[Properties.std.getInt("RX_BUFFER_SIZE") + 1];
DatagramPacket datagram = new DatagramPacket(buffer, buffer.length);
try {
socket.receive(datagram);
} catch (IOException e) {
LOG.severe("Could not receive datagram: " + e.getMessage());
e.printStackTrace();
continue;
}
// TODO: Dispatch to worker thread
datagramReceived(datagram);
}
}
}
public DTLSLayer(int port, boolean daemon) throws SocketException {
this.socket = new DatagramSocket(port);
this.receiverThread = new ReceiverThread();
receiverThread.setDaemon(false);
this.receiverThread.start();
}
public DTLSLayer() throws SocketException {
this(0, true); // use any available port on the local host machine
}
@Override
protected void doSendMessage(Message message) throws IOException {
EndpointAddress peerAddress = message.getPeerAddress();
DTLSSession session = dtlsSessions.get(peerAddress.toString());
Record record = null;
Handshaker handshaker = null;
if (session == null) {
// no session with endpoint available, create new empty session,
// start fresh handshake
session = new DTLSSession(true);
dtlsSessions.put(peerAddress.toString(), session);
handshaker = new ClientHandshaker(peerAddress, message, session);
} else {
if (session.isActive()) {
// session to peer is active, send encrypted message
DTLSMessage fragment = new ApplicationMessage(message.toByteArray());
record = new Record(ContentType.APPLICATION_DATA, session.getWriteEpoch(), session.getSequenceNumber(), fragment, session);
} else {
// try resuming session
handshaker = new ResumingClientHandshaker(peerAddress, message, session);
}
}
// get starting handshake message
if (handshaker != null) {
handshakers.put(peerAddress.toString(), handshaker);
DTLSFlight flight = handshaker.getStartHandshakeMessage();
flight.setPeerAddress(peerAddress);
flight.setSession(session);
flights.put(peerAddress.toString(), flight);
scheduleRetransmission(flight);
sendFlight(flight);
}
if (record != null) {
// retrieve payload
System.out.println(record.toString());
byte[] payload = record.toByteArray();
// create datagram
DatagramPacket datagram = new DatagramPacket(payload, payload.length, peerAddress.getAddress(), peerAddress.getPort());
// remember when this message was sent for the first time
// set timestamp only once in order
// to handle retransmissions correctly
if (message.getTimestamp() == -1) {
message.setTimestamp(System.nanoTime());
}
// send it over the UDP socket
socket.send(datagram);
}
}
@Override
protected void doReceiveMessage(Message msg) {
deliverMessage(msg);
}
private void datagramReceived(DatagramPacket datagram) {
if (datagram.getLength() > 0) {
long timestamp = System.nanoTime();
EndpointAddress peerAddress = new EndpointAddress(datagram.getAddress(), datagram.getPort());
DTLSSession session = dtlsSessions.get(peerAddress.toString());
Handshaker handshaker = handshakers.get(peerAddress.toString());
byte[] data = Arrays.copyOfRange(datagram.getData(), datagram.getOffset(), datagram.getLength());
// TODO multiplex message types: DTLS or CoAP
List<Record> records = Record.fromByteArray(data);
for (Record record : records) {
record.setSession(session);
Message msg = null;
ContentType contentType = record.getType();
switch (contentType) {
case APPLICATION_DATA:
if (session == null) {
// There is no session available, so no application data
// should be received
// TODO alert, abort
}
ApplicationMessage applicationData = (ApplicationMessage) record.getFragment();
msg = Message.fromByteArray(applicationData.getData());
break;
case ALERT:
case CHANGE_CIPHER_SPEC:
case HANDSHAKE:
if (handshaker == null) {
/*
* A handshake message received, but no handshaker
* available: this must mean that we either received a
* HELLO_REQUEST (from server) or a CLIENT_HELLO (from
* client)
*/
HandshakeMessage message = (HandshakeMessage) record.getFragment();
switch (message.getMessageType()) {
case HELLO_REQUEST:
// client side
if (session == null) {
// create new session
session = new DTLSSession(true);
// store session according to peer address
dtlsSessions.put(peerAddress.toString(), session);
LOG.finest("Client: Created new session with peer: " + peerAddress.toString());
}
handshaker = new ClientHandshaker(peerAddress, null, session);
handshakers.put(peerAddress.toString(), handshaker);
break;
case CLIENT_HELLO:
/*
* Server side: server received a client hello:
* check first if client wants to resume a session
* (message must contain session identifier) and
* then check if particular session still available,
* otherwise conduct full handshake with fresh
* session.
*/
ClientHello clientHello = (ClientHello) message;
session = getSessionByIdentifier(clientHello.getSessionId().getSessionId());
if (session == null) {
// create new session
session = new DTLSSession(false);
// store session according to peer address
dtlsSessions.put(peerAddress.toString(), session);
LOG.info("Server: Created new session with peer: " + peerAddress.toString());
handshaker = new ServerHandshaker(peerAddress, getCertificates(), session);
} else {
handshaker = new ResumingServerHandshaker(peerAddress, session);
}
handshakers.put(peerAddress.toString(), handshaker);
break;
default:
LOG.severe("Received unexpected first handshake message:\n");
System.out.println(message.toString());
break;
}
}
DTLSFlight flight = handshaker.processMessage(record);
if (flight != null) {
// cancel previous flight, since we are now able to send
// next one
DTLSFlight prevFlight = flights.get(peerAddress.toString());
if (prevFlight != null) {
prevFlight.getRetransmitTask().cancel();
prevFlight.setRetransmitTask(null);
flights.remove(peerAddress.toString());
}
flight.setPeerAddress(peerAddress);
flight.setSession(session);
if (flight.isRetransmissionNeeded()) {
flights.put(peerAddress.toString(), flight);
scheduleRetransmission(flight);
}
try {
// Collections.shuffle(flight.getMessages());
sendFlight(flight);
} catch (IOException e) {
e.printStackTrace();
}
}
break;
default:
LOG.severe("Received unknown DTLS record:\n" + data.toString());
break;
}
if (msg != null) {
// remember when this message was received
msg.setTimestamp(timestamp);
msg.setPeerAddress(new EndpointAddress(datagram.getAddress(), datagram.getPort()));
if (datagram.getLength() > Properties.std.getInt("RX_BUFFER_SIZE")) {
LOG.info(String.format("Marking large datagram for blockwise transfer: %s", msg.key()));
msg.requiresBlockwise(true);
}
// protect against unknown exceptions
try {
// call receive handler
receiveMessage(msg);
} catch (Exception e) {
}
}
}
}
}
public boolean isDaemon() {
return receiverThread.isDaemon();
}
public int getPort() {
return socket.getLocalPort();
}
/**
* Searches through all stored sessions and returns that session which
* matches the session identifier or <code>null</code> if no such session
* available. This method is used when the server receives a
* {@link ClientHello} containing a session identifier indicating that the
* client wants to resume a previous session. If a matching session is
* found, the server will resume the session with a abbreviated handshake,
* otherwise a full handshake (with new session identifier in
* {@link ServerHello}) is conducted.
*
* @param sessionID
* the client's session identifier.
* @return the session which matches the session identifier or
* <code>null</code> if no such session exists.
*/
private DTLSSession getSessionByIdentifier(byte[] sessionID) {
if (sessionID == null) {
return null;
}
for (Entry<String, DTLSSession> entry : dtlsSessions.entrySet()) {
byte[] id = entry.getValue().getSessionIdentifier().getSessionId();
if (Arrays.equals(sessionID, id)) {
return entry.getValue();
}
}
return null;
}
private X509Certificate[] getCertificates() {
X509Certificate[] certificates = new X509Certificate[1];
try {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
FileInputStream in = new FileInputStream("C:\\Users\\Jucker\\git\\Californium\\src\\ch\\ethz\\inf\\vs\\californium\\dtls\\ec3.crt");
Certificate certificate = cf.generateCertificate(in);
in.close();
certificates[0] = (X509Certificate) certificate;
} catch (Exception e) {
LOG.severe("Could not create the certificates.");
e.printStackTrace();
certificates = null;
}
return certificates;
}
private void sendFlight(DTLSFlight flight) throws IOException {
// FIXME debug infos
boolean allInOneRecord = true;
if (flight.getTries() > 0) {
// LOG.info("Retransmit current flight:\n" +
// flight.getMessages().toString());
}
if (allInOneRecord) {
byte[] payload = new byte[0];
for (Record record : flight.getMessages()) {
if (flight.getTries() > 0) {
// adjust the record sequence number
int epoch = record.getEpoch();
record.setSequenceNumber(flight.getSession().getSequenceNumber(epoch));
}
System.out.println("Sending Message:\n" + record.toString());
// retrieve payload
payload = ByteArrayUtils.concatenate(payload, record.toByteArray());
}
// create datagram
DatagramPacket datagram = new DatagramPacket(payload, payload.length, flight.getPeerAddress().getAddress(), flight.getPeerAddress().getPort());
// send it over the UDP socket
socket.send(datagram);
} else {
for (Record record : flight.getMessages()) {
if (flight.getTries() > 0) {
// adjust the record sequence number
int epoch = record.getEpoch();
record.setSequenceNumber(flight.getSession().getSequenceNumber(epoch));
}
// retrieve payload
byte[] payload = record.toByteArray();
// create datagram
DatagramPacket datagram = new DatagramPacket(payload, payload.length, flight.getPeerAddress().getAddress(), flight.getPeerAddress().getPort());
// send it over the UDP socket
socket.send(datagram);
}
}
}
private void handleTimeout(DTLSFlight flight) {
final int max = Properties.std.getInt("MAX_RETRANSMIT");
// check if limit of retransmissions reached
if (flight.getTries() < max) {
flight.incrementTries();
try {
sendFlight(flight);
} catch (IOException e) {
return;
}
// schedule next retransmission
scheduleRetransmission(flight);
} else {
// TODO maximum tries reached
}
}
private void scheduleRetransmission(DTLSFlight flight) {
// cancel existing schedule (if any)
if (flight.getRetransmitTask() != null) {
flight.getRetransmitTask().cancel();
}
// create new retransmission task
flight.setRetransmitTask(new RetransmitTask(flight));
// calculate timeout using exponential back-off
if (flight.getTimeout() == 0) {
// use initial timeout
flight.setTimeout(initialTimeout());
} else {
// double timeout
flight.incrementTimeout();
}
// schedule retransmission task
timer.schedule(flight.getRetransmitTask(), flight.getTimeout());
}
private int initialTimeout() {
// TODO load this from config file
return 1000;
}
} |
package com.fishercoder.solutions;
import java.util.HashMap;
import java.util.Map;
public class _340 {
public static class Solution1 {
public int lengthOfLongestSubstringKDistinct(String s, int k) {
int[] count = new int[256];
int left = 0;
int result = 0;
int num = 0;
for (int right = 0; right < s.length(); right++) {
if (count[s.charAt(right)]++ == 0) {
num++;
}
if (num > k) {
while (--count[s.charAt(left++)] > 0) {
}
;
num
}
result = Math.max(result, right - left + 1);
}
return result;
}
}
public static class Solution2 {
/**
* This is a more generic solution for any characters, not limited to ASCII characters.
*/
public int lengthOfLongestSubstringKDistinct(String s, int k) {
Map<Character, Integer> map = new HashMap<>();
int longest = 0;
int left = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
map.put(c, map.getOrDefault(c, 0) + 1);
while (map.size() > k) {
char leftChar = s.charAt(left);
if (map.containsKey(leftChar)) {
map.put(leftChar, map.get(leftChar) - 1);
if (map.get(leftChar) == 0) {
map.remove(leftChar);
}
}
left++;
}
longest = Math.max(longest, i - left + 1);
}
return longest;
}
}
} |
package com.couchbase.lite;
import com.couchbase.lite.internal.InterfaceAudience;
import com.couchbase.lite.util.Log;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* A Query subclass that automatically refreshes the result rows every time the database changes.
* All you need to do is use add a listener to observe changes.
*/
public final class LiveQuery extends Query implements Database.ChangeListener {
private boolean observing;
private QueryEnumerator rows;
private List<ChangeListener> observers = new ArrayList<ChangeListener>();
private Throwable lastError;
private AtomicBoolean runningState; // true == running, false == stopped
/**
* If a query is running and the user calls stop() on this query, the future
* will be used in order to cancel the query in progress.
*/
protected Future queryFuture;
/**
* If the update() method is called while a query is in progress, once it is
* finished it will be scheduled to re-run update(). This tracks the future
* related to that scheduled task.
*/
protected Future rerunUpdateFuture;
/**
* Constructor
*/
@InterfaceAudience.Private
/* package */ LiveQuery(Query query) {
super(query.getDatabase(), query.getView());
runningState = new AtomicBoolean(false);
setLimit(query.getLimit());
setSkip(query.getSkip());
setStartKey(query.getStartKey());
setEndKey(query.getEndKey());
setDescending(query.isDescending());
setPrefetch(query.shouldPrefetch());
setKeys(query.getKeys());
setGroupLevel(query.getGroupLevel());
setMapOnly(query.isMapOnly());
setStartKeyDocId(query.getStartKeyDocId());
setEndKeyDocId(query.getEndKeyDocId());
setIndexUpdateMode(query.getIndexUpdateMode());
}
/**
* Sends the query to the server and returns an enumerator over the result rows (Synchronous).
* Note: In a LiveQuery you should consider adding a ChangeListener and calling start() instead.
*/
@Override
@InterfaceAudience.Public
public QueryEnumerator run() throws CouchbaseLiteException {
while (true) {
try {
waitForRows();
break;
} catch (Exception e) {
if (e instanceof CancellationException) {
continue;
} else {
lastError = e;
throw new CouchbaseLiteException(e, Status.INTERNAL_SERVER_ERROR);
}
}
}
if (rows == null) {
return null;
}
else {
// Have to return a copy because the enumeration has to start at item #0 every time
return new QueryEnumerator(rows);
}
}
/**
* Returns the last error, if any, that occured while executing the Query, otherwise null.
*/
@InterfaceAudience.Public
public Throwable getLastError() {
return lastError;
}
/**
* Starts observing database changes. The .rows property will now update automatically. (You
* usually don't need to call this yourself, since calling getRows() will start it for you
*/
@InterfaceAudience.Public
public void start() {
if (runningState.get() == true) {
Log.v(Log.TAG_QUERY, "%s: start() called, but runningState is already true. Ignoring.", this);
return;
} else {
Log.d(Log.TAG_QUERY, "%s: start() called", this);
runningState.set(true);
}
if (!observing) {
observing = true;
getDatabase().addChangeListener(this);
Log.v(Log.TAG_QUERY, "%s: start() is calling update()", this);
update();
}
}
/**
* Stops observing database changes. Calling start() or rows() will restart it.
*/
@InterfaceAudience.Public
public void stop() {
if (runningState.get() == false) {
Log.d(Log.TAG_QUERY, "%s: stop() called, but runningState is already false. Ignoring.", this);
return;
} else {
Log.d(Log.TAG_QUERY, "%s: stop() called", this);
runningState.set(false);
}
if (observing) {
observing = false;
getDatabase().removeChangeListener(this);
}
// slight diversion from iOS version -- cancel the queryFuture
// regardless of the willUpdate value, since there can be an update in flight
// with willUpdate set to false. was needed to make testLiveQueryStop() unit test pass.
if (queryFuture != null) {
boolean cancelled = queryFuture.cancel(true);
Log.v(Log.TAG_QUERY, "%s: cancelled queryFuture %s, returned: %s", this, queryFuture, cancelled);
}
if (rerunUpdateFuture != null) {
boolean cancelled = rerunUpdateFuture.cancel(true);
Log.d(Log.TAG_QUERY, "%s: cancelled rerunUpdateFuture %s, returned: %s", this, rerunUpdateFuture, cancelled);
}
}
/**
* Blocks until the intial async query finishes. After this call either .rows or .error will be non-nil.
*/
@InterfaceAudience.Public
public void waitForRows() throws CouchbaseLiteException {
start();
while (true) {
try {
queryFuture.get();
break;
} catch (Exception e) {
if (e instanceof CancellationException) {
continue;
} else {
lastError = e;
throw new CouchbaseLiteException(e, Status.INTERNAL_SERVER_ERROR);
}
}
}
}
/**
* Gets the results of the Query. The value will be null until the initial Query completes.
*/
@InterfaceAudience.Public
public QueryEnumerator getRows() {
start();
if (rows == null) {
return null;
}
else {
// Have to return a copy because the enumeration has to start at item #0 every time
return new QueryEnumerator(rows);
}
}
/**
* Add a change listener to be notified when the live query result
* set changes.
*/
@InterfaceAudience.Public
public void addChangeListener(ChangeListener changeListener) {
observers.add(changeListener);
}
/**
* Remove previously added change listener
*/
@InterfaceAudience.Public
public void removeChangeListener(ChangeListener changeListener) {
observers.remove(changeListener);
}
/**
* The type of event raised when a LiveQuery result set changes.
*/
@InterfaceAudience.Public
public static class ChangeEvent {
private LiveQuery source;
private Throwable error;
private QueryEnumerator queryEnumerator;
ChangeEvent() {
}
ChangeEvent(LiveQuery source, QueryEnumerator queryEnumerator) {
this.source = source;
this.queryEnumerator = queryEnumerator;
}
ChangeEvent(Throwable error) {
this.error = error;
}
public LiveQuery getSource() {
return source;
}
public Throwable getError() {
return error;
}
public QueryEnumerator getRows() {
return queryEnumerator;
}
}
/**
* A delegate that can be used to listen for LiveQuery result set changes.
*/
@InterfaceAudience.Public
public static interface ChangeListener {
public void changed(ChangeEvent event);
}
@InterfaceAudience.Private
/* package */ void update() {
Log.v(Log.TAG_QUERY, "%s: update() called.", this);
if (getView() == null) {
throw new IllegalStateException("Cannot start LiveQuery when view is null");
}
if (runningState.get() == false) {
Log.d(Log.TAG_QUERY, "%s: update() called, but running state == false. Ignoring.", this);
return;
}
if (queryFuture != null && !queryFuture.isCancelled() && !queryFuture.isDone()) {
// There is a already a query in flight, so leave it alone except to schedule something
// to run update() again once it finishes.
Log.d(Log.TAG_QUERY, "%s: already a query in flight, scheduling call to update() once it's done", LiveQuery.this);
if (rerunUpdateFuture != null && !rerunUpdateFuture.isCancelled() && !rerunUpdateFuture.isDone()) {
boolean cancelResult = rerunUpdateFuture.cancel(true);
Log.d(Log.TAG_QUERY, "%s: cancelled %s result: %s", LiveQuery.this, rerunUpdateFuture, cancelResult);
}
rerunUpdateFuture = rerunUpdateAfterQueryFinishes(queryFuture);
Log.d(Log.TAG_QUERY, "%s: created new rerunUpdateFuture: %s", LiveQuery.this, rerunUpdateFuture);
return;
}
// No query in flight, so kick one off
queryFuture = runAsyncInternal(new QueryCompleteListener() {
@Override
public void completed(QueryEnumerator rowsParam, Throwable error) {
if (error != null) {
for (ChangeListener observer : observers) {
observer.changed(new ChangeEvent(error));
}
lastError = error;
} else {
if (runningState.get() == false) {
Log.d(Log.TAG_QUERY, "%s: update() finished query, but running state == false.", this);
return;
}
if (rowsParam != null && !rowsParam.equals(rows)) {
setRows(rowsParam);
for (ChangeListener observer : observers) {
Log.d(Log.TAG_QUERY, "%s: update() calling back observer with rows", LiveQuery.this);
observer.changed(new ChangeEvent(LiveQuery.this, rows));
}
}
lastError = null;
}
}
});
Log.d(Log.TAG_QUERY, "%s: update() created queryFuture: %s", this, queryFuture);
}
/**
* kick off async task that will wait until the query finishes, and after it
* does, it will run upate() again in case the current query in flight misses
* some of the recently added items.
*/
private Future rerunUpdateAfterQueryFinishes(final Future queryFutureInProgress) {
return getDatabase().getManager().runAsync(new Runnable() {
@Override
public void run() {
if (runningState.get() == false) {
Log.v(Log.TAG_QUERY, "%s: rerunUpdateAfterQueryFinishes.run() fired, but running state == false. Ignoring.", this);
return;
}
if (queryFutureInProgress != null) {
try {
queryFutureInProgress.get();
if (runningState.get() == false) {
Log.v(Log.TAG_QUERY, "%s: queryFutureInProgress.get() done, but running state == false.", this);
return;
}
update();
} catch (Exception e) {
if (e instanceof CancellationException) {
// can safely ignore these
} else {
Log.e(Log.TAG_QUERY, "Got exception waiting for queryFutureInProgress to finish", e);
}
}
}
}
});
}
/**
* @exclude
*/
@Override
@InterfaceAudience.Private
public void changed(Database.ChangeEvent event) {
update();
}
@InterfaceAudience.Private
private synchronized void setRows(QueryEnumerator queryEnumerator) {
rows = queryEnumerator;
}
} |
package org.openmrs.api.db.hibernate;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
import java.util.Properties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.FlushMode;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.stat.QueryStatistics;
import org.hibernate.stat.Statistics;
import org.openmrs.GlobalProperty;
import org.openmrs.User;
import org.openmrs.api.context.ContextAuthenticationException;
import org.openmrs.api.db.ContextDAO;
import org.openmrs.util.OpenmrsConstants;
import org.openmrs.util.Security;
import org.springframework.orm.hibernate3.SessionFactoryUtils;
import org.springframework.orm.hibernate3.SessionHolder;
import org.springframework.transaction.support.TransactionSynchronizationManager;
public class HibernateContextDAO implements ContextDAO {
private static Log log = LogFactory.getLog(HibernateContextDAO.class);
/**
* Hibernate session factory
*/
private SessionFactory sessionFactory;
/**
* Default public constructor
*/
public HibernateContextDAO() {
}
/**
* Set session factory
*
* @param sessionFactory
*/
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
/**
* Authenticate the user for this context.
*
* @param username
* @param password
*
* @see org.openmrs.api.context.Context#authenticate(String, String)
* @throws ContextAuthenticationException
*/
public User authenticate(String login, String password)
throws ContextAuthenticationException {
String errorMsg = "Invalid username and/or password: " + login;
Session session = sessionFactory.getCurrentSession();
User candidateUser = null;
if (login != null) {
// loginWithoutDash is used to compare to the system id
String loginWithoutDash = login;
if (login.length() >= 3 && login.charAt(login.length() - 2) == '-')
loginWithoutDash = login.substring(0, login.length() - 2)
+ login.charAt(login.length() - 1);
try {
candidateUser = (User) session
.createQuery(
"from User u where (u.username = ? or u.systemId = ? or u.systemId = ?) and u.voided = 0")
.setString(0, login)
.setString(1, login)
.setString(2, loginWithoutDash)
.uniqueResult();
} catch (HibernateException he) {
log.error("Got hibernate exception while logging in: '" + login
+ "'", he);
} catch (Exception e) {
log.error(
"Got regular exception while logging in: '" + login + "'",
e);
}
}
if (candidateUser == null)
throw new ContextAuthenticationException("User not found: " + login);
if (log.isDebugEnabled())
log.debug("Candidate user id: " + candidateUser.getUserId());
if (password == null)
throw new ContextAuthenticationException("Password cannot be null");
String passwordOnRecord = (String) session.createSQLQuery(
"select password from users where user_id = ?")
.addScalar("password", Hibernate.STRING)
.setInteger(0, candidateUser.getUserId())
.uniqueResult();
String saltOnRecord = (String) session.createSQLQuery(
"select salt from users where user_id = ?")
.addScalar("salt", Hibernate.STRING)
.setInteger(0, candidateUser.getUserId())
.uniqueResult();
String hashedPassword = Security.encodeString(password + saltOnRecord);
User user = null;
if (hashedPassword != null && hashedPassword.equals(passwordOnRecord))
user = candidateUser;
if (user == null) {
log.info("Failed login attempt (login=" + login + ") - "
+ errorMsg);
throw new ContextAuthenticationException(errorMsg);
}
// hydrate the user object
user.getAllRoles().size();
user.getUserProperties().size();
user.getPrivileges().size();
return user;
}
/**
* @see org.openmrs.api.context.Context#openSession()
*/
private boolean participate = false;
public void openSession() {
log.debug("HibernateContext: Opening Hibernate Session");
if (TransactionSynchronizationManager.hasResource(sessionFactory)) {
if (log.isDebugEnabled())
log.debug("Participating in existing session ("
+ sessionFactory.hashCode() + ")");
participate = true;
} else {
if (log.isDebugEnabled())
log.debug("Registering session with synchronization manager ("
+ sessionFactory.hashCode() + ")");
Session session = SessionFactoryUtils.getSession(sessionFactory,
true);
session.setFlushMode(FlushMode.MANUAL);
TransactionSynchronizationManager.bindResource(sessionFactory,
new SessionHolder(session));
}
}
/**
* @see org.openmrs.api.context.Context#closeSession()
*/
public void closeSession() {
log.debug("HibernateContext: closing Hibernate Session");
if (!participate) {
log.debug("Unbinding session from synchronization mangaer ("
+ sessionFactory.hashCode() + ")");
if (TransactionSynchronizationManager.hasResource(sessionFactory)) {
Object value = TransactionSynchronizationManager.unbindResource(sessionFactory);
try {
if (value instanceof SessionHolder) {
Session session = ((SessionHolder)value).getSession();
SessionFactoryUtils.releaseSession(session, sessionFactory);
}
} catch (RuntimeException e) {
log.error("Unexpected exception on closing Hibernate Session", e);
}
}
} else {
log.debug("Participating in existing session, so not releasing session through synchronization manager");
}
}
/**
* Perform cleanup on current session
*/
public void clearSession() {
sessionFactory.getCurrentSession().clear();
}
/**
* @see org.openmrs.api.context.Context#startup(Properties)
*/
public void startup(Properties properties) {
}
/**
* @see org.openmrs.api.context.Context#shutdown()
*/
public void shutdown() {
if (log.isInfoEnabled())
showUsageStatistics();
if (sessionFactory != null) {
// session is closed by spring on session end
log.debug("Closing any open sessions");
// closeSession();
log.debug("Shutting down threadLocalSession factory");
// sessionFactory.close();
log.debug("The threadLocalSession has been closed");
log.debug("Setting static variables to null");
// sessionFactory = null;
} else
log.error("SessionFactory is null");
}
/**
* Compares core data against the current database and inserts data into the
* database where necessary
*/
public void checkCoreDataset() {
PreparedStatement psSelect;
PreparedStatement psInsert;
PreparedStatement psUpdate;
Map<String, String> map;
// setting core roles
try {
Connection conn = sessionFactory.getCurrentSession().connection();
psSelect = conn
.prepareStatement("SELECT * FROM role WHERE UPPER(role) = UPPER(?)");
psInsert = conn.prepareStatement("INSERT INTO role VALUES (?, ?)");
map = OpenmrsConstants.CORE_ROLES();
for (String role : map.keySet()) {
psSelect.setString(1, role);
ResultSet result = psSelect.executeQuery();
if (!result.next()) {
psInsert.setString(1, role);
psInsert.setString(2, map.get(role));
psInsert.execute();
}
}
conn.commit();
} catch (Exception e) {
log.error("Error while setting core roles for openmrs system", e);
}
// setting core privileges
try {
Connection conn = sessionFactory.getCurrentSession().connection();
psSelect = conn
.prepareStatement("SELECT * FROM privilege WHERE UPPER(privilege) = UPPER(?)");
psInsert = conn
.prepareStatement("INSERT INTO privilege VALUES (?, ?)");
map = OpenmrsConstants.CORE_PRIVILEGES();
for (String priv : map.keySet()) {
psSelect.setString(1, priv);
ResultSet result = psSelect.executeQuery();
if (!result.next()) {
psInsert.setString(1, priv);
psInsert.setString(2, map.get(priv));
psInsert.execute();
}
}
conn.commit();
} catch (SQLException e) {
log.error("Error while setting core privileges", e);
}
// setting core global properties
try {
Connection conn = sessionFactory.getCurrentSession().connection();
psSelect = conn
.prepareStatement("SELECT * FROM global_property WHERE UPPER(property) = UPPER(?)");
psInsert = conn
.prepareStatement("INSERT INTO global_property (property, property_value, description) VALUES (?, ?, ?)");
// this update should only be temporary until everyone has the new global property description code
psUpdate = conn
.prepareStatement("UPDATE global_property SET description = ? WHERE UPPER(property) = UPPER(?) AND description IS null");
for (GlobalProperty gp : OpenmrsConstants.CORE_GLOBAL_PROPERTIES()) {
psSelect.setString(1, gp.getProperty());
ResultSet result = psSelect.executeQuery();
if (!result.next()) {
psInsert.setString(1, gp.getProperty());
psInsert.setString(2, gp.getPropertyValue());
psInsert.setString(3, gp.getDescription());
psInsert.execute();
}
else {
// should only be temporary
psUpdate.setString(1, gp.getDescription());
psUpdate.setString(2, gp.getProperty());
psUpdate.execute();
}
}
conn.commit();
} catch (SQLException e) {
log.error("Error while setting core global properties", e);
}
}
private void showUsageStatistics() {
if (sessionFactory.getStatistics().isStatisticsEnabled()) {
log.debug("Getting query statistics: ");
Statistics stats = sessionFactory.getStatistics();
for (String query : stats.getQueries()) {
log.info("QUERY: " + query);
QueryStatistics qstats = stats.getQueryStatistics(query);
log.info("Cache Hit Count : " + qstats.getCacheHitCount());
log.info("Cache Miss Count: " + qstats.getCacheMissCount());
log.info("Cache Put Count : " + qstats.getCachePutCount());
log.info("Execution Count : " + qstats.getExecutionCount());
log.info("Average time : " + qstats.getExecutionAvgTime());
log.info("Row Count : " + qstats.getExecutionRowCount());
}
}
}
public void closeDatabaseConnection() {
sessionFactory.close();
}
} |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ch.unizh.ini.jaer.projects.holger;
import net.sf.jaer.chip.*;
import net.sf.jaer.event.*;
import net.sf.jaer.event.EventPacket;
import net.sf.jaer.eventprocessing.EventFilter2D;
import java.util.*;
import com.sun.opengl.util.GLUT;
import java.awt.Graphics2D;
import javax.media.opengl.GL;
import javax.media.opengl.GLAutoDrawable;
import net.sf.jaer.graphics.FrameAnnotater;
import net.sf.jaer.util.EngineeringFormat;
import java.io.*;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;
/**
* Extracts interaural time difference (ITD) from a binaural cochlea input.
*
* @author Holger
*/
public class ITDFilter extends EventFilter2D implements Observer, FrameAnnotater {
private ITDCalibrationGaussians calibration = null;
private float averagingDecay;
private int maxITD;
private int numOfBins;
private int maxWeight;
private int dimLastTs;
private int maxWeightTime;
private int confidenceThreshold;
private int numLoopMean;
private boolean display;
private boolean useLaterSpikeForWeight;
private boolean usePriorSpikeForWeight;
private boolean computeMeanInLoop;
private boolean useCalibration;
private boolean writeITD2File;
private String calibrationFilePath = getPrefs().get("ITDFilter.calibrationFilePath", null);
ITDFrame frame;
private ITDBins myBins;
//private LinkedList[][] lastTimestamps;
//private ArrayList<LinkedList<Integer>> lastTimestamps0;
//private ArrayList<LinkedList<Integer>> lastTimestamps1;
private int[][][] lastTs;
private int[][] lastTsCursor;
//private int[][] AbsoluteLastTimestamp;
Iterator iterator;
private float lastWeight = 1f;
private int avgITD;
private float avgITDConfidence = 0;
private float ILD;
EngineeringFormat fmt = new EngineeringFormat();
FileWriter fstream;
BufferedWriter ITDFile;
public enum EstimationMethod{
useMedian, useMean, useMax
};
private EstimationMethod estimationMethod=EstimationMethod.valueOf(getPrefs().get("ITDFilter.estimationMethod","useMedian"));
public ITDFilter(AEChip chip) {
super(chip);
initFilter();
//resetFilter();
//lastTimestamps = (LinkedList[][])new LinkedList[32][2];
//LinkedList[][] <Integer>lastTimestamps = new LinkedList<Integer>[1][2]();
// lastTimestamps0 = new ArrayList<LinkedList<Integer>>(32);
// lastTimestamps1 = new ArrayList<LinkedList<Integer>>(32);
// for (int k=0;k<32;k++) {
// lastTimestamps0.add(new LinkedList<Integer>());
// lastTimestamps1.add(new LinkedList<Integer>());
lastTs = new int[32][2][dimLastTs];
lastTsCursor = new int[32][2];
//AbsoluteLastTimestamp = new int[32][2];
setPropertyTooltip("averagingDecay", "The decay constant of the fade out of old ITDs (in us)");
setPropertyTooltip("maxITD", "maximum ITD to compute in us");
setPropertyTooltip("numOfBins", "total number of bins");
setPropertyTooltip("dimLastTs", "how many lastTs save");
setPropertyTooltip("maxWeight", "maximum weight for ITDs");
setPropertyTooltip("maxWeightTime", "maximum time to use for weighting ITDs");
setPropertyTooltip("display", "display bins");
setPropertyTooltip("useLaterSpikeForWeight", "use the side of the later arriving spike to weight the ITD");
setPropertyTooltip("usePriorSpikeForWeight", "use the side of the prior arriving spike to weight the ITD");
setPropertyTooltip("computeMeanInLoop", "use a loop to compute the mean or median to avoid biasing");
setPropertyTooltip("useCalibration", "use xml calibration file");
setPropertyTooltip("confidenceThreshold", "ITDs with confidence below this threshold are neglected");
setPropertyTooltip("writeITD2File", "Write the ITD-values to a File");
setPropertyTooltip("SelectCalibrationFile", "select the xml file which can be created by matlab");
setPropertyTooltip("calibrationFilePath", "Full path to xml calibration file");
setPropertyTooltip("estimationMethod", "Method used to compute the ITD");
setPropertyTooltip("numLoopMean", "Method used to compute the ITD");
}
public EventPacket<?> filterPacket(EventPacket<?> in) {
if (enclosedFilter != null) {
in = enclosedFilter.filterPacket(in);
}
if (!isFilterEnabled() || in.getSize() == 0) {
return in;
}
checkOutputPacketEventType(in);
int nleft = 0, nright = 0;
for (Object e : in) {
BasicEvent i = (BasicEvent) e;
try {
int cursor = lastTsCursor[i.x][1 - i.y];
do {
int diff = i.timestamp - lastTs[i.x][1 - i.y][cursor]; // compare actual ts with last complementary ts of that channel
// x = channel y = side!!
if (i.y == 0) {
diff = -diff; // to distingiuish plus- and minus-delay
nright++;
} else {
nleft++;
}
if (java.lang.Math.abs(diff) < maxITD) {
lastWeight = 1f;
//Compute weight:
if (useLaterSpikeForWeight == true) {
int weightTimeThisSide = i.timestamp - lastTs[i.x][i.y][lastTsCursor[i.x][i.y]];
if (weightTimeThisSide > maxWeightTime) {
weightTimeThisSide = maxWeightTime;
}
lastWeight *= ((weightTimeThisSide * (maxWeight - 1f)) / (float)maxWeightTime) + 1f;
}
if (usePriorSpikeForWeight == true) {
int weightTimeOtherSide = lastTs[i.x][1 - i.y][cursor] - lastTs[i.x][1 - i.y][(cursor + 1) % dimLastTs];
if (weightTimeOtherSide > maxWeightTime) {
weightTimeOtherSide = maxWeightTime;
}
lastWeight *= ((weightTimeOtherSide * (maxWeight - 1f)) / (float)maxWeightTime) + 1f;
if (weightTimeOtherSide < 0) {
log.warning("weight<0");
}
}
myBins.addITD(diff, i.timestamp, i.x, lastWeight);
} else {
break;
}
cursor = (++cursor) % dimLastTs;
} while (cursor != lastTsCursor[i.x][1 - i.y]);
//Now decrement the cursor (circularly)
if (lastTsCursor[i.x][i.y] == 0) {
lastTsCursor[i.x][i.y] = dimLastTs;
}
lastTsCursor[i.x][i.y]
//Add the new timestamp to the list
lastTs[i.x][i.y][lastTsCursor[i.x][i.y]] = i.timestamp;
if (this.writeITD2File == true) {
refreshITD();
ITDFile.write(i.timestamp + "\t" + avgITD + "\t" + avgITDConfidence + "\n");
}
} catch (Exception e1) {
log.warning("In for-loop in filterPacket caught exception " + e1);
e1.printStackTrace();
}
}
try {
refreshITD();
if (display == true && frame != null) {
frame.setITD(avgITD);
}
ILD = (float) (nright - nleft) / (float) (nright + nleft); //Max ILD is 1 (if only one side active)
} catch (Exception e) {
log.warning("In filterPacket caught exception " + e);
e.printStackTrace();
}
return in;
}
public void refreshITD() {
int avgITDtemp = 0;
switch(estimationMethod){
case useMedian:
avgITDtemp = myBins.getITDMedian();
break;
case useMean:
avgITDtemp = myBins.getITDMean();
break;
case useMax:
avgITDtemp = myBins.getITDMax();
}
avgITDConfidence = myBins.getITDConfidence();
if (avgITDConfidence > confidenceThreshold) {
avgITD = avgITDtemp;
}
}
public Object getFilterState() {
return null;
}
public void resetFilter() {
createBins();
lastTs = new int[32][2][dimLastTs];
}
@Override
public void initFilter() {
log.info("init() called");
averagingDecay = getPrefs().getFloat("ITDFilter.averagingDecay", 1000000);
maxITD = getPrefs().getInt("ITDFilter.maxITD", 800);
numOfBins = getPrefs().getInt("ITDFilter.numOfBins", 16);
maxWeight = getPrefs().getInt("ITDFilter.maxWeight", 50);
dimLastTs = getPrefs().getInt("ITDFilter.dimLastTs", 4);
maxWeightTime = getPrefs().getInt("ITDFilter.maxWeightTime", 500000);
display = getPrefs().getBoolean("ITDFilter.display", false);
useLaterSpikeForWeight = getPrefs().getBoolean("ITDFilter.useLaterSpikeForWeight", true);
usePriorSpikeForWeight = getPrefs().getBoolean("ITDFilter.usePriorSpikeForWeight", true);
computeMeanInLoop = getPrefs().getBoolean("ITDFilter.computeMeanInLoop", true);
writeITD2File = getPrefs().getBoolean("ITDFilter.writeITD2File", false);
confidenceThreshold = getPrefs().getInt("ITDFilter.confidenceThreshold", 30);
numLoopMean = getPrefs().getInt("ITDFilter.numLoopMean", 2);
if (isFilterEnabled()) {
createBins();
setDisplay(display);
}
}
@Override
public void setFilterEnabled(boolean yes) {
log.info("ITDFilter.setFilterEnabled() is called");
super.setFilterEnabled(yes);
if (yes) {
try {
createBins();
} catch (Exception e) {
log.warning("In genBins() caught exception " + e);
e.printStackTrace();
}
display = getPrefs().getBoolean("ITDFilter.display", false);
setDisplay(display);
}
}
public void update(Observable o, Object arg) {
log.info("ITDFilter.update() is called");
}
public int getMaxITD() {
return this.maxITD;
}
public void setMaxITD(int maxITD) {
getPrefs().putInt("ITDFilter.shiftSize", maxITD);
support.firePropertyChange("shiftSize", this.maxITD, maxITD);
this.maxITD = maxITD;
createBins();
}
public int getNumOfBins() {
return this.numOfBins;
}
public void setNumOfBins(int numOfBins) {
getPrefs().putInt("ITDFilter.binSize", numOfBins);
support.firePropertyChange("binSize", this.numOfBins, numOfBins);
this.numOfBins = numOfBins;
createBins();
}
public int getMaxWeight() {
return this.maxWeight;
}
public void setMaxWeight(int maxWeight) {
getPrefs().putInt("ITDFilter.maxWeights", maxWeight);
support.firePropertyChange("maxWeight", this.maxWeight, maxWeight);
this.maxWeight = maxWeight;
if (!isFilterEnabled()) {
return;
}
createBins();
}
public int getConfidenceThreshold() {
return this.confidenceThreshold;
}
public void setConfidenceThreshold(int confidenceThreshold) {
getPrefs().putInt("ITDFilter.maxWeights", confidenceThreshold);
support.firePropertyChange("confidenceThreshold", this.confidenceThreshold, confidenceThreshold);
this.confidenceThreshold = confidenceThreshold;
}
public int getMaxWeightTime() {
return this.maxWeightTime;
}
public void setMaxWeightTime(int maxWeightTime) {
getPrefs().putInt("ITDFilter.maxWeightTime", maxWeightTime);
support.firePropertyChange("maxWeightTime", this.maxWeightTime, maxWeightTime);
this.maxWeightTime = maxWeightTime;
if (!isFilterEnabled()) {
return;
}
createBins();
}
public int getDimLastTs() {
return this.dimLastTs;
}
public void setDimLastTs(int dimLastTs) {
getPrefs().putInt("ITDFilter.dimLastTs", dimLastTs);
support.firePropertyChange("dimLastTs", this.dimLastTs, dimLastTs);
lastTs = new int[32][2][dimLastTs];
this.dimLastTs = dimLastTs;
}
public int getNumLoopMean() {
return this.numLoopMean;
}
public void setNumLoopMean(int numLoopMean) {
getPrefs().putInt("ITDFilter.numLoopMean", numLoopMean);
support.firePropertyChange("numLoopMean", this.numLoopMean, numLoopMean);
this.numLoopMean = numLoopMean;
if (!isFilterEnabled() || this.computeMeanInLoop == false) {
return;
}
if (myBins == null) {
createBins();
} else {
myBins.setNumLoopMean(numLoopMean);
}
}
public float getAveragingDecay() {
return this.averagingDecay;
}
public void setAveragingDecay(float averagingDecay) {
getPrefs().putDouble("ITDFilter.averagingDecay", averagingDecay);
support.firePropertyChange("averagingDecay", this.averagingDecay, averagingDecay);
this.averagingDecay = averagingDecay;
if (!isFilterEnabled()) {
return;
}
if (myBins == null) {
createBins();
} else {
myBins.setAveragingDecay(averagingDecay);
}
}
public boolean isDisplay() {
return this.display;
}
public void setDisplay(boolean display) {
this.display = display;
if (!isFilterEnabled()) {
return;
}
if (display == false && frame != null) {
frame.setVisible(false);
frame = null;
} else if (display == true) {
if (frame == null) {
try {
frame = new ITDFrame();
frame.binsPanel.updateBins(myBins);
log.info("ITD-Jframe created with height=" + frame.getHeight() + " and width:" + frame.getWidth());
} catch (Exception e) {
log.warning("while creating ITD-Jframe, caught exception " + e);
e.printStackTrace();
}
}
frame.setVisible(true);
}
}
public boolean getUseLaterSpikeForWeight() {
return this.useLaterSpikeForWeight;
}
public void setUseLaterSpikeForWeight(boolean useLaterSpikeForWeight) {
log.info("ITDFilter.setUseLaterSpikeForWeight() is called");
this.useLaterSpikeForWeight = useLaterSpikeForWeight;
if (!isFilterEnabled()) {
return;
}
createBins();
}
public boolean isUsePriorSpikeForWeight() {
return this.usePriorSpikeForWeight;
}
public void setUsePriorSpikeForWeight(boolean usePriorSpikeForWeight) {
log.info("ITDFilter.setUseBothSidesForWeights() is called");
this.usePriorSpikeForWeight = usePriorSpikeForWeight;
if (!isFilterEnabled()) {
return;
}
createBins();
}
public boolean isWriteITD2File() {
return this.writeITD2File;
}
public void setWriteITD2File(boolean writeITD2File) {
this.writeITD2File = writeITD2File;
if (writeITD2File == true) {
try {
// Create file
fstream = new FileWriter("ITDoutput.dat");
ITDFile = new BufferedWriter(fstream);
ITDFile.write("time\tITD\tconf\n");
} catch (Exception e) {//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
} else {
try {
//Close the output stream
ITDFile.close();
} catch (Exception e) {//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
public boolean isComputeMeanInLoop() {
return this.useLaterSpikeForWeight;
}
public void setComputeMeanInLoop(boolean computeMeanInLoop) {
this.computeMeanInLoop = computeMeanInLoop;
if (!isFilterEnabled()) {
return;
}
if (computeMeanInLoop == true) {
if (myBins == null) {
createBins();
} else {
myBins.setNumLoopMean(numLoopMean);
}
} else {
if (myBins == null) {
createBins();
} else {
myBins.setNumLoopMean(1);
}
}
}
public boolean isUseCalibration() {
return this.useCalibration;
}
public void setUseCalibration(boolean useCalibration) {
this.useCalibration = useCalibration;
createBins();
}
public void doSelectCalibrationFile() {
if (calibrationFilePath == null || calibrationFilePath.isEmpty()) {
calibrationFilePath = System.getProperty("user.dir");
}
JFileChooser chooser = new JFileChooser(calibrationFilePath);
chooser.setDialogTitle("Choose calibration .xml file (created with matlab)");
chooser.setFileFilter(new FileFilter() {
@Override
public boolean accept(File f) {
return f.isDirectory() || f.getName().toLowerCase().endsWith(".xml");
}
@Override
public String getDescription() {
return "Executables";
}
});
chooser.setMultiSelectionEnabled(false);
int retval = chooser.showOpenDialog(getChip().getAeViewer().getFilterFrame());
if (retval == JFileChooser.APPROVE_OPTION) {
File f = chooser.getSelectedFile();
if (f != null && f.isFile()) {
setCalibrationFilePath(f.toString());
log.info("selected xml calibration file " + calibrationFilePath);
setUseCalibration(true);
}
}
}
/**
* @return the calibrationFilePath
*/
public String getCalibrationFilePath() {
return calibrationFilePath;
}
/**
* @param calibrationFilePath the calibrationFilePath to set
*/
public void setCalibrationFilePath(String calibrationFilePath) {
support.firePropertyChange("calibrationFilePath", this.calibrationFilePath, calibrationFilePath);
this.calibrationFilePath = calibrationFilePath;
getPrefs().put("ITDFilter.calibrationFilePath", calibrationFilePath);
}
public EstimationMethod getEstimationMethod(){
return estimationMethod;
}
synchronized public void setEstimationMethod(EstimationMethod estimationMethod){
this.estimationMethod=estimationMethod;
getPrefs().put("ITDfilter.estimationMethod",estimationMethod.toString());
}
private void createBins() {
int numLoop;
if (this.computeMeanInLoop==true)
numLoop = numLoopMean;
else
numLoop = 1;
if (useCalibration == false) {
log.info("create Bins with averagingDecay=" + averagingDecay + " and maxITD=" + maxITD + " and numOfBins=" + numOfBins);
myBins = new ITDBins((float) averagingDecay, numLoop, maxITD, numOfBins);
} else {
if (calibration == null) {
calibration = new ITDCalibrationGaussians();
calibration.loadCalibrationFile(calibrationFilePath);
support.firePropertyChange("numOfBins", this.numOfBins, calibration.getNumOfBins());
this.numOfBins = calibration.getNumOfBins();
//getPrefs().putInt("numOfBins", this.numOfBins);
}
log.info("create Bins with averagingDecay=" + averagingDecay + " and calibration file");
myBins = new ITDBins((float) averagingDecay, numLoop, calibration);
}
if (display == true && frame != null) {
frame.binsPanel.updateBins(myBins);
}
}
public void annotate(GLAutoDrawable drawable) {
if (!isFilterEnabled()) {
return;
}
GL gl = drawable.getGL();
gl.glPushMatrix();
final GLUT glut = new GLUT();
gl.glColor3f(1, 1, 1);
gl.glRasterPos3f(0, 0, 0);
glut.glutBitmapString(GLUT.BITMAP_HELVETICA_18, String.format("avgITD(us)=%s", fmt.format(avgITD)));
glut.glutBitmapString(GLUT.BITMAP_HELVETICA_18, String.format(" ITDConfidence=%f", avgITDConfidence));
glut.glutBitmapString(GLUT.BITMAP_HELVETICA_18, String.format(" ILD=%f", ILD));
if (useLaterSpikeForWeight == true) {
glut.glutBitmapString(GLUT.BITMAP_HELVETICA_18, String.format(" lastWeight=%f", lastWeight));
}
gl.glPopMatrix();
}
public void annotate(float[][][] frame) {
throw new UnsupportedOperationException("Not supported yet, use openGL rendering.");
}
public void annotate(Graphics2D g) {
throw new UnsupportedOperationException("Not supported yet, use openGL rendering..");
}
} |
package com.fishercoder.solutions;
import java.util.Deque;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Set;
public class _353 {
public class SnakeGame {
private Set<Integer> set;//Use a set to hold all occupied points for the snake body, this is for easy access for the case of eating its own body
private Deque<Integer> body;//use a queue to hold all occupied points for the snake body as well, this is for easy access to update the tail
int[][] food;
int score;
int foodIndex;
int width;
int height;
/**
* Initialize your data structure here.
*
* @param width - screen width
* @param height - screen height
* @param food - A list of food positions
* E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0].
*/
public SnakeGame(int width, int height, int[][] food) {
this.set = new HashSet();
set.add(0);//initially at [0][0]
this.body = new LinkedList<Integer>();
body.offerLast(0);
this.food = food;
this.width = width;
this.height = height;
}
/**
* Moves the snake.
*
* @param direction - 'U' = Up, 'L' = Left, 'R' = Right, 'D' = Down
* @return The game's score after the move. Return -1 if game over.
* Game over when snake crosses the screen boundary or bites its body.
*/
public int move(String direction) {
if (score == -1) {
return -1;
}
//compute head
int rowHead = body.peekFirst() / width;
int colHead = body.peekFirst() % width;
switch (direction) {
case "U":
rowHead
break;
case "D":
rowHead++;
break;
case "L":
colHead
break;
default:
colHead++;
}
int newHead = rowHead * width + colHead;
set.remove(body.peekLast());//we'll remove the tail from set for now to see if it hits its tail
//if it hits the boundary
if (set.contains(newHead) || rowHead < 0 || colHead < 0 || rowHead >= height || colHead >= width) {
return score = -1;
}
//add head for the following two normal cases:
set.add(newHead);
body.offerFirst(newHead);
//normal eat case: keep tail, add head
if (foodIndex < food.length && rowHead == food[foodIndex][0] && colHead == food[foodIndex][1]) {
set.add(body.peekLast());//old tail does not change, so add it back to set since we removed it earlier
foodIndex++;
return ++score;
}
//normal move case without eating: move head and remove tail
body.pollLast();
return score;
}
}
/**
* Your SnakeGame object will be instantiated and called as such:
* SnakeGame obj = new SnakeGame(width, height, food);
* int param_1 = obj.move(direction);
*/
} |
package com.diskoverorta.vo;
import com.diskoverorta.entities.*;
import java.util.Map;
import java.util.TreeMap;
public class TAConfig
{
public Map<String,String> analysisConfig = null;
public Map<String,String> entityConfig = null;
public Map<String,String> bioentityConfig = null;
public Map<String,String> outputConfig = null;
public Map<String,String> corefConfig = null;
public Map<String,String> ontologyConfig = null;
public TAConfig()
{
analysisConfig = new TreeMap<String,String>();
entityConfig = new TreeMap<String,String>();
bioentityConfig = new TreeMap<String,String>();
outputConfig = new TreeMap<String,String>();
corefConfig = new TreeMap<String,String>();
ontologyConfig = new TreeMap<String,String>();
analysisConfig.put("Entity","FALSE");
analysisConfig.put("Coref","FALSE");
ontologyConfig.put("topics","FALSE");
ontologyConfig.put("events","FALSE");
corefConfig.put("Person","FALSE");
corefConfig.put("Organization", "FALSE");
corefConfig.put("CorefMethod","SUBSTRING");
entityConfig.put("Person","FALSE");
entityConfig.put("Organization","FALSE");
entityConfig.put("Location","FALSE");
entityConfig.put("Date","FALSE");
entityConfig.put("Time","FALSE");
entityConfig.put("Currency","FALSE");
entityConfig.put("Percent","FALSE");
}
} |
package org.apache.xerces.dom;
import java.util.Enumeration;
import java.util.Hashtable;
import java.io.Serializable;
import org.w3c.dom.ls.DocumentLS;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.DOMWriter;
import org.w3c.dom.Attr;
import org.w3c.dom.CDATASection;
import org.w3c.dom.Comment;
import org.w3c.dom.DOMException;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.DocumentFragment;
import org.w3c.dom.DocumentType;
import org.w3c.dom.Element;
import org.w3c.dom.Entity;
import org.w3c.dom.EntityReference;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Notation;
import org.w3c.dom.ProcessingInstruction;
import org.w3c.dom.Text;
// DOM Level 3
import org.w3c.dom.UserDataHandler;
import org.w3c.dom.DOMErrorHandler;
import org.w3c.dom.events.Event;
import org.w3c.dom.events.EventListener;
import org.w3c.dom.events.EventTarget;
import org.apache.xerces.impl.Constants;
import org.apache.xerces.util.XMLChar;
import org.apache.xerces.util.SymbolTable;
import org.apache.xerces.util.DOMErrorHandlerWrapper;
import org.apache.xerces.util.ShadowedSymbolTable;
import org.apache.xerces.xni.parser.XMLErrorHandler;
import org.apache.xerces.xni.parser.XMLEntityResolver;
import org.apache.xerces.xni.parser.XMLParserConfiguration;
import org.apache.xerces.xni.grammars.XMLGrammarPool;
import org.apache.xerces.xni.grammars.Grammar;
import org.apache.xerces.xni.grammars.XMLGrammarDescription;
/**
* The Document interface represents the entire HTML or XML document.
* Conceptually, it is the root of the document tree, and provides the
* primary access to the document's data.
* <P>
* Since elements, text nodes, comments, processing instructions,
* etc. cannot exist outside the context of a Document, the Document
* interface also contains the factory methods needed to create these
* objects. The Node objects created have a ownerDocument attribute
* which associates them with the Document within whose context they
* were created.
* <p>
* The CoreDocumentImpl class only implements the DOM Core. Additional modules
* are supported by the more complete DocumentImpl subclass.
* <p>
* <b>Note:</b> When any node in the document is serialized, the
* entire document is serialized along with it.
*
* @author Arnaud Le Hors, IBM
* @author Joe Kesselman, IBM
* @author Andy Clark, IBM
* @author Ralf Pfeiffer, IBM
* @version $Id$
* @since PR-DOM-Level-1-19980818.
*/
public class CoreDocumentImpl
extends ParentNode implements Document, DocumentLS {
// Constants
/** Serialization version. */
static final long serialVersionUID = 0;
// Data
// document information
/** Document type. */
protected DocumentTypeImpl docType;
/** Document element. */
protected ElementImpl docElement;
/** NodeListCache free list */
transient NodeListCache fFreeNLCache;
/**Experimental DOM Level 3 feature: Document encoding */
protected String encoding;
/**Experimental DOM Level 3 feature: Document actualEncoding */
protected String actualEncoding;
/**Experimental DOM Level 3 feature: Document version */
protected String version;
/**Experimental DOM Level 3 feature: Document standalone */
protected boolean standalone;
/**Experimental DOM Level 3 feature: documentURI */
protected String fDocumentURI;
/**Experimental DOM Level 3 feature: errorHandler */
protected final transient DOMErrorHandlerWrapper fErrorHandlerWrapper = new DOMErrorHandlerWrapper();
/** Table for user data attached to this document nodes. */
protected Hashtable userData;
/** Identifiers. */
protected Hashtable identifiers;
/** Normalization features*/
protected short features = 0;
protected final static short NSPROCESSING = 0x1<<0;
protected final static short DTNORMALIZATION = 0x1<<1;
protected final static short ENTITIES = 0x1<<2;
protected final static short CDATA = 0x1<<3;
protected final static short DEFAULTS = 0x1<<4;
protected final static short SPLITCDATA = 0x1<<5;
protected final static short COMMENTS = 0x1<<6;
protected final static short VALIDATION = 0x1<<7;
// DOM Revalidation
protected DOMNormalizer domNormalizer = null;
protected DOMValidationConfiguration fConfiguration= null;
protected ShadowedSymbolTable fSymbolTable = null;
protected XMLEntityResolver fEntityResolver = null;
protected Grammar fGrammar = null;
/** Table for quick check of child insertion. */
private final static int[] kidOK;
/**
* Number of alterations made to this document since its creation.
* Serves as a "dirty bit" so that live objects such as NodeList can
* recognize when an alteration has been made and discard its cached
* state information.
* <p>
* Any method that alters the tree structure MUST cause or be
* accompanied by a call to changed(), to inform it that any outstanding
* NodeLists may have to be updated.
* <p>
* (Required because NodeList is simultaneously "live" and integer-
* indexed -- a bad decision in the DOM's design.)
* <p>
* Note that changes which do not affect the tree's structure -- changing
* the node's name, for example -- do _not_ have to call changed().
* <p>
* Alternative implementation would be to use a cryptographic
* Digest value rather than a count. This would have the advantage that
* "harmless" changes (those producing equal() trees) would not force
* NodeList to resynchronize. Disadvantage is that it's slightly more prone
* to "false negatives", though that's the difference between "wildly
* unlikely" and "absurdly unlikely". IF we start maintaining digests,
* we should consider taking advantage of them.
*
* Note: This used to be done a node basis, so that we knew what
* subtree changed. But since only DeepNodeList really use this today,
* the gain appears to be really small compared to the cost of having
* an int on every (parent) node plus having to walk up the tree all the
* way to the root to mark the branch as changed everytime a node is
* changed.
* So we now have a single counter global to the document. It means that
* some objects may flush their cache more often than necessary, but this
* makes nodes smaller and only the document needs to be marked as changed.
*/
protected int changes = 0;
// experimental
/** Allow grammar access. */
protected boolean allowGrammarAccess;
/** Bypass error checking. */
protected boolean errorChecking = true;
// Static initialization
static {
kidOK = new int[13];
kidOK[DOCUMENT_NODE] =
1 << ELEMENT_NODE | 1 << PROCESSING_INSTRUCTION_NODE |
1 << COMMENT_NODE | 1 << DOCUMENT_TYPE_NODE;
kidOK[DOCUMENT_FRAGMENT_NODE] =
kidOK[ENTITY_NODE] =
kidOK[ENTITY_REFERENCE_NODE] =
kidOK[ELEMENT_NODE] =
1 << ELEMENT_NODE | 1 << PROCESSING_INSTRUCTION_NODE |
1 << COMMENT_NODE | 1 << TEXT_NODE |
1 << CDATA_SECTION_NODE | 1 << ENTITY_REFERENCE_NODE ;
kidOK[ATTRIBUTE_NODE] =
1 << TEXT_NODE | 1 << ENTITY_REFERENCE_NODE;
kidOK[DOCUMENT_TYPE_NODE] =
kidOK[PROCESSING_INSTRUCTION_NODE] =
kidOK[COMMENT_NODE] =
kidOK[TEXT_NODE] =
kidOK[CDATA_SECTION_NODE] =
kidOK[NOTATION_NODE] =
0;
} // static
// Constructors
/**
* NON-DOM: Actually creating a Document is outside the DOM's spec,
* since it has to operate in terms of a particular implementation.
*/
public CoreDocumentImpl() {
this(false);
}
/** Constructor. */
public CoreDocumentImpl(boolean grammarAccess) {
super(null);
ownerDocument = this;
allowGrammarAccess = grammarAccess;
// set default values for normalization features
features |= NSPROCESSING; //namespace processing was performed.
features |= ENTITIES;
features |= COMMENTS;
features |= DTNORMALIZATION;
features |= CDATA;
features |= DEFAULTS;
features |= SPLITCDATA;
}
/**
* For DOM2 support.
* The createDocument factory method is in DOMImplementation.
*/
public CoreDocumentImpl(DocumentType doctype)
{
this(doctype, false);
}
/** For DOM2 support. */
public CoreDocumentImpl(DocumentType doctype, boolean grammarAccess) {
this(grammarAccess);
if (doctype != null) {
DocumentTypeImpl doctypeImpl;
try {
doctypeImpl = (DocumentTypeImpl) doctype;
} catch (ClassCastException e) {
throw new DOMException(DOMException.WRONG_DOCUMENT_ERR,
"DOM005 Wrong document");
}
doctypeImpl.ownerDocument = this;
appendChild(doctype);
}
}
// Node methods
// even though ownerDocument refers to this in this implementation
// the DOM Level 2 spec says it must be null, so make it appear so
final public Document getOwnerDocument() {
return null;
}
/** Returns the node type. */
public short getNodeType() {
return Node.DOCUMENT_NODE;
}
/** Returns the node name. */
public String getNodeName() {
return "#document";
}
/**
* Deep-clone a document, including fixing ownerDoc for the cloned
* children. Note that this requires bypassing the WRONG_DOCUMENT_ERR
* protection. I've chosen to implement it by calling importNode
* which is DOM Level 2.
*
* @return org.w3c.dom.Node
* @param deep boolean, iff true replicate children
*/
public Node cloneNode(boolean deep) {
CoreDocumentImpl newdoc = new CoreDocumentImpl();
callUserDataHandlers(this, newdoc, UserDataHandler.NODE_CLONED);
cloneNode(newdoc, deep);
return newdoc;
} // cloneNode(boolean):Node
/**
* internal method to share code with subclass
**/
protected void cloneNode(CoreDocumentImpl newdoc, boolean deep) {
// clone the children by importing them
if (needsSyncChildren()) {
synchronizeChildren();
}
if (deep) {
Hashtable reversedIdentifiers = null;
if (identifiers != null) {
// Build a reverse mapping from element to identifier.
reversedIdentifiers = new Hashtable();
Enumeration elementIds = identifiers.keys();
while (elementIds.hasMoreElements()) {
Object elementId = elementIds.nextElement();
reversedIdentifiers.put(identifiers.get(elementId),
elementId);
}
}
// Copy children into new document.
for (ChildNode kid = firstChild; kid != null;
kid = kid.nextSibling) {
newdoc.appendChild(newdoc.importNode(kid, true, true,
reversedIdentifiers));
}
}
// experimental
newdoc.allowGrammarAccess = allowGrammarAccess;
newdoc.errorChecking = errorChecking;
} // cloneNode(CoreDocumentImpl,boolean):void
/**
* Since a Document may contain at most one top-level Element child,
* and at most one DocumentType declaraction, we need to subclass our
* add-children methods to implement this constraint.
* Since appendChild() is implemented as insertBefore(,null),
* altering the latter fixes both.
* <p>
* While I'm doing so, I've taken advantage of the opportunity to
* cache documentElement and docType so we don't have to
* search for them.
*
* REVISIT: According to the spec it is not allowed to alter neither the
* document element nor the document type in any way
*/
public Node insertBefore(Node newChild, Node refChild)
throws DOMException {
// Only one such child permitted
int type = newChild.getNodeType();
if (errorChecking) {
if((type == Node.ELEMENT_NODE && docElement != null) ||
(type == Node.DOCUMENT_TYPE_NODE && docType != null)) {
throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR,
"DOM006 Hierarchy request error");
}
}
// Adopt orphan doctypes
if (newChild.getOwnerDocument() == null &&
newChild instanceof DocumentTypeImpl) {
((DocumentTypeImpl) newChild).ownerDocument = this;
}
super.insertBefore(newChild,refChild);
// If insert succeeded, cache the kid appropriately
if (type == Node.ELEMENT_NODE) {
docElement = (ElementImpl)newChild;
}
else if (type == Node.DOCUMENT_TYPE_NODE) {
docType = (DocumentTypeImpl)newChild;
}
return newChild;
} // insertBefore(Node,Node):Node
/**
* Since insertBefore caches the docElement (and, currently, docType),
* removeChild has to know how to undo the cache
*
* REVISIT: According to the spec it is not allowed to alter neither the
* document element nor the document type in any way
*/
public Node removeChild(Node oldChild) throws DOMException {
super.removeChild(oldChild);
// If remove succeeded, un-cache the kid appropriately
int type = oldChild.getNodeType();
if(type == Node.ELEMENT_NODE) {
docElement = null;
}
else if (type == Node.DOCUMENT_TYPE_NODE) {
docType = null;
}
return oldChild;
} // removeChild(Node):Node
/**
* Since we cache the docElement (and, currently, docType),
* replaceChild has to update the cache
*
* REVISIT: According to the spec it is not allowed to alter neither the
* document element nor the document type in any way
*/
public Node replaceChild(Node newChild, Node oldChild)
throws DOMException {
// Adopt orphan doctypes
if (newChild.getOwnerDocument() == null &&
newChild instanceof DocumentTypeImpl) {
((DocumentTypeImpl) newChild).ownerDocument = this;
}
super.replaceChild(newChild, oldChild);
int type = oldChild.getNodeType();
if(type == Node.ELEMENT_NODE) {
docElement = (ElementImpl)newChild;
}
else if (type == Node.DOCUMENT_TYPE_NODE) {
docType = (DocumentTypeImpl)newChild;
}
return oldChild;
} // replaceChild(Node,Node):Node
/*
* Get Node text content
* @since DOM Level 3
*/
public String getTextContent() throws DOMException {
return null;
}
/*
* Set Node text content
* @since DOM Level 3
*/
public void setTextContent(String textContent)
throws DOMException {
// no-op
}
// Document methods
// factory methods
/**
* Factory method; creates an Attribute having this Document as its
* OwnerDoc.
*
* @param name The name of the attribute. Note that the attribute's value
* is _not_ established at the factory; remember to set it!
*
* @throws DOMException(INVALID_NAME_ERR) if the attribute name is not
* acceptable.
*/
public Attr createAttribute(String name)
throws DOMException {
if (errorChecking && !isXMLName(name)) {
throw new DOMException(DOMException.INVALID_CHARACTER_ERR,
"DOM002 Illegal character");
}
return new AttrImpl(this, name);
} // createAttribute(String):Attr
/**
* Factory method; creates a CDATASection having this Document as
* its OwnerDoc.
*
* @param data The initial contents of the CDATA
*
* @throws DOMException(NOT_SUPPORTED_ERR) for HTML documents. (HTML
* not yet implemented.)
*/
public CDATASection createCDATASection(String data)
throws DOMException {
return new CDATASectionImpl(this, data);
}
/**
* Factory method; creates a Comment having this Document as its
* OwnerDoc.
*
* @param data The initial contents of the Comment. */
public Comment createComment(String data) {
return new CommentImpl(this, data);
}
/**
* Factory method; creates a DocumentFragment having this Document
* as its OwnerDoc.
*/
public DocumentFragment createDocumentFragment() {
return new DocumentFragmentImpl(this);
}
/**
* Factory method; creates an Element having this Document
* as its OwnerDoc.
*
* @param tagName The name of the element type to instantiate. For
* XML, this is case-sensitive. For HTML, the tagName parameter may
* be provided in any case, but it must be mapped to the canonical
* uppercase form by the DOM implementation.
*
* @throws DOMException(INVALID_NAME_ERR) if the tag name is not
* acceptable.
*/
public Element createElement(String tagName)
throws DOMException {
if (errorChecking && !isXMLName(tagName)) {
throw new DOMException(DOMException.INVALID_CHARACTER_ERR,
"DOM002 Illegal character");
}
return new ElementImpl(this, tagName);
} // createElement(String):Element
/**
* Factory method; creates an EntityReference having this Document
* as its OwnerDoc.
*
* @param name The name of the Entity we wish to refer to
*
* @throws DOMException(NOT_SUPPORTED_ERR) for HTML documents, where
* nonstandard entities are not permitted. (HTML not yet
* implemented.)
*/
public EntityReference createEntityReference(String name)
throws DOMException {
if (errorChecking && !isXMLName(name)) {
throw new DOMException(DOMException.INVALID_CHARACTER_ERR,
"DOM002 Illegal character");
}
return new EntityReferenceImpl(this, name);
} // createEntityReference(String):EntityReference
/**
* Factory method; creates a ProcessingInstruction having this Document
* as its OwnerDoc.
*
* @param target The target "processor channel"
* @param data Parameter string to be passed to the target.
*
* @throws DOMException(INVALID_NAME_ERR) if the target name is not
* acceptable.
*
* @throws DOMException(NOT_SUPPORTED_ERR) for HTML documents. (HTML
* not yet implemented.)
*/
public ProcessingInstruction createProcessingInstruction(String target,
String data)
throws DOMException {
if (errorChecking && !isXMLName(target)) {
throw new DOMException(DOMException.INVALID_CHARACTER_ERR,
"DOM002 Illegal character");
}
return new ProcessingInstructionImpl(this, target, data);
} // createProcessingInstruction(String,String):ProcessingInstruction
/**
* Factory method; creates a Text node having this Document as its
* OwnerDoc.
*
* @param data The initial contents of the Text.
*/
public Text createTextNode(String data) {
return new TextImpl(this, data);
}
// other document methods
/**
* For XML, this provides access to the Document Type Definition.
* For HTML documents, and XML documents which don't specify a DTD,
* it will be null.
*/
public DocumentType getDoctype() {
if (needsSyncChildren()) {
synchronizeChildren();
}
return docType;
}
public Element getDocumentElement() {
if (needsSyncChildren()) {
synchronizeChildren();
}
return docElement;
}
/**
* Return a <em>live</em> collection of all descendent Elements (not just
* immediate children) having the specified tag name.
*
* @param tagname The type of Element we want to gather. "*" will be
* taken as a wildcard, meaning "all elements in the document."
*
* @see DeepNodeListImpl
*/
public NodeList getElementsByTagName(String tagname) {
return new DeepNodeListImpl(this,tagname);
}
/**
* Retrieve information describing the abilities of this particular
* DOM implementation. Intended to support applications that may be
* using DOMs retrieved from several different sources, potentially
* with different underlying representations.
*/
public DOMImplementation getImplementation() {
// Currently implemented as a singleton, since it's hardcoded
// information anyway.
return CoreDOMImplementationImpl.getDOMImplementation();
}
// Public methods
// properties
public void setErrorChecking(boolean check) {
errorChecking = check;
}
/*
* DOM Level 3 WD - Experimental.
*/
public void setStrictErrorChecking(boolean check) {
errorChecking = check;
}
/**
* Returns true if the DOM implementation performs error checking.
*/
public boolean getErrorChecking() {
return errorChecking;
}
/*
* DOM Level 3 WD - Experimental.
*/
public boolean getStrictErrorChecking() {
return errorChecking;
}
/**
* DOM Level 3 WD - Experimental.
* An attribute specifying the actual encoding of this document. This is
* <code>null</code> otherwise.
* <br> This attribute represents the property [character encoding scheme]
* defined in .
* @since DOM Level 3
*/
public String getActualEncoding() {
return actualEncoding;
}
/**
* DOM Level 3 WD - Experimental.
* An attribute specifying the actual encoding of this document. This is
* <code>null</code> otherwise.
* <br> This attribute represents the property [character encoding scheme]
* defined in .
* @since DOM Level 3
*/
public void setActualEncoding(String value) {
actualEncoding = value;
}
/**
* DOM Level 3 WD - Experimental.
* An attribute specifying, as part of the XML declaration,
* the encoding of this document. This is null when unspecified.
*/
public void setEncoding(String value) {
encoding = value;
}
/**
* DOM Level 3 WD - Experimental.
* The encoding of this document (part of XML Declaration)
*/
public String getEncoding() {
return encoding;
}
/**
* DOM Level 3 WD - Experimental.
* version - An attribute specifying, as part of the XML declaration,
* the version number of this document. This is null when unspecified
*/
public void setVersion(String value) {
version = value;
}
/**
* DOM Level 3 WD - Experimental.
* The version of this document (part of XML Declaration)
*/
public String getVersion() {
return version;
}
/**
* DOM Level 3 WD - Experimental.
* standalone - An attribute specifying, as part of the XML declaration,
* whether this document is standalone
*/
public void setStandalone(boolean value) {
standalone = value;
}
/**
* DOM Level 3 WD - Experimental.
* standalone that specifies whether this document is standalone
* (part of XML Declaration)
*/
public boolean getStandalone() {
return standalone;
}
/**
* DOM Level 3 WD - Experimental.
* The location of the document or <code>null</code> if undefined.
* <br>Beware that when the <code>Document</code> supports the feature
* "HTML" , the href attribute of the HTML BASE element takes precedence
* over this attribute.
* @since DOM Level 3
*/
public String getDocumentURI(){
return fDocumentURI;
}
/**
* DOM Level 3 WD - Experimental.
* Retrieve error handler.
*/
public DOMErrorHandler getErrorHandler(){
return fErrorHandlerWrapper.getErrorHandler();
}
/**
* DOM Level 3 WD - Experimental.
* Set error handler. It will be called in teh event that an error
* is encountered while performing an operation on a document.
*/
public void setErrorHandler(DOMErrorHandler errorHandler) {
fErrorHandlerWrapper.setErrorHandler(errorHandler);
}
/**
* DOM Level 3 WD - Experimental.
* Renaming node
*/
public Node renameNode(Node n,
String namespaceURI,
String name)
throws DOMException{
if (n.getOwnerDocument() != this) {
throw new DOMException(DOMException.WRONG_DOCUMENT_ERR,
"DOM005 Wrong document");
}
switch (n.getNodeType()) {
case ELEMENT_NODE: {
ElementImpl el = (ElementImpl) n;
if (el instanceof ElementNSImpl) {
((ElementNSImpl) el).rename(namespaceURI, name);
}
else {
if (namespaceURI == null) {
el.rename(name);
}
else {
// we need to create a new object
ElementNSImpl nel =
new ElementNSImpl(this, namespaceURI, name);
// register event listeners on new node
copyEventListeners(el, nel);
// remove user data from old node
Hashtable data = removeUserDataTable(el);
// remove old node from parent if any
Node parent = el.getParentNode();
Node nextSib = el.getNextSibling();
if (parent != null) {
parent.removeChild(el);
}
// move children to new node
Node child = el.getFirstChild();
while (child != null) {
el.removeChild(child);
nel.appendChild(child);
child = el.getFirstChild();
}
// move specified attributes to new node
nel.moveSpecifiedAttributes(el);
// attach user data to new node
setUserDataTable(nel, data);
// and fire user data NODE_RENAMED event
callUserDataHandlers(el, nel,
UserDataHandler.NODE_RENAMED);
// insert new node where old one was
if (parent != null) {
parent.insertBefore(nel, nextSib);
}
el = nel;
}
}
// fire ElementNameChanged event
renamedElement((Element) n, el);
return el;
}
case ATTRIBUTE_NODE: {
AttrImpl at = (AttrImpl) n;
// dettach attr from element
Element el = at.getOwnerElement();
if (el != null) {
el.removeAttributeNode(at);
}
if (n instanceof AttrNSImpl) {
((AttrNSImpl) at).rename(namespaceURI, name);
// reattach attr to element
if (el != null) {
el.setAttributeNodeNS(at);
}
}
else {
if (namespaceURI == null) {
at.rename(name);
// reattach attr to element
if (el != null) {
el.setAttributeNode(at);
}
}
else {
// we need to create a new object
AttrNSImpl nat =
new AttrNSImpl(this, namespaceURI, name);
// register event listeners on new node
copyEventListeners(at, nat);
// remove user data from old node
Hashtable data = removeUserDataTable(at);
// move children to new node
Node child = at.getFirstChild();
while (child != null) {
at.removeChild(child);
nat.appendChild(child);
child = at.getFirstChild();
}
// attach user data to new node
setUserDataTable(nat, data);
// and fire user data NODE_RENAMED event
callUserDataHandlers(at, nat,
UserDataHandler.NODE_RENAMED);
// reattach attr to element
if (el != null) {
el.setAttributeNode(nat);
}
at = nat;
}
}
// fire AttributeNameChanged event
renamedAttrNode((Attr) n, at);
return at;
}
default: {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR,
"cannot rename this type of node.");
}
}
}
/**
* DOM Level 3 WD - Experimental
* Normalize document.
*/
public void normalizeDocument(){
// No need to normalize if already normalized.
if (isNormalized() && !isNormalizeDocRequired()) {
return;
}
if (needsSyncChildren()) {
synchronizeChildren();
}
if (domNormalizer == null) {
domNormalizer = new DOMNormalizer();
}
if ((features & VALIDATION) != 0) {
if (fConfiguration == null) {
// if symbol table is not available
fConfiguration = new DOMValidationConfiguration(fSymbolTable);
}
if (fErrorHandlerWrapper.getErrorHandler() !=null) {
fConfiguration.setErrorHandler(fErrorHandlerWrapper);
}
// resets components.
fConfiguration.reset();
// REVISIT: validation is performed only against one type of grammar
// if doctype is available -- DTD validation
// otherwise XML Schema validation.
// set validation feature on the configuration
fConfiguration.setFeature(DOMValidationConfiguration.VALIDATION, true);
fConfiguration.setFeature(DOMValidationConfiguration.SCHEMA, true);
// set xml-schema validator handler
domNormalizer.setValidationHandler(
CoreDOMImplementationImpl.singleton.getValidator(XMLGrammarDescription.XML_SCHEMA));
if (fGrammar != null) {
fConfiguration.setProperty(DOMValidationConfiguration.GRAMMAR_POOL, domNormalizer);
}
} else { // remove validation handler
domNormalizer.setValidationHandler(null);
}
domNormalizer.reset(fConfiguration);
domNormalizer.normalizeDocument(this);
if ((features & VALIDATION) != 0) {
CoreDOMImplementationImpl.singleton.releaseValidator(XMLGrammarDescription.XML_SCHEMA);
}
isNormalized(true);
}
protected boolean isNormalizeDocRequired (){
// REVISIT: Implement to optimize when normalization is required
return true;
}
public void setNamespaceProcessing(boolean value){
features = (short) (value ? flags | NSPROCESSING : flags & ~NSPROCESSING);
}
/**
* DOM Level 3 WD - Experimental.
* setNormalizationFeature
*/
public void setNormalizationFeature(String name,
boolean state)
throws DOMException{
// REVISIT: Recognizes DOM L3 default features only.
// Does not yet recognize Xerces features.
if (name.equals(Constants.DOM_COMMENTS)) {
features = (short) (state ? features | COMMENTS : features & ~COMMENTS);
} else if (name.equals(Constants.DOM_DATATYPE_NORMALIZATION)) {
// REVISIT: datatype-normalization only takes effect if validation is on
features = (short) (state ? features | DTNORMALIZATION : features & ~DTNORMALIZATION);
} else if (name.equals(Constants.DOM_CDATA_SECTIONS)) {
features = (short) (state ? features | CDATA : features & ~CDATA);
} else if (name.equals(Constants.DOM_ENTITIES)) {
features = (short) (state ? features | ENTITIES : features & ~ENTITIES);
} else if (name.equals(Constants.DOM_DISCARD_DEFAULT_CONTENT)) {
features = (short) (state ? features | DEFAULTS : features & ~DEFAULTS);
} else if (name.equals(Constants.DOM_SPLIT_CDATA)) {
features = (short) (state ? features | SPLITCDATA : features & ~SPLITCDATA);
} else if (name.equals(Constants.DOM_VALIDATE)) {
features = (short) (state ? features | VALIDATION : features & ~VALIDATION);
} else if (name.equals(Constants.DOM_INFOSET) ||
name.equals(Constants.DOM_NORMALIZE_CHARACTERS) ||
name.equals(Constants.DOM_CANONICAL_FORM) ||
name.equals(Constants.DOM_VALIDATE_IF_SCHEMA)) {
if (state) { // true is not supported
throw new DOMException(DOMException.NOT_SUPPORTED_ERR,"Feature \""+name+"\" cannot be set to \""+state+"\"");
}
} else if (name.equals(Constants.DOM_NAMESPACE_DECLARATIONS) ||
name.equals(Constants.DOM_WHITESPACE_IN_ELEMENT_CONTENT)) {
if (!state) { // false is not supported
throw new DOMException(DOMException.NOT_SUPPORTED_ERR,"Feature \""+name+"\" cannot be set to \""+state+"\"");
}
} else {
throw new DOMException(DOMException.NOT_FOUND_ERR,"Feature \""+name+"\" not recognized");
}
}
/**
* DOM Level 3 WD - Experimental.
* getNormalizationFeature
*/
public boolean getNormalizationFeature(String name)
throws DOMException{
// REVISIT: Recognizes DOM L3 default features only.
// Does not yet recognize Xerces features.
if (name.equals(Constants.DOM_COMMENTS)) {
return (features & COMMENTS) != 0;
} else if (name.equals(Constants.DOM_DATATYPE_NORMALIZATION)) {
// REVISIT: datatype-normalization only takes effect if validation is on
return (features & DTNORMALIZATION) != 0;
} else if (name.equals(Constants.DOM_CDATA_SECTIONS)) {
return (features & CDATA) != 0;
} else if (name.equals(Constants.DOM_ENTITIES)) {
return (features & ENTITIES) != 0;
} else if (name.equals(Constants.DOM_DISCARD_DEFAULT_CONTENT)) {
return (features & DEFAULTS) != 0;
} else if (name.equals(Constants.DOM_SPLIT_CDATA)) {
return (features & SPLITCDATA) != 0;
} else if (name.equals(Constants.DOM_INFOSET) ||
name.equals(Constants.DOM_NORMALIZE_CHARACTERS) ||
name.equals(Constants.DOM_CANONICAL_FORM) ||
name.equals(Constants.DOM_VALIDATE) ||
name.equals(Constants.DOM_VALIDATE_IF_SCHEMA)) {
return false;
} else if (name.equals(Constants.DOM_NAMESPACE_DECLARATIONS) ||
name.equals(Constants.DOM_WHITESPACE_IN_ELEMENT_CONTENT)) {
return true;
} else {
throw new DOMException(DOMException.NOT_FOUND_ERR,"Feature \""+name+"\" not recognized");
}
}
/**
* DOM Level 3 WD - Experimental.
* canSetNormalizationFeature
*/
public boolean canSetNormalizationFeature(String name,
boolean state){
if (name.equals(Constants.DOM_COMMENTS) ||
name.equals(Constants.DOM_DATATYPE_NORMALIZATION) ||
name.equals(Constants.DOM_CDATA_SECTIONS) ||
name.equals(Constants.DOM_ENTITIES) ||
name.equals(Constants.DOM_DISCARD_DEFAULT_CONTENT) ||
name.equals(Constants.DOM_SPLIT_CDATA)) {
return true;
} else if (name.equals(Constants.DOM_INFOSET) ||
name.equals(Constants.DOM_NORMALIZE_CHARACTERS) ||
name.equals(Constants.DOM_CANONICAL_FORM) ||
name.equals(Constants.DOM_VALIDATE) ||
name.equals(Constants.DOM_VALIDATE_IF_SCHEMA)) {
return (state)?false:true;
} else if (name.equals(Constants.DOM_NAMESPACE_DECLARATIONS) ||
name.equals(Constants.DOM_WHITESPACE_IN_ELEMENT_CONTENT)) {
return (state)?true:false;
} else {
throw new DOMException(DOMException.NOT_FOUND_ERR,"Feature \""+name+"\" not recognized");
}
}
/**
* DOM Level 3 WD - Experimental.
* Retrieve baseURI
*/
public String getBaseURI() {
return fDocumentURI;
}
/**
* DOM Level 3 WD - Experimental.
*/
public void setDocumentURI(String documentURI){
fDocumentURI = documentURI;
}
// DOM L3 LS
/**
* DOM Level 3 WD - Experimental.
* Indicates whether the method load should be synchronous or
* asynchronous. When the async attribute is set to <code>true</code>
* the load method returns control to the caller before the document has
* completed loading. The default value of this property is
* <code>false</code>.
* <br>Setting the value of this attribute might throw NOT_SUPPORTED_ERR
* if the implementation doesn't support the mode the attribute is being
* set to. Should the DOM spec define the default value of this
* property? What if implementing both async and sync IO is impractical
* in some systems? 2001-09-14. default is <code>false</code> but we
* need to check with Mozilla and IE.
*/
public boolean getAsync() {
return false;
}
/**
* DOM Level 3 WD - Experimental.
* Indicates whether the method load should be synchronous or
* asynchronous. When the async attribute is set to <code>true</code>
* the load method returns control to the caller before the document has
* completed loading. The default value of this property is
* <code>false</code>.
* <br>Setting the value of this attribute might throw NOT_SUPPORTED_ERR
* if the implementation doesn't support the mode the attribute is being
* set to. Should the DOM spec define the default value of this
* property? What if implementing both async and sync IO is impractical
* in some systems? 2001-09-14. default is <code>false</code> but we
* need to check with Mozilla and IE.
*/
public void setAsync(boolean async) {
if (async) {
// NOT SUPPORTED
throw new DOMException(DOMException.NOT_SUPPORTED_ERR,
"Asynchronous mode is not supported");
}
}
/**
* DOM Level 3 WD - Experimental.
* If the document is currently being loaded as a result of the method
* <code>load</code> being invoked the loading and parsing is
* immediately aborted. The possibly partial result of parsing the
* document is discarded and the document is cleared.
*/
public void abort() {
}
/**
* DOM Level 3 WD - Experimental.
* Replaces the content of the document with the result of parsing the
* given URI. Invoking this method will either block the caller or
* return to the caller immediately depending on the value of the async
* attribute. Once the document is fully loaded the document will fire a
* "load" event that the caller can register as a listener for. If an
* error occurs the document will fire an "error" event so that the
* caller knows that the load failed (see <code>ParseErrorEvent</code>).
* @param uri The URI reference for the XML file to be loaded. If this is
* a relative URI...
* @return If async is set to <code>true</code> <code>load</code> returns
* <code>true</code> if the document load was successfully initiated.
* If an error occurred when initiating the document load
* <code>load</code> returns <code>false</code>.If async is set to
* <code>false</code> <code>load</code> returns <code>true</code> if
* the document was successfully loaded and parsed. If an error
* occurred when either loading or parsing the URI <code>load</code>
* returns <code>false</code>.
*/
public boolean load(String uri) {
return false;
}
/**
* DOM Level 3 WD - Experimental.
* Replace the content of the document with the result of parsing the
* input string, this method is always synchronous.
* @param source A string containing an XML document.
* @return <code>true</code> if parsing the input string succeeded
* without errors, otherwise <code>false</code>.
*/
public boolean loadXML(String source) {
return false;
}
/**
* DOM Level 3 WD - Experimental.
* Save the document or the given node to a string (i.e. serialize the
* document or node).
* @param snode Specifies what to serialize, if this parameter is
* <code>null</code> the whole document is serialized, if it's
* non-null the given node is serialized.
* @return The serialized document or <code>null</code>.
* @exception DOMException
* WRONG_DOCUMENT_ERR: Raised if the node passed in as the node
* parameter is from an other document.
*/
public String saveXML(Node snode)
throws DOMException {
if ( snode != null &&
getOwnerDocument() != snode.getOwnerDocument() )
throw new DOMException(DOMException.WRONG_DOCUMENT_ERR,"Node "+snode.getNodeName()+" does not belongs to this Document.");
DOMImplementationLS domImplLS = (DOMImplementationLS)DOMImplementationImpl.getDOMImplementation();
DOMWriter xmlWriter = domImplLS.createDOMWriter();
if (snode == null) {
snode = this;
}
return xmlWriter.writeToString(snode);
}
/**
* Sets whether the DOM implementation generates mutation events
* upon operations.
*/
void setMutationEvents(boolean set) {
// does nothing by default - overidden in subclass
}
/**
* Returns true if the DOM implementation generates mutation events.
*/
boolean getMutationEvents() {
// does nothing by default - overriden in subclass
return false;
}
// non-DOM factory methods
/**
* NON-DOM
* Factory method; creates a DocumentType having this Document
* as its OwnerDoc. (REC-DOM-Level-1-19981001 left the process of building
* DTD information unspecified.)
*
* @param name The name of the Entity we wish to provide a value for.
*
* @throws DOMException(NOT_SUPPORTED_ERR) for HTML documents, where
* DTDs are not permitted. (HTML not yet implemented.)
*/
public DocumentType createDocumentType(String qualifiedName,
String publicID,
String systemID)
throws DOMException {
if (errorChecking && !isXMLName(qualifiedName)) {
throw new DOMException(DOMException.INVALID_CHARACTER_ERR,
"DOM002 Illegal character");
}
return new DocumentTypeImpl(this, qualifiedName, publicID, systemID);
} // createDocumentType(String):DocumentType
/**
* NON-DOM
* Factory method; creates an Entity having this Document
* as its OwnerDoc. (REC-DOM-Level-1-19981001 left the process of building
* DTD information unspecified.)
*
* @param name The name of the Entity we wish to provide a value for.
*
* @throws DOMException(NOT_SUPPORTED_ERR) for HTML documents, where
* nonstandard entities are not permitted. (HTML not yet
* implemented.)
*/
public Entity createEntity(String name)
throws DOMException {
if (errorChecking && !isXMLName(name)) {
throw new DOMException(DOMException.INVALID_CHARACTER_ERR,
"DOM002 Illegal character");
}
return new EntityImpl(this, name);
} // createEntity(String):Entity
/**
* NON-DOM
* Factory method; creates a Notation having this Document
* as its OwnerDoc. (REC-DOM-Level-1-19981001 left the process of building
* DTD information unspecified.)
*
* @param name The name of the Notation we wish to describe
*
* @throws DOMException(NOT_SUPPORTED_ERR) for HTML documents, where
* notations are not permitted. (HTML not yet
* implemented.)
*/
public Notation createNotation(String name)
throws DOMException {
if (errorChecking && !isXMLName(name)) {
throw new DOMException(DOMException.INVALID_CHARACTER_ERR,
"DOM002 Illegal character");
}
return new NotationImpl(this, name);
} // createNotation(String):Notation
/**
* NON-DOM Factory method: creates an element definition. Element
* definitions hold default attribute values.
*/
public ElementDefinitionImpl createElementDefinition(String name)
throws DOMException {
if (errorChecking && !isXMLName(name)) {
throw new DOMException(DOMException.INVALID_CHARACTER_ERR,
"DOM002 Illegal character");
}
return new ElementDefinitionImpl(this, name);
} // createElementDefinition(String):ElementDefinitionImpl
// other non-DOM methods
/**
* Copies a node from another document to this document. The new nodes are
* created using this document's factory methods and are populated with the
* data from the source's accessor methods defined by the DOM interfaces.
* Its behavior is otherwise similar to that of cloneNode.
* <p>
* According to the DOM specifications, document nodes cannot be imported
* and a NOT_SUPPORTED_ERR exception is thrown if attempted.
*/
public Node importNode(Node source, boolean deep)
throws DOMException {
return importNode(source, deep, false, null);
} // importNode(Node,boolean):Node
/**
* Overloaded implementation of DOM's importNode method. This method
* provides the core functionality for the public importNode and cloneNode
* methods.
*
* The reversedIdentifiers parameter is provided for cloneNode to
* preserve the document's identifiers. The Hashtable has Elements as the
* keys and their identifiers as the values. When an element is being
* imported, a check is done for an associated identifier. If one exists,
* the identifier is registered with the new, imported element. If
* reversedIdentifiers is null, the parameter is not applied.
*/
private Node importNode(Node source, boolean deep, boolean cloningDoc,
Hashtable reversedIdentifiers)
throws DOMException {
Node newnode=null;
// Sigh. This doesn't work; too many nodes have private data that
// would have to be manually tweaked. May be able to add local
// shortcuts to each nodetype. Consider ?????
// if(source instanceof NodeImpl &&
// !(source instanceof DocumentImpl))
// // Can't clone DocumentImpl since it invokes us...
// newnode=(NodeImpl)source.cloneNode(false);
// newnode.ownerDocument=this;
// else
int type = source.getNodeType();
switch (type) {
case ELEMENT_NODE: {
Element newElement;
boolean domLevel20 = source.getOwnerDocument().getImplementation().hasFeature("XML", "2.0");
// Create element according to namespace support/qualification.
if(domLevel20 == false || source.getLocalName() == null)
newElement = createElement(source.getNodeName());
else
newElement = createElementNS(source.getNamespaceURI(),
source.getNodeName());
// Copy element's attributes, if any.
NamedNodeMap sourceAttrs = source.getAttributes();
if (sourceAttrs != null) {
int length = sourceAttrs.getLength();
for (int index = 0; index < length; index++) {
Attr attr = (Attr)sourceAttrs.item(index);
// Copy the attribute only if it is not a default.
if (attr.getSpecified()) {
Attr newAttr = (Attr)importNode(attr, true, false,
reversedIdentifiers);
// Attach attribute according to namespace
// support/qualification.
if (domLevel20 == false ||
attr.getLocalName() == null)
newElement.setAttributeNode(newAttr);
else
newElement.setAttributeNodeNS(newAttr);
}
}
}
// Register element identifier.
if (reversedIdentifiers != null) {
// Does element have an associated identifier?
Object elementId = reversedIdentifiers.get(source);
if (elementId != null) {
if (identifiers == null)
identifiers = new Hashtable();
identifiers.put(elementId, newElement);
}
}
newnode = newElement;
break;
}
case ATTRIBUTE_NODE: {
if( source.getOwnerDocument().getImplementation().hasFeature("XML", "2.0") ){
if (source.getLocalName() == null) {
newnode = createAttribute(source.getNodeName());
} else {
newnode = createAttributeNS(source.getNamespaceURI(),
source.getNodeName());
}
}
else {
newnode = createAttribute(source.getNodeName());
}
// if source is an AttrImpl from this very same implementation
// avoid creating the child nodes if possible
if (source instanceof AttrImpl) {
AttrImpl attr = (AttrImpl) source;
if (attr.hasStringValue()) {
AttrImpl newattr = (AttrImpl) newnode;
newattr.setValue(attr.getValue());
deep = false;
}
else {
deep = true;
}
}
else {
// According to the DOM spec the kids carry the value.
// However, there are non compliant implementations out
// there that fail to do so. To avoid ending up with no
// value at all, in this case we simply copy the text value
// directly.
if (source.getFirstChild() == null) {
newnode.setNodeValue(source.getNodeValue());
deep = false;
} else {
deep = true;
}
}
break;
}
case TEXT_NODE: {
newnode = createTextNode(source.getNodeValue());
break;
}
case CDATA_SECTION_NODE: {
newnode = createCDATASection(source.getNodeValue());
break;
}
case ENTITY_REFERENCE_NODE: {
newnode = createEntityReference(source.getNodeName());
// the subtree is created according to this doc by the method
// above, so avoid carrying over original subtree
deep = false;
break;
}
case ENTITY_NODE: {
Entity srcentity = (Entity)source;
EntityImpl newentity =
(EntityImpl)createEntity(source.getNodeName());
newentity.setPublicId(srcentity.getPublicId());
newentity.setSystemId(srcentity.getSystemId());
newentity.setNotationName(srcentity.getNotationName());
// Kids carry additional value,
// allow deep import temporarily
newentity.isReadOnly(false);
newnode = newentity;
break;
}
case PROCESSING_INSTRUCTION_NODE: {
newnode = createProcessingInstruction(source.getNodeName(),
source.getNodeValue());
break;
}
case COMMENT_NODE: {
newnode = createComment(source.getNodeValue());
break;
}
case DOCUMENT_TYPE_NODE: {
// unless this is used as part of cloning a Document
// forbid it for the sake of being compliant to the DOM spec
if (!cloningDoc) {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR,
"Node type being imported is not supported");
}
DocumentType srcdoctype = (DocumentType)source;
DocumentTypeImpl newdoctype = (DocumentTypeImpl)
createDocumentType(srcdoctype.getNodeName(),
srcdoctype.getPublicId(),
srcdoctype.getSystemId());
// Values are on NamedNodeMaps
NamedNodeMap smap = srcdoctype.getEntities();
NamedNodeMap tmap = newdoctype.getEntities();
if(smap != null) {
for(int i = 0; i < smap.getLength(); i++) {
tmap.setNamedItem(importNode(smap.item(i), true, false,
reversedIdentifiers));
}
}
smap = srcdoctype.getNotations();
tmap = newdoctype.getNotations();
if (smap != null) {
for(int i = 0; i < smap.getLength(); i++) {
tmap.setNamedItem(importNode(smap.item(i), true, false,
reversedIdentifiers));
}
}
// NOTE: At this time, the DOM definition of DocumentType
// doesn't cover Elements and their Attributes. domimpl's
// extentions in that area will not be preserved, even if
// copying from domimpl to domimpl. We could special-case
// that here. Arguably we should. Consider. ?????
newnode = newdoctype;
break;
}
case DOCUMENT_FRAGMENT_NODE: {
newnode = createDocumentFragment();
// No name, kids carry value
break;
}
case NOTATION_NODE: {
Notation srcnotation = (Notation)source;
NotationImpl newnotation =
(NotationImpl)createNotation(source.getNodeName());
newnotation.setPublicId(srcnotation.getPublicId());
newnotation.setSystemId(srcnotation.getSystemId());
// Kids carry additional value
newnode = newnotation;
// No name, no value
break;
}
case DOCUMENT_NODE : // Can't import document nodes
default: { // Unknown node type
throw new DOMException(DOMException.NOT_SUPPORTED_ERR,
"Node type being imported is not supported");
}
}
callUserDataHandlers(source, newnode, UserDataHandler.NODE_IMPORTED);
// If deep, replicate and attach the kids.
if (deep) {
for (Node srckid = source.getFirstChild();
srckid != null;
srckid = srckid.getNextSibling()) {
newnode.appendChild(importNode(srckid, true, false,
reversedIdentifiers));
}
}
if (newnode.getNodeType() == Node.ENTITY_NODE) {
((NodeImpl)newnode).setReadOnly(true, true);
}
return newnode;
} // importNode(Node,boolean,boolean,Hashtable):Node
/**
* DOM Level 3 WD - Experimental
* Change the node's ownerDocument, and its subtree, to this Document
*
* @param source The node to adopt.
* @see #importNode
**/
public Node adoptNode(Node source) {
NodeImpl node;
try {
node = (NodeImpl) source;
} catch (ClassCastException e) {
// source node comes from a different DOMImplementation
return null;
}
switch (node.getNodeType()) {
case ATTRIBUTE_NODE: {
AttrImpl attr = (AttrImpl) node;
// remove node from wherever it is
attr.getOwnerElement().removeAttributeNode(attr);
// mark it as specified
attr.isSpecified(true);
// change ownership
attr.setOwnerDocument(this);
break;
}
case DOCUMENT_NODE:
case DOCUMENT_TYPE_NODE: {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR,
"cannot adopt this type of node.");
}
case ENTITY_REFERENCE_NODE: {
// remove node from wherever it is
Node parent = node.getParentNode();
if (parent != null) {
parent.removeChild(source);
}
// discard its replacement value
Node child;
while ((child = node.getFirstChild()) != null) {
node.removeChild(child);
}
// change ownership
node.setOwnerDocument(this);
// set its new replacement value if any
if (docType == null) {
break;
}
NamedNodeMap entities = docType.getEntities();
Node entityNode = entities.getNamedItem(node.getNodeName());
if (entityNode == null) {
break;
}
EntityImpl entity = (EntityImpl) entityNode;
for (child = entityNode.getFirstChild();
child != null; child = child.getNextSibling()) {
Node childClone = child.cloneNode(true);
node.appendChild(childClone);
}
break;
}
case ELEMENT_NODE: {
// remove node from wherever it is
Node parent = node.getParentNode();
if (parent != null) {
parent.removeChild(source);
}
// change ownership
node.setOwnerDocument(this);
// reconcile default attributes
((ElementImpl)node).reconcileDefaultAttributes();
break;
}
default: {
// remove node from wherever it is
Node parent = node.getParentNode();
if (parent != null) {
parent.removeChild(source);
}
// change ownership
node.setOwnerDocument(this);
}
}
return node;
}
// identifier maintenence
/**
* Introduced in DOM Level 2
* Returns the Element whose ID is given by elementId. If no such element
* exists, returns null. Behavior is not defined if more than one element
* has this ID.
* <p>
* Note: The DOM implementation must have information that says which
* attributes are of type ID. Attributes with the name "ID" are not of type
* ID unless so defined. Implementations that do not know whether
* attributes are of type ID or not are expected to return null.
* @see #getIdentifier
*/
public Element getElementById(String elementId) {
return getIdentifier(elementId);
}
/**
* Registers an identifier name with a specified element node.
* If the identifier is already registered, the new element
* node replaces the previous node. If the specified element
* node is null, removeIdentifier() is called.
*
* @see #getIdentifier
* @see #removeIdentifier
*/
public void putIdentifier(String idName, Element element) {
if (element == null) {
removeIdentifier(idName);
return;
}
if (needsSyncData()) {
synchronizeData();
}
if (identifiers == null) {
identifiers = new Hashtable();
}
identifiers.put(idName, element);
} // putIdentifier(String,Element)
/**
* Returns a previously registered element with the specified
* identifier name, or null if no element is registered.
*
* @see #putIdentifier
* @see #removeIdentifier
*/
public Element getIdentifier(String idName) {
if (needsSyncData()) {
synchronizeData();
}
if (identifiers == null) {
return null;
}
return (Element)identifiers.get(idName);
} // getIdentifier(String):Element
/**
* Removes a previously registered element with the specified
* identifier name.
*
* @see #putIdentifier
* @see #getIdentifier
*/
public void removeIdentifier(String idName) {
if (needsSyncData()) {
synchronizeData();
}
if (identifiers == null) {
return;
}
identifiers.remove(idName);
} // removeIdentifier(String)
/** Returns an enumeration registered of identifier names. */
public Enumeration getIdentifiers() {
if (needsSyncData()) {
synchronizeData();
}
if (identifiers == null) {
identifiers = new Hashtable();
}
return identifiers.keys();
} // getIdentifiers():Enumeration
// DOM2: Namespace methods
public Element createElementNS(String namespaceURI, String qualifiedName)
throws DOMException
{
if (errorChecking && !isXMLName(qualifiedName)) {
throw new DOMException(DOMException.INVALID_CHARACTER_ERR,
"DOM002 Illegal character");
}
return new ElementNSImpl(this, namespaceURI, qualifiedName);
}
/**
* NON-DOM: Xerces-specific constructor. "localName" is passed in, so we don't need
* to create a new String for it.
*
* @param namespaceURI The namespace URI of the element to
* create.
* @param qualifiedName The qualified name of the element type to
* instantiate.
* @param localName The local name of the element to instantiate.
* @return Element A new Element object with the following attributes:
* @throws DOMException INVALID_CHARACTER_ERR: Raised if the specified
* name contains an invalid character.
*/
public Element createElementNS(String namespaceURI, String qualifiedName,
String localpart)
throws DOMException
{
return new ElementNSImpl(this, namespaceURI, qualifiedName, localpart);
}
public Attr createAttributeNS(String namespaceURI, String qualifiedName)
throws DOMException
{
if (errorChecking && !isXMLName(qualifiedName)) {
throw new DOMException(DOMException.INVALID_CHARACTER_ERR,
"DOM002 Illegal character");
}
return new AttrNSImpl(this, namespaceURI, qualifiedName);
}
/**
* Xerces-specific constructor. "localName" is passed in, so we don't need
* to create a new String for it.
*
* @param namespaceURI The namespace URI of the attribute to
* create. When it is null or an empty string,
* this method behaves like createAttribute.
* @param qualifiedName The qualified name of the attribute to
* instantiate.
* @param localName The local name of the attribute to instantiate.
* @return Attr A new Attr object.
* @throws DOMException INVALID_CHARACTER_ERR: Raised if the specified
name contains an invalid character.
*/
public Attr createAttributeNS(String namespaceURI, String qualifiedName,
String localName)
throws DOMException
{
return new AttrNSImpl(this, namespaceURI, qualifiedName, localName);
}
/**
* Introduced in DOM Level 2. <p>
* Returns a NodeList of all the Elements with a given local name and
* namespace URI in the order in which they would be encountered in a
* preorder traversal of the Document tree.
* @param namespaceURI The namespace URI of the elements to match
* on. The special value "*" matches all
* namespaces. When it is null or an empty
* string, this method behaves like
* getElementsByTagName.
* @param localName The local name of the elements to match on.
* The special value "*" matches all local names.
* @return NodeList A new NodeList object containing all the matched
* Elements.
* @since WD-DOM-Level-2-19990923
*/
public NodeList getElementsByTagNameNS(String namespaceURI,
String localName)
{
return new DeepNodeListImpl(this, namespaceURI, localName);
}
// Object methods
/** Clone. */
public Object clone() throws CloneNotSupportedException {
CoreDocumentImpl newdoc = (CoreDocumentImpl) super.clone();
newdoc.docType = null;
newdoc.docElement = null;
return newdoc;
}
// Public static methods
/**
* Check the string against XML's definition of acceptable names for
* elements and attributes and so on using the XMLCharacterProperties
* utility class
*/
public static boolean isXMLName(String s) {
if (s == null) {
return false;
}
return XMLChar.isValidName(s);
} // isXMLName(String):boolean
// Protected methods
protected boolean isKidOK(Node parent, Node child) {
if (allowGrammarAccess &&
parent.getNodeType() == Node.DOCUMENT_TYPE_NODE) {
return child.getNodeType() == Node.ELEMENT_NODE;
}
return 0 != (kidOK[parent.getNodeType()] & 1 << child.getNodeType());
}
/**
* Denotes that this node has changed.
*/
protected void changed() {
changes++;
}
/**
* Returns the number of changes to this node.
*/
protected int changes() {
return changes;
}
// NodeListCache pool
/**
* Returns a NodeListCache for the given node.
*/
NodeListCache getNodeListCache(ParentNode owner) {
if (fFreeNLCache == null) {
return new NodeListCache(owner);
}
NodeListCache c = fFreeNLCache;
fFreeNLCache = fFreeNLCache.next;
c.fChild = null;
c.fChildIndex = -1;
c.fLength = -1;
// revoke previous ownership
if (c.fOwner != null) {
c.fOwner.fNodeListCache = null;
}
c.fOwner = owner;
// c.next = null; not necessary, except for confused people...
return c;
}
/**
* Puts the given NodeListCache in the free list.
* Note: The owner node can keep using it until we reuse it
*/
void freeNodeListCache(NodeListCache c) {
c.next = fFreeNLCache;
fFreeNLCache = c;
}
/*
* a class to store some user data along with its handler
*/
class UserDataRecord implements Serializable {
Object fData;
UserDataHandler fHandler;
UserDataRecord(Object data, UserDataHandler handler) {
fData = data;
fHandler = handler;
}
}
/**
* Associate an object to a key on this node. The object can later be
* retrieved from this node by calling <code>getUserData</code> with the
* same key.
* @param n The node to associate the object to.
* @param key The key to associate the object to.
* @param data The object to associate to the given key, or
* <code>null</code> to remove any existing association to that key.
* @param handler The handler to associate to that key, or
* <code>null</code>.
* @return Returns the <code>DOMObject</code> previously associated to
* the given key on this node, or <code>null</code> if there was none.
* @since DOM Level 3
*
* REVISIT: we could use a free list of UserDataRecord here
*/
public Object setUserData(Node n, String key,
Object data, UserDataHandler handler) {
if (data == null) {
if (userData != null) {
Hashtable t = (Hashtable) userData.get(n);
if (t != null) {
Object o = t.remove(key);
if (o != null) {
UserDataRecord r = (UserDataRecord) o;
return r.fData;
}
}
}
return null;
}
else {
Hashtable t;
if (userData == null) {
userData = new Hashtable();
t = new Hashtable();
userData.put(n, t);
}
else {
t = (Hashtable) userData.get(n);
if (t == null) {
t = new Hashtable();
userData.put(n, t);
}
}
Object o = t.put(key, new UserDataRecord(data, handler));
if (o != null) {
UserDataRecord r = (UserDataRecord) o;
return r.fData;
}
return null;
}
}
/**
* Retrieves the object associated to a key on a this node. The object
* must first have been set to this node by calling
* <code>setUserData</code> with the same key.
* @param n The node the object is associated to.
* @param key The key the object is associated to.
* @return Returns the <code>DOMObject</code> associated to the given key
* on this node, or <code>null</code> if there was none.
* @since DOM Level 3
*/
public Object getUserData(Node n, String key) {
if (userData == null) {
return null;
}
Hashtable t = (Hashtable) userData.get(n);
if (t == null) {
return null;
}
Object o = t.get(key);
if (o != null) {
UserDataRecord r = (UserDataRecord) o;
return r.fData;
}
return null;
}
/**
* Remove user data table for the given node.
* @param n The node this operation applies to.
* @return The removed table.
*/
Hashtable removeUserDataTable(Node n) {
if (userData == null) {
return null;
}
return (Hashtable) userData.get(n);
}
/**
* Set user data table for the given node.
* @param n The node this operation applies to.
* @param data The user data table.
*/
void setUserDataTable(Node n, Hashtable data) {
if (data != null) {
userData.put(n, data);
}
}
/**
* Call user data handlers when a node is deleted (finalized)
* @param n The node this operation applies to.
* @param c The copy node or null.
* @param operation The operation - import, clone, or delete.
*/
void callUserDataHandlers(Node n, Node c, short operation) {
if (userData == null) {
return;
}
Hashtable t = (Hashtable) userData.get(n);
if (t == null || t.isEmpty()) {
return;
}
Enumeration keys = t.keys();
while (keys.hasMoreElements()) {
String key = (String) keys.nextElement();
UserDataRecord r = (UserDataRecord) t.get(key);
if (r.fHandler != null) {
r.fHandler.handle(operation, key, r.fData, n, c);
}
}
}
/**
* Call user data handlers to let them know the nodes they are related to
* are being deleted. The alternative would be to do that on Node but
* because the nodes are used as the keys we have a reference to them that
* prevents them from being gc'ed until the document is. At the same time,
* doing it here has the advantage of avoiding a finalize() method on Node,
* which would affect all nodes and not just the ones that have a user
* data.
*/
public void finalize() {
if (userData == null) {
return;
}
Enumeration nodes = userData.keys();
while (nodes.hasMoreElements()) {
Object node = nodes.nextElement();
Hashtable t = (Hashtable) userData.get(node);
if (t != null && !t.isEmpty()) {
Enumeration keys = t.keys();
while (keys.hasMoreElements()) {
String key = (String) keys.nextElement();
UserDataRecord r = (UserDataRecord) t.get(key);
if (r.fHandler != null) {
r.fHandler.handle(UserDataHandler.NODE_DELETED,
key, r.fData, null, null);
}
}
}
}
}
/**
* NON-DOM: copy configuration properties from the parsing configuration.
* This method is called after the parsing is done
*/
public void copyConfigurationProperties(XMLParserConfiguration config){
// REVISIT: how should we copy symbol table?
// It usually grows with the parser, do we need to carry all
// data per document?
fSymbolTable = new ShadowedSymbolTable((SymbolTable)config.getProperty(DOMValidationConfiguration.SYMBOL_TABLE));
fEntityResolver = config.getEntityResolver();
// REVISIT: storing one grammar per document is not efficient
// and might not be enough. We need to implement some grammar
// cashing possibly on DOM Implementation
XMLGrammarPool pool = (XMLGrammarPool)config.getProperty(DOMValidationConfiguration.GRAMMAR_POOL);
if (pool != null) {
// retrieve either a DTD or XML Schema grammar
if (docType != null) {
// retrieve DTD grammar
// pool.retrieveGrammar();
} else {
// retrieve XML Schema grammar based on teh namespace
// of the root element
String targetNamespace = this.docElement.getNamespaceURI();
// pool.retrieveGrammar();
}
}
}
/**
* NON-DOM: kept for backward compatibility
* Store user data related to a given node
* This is a place where we could use weak references! Indeed, the node
* here won't be GC'ed as long as some user data is attached to it, since
* the userData table will have a reference to the node.
*/
protected void setUserData(NodeImpl n, Object data) {
setUserData(n, "XERCES1DOMUSERDATA", data, null);
}
/**
* NON-DOM: kept for backward compatibility
* Retreive user data related to a given node
*/
protected Object getUserData(NodeImpl n) {
return getUserData(n, "XERCES1DOMUSERDATA");
}
// Event related methods overidden in subclass
protected void addEventListener(NodeImpl node, String type,
EventListener listener,
boolean useCapture) {
// does nothing by default - overidden in subclass
}
protected void removeEventListener(NodeImpl node, String type,
EventListener listener,
boolean useCapture) {
// does nothing by default - overidden in subclass
}
protected void copyEventListeners(NodeImpl src, NodeImpl tgt) {
// does nothing by default - overidden in subclass
}
protected boolean dispatchEvent(NodeImpl node, Event event) {
// does nothing by default - overidden in subclass
return false;
}
// Notification methods overidden in subclasses
/**
* A method to be called when some text was changed in a text node,
* so that live objects can be notified.
*/
void replacedText(NodeImpl node) {
}
/**
* A method to be called when some text was deleted from a text node,
* so that live objects can be notified.
*/
void deletedText(NodeImpl node, int offset, int count) {
}
/**
* A method to be called when some text was inserted into a text node,
* so that live objects can be notified.
*/
void insertedText(NodeImpl node, int offset, int count) {
}
/**
* A method to be called when a character data node has been modified
*/
void modifyingCharacterData(NodeImpl node) {
}
/**
* A method to be called when a character data node has been modified
*/
void modifiedCharacterData(NodeImpl node, String oldvalue, String value) {
}
/**
* A method to be called when a node is about to be inserted in the tree.
*/
void insertingNode(NodeImpl node, boolean replace) {
}
/**
* A method to be called when a node has been inserted in the tree.
*/
void insertedNode(NodeImpl node, NodeImpl newInternal, boolean replace) {
}
/**
* A method to be called when a node is about to be removed from the tree.
*/
void removingNode(NodeImpl node, NodeImpl oldChild, boolean replace) {
}
/**
* A method to be called when a node has been removed from the tree.
*/
void removedNode(NodeImpl node, boolean replace) {
}
/**
* A method to be called when a node is about to be replaced in the tree.
*/
void replacingNode(NodeImpl node) {
}
/**
* A method to be called when a node has been replaced in the tree.
*/
void replacedNode(NodeImpl node) {
}
/**
* A method to be called when an attribute value has been modified
*/
void modifiedAttrValue(AttrImpl attr, String oldvalue) {
}
/**
* A method to be called when an attribute node has been set
*/
void setAttrNode(AttrImpl attr, AttrImpl previous) {
}
/**
* A method to be called when an attribute node has been removed
*/
void removedAttrNode(AttrImpl attr, NodeImpl oldOwner, String name) {
}
/**
* A method to be called when an attribute node has been renamed
*/
void renamedAttrNode(Attr oldAt, Attr newAt) {
}
/**
* A method to be called when an element has been renamed
*/
void renamedElement(Element oldEl, Element newEl) {
}
} // class CoreDocumentImpl |
package com.gdglc.spring.dao;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class BaseDao {
static SessionFactory sessionFactory;
static{
Configuration configuration = new Configuration().configure("/hibernate/hibernate.xml");
System.out.println("");
sessionFactory = configuration.buildSessionFactory();
}
static{
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
@Override
public void run() {
System.out.println("");
try{
if(null!=sessionFactory){
sessionFactory.close();
}
}catch(Exception e){
e.printStackTrace();
}finally{
sessionFactory = null;
}
System.out.println("");
}
}));
}
public Session getSession(){
return sessionFactory.openSession();
}
public static void main(String[] args) {
//System.exit(0);
}
} |
package com.fishercoder.solutions;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.Random;
public class _380 {
public static class Solution1 {
public static class RandomizedSet {
Map<Integer, Integer> locationMap;
List<Integer> list;
Random random;
/**
* Initialize your data structure here.
*/
public RandomizedSet() {
locationMap = new HashMap<>();
list = new ArrayList<>();
random = new Random();
}
/**
* Inserts a value to the set. Returns true if the set did not already contain the specified element.
*/
public boolean insert(int val) {
if (locationMap.containsKey(val)) {
return false;
} else {
locationMap.put(val, list.size());
list.add(val);
return true;
}
}
/**
* Removes a value from the set. Returns true if the set contained the specified element.
*/
public boolean remove(int val) {
if (!locationMap.containsKey(val)) {
return false;
} else {
int location = locationMap.get(val);
/**if it's not the last one, then swap the last one with this val*/
if (location < list.size() - 1) {
int lastOne = list.get(list.size() - 1);
list.set(location, lastOne);
locationMap.put(lastOne, location);
}
locationMap.remove(val);
list.remove(list.size() - 1);
return true;
}
}
/**
* Get a random element from the set.
*/
public int getRandom() {
return list.get(random.nextInt(list.size()));
}
}
}
/**
* Your _380 object will be instantiated and called as such:
* _380 obj = new _380();
* boolean param_1 = obj.insert(val);
* boolean param_2 = obj.delete(val);
* int param_3 = obj.getRandom();
*/
public static class Solution2 {
/**This is not ideal and not meeting average O(1) time for all three operations.*/
public static class RandomizedSet {
Map<Integer, Integer> forwardMap;
//key is auto increment index, value if the inserted val
Map<Integer, Integer> reverseMap;//the other way around
int index;
Random random;
/**
* Initialize your data structure here.
*/
public RandomizedSet() {
forwardMap = new HashMap();
reverseMap = new HashMap();
index = 0;
random = new Random();
}
/**
* Inserts a value to the set. Returns true if the set did not already contain the specified
* element.
*/
public boolean insert(int val) {
if (forwardMap.containsValue(val)) {
return false;
} else {
forwardMap.put(index, val);
reverseMap.put(val, index++);
return true;
}
}
/**
* Deletes a value from the set. Returns true if the set contained the specified element.
*/
public boolean remove(int val) {
if (forwardMap.containsValue(val)) {
int key = reverseMap.get(val);
reverseMap.remove(val);
forwardMap.remove(key);
return true;
} else {
return false;
}
}
/**
* Get a random element from the set.
*/
public int getRandom() {
int max = forwardMap.size();
if (max == 1) {
return forwardMap.get(index - 1);
}
int randomNum = random.nextInt(max);
while (!forwardMap.containsKey(randomNum)) {
randomNum = random.nextInt(max);
}
return forwardMap.get(randomNum);
}
}
}
} |
package com.fishercoder.solutions;
import java.util.PriorityQueue;
/**
* 407. Trapping Rain Water II
*
* Given an m x n matrix of positive integers representing the height of each unit cell in a 2D elevation map, compute the volume of water it is able to trap after raining.
Note:
Both m and n are less than 110. The height of each unit cell is greater than 0 and is less than 20,000.
Example:
Given the following 3x6 height map:
[
[1,4,3,1,3,2],
[3,2,1,3,2,4],
[2,3,3,2,3,1]
]
Return 4.
The above image represents the elevation map [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]] before the rain.
After the rain, water are trapped between the blocks. The total volume of water trapped is 4.
*/
public class _407 {
public static class Solution1 {
public class Cell {
int row;
int col;
int height;
public Cell(int row, int col, int height) {
this.row = row;
this.col = col;
this.height = height;
}
}
public int trapRainWater(int[][] heights) {
if (heights == null || heights.length == 0 || heights[0].length == 0) {
return 0;
}
PriorityQueue<Cell> queue = new PriorityQueue<>(1, (a, b) -> a.height - b.height);
int m = heights.length;
int n = heights[0].length;
boolean[][] visited = new boolean[m][n];
// Initially, add all the Cells which are on borders to the queue.
for (int i = 0; i < m; i++) {
visited[i][0] = true;
visited[i][n - 1] = true;
queue.offer(new Cell(i, 0, heights[i][0]));
queue.offer(new Cell(i, n - 1, heights[i][n - 1]));
}
for (int i = 0; i < n; i++) {
visited[0][i] = true;
visited[m - 1][i] = true;
queue.offer(new Cell(0, i, heights[0][i]));
queue.offer(new Cell(m - 1, i, heights[m - 1][i]));
}
// from the borders, pick the shortest cell visited and check its neighbors:
// if the neighbor is shorter, collect the water it can trap and update its height as its height plus the water trapped
// add all its neighbors to the queue.
int[][] dirs = new int[][] {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
int res = 0;
while (!queue.isEmpty()) {
Cell cell = queue.poll();
for (int[] dir : dirs) {
int row = cell.row + dir[0];
int col = cell.col + dir[1];
if (row >= 0 && row < m && col >= 0 && col < n && !visited[row][col]) {
visited[row][col] = true;
res += Math.max(0, cell.height - heights[row][col]);
queue.offer(new Cell(row, col, Math.max(heights[row][col], cell.height)));
}
}
}
return res;
}
}
} |
package com.matt.forgehax.mods;
import com.matt.forgehax.asm.ForgeHaxHooks;
import com.matt.forgehax.asm.events.AddCollisionBoxToListEvent;
import com.matt.forgehax.asm.events.PacketEvent;
import com.matt.forgehax.asm.reflection.FastReflection;
import com.matt.forgehax.events.LocalPlayerUpdateEvent;
import com.matt.forgehax.util.entity.EntityUtils;
import com.matt.forgehax.util.mod.ToggleMod;
import com.matt.forgehax.util.mod.loader.RegisterMod;
import net.minecraft.block.BlockLiquid;
import net.minecraft.entity.Entity;
import net.minecraft.entity.item.EntityBoat;
import net.minecraft.network.play.client.CPacketPlayer;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import static com.matt.forgehax.Helper.getModManager;
@RegisterMod
public class Jesus extends ToggleMod {
public Jesus() { super("Jesus", false, "Walk on water"); }
@SubscribeEvent
public void onLocalPlayerUpdate(LocalPlayerUpdateEvent event) {
if (!getModManager().getMod("Freecam").isEnabled()) {
if (isInWater(MC.player) && !MC.player.isSneaking()) {
MC.player.motionY = 0.1;
if (MC.player.getRidingEntity() != null && !(MC.player.getRidingEntity() instanceof EntityBoat)) {
MC.player.getRidingEntity().motionY = 0.3;
}
}
}
}
@SubscribeEvent
public void onAddCollisionBox(AddCollisionBoxToListEvent event) {
if (MC.player == null) return;
AxisAlignedBB bb = new AxisAlignedBB(0, 0, 0, 1, 0.99, 1);
if (!(event.getBlock() instanceof BlockLiquid) || !(EntityUtils.isDrivenByPlayer(event.getEntity()) || EntityUtils.isPlayer(event.getEntity()))) {
bb = null;
}
if (isInWater(MC.player) || MC.player.isSneaking() || MC.player.fallDistance > 3) {
bb = null;
}
ForgeHaxHooks.blockBoxOverride = bb;
}
@Override
public void onDisabled() {
ForgeHaxHooks.blockBoxOverride = null;
}
@SubscribeEvent
public void onPacketSending(PacketEvent.Outgoing.Pre event) {
if (event.getPacket() instanceof CPacketPlayer) {
if (isAboveWater(MC.player) && !isInWater(MC.player) && !isAboveLand(MC.player)) {
int ticks = MC.player.ticksExisted % 2;
double Y = FastReflection.Fields.CPacketPlayer_Y.get(event.getPacket());
if (ticks == 0) FastReflection.Fields.CPacketPlayer_Y.set(event.getPacket(), Y + 0.02 );
}
}
}
@SuppressWarnings("deprecation")
private static boolean isAboveLand(Entity entity){
if(entity == null) return false;
double y = entity.posY - 0.01;
for(int x = MathHelper.floor(entity.posX); x < MathHelper.ceil(entity.posX); x++)
for (int z = MathHelper.floor(entity.posZ); z < MathHelper.ceil(entity.posZ); z++) {
BlockPos pos = new BlockPos(x, MathHelper.floor(y), z);
if (MC.world.getBlockState(pos).getBlock().isFullBlock(MC.world.getBlockState(pos))) return true;
}
return false;
}
private static boolean isAboveWater(Entity entity){
double y = entity.posY - 0.03;
for(int x = MathHelper.floor(entity.posX); x < MathHelper.ceil(entity.posX); x++)
for (int z = MathHelper.floor(entity.posZ); z < MathHelper.ceil(entity.posZ); z++) {
BlockPos pos = new BlockPos(x, MathHelper.floor(y), z);
if (MC.world.getBlockState(pos).getBlock() instanceof BlockLiquid) return true;
}
return false;
}
private static boolean isInWater(Entity entity) {
if(entity == null) return false;
double y = entity.posY + 0.01;
for(int x = MathHelper.floor(entity.posX); x < MathHelper.ceil(entity.posX); x++)
for (int z = MathHelper.floor(entity.posZ); z < MathHelper.ceil(entity.posZ); z++) {
BlockPos pos = new BlockPos(x, (int) y, z);
if (MC.world.getBlockState(pos).getBlock() instanceof BlockLiquid) return true;
}
return false;
}
} |
package org.talend.dataprep.preparation.service;
import static java.lang.Integer.MAX_VALUE;
import static java.util.Collections.emptyList;
import static java.util.stream.Collectors.toList;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
import static org.springframework.http.MediaType.TEXT_PLAIN_VALUE;
import static org.springframework.web.bind.annotation.RequestMethod.*;
import static org.talend.dataprep.api.preparation.Step.ROOT_STEP;
import static org.talend.dataprep.exception.error.PreparationErrorCodes.*;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.talend.daikon.exception.ExceptionContext;
import org.talend.dataprep.api.preparation.Action;
import org.talend.dataprep.api.preparation.AppendStep;
import org.talend.dataprep.api.preparation.Preparation;
import org.talend.dataprep.api.preparation.PreparationActions;
import org.talend.dataprep.api.preparation.PreparationUtils;
import org.talend.dataprep.api.preparation.Step;
import org.talend.dataprep.exception.TDPException;
import org.talend.dataprep.exception.error.CommonErrorCodes;
import org.talend.dataprep.exception.error.PreparationErrorCodes;
import org.talend.dataprep.exception.json.JsonErrorCodeDescription;
import org.talend.dataprep.metrics.Timed;
import org.talend.dataprep.preparation.store.PreparationRepository;
import org.talend.dataprep.security.Security;
import org.talend.dataprep.transformation.api.action.validation.ActionMetadataValidation;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
@RestController
@Api(value = "preparations", basePath = "/preparations", description = "Operations on preparations")
public class PreparationService {
private static final Logger LOGGER = LoggerFactory.getLogger(PreparationService.class);
@Autowired
private PreparationRepository preparationRepository = null;
@Autowired
private Jackson2ObjectMapperBuilder builder;
@Autowired
private ActionMetadataValidation validator;
/** DataPrep abstraction to the underlying security (whether it's enabled or not). */
@Autowired
private Security security;
@RequestMapping(value = "/preparations", method = GET, produces = APPLICATION_JSON_VALUE)
@ApiOperation(value = "List all preparations", notes = "Returns the list of preparations ids the current user is allowed to see. Creation date is always displayed in UTC time zone. See 'preparations/all' to get all details at once.")
@Timed
public List<String> list() {
LOGGER.debug("Get list of preparations (summary).");
return preparationRepository.listAll(Preparation.class).stream().map(Preparation::id).collect(toList());
}
@RequestMapping(value = "/preparations", method = GET, params = "dataSetId", produces = APPLICATION_JSON_VALUE)
@ApiOperation(value = "List all preparations for the given DataSet id", notes = "Returns the list of preparations for the given Dataset id the current user is allowed to see. Creation date is always displayed in UTC time zone. See 'preparations/all' to get all details at once.")
@Timed
public Collection<Preparation> listByDataSet(@RequestParam("dataSetId") @ApiParam("dataSetId") String dataSetId) {
Collection<Preparation> preparations = preparationRepository.getByDataSet(dataSetId);
LOGGER.debug("{} preparation(s) use dataset {}.", preparations.size(), dataSetId);
return preparations;
}
@RequestMapping(value = "/preparations/all", method = GET, produces = APPLICATION_JSON_VALUE)
@ApiOperation(value = "List all preparations", notes = "Returns the list of preparations the current user is allowed to see. Creation date is always displayed in UTC time zone. This operation return all details on the preparations.")
@Timed
public Collection<Preparation> listAll() {
LOGGER.debug("Get list of preparations (with details).");
return preparationRepository.listAll(Preparation.class);
}
@RequestMapping(value = "/preparations", method = PUT, produces = TEXT_PLAIN_VALUE, consumes = APPLICATION_JSON_VALUE)
@ApiOperation(value = "Create a preparation", notes = "Returns the id of the created preparation.")
@Timed
public String create(@ApiParam("preparation") @RequestBody final Preparation preparation) {
LOGGER.debug("Create new preparation for data set {}", preparation.getDataSetId());
preparation.setStep(ROOT_STEP);
preparation.setAuthor(security.getUserId());
preparationRepository.add(preparation);
LOGGER.debug("Created new preparation: {}", preparation);
return preparation.id();
}
@RequestMapping(value = "/preparations/{id}", method = RequestMethod.DELETE, consumes = MediaType.ALL_VALUE, produces = MediaType.TEXT_PLAIN_VALUE)
@ApiOperation(value = "Delete a preparation by id", notes = "Delete a preparation content based on provided id. Id should be a UUID returned by the list operation. Not valid or non existing preparation id returns empty content.")
@Timed
public void delete(@PathVariable(value = "id") @ApiParam(name = "id", value = "Id of the preparation to delete") String id) {
LOGGER.debug("Deletion of preparation #{} requested.", id);
Preparation preparationToDelete = preparationRepository.get(id, Preparation.class);
preparationRepository.remove(preparationToDelete);
LOGGER.debug("Deletion of preparation #{} done.", id);
}
@RequestMapping(value = "/preparations/{id}", method = PUT, produces = TEXT_PLAIN_VALUE, consumes = APPLICATION_JSON_VALUE)
@ApiOperation(value = "Create a preparation", notes = "Returns the id of the updated preparation.")
@Timed
public String update(@ApiParam("id") @PathVariable("id") String id,
@RequestBody @ApiParam("preparation") final Preparation preparation) {
Preparation previousPreparation = preparationRepository.get(id, Preparation.class);
LOGGER.debug("Updating preparation with id {}: {}", preparation.id(), previousPreparation);
Preparation updated = previousPreparation.merge(preparation);
if (!updated.id().equals(id)) {
preparationRepository.remove(previousPreparation);
}
preparationRepository.add(updated);
LOGGER.debug("Updated preparation: {}", updated);
return updated.id();
}
@RequestMapping(value = "/preparations/{id}", method = GET, produces = APPLICATION_JSON_VALUE)
@ApiOperation(value = "Get preparation details", notes = "Return the details of the preparation with provided id.")
@Timed
public Preparation get(@ApiParam("id") @PathVariable("id") String id) {
LOGGER.debug("Get content of preparation details for
return preparationRepository.get(id, Preparation.class);
}
@RequestMapping(value = "/preparations/clone/{id}", method = PUT, produces = TEXT_PLAIN_VALUE)
@ApiOperation(value = "Clone preparation", notes = "Clone of the preparation with provided id. The new name will the previous one concat with ' Copy', "
+ "Return the id of the new preparation ")
@Timed
public String clone(@ApiParam("id") @PathVariable("id") String id) {
LOGGER.debug("Clone preparation
Preparation preparation = preparationRepository.get(id, Preparation.class);
preparation.setName( preparation.getName() + " Copy" );
preparation.setCreationDate(System.currentTimeMillis());
preparationRepository.add(preparation);
return preparation.getId();
}
@RequestMapping(value = "/preparations/{id}/steps", method = GET, produces = APPLICATION_JSON_VALUE)
@ApiOperation(value = "Get all preparation steps id", notes = "Return the steps of the preparation with provided id.")
@Timed
public List<String> getSteps(@ApiParam("id") @PathVariable("id") String id) {
LOGGER.debug("Get steps of preparation for
final Step step = getStep(id);
return PreparationUtils.listStepsIds(step, preparationRepository);
}
/**
* Append step(s) in a preparation.
*/
@RequestMapping(value = "/preparations/{id}/actions", method = POST, consumes = APPLICATION_JSON_VALUE)
@ApiOperation(value = "Adds an action to a preparation", notes = "Append an action at end of the preparation with given id.")
@Timed
public void appendSteps(@PathVariable("id")
final String id,
@RequestBody
final AppendStep stepsToAppend) {
checkActionStepConsistency(stepsToAppend);
LOGGER.debug("Adding actions to preparation
final Preparation preparation = getPreparation(id);
LOGGER.debug("Current head for preparation #{}: {}", id, preparation.getStep());
final List<AppendStep> actionsSteps = new ArrayList<>(1);
actionsSteps.add(stepsToAppend);
// rebuild history from head
replaceHistory(preparation, preparation.getStep().id(), actionsSteps);
LOGGER.debug("Added head to preparation #{}: head is now {}", id, preparation.getStep().id());
}
@RequestMapping(value = "/preparations/{id}/actions/{stepId}", method = PUT, consumes = APPLICATION_JSON_VALUE)
@ApiOperation(value = "Updates an action in a preparation", notes = "Modifies an action in preparation's steps.")
@Timed
public void updateAction(@PathVariable("id") final String preparationId,
@PathVariable("stepId") final String stepToModifyId,
@RequestBody final AppendStep newStep) {
checkActionStepConsistency(newStep);
LOGGER.debug("Modifying actions in preparation #{}", preparationId);
final Preparation preparation = getPreparation(preparationId);
LOGGER.debug("Current head for preparation #{}: {}", preparationId, preparation.getStep());
// Get steps from "step to modify" to the head
final List<String> steps = extractSteps(preparation, stepToModifyId); // throws an exception if stepId is not in
// the preparation
LOGGER.debug("Rewriting history for {} steps.", steps.size());
// Extract created columns ids diff infos
final Step stm = getStep(stepToModifyId);
final List<String> originalCreatedColumns = stm.getDiff().getCreatedColumns();
final List<String> updatedCreatedColumns = newStep.getDiff().getCreatedColumns();
final List<String> deletedColumns = originalCreatedColumns.stream() // columns that the step was creating but
// not anymore
.filter(id -> !updatedCreatedColumns.contains(id)).collect(toList());
final int columnsDiffNumber = updatedCreatedColumns.size() - originalCreatedColumns.size();
final int maxCreatedColumnIdBeforeUpdate = (originalCreatedColumns.isEmpty()) ? MAX_VALUE
: originalCreatedColumns.stream().mapToInt(Integer::parseInt).max().getAsInt();
final List<AppendStep> actionsSteps = getStepsWithShiftedColumnIds(steps, stepToModifyId, deletedColumns,
maxCreatedColumnIdBeforeUpdate, columnsDiffNumber);
actionsSteps.add(0, newStep);
// Rebuild history from modified step
final Step stepToModify = getStep(stepToModifyId);
replaceHistory(preparation, stepToModify.getParent(), actionsSteps);
LOGGER.debug("Modified head of preparation #{}: head is now {}", preparation.getStep().getId());
}
@RequestMapping(value = "/preparations/{id}/actions/{stepId}", method = DELETE)
@ApiOperation(value = "Delete an action in a preparation", notes = "Delete a step and all following steps from a preparation")
@Timed
public void deleteAction(@PathVariable("id")
final String id,
@PathVariable("stepId")
final String stepToDeleteId) {
if (ROOT_STEP.getId().equals(stepToDeleteId)) {
throw new TDPException(PREPARATION_ROOT_STEP_CANNOT_BE_DELETED);
}
// get steps from 'step to delete' to head
final Preparation preparation = getPreparation(id);
final List<String> steps = extractSteps(preparation, stepToDeleteId); // throws an exception if stepId is not in
// the preparation
// get created columns by step to delete
final Step std = getStep(stepToDeleteId);
final List<String> deletedColumns = std.getDiff().getCreatedColumns();
final int columnsDiffNumber = -deletedColumns.size();
final int maxCreatedColumnIdBeforeUpdate = (deletedColumns.isEmpty()) ? MAX_VALUE
: deletedColumns.stream().mapToInt(Integer::parseInt).max().getAsInt();
LOGGER.debug("Deleting actions in preparation #{} at step #{}", id, stepToDeleteId); //$NON-NLS-1$
// get new actions to rewrite history from deleted step
final List<AppendStep> actions = getStepsWithShiftedColumnIds(steps, stepToDeleteId, deletedColumns,
maxCreatedColumnIdBeforeUpdate, columnsDiffNumber);
// rewrite history
final Step stepToDelete = getStep(stepToDeleteId);
replaceHistory(preparation, stepToDelete.getParent(), actions);
}
@RequestMapping(value = "/preparations/{id}/head/{headId}", method = PUT)
@ApiOperation(value = "Move preparation head", notes = "Set head to the specified head id")
@Timed
public void setPreparationHead(@PathVariable("id") final String preparationId,
@PathVariable("headId") final String headId) {
final Step head = getStep(headId);
if (head == null) {
throw new TDPException(PREPARATION_STEP_DOES_NOT_EXIST,
ExceptionContext.build().put("id", preparationId).put("stepId", headId));
}
final Preparation preparation = getPreparation(preparationId);
setPreparationHead(preparation, head);
}
@RequestMapping(value = "/preparations/{id}/actions/{version}", method = GET, produces = APPLICATION_JSON_VALUE)
@ApiOperation(value = "Get all the actions of a preparation at given version.", notes = "Returns the action JSON at version.")
@Timed
public List<Action> getVersionedAction(@ApiParam("id") @PathVariable("id") final String id,
@ApiParam("version") @PathVariable("version") final String version) {
LOGGER.debug("Get list of actions of preparations #{} at version {}.", id, version);
final Preparation preparation = preparationRepository.get(id, Preparation.class);
if (preparation != null) {
final String stepId = getStepId(version, preparation);
final Step step = getStep(stepId);
return getActions(step);
} else {
throw new TDPException(PREPARATION_DOES_NOT_EXIST, ExceptionContext.build().put("id", id));
}
}
/**
* List all preparation related error codes.git
*/
@RequestMapping(value = "/preparations/errors", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@ApiOperation(value = "Get all preparation related error codes.", notes = "Returns the list of all preparation related error codes.")
@Timed
public void listErrors(HttpServletResponse response) {
try {
// need to cast the typed dataset errors into mock ones to use json parsing
List<JsonErrorCodeDescription> errors = new ArrayList<>(PreparationErrorCodes.values().length);
for (PreparationErrorCodes code : PreparationErrorCodes.values()) {
errors.add(new JsonErrorCodeDescription(code));
}
builder.build().writer().writeValue(response.getOutputStream(), errors);
} catch (IOException e) {
throw new TDPException(CommonErrorCodes.UNEXPECTED_EXCEPTION, e);
}
}
/**
* Get the actual step id by converting "head" and "origin" to the hash
*
* @param version The version to convert to step id
* @param preparation The preparation
* @return The converted step Id
*/
private static String getStepId(final String version, final Preparation preparation) {
if ("head".equalsIgnoreCase(version)) { //$NON-NLS-1$
return preparation.getStep().id();
} else if ("origin".equalsIgnoreCase(version)) { //$NON-NLS-1$
return ROOT_STEP.id();
}
return version;
}
/**
* Get actions list from root to the provided step
*
* @param step The step
* @return The list of actions
*/
private List<Action> getActions(final Step step) {
return new ArrayList<>(preparationRepository.get(step.getContent(), PreparationActions.class).getActions());
}
/**
* Get the step from id
*
* @param stepId The step id
* @return Le step with the provided id
*/
private Step getStep(final String stepId) {
return preparationRepository.get(stepId, Step.class);
}
/**
* Get preparation from id
*
* @param id The preparation id.
* @return The preparation with the provided id
* @throws TDPException when no preparation has the provided id
*/
private Preparation getPreparation(final String id) {
final Preparation preparation = preparationRepository.get(id, Preparation.class);
if (preparation == null) {
LOGGER.error("Preparation #{} does not exist", id);
throw new TDPException(PREPARATION_DOES_NOT_EXIST, ExceptionContext.build().put("id", id));
}
return preparation;
}
/**
* Extract all actions after a provided step
*
* @param stepsIds The steps list
* @param afterStep The (excluded) step id where to start the extraction
* @return The actions after 'afterStep' to the end of the list
*/
private List<AppendStep> extractActionsAfterStep(final List<String> stepsIds, final String afterStep) {
final int stepIndex = stepsIds.indexOf(afterStep);
if (stepIndex == -1) {
return emptyList();
}
final List<Step> steps = IntStream.range(stepIndex, stepsIds.size()).mapToObj(index -> getStep(stepsIds.get(index)))
.collect(toList());
final List<List<Action>> stepActions = steps.stream().map(this::getActions).collect(toList());
return IntStream.range(1, steps.size()).mapToObj(index -> {
final List<Action> previous = stepActions.get(index - 1);
final List<Action> current = stepActions.get(index);
final Step step = steps.get(index);
final AppendStep appendStep = new AppendStep();
appendStep.setDiff(step.getDiff());
appendStep.setActions(current.subList(previous.size(), current.size()));
return appendStep;
}).collect(toList());
}
/**
* Get the steps ids from a specific step to the head. The specific step MUST be defined as an existing step of the
* preparation
*
* @param preparation The preparation
* @param fromStepId The starting step id
* @return The steps ids from 'fromStepId' to the head
* @throws TDPException If 'fromStepId' is not a step of the provided preparation
*/
private List<String> extractSteps(final Preparation preparation, final String fromStepId) {
final List<String> steps = PreparationUtils.listStepsIds(preparation.getStep(), fromStepId, preparationRepository);
if (!fromStepId.equals(steps.get(0))) {
throw new TDPException(PREPARATION_STEP_DOES_NOT_EXIST,
ExceptionContext.build().put("id", preparation.getId()).put("stepId", fromStepId));
}
return steps;
}
/**
* Test if the stepId is the preparation head. Null, "head", "origin" and the actual step id are considered to be
* the head
*
* @param preparation The preparation to test
* @param stepId The step id to test
* @return True if 'stepId' is considered as the preparation head
*/
private boolean isPreparationHead(final Preparation preparation, final String stepId) {
return stepId == null || "head".equals(stepId) || "origin".equals(stepId) || preparation.getStep().getId().equals(stepId);
}
/**
* Check the action parameters consistency
*
* @param step the step to check
*/
private void checkActionStepConsistency(final AppendStep step) {
for (final Action stepAction : step.getActions()) {
validator.checkScopeConsistency(stepAction.getAction(), stepAction.getParameters());
}
}
/**
* Currently, the columns ids are generated sequentially. There are 2 cases where those ids change in a step :
* <ul>
* <li>1. when a step that creates columns is deleted (ex1 : columns '0009' and '0010').</li>
* <li>2. when a step that creates columns is updated : it can create more (add) or less (remove) columns. (ex2 :
* add column '0009', '0010' + '0011' --> add 1 column)</li>
* </ul>
* In those cases, we have to
* <ul>
* <li>remove all steps that has action on a deleted column</li>
* <li>shift all columns created after this step (ex1: columns > '0010', ex2: columns > '0011') by the number of
* columns diff (ex1: remove 2 columns --> shift -2, ex2: add 1 column --> shift +1)</li>
* <li>shift all actions that has one of the deleted columns as parameter (ex1: columns > '0010', ex2: columns >
* '0011') by the number of columns diff (ex1: remove 2 columns --> shift -2, ex2: add 1 column --> shift +1)</li>
* </ul>
*
* 1. Get the steps with ids after 'afterStepId' 2. Rule 1 : Remove (filter) the steps which action is on one of the
* 'deletedColumns' 3. Rule 2 : For all actions on columns ids > 'shiftColumnAfterId', we shift the column_id
* parameter with a 'columnShiftNumber' value. (New_column_id = column_id + columnShiftNumber, only if column_id >
* 'shiftColumnAfterId') 4. Rule 3 : The columns created AFTER 'shiftColumnAfterId' are shifted with the same rules
* as rule 2. (New_created_column_id = created_column_id + columnShiftNumber, only if created_column_id >
* 'shiftColumnAfterId')
*
* @param stepsIds The steps ids
* @param afterStepId The (EXCLUDED) step where the extraction starts
* @param deletedColumns The column ids that will be removed
* @param shiftColumnAfterId The (EXCLUDED) column id where we start the shift
* @param shiftNumber The shift number. new_column_id = old_columns_id + columnShiftNumber
* @return The adapted steps
*/
private List<AppendStep> getStepsWithShiftedColumnIds(final List<String> stepsIds, final String afterStepId,
final List<String> deletedColumns, final int shiftColumnAfterId, final int shiftNumber) {
Stream<AppendStep> stream = extractActionsAfterStep(stepsIds, afterStepId).stream();
// rule 1 : remove all steps that modify one of the created columns
if (deletedColumns.size() > 0) {
stream = stream.filter(stepColumnIsNotIn(deletedColumns));
}
// when there is nothing to shift, we just return the filtered steps to avoid extra code
if (shiftNumber == 0) {
return stream.collect(toList());
}
// rule 2 : we have to shift all columns ids created after the step to delete/modify, in the column_id
// parameters
// For example, if the step to delete/modify creates columns 0010 and 0011, all steps that apply to column 0012
// should now apply to 0012 - (2 created columns) = 0010
stream = stream.map(shiftStepParameter(shiftColumnAfterId, shiftNumber));
// rule 3 : we have to shift all columns ids created after the step to delete, in the steps diff
stream = stream.map(shiftCreatedColumns(shiftColumnAfterId, shiftNumber));
return stream.collect(toList());
}
/**
* When the step diff created column ids > 'shiftColumnAfterId', we shift it by +columnShiftNumber (that wan be
* negative)
*
* @param shiftColumnAfterId The shift is performed if created column id > shiftColumnAfterId
* @param shiftNumber The number to shift (can be negative)
* @return The same step but modified
*/
private Function<AppendStep, AppendStep> shiftCreatedColumns(final int shiftColumnAfterId, final int shiftNumber) {
final DecimalFormat format = new DecimalFormat("0000"); //$NON-NLS-1$
return step -> {
final List<String> stepCreatedCols = step.getDiff().getCreatedColumns();
final List<String> shiftedStepCreatedCols = stepCreatedCols.stream().map(colIdStr -> {
final int columnId = Integer.parseInt(colIdStr);
if (columnId > shiftColumnAfterId) {
return format.format(columnId + shiftNumber);
}
return colIdStr;
}).collect(toList());
step.getDiff().setCreatedColumns(shiftedStepCreatedCols);
return step;
};
}
/**
* When the step column_id parameter > 'shiftColumnAfterId', we shift it by +columnShiftNumber (that wan be
* negative)
*
* @param shiftColumnAfterId The shift is performed if column id > shiftColumnAfterId
* @param shiftNumber The number to shift (can be negative)
* @return The same step but modified
*/
private Function<AppendStep, AppendStep> shiftStepParameter(final int shiftColumnAfterId, final int shiftNumber) {
final DecimalFormat format = new DecimalFormat("0000"); //$NON-NLS-1$
return step -> {
final Map<String, String> parameters = step.getActions().get(0).getParameters();
final int columnId = Integer.parseInt(step.getActions().get(0).getParameters().get("column_id")); //$NON-NLS-1$
if (columnId > shiftColumnAfterId) {
parameters.put("column_id", format.format(columnId + shiftNumber)); //$NON-NLS-1$
}
return step;
};
}
/***
* Predicate that returns if a step action is NOT on one of the columns list
*
* @param columns The columns ids list
*/
private Predicate<AppendStep> stepColumnIsNotIn(final List<String> columns) {
return step -> {
final String columnId = step.getActions().get(0).getParameters().get("column_id"); //$NON-NLS-1$
return columnId == null || !columns.contains(columnId);
};
}
/**
* Update the head step of a preparation
*
* @param preparation The preparation to update
* @param head The head step
*/
private void setPreparationHead(final Preparation preparation, final Step head) {
preparation.setStep(head);
preparation.updateLastModificationDate();
preparationRepository.add(preparation);
}
/**
* Rewrite the preparation history from a specific step, with the provided actions
*
* @param preparation The preparation
* @param startStepId The step id to start the (re)write. The following steps will be erased
* @param actionsSteps The actions to perform
*/
private void replaceHistory(final Preparation preparation, final String startStepId, final List<AppendStep> actionsSteps) {
// move preparation head to the starting step
if (!isPreparationHead(preparation, startStepId)) {
final Step startingStep = getStep(startStepId);
setPreparationHead(preparation, startingStep);
}
actionsSteps.stream().forEach(step -> appendStepToHead(preparation, step));
}
/**
* Append a single step after the preparation head
*
* @param preparation The preparation
* @param step The step to apply
*/
private void appendStepToHead(final Preparation preparation, final AppendStep step) {
// Add new actions after head
final Step head = preparation.getStep();
final PreparationActions headContent = preparationRepository.get(head.getContent(), PreparationActions.class);
final PreparationActions newContent = headContent.append(step.getActions());
preparationRepository.add(newContent);
// Create new step from new content
final Step newStep = new Step(head.id(), newContent.id(), step.getDiff());
preparationRepository.add(newStep);
// Update preparation head step
setPreparationHead(preparation, newStep);
}
} |
package com.fishercoder.solutions;
public class _461 {
public static class Solution1 {
public int hammingDistance(int x, int y) {
int n = x ^ y;
int count = 0;
while (n != 0) {
count++;
n &= (n - 1);
}
return count;
}
}
} |
package org.datavaultplatform.common.storage.impl;
import org.apache.commons.io.IOUtils;
import org.datavaultplatform.common.io.Progress;
import org.datavaultplatform.common.storage.ArchiveStore;
import org.datavaultplatform.common.storage.Device;
import org.datavaultplatform.common.storage.Verify;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Map;
import java.util.concurrent.TimeUnit;
public class TivoliStorageManager extends Device implements ArchiveStore {
private static final Logger logger = LoggerFactory.getLogger(TivoliStorageManager.class);
// default locations of TSM option files
public static String TSM_SERVER_NODE1_OPT = "/opt/tivoli/tsm/client/ba/bin/dsm1.opt";
public static String TSM_SERVER_NODE2_OPT = "/opt/tivoli/tsm/client/ba/bin/dsm2.opt";
public static String TEMP_PATH_PREFIX = "/tmp/datavault/temp/";
public Verify.Method verificationMethod = Verify.Method.COPY_BACK;
private static int defaultRetryTime = 30;
private static int defaultMaxRetries = 48; // 24 hours if retry time is 30 minutes
private static int retryTime = TivoliStorageManager.defaultRetryTime;
private static int maxRetries = TivoliStorageManager.defaultMaxRetries;
public TivoliStorageManager(String name, Map<String,String> config) throws Exception {
super(name, config);
String optionsKey = "optionsDir";
String tempKey = "tempDir";
String retryKey = "tsmRetryTime";
String maxKey = "tsmMaxRetries";
// if we have non default options in datavault.properties use them
if (config.containsKey(optionsKey)) {
String optionsDir = config.get(optionsKey);
TivoliStorageManager.TSM_SERVER_NODE1_OPT = optionsDir + "/dsm1.opt";
TivoliStorageManager.TSM_SERVER_NODE2_OPT = optionsDir + "/dsm2.opt";
}
if (config.containsKey(tempKey)) {
TivoliStorageManager.TEMP_PATH_PREFIX = config.get(tempKey);
}
if (config.containsKey(retryKey)){
try {
TivoliStorageManager.retryTime = Integer.parseInt(config.get(retryKey));
} catch (NumberFormatException nfe) {
TivoliStorageManager.retryTime = TivoliStorageManager.defaultRetryTime;
}
}
if (config.containsKey(maxKey)) {
try {
TivoliStorageManager.maxRetries = Integer.parseInt(config.get(maxKey));
} catch (NumberFormatException nfe) {
TivoliStorageManager.maxRetries = TivoliStorageManager.defaultMaxRetries;
}
}
locations = new ArrayList<String>();
locations.add(TivoliStorageManager.TSM_SERVER_NODE1_OPT);
locations.add(TivoliStorageManager.TSM_SERVER_NODE2_OPT);
super.multipleCopies = true;
super.depositIdStorageKey = true;
for (String key : config.keySet()) {
logger.info("Config value for " + key + " is " + config.get(key));
}
}
@Override
public long getUsableSpace() throws Exception {
long retVal = 0;
ProcessBuilder pb = new ProcessBuilder("dsmc", "query", "filespace");
Process p = pb.start();
// This class is already running in its own thread so it can happily pause until finished.
p.waitFor();
if (p.exitValue() != 0) {
logger.info("Filespace output failed.");
logger.info(p.getErrorStream().toString());
logger.info(p.getOutputStream().toString());
throw new Exception("Filespace output failed.");
}
// need to parse the output to get the usable space value
// this looks like it will be a bit of a pain
// I suspect the format might be quite awkward
// (need to wait till I can actually connect to a tsm before I can do this)
return retVal;
}
@Override
public void retrieve(String path, File working, Progress progress) throws Exception {
throw new UnsupportedOperationException();
}
@Override
public void retrieve(String depositId, File working, Progress progress, String optFilePath) throws Exception {
String fileDir = TivoliStorageManager.TEMP_PATH_PREFIX + "/" + depositId;
String filePath = fileDir + "/" + working.getName();
if (! Files.exists(Paths.get(fileDir))) {
Files.createDirectory(Paths.get(fileDir));
}
logger.info("Retrieve command is " + "dsmc " + " retrieve " + filePath + " -description=" + depositId + " -optfile=" + optFilePath + "-replace=true");
for (int r = 0; r < TivoliStorageManager.maxRetries; r++) {
ProcessBuilder pb = new ProcessBuilder("dsmc", "retrieve", filePath, "-description=" + depositId, "-optfile=" + optFilePath, "-replace=true");
Process p = pb.start();
// This class is already running in its own thread so it can happily pause until finished.
p.waitFor();
if (p.exitValue() != 0) {
logger.info("Retrieval of " + working.getName() + " failed using " + optFilePath + ". ");
InputStream error = p.getErrorStream();
for (int i = 0; i < error.available(); i++) {
logger.info("" + error.read());
}
if (r == (TivoliStorageManager.maxRetries - 1)) {
throw new Exception("Retrieval of " + working.getName() + " failed. ");
}
logger.info("Retrieval of " + working.getName() + " failed. Retrying in " + TivoliStorageManager.retryTime + " mins");
TimeUnit.MINUTES.sleep(TivoliStorageManager.retryTime);
} else {
// FILL IN THE REST OF PROGRESS x dirs, x files, x bytes etc.
if (Files.exists(Paths.get(filePath))) {
Files.move(Paths.get(filePath), Paths.get(working.getAbsolutePath()), StandardCopyOption.REPLACE_EXISTING);
}
Files.delete(Paths.get(fileDir));
break;
}
}
}
@Override
public String store(String depositId, File working, Progress progress) throws Exception {
// todo : monitor progress
// Note: generate a uuid to be passed as the description. We should probably use the deposit UUID instead (do we need a specialised archive method)?
// Just a thought - Does the filename contain the deposit uuid? Could we use that as the description?
//String randomUUIDString = UUID.randomUUID().toString();
String pathPrefix = TivoliStorageManager.TEMP_PATH_PREFIX;
Path sourcePath = Paths.get(working.getAbsolutePath());
Path destinationDir = Paths.get(pathPrefix + "/" + depositId);
Path destinationFile = Paths.get(pathPrefix + "/" + depositId + "/" + working.getName());
if (Files.exists(sourcePath)) {
logger.info("Moving from temp to deposit id");
Files.createDirectory(destinationDir);
Files.move(sourcePath, destinationFile, StandardCopyOption.REPLACE_EXISTING);
}
File tsmFile = new File(pathPrefix + "/" + depositId + "/" + working.getName());
this.storeInTSMNode(tsmFile, progress, TivoliStorageManager.TSM_SERVER_NODE1_OPT, depositId);
this.storeInTSMNode(tsmFile, progress, TivoliStorageManager.TSM_SERVER_NODE2_OPT, depositId);
if (Files.exists(destinationFile)) {
logger.info("Moving from deposit id to temp");
Files.move(destinationFile, sourcePath, StandardCopyOption.REPLACE_EXISTING);
Files.delete(destinationDir);
}
return depositId;
}
private String storeInTSMNode(File working, Progress progress, String optFilePath, String description) throws Exception {
// check we have enough space to store the data (is the file bagged and tarred atm or is the actual space going to be different?)
// actually the Deposit / Retreive worker classes check the free space it appears if we get here we don't need to check
// The working file appears to be bagged and tarred when we get here
// in the local version of this class the FileCopy class adds info to the progress object
// I don't think we need to use the patch at all in this version
//File path = working.getAbsoluteFile().getParentFile();
logger.info("Store command is " + "dsmc" + " archive " + working.getAbsolutePath() + " -description=" + description + " -optfile=" + optFilePath);
ProcessBuilder pb = new ProcessBuilder("dsmc", "archive", working.getAbsolutePath(), "-description=" + description, "-optfile=" + optFilePath);
//pb.directory(path);
for (int r = 0; r < TivoliStorageManager.maxRetries; r++) {
Process p = pb.start();
// This class is already running in its own thread so it can happily pause until finished.
p.waitFor();
if (p.exitValue() != 0) {
logger.info("Deposit of " + working.getName() + " using " + optFilePath + " failed. ");
InputStream error = p.getErrorStream();
if (error != null) {
logger.info(IOUtils.toString(error, StandardCharsets.UTF_8));
}
InputStream output = p.getInputStream();
if (output != null) {
logger.info(IOUtils.toString(output, StandardCharsets.UTF_8));
}
if (r == (TivoliStorageManager.maxRetries -1)) {
throw new Exception("Deposit of " + working.getName() + " using " + optFilePath + " failed. ");
}
logger.info("Deposit of " + working.getName() + " using " + optFilePath + " failed. Retrying in " + TivoliStorageManager.retryTime + " mins");
TimeUnit.MINUTES.sleep(TivoliStorageManager.retryTime);
} else {
break;
}
}
return description;
}
@Override
public Verify.Method getVerifyMethod() {
return verificationMethod;
}
@Override
public void delete(String depositId, File working, Progress progress, String optFilePath) throws Exception {
String fileDir = TivoliStorageManager.TEMP_PATH_PREFIX + "/" + depositId;
String filePath = fileDir + "/" + working.getName();
for (int r = 0; r < TivoliStorageManager.maxRetries; r++) {
logger.info("Delete command is " + "dsmc delete archive " + filePath + " -noprompt -optfile=" + optFilePath);
ProcessBuilder pb = new ProcessBuilder("dsmc", "delete", "archive", filePath, "-noprompt" , "-optfile=" + optFilePath);
Process p = pb.start();
p.waitFor();
if (p.exitValue() != 0) {
logger.info("Delete of " + depositId + " failed.");
InputStream error = p.getErrorStream();
for (int i = 0; i < error.available(); i++) {
logger.info("" + error.read());
}
if (r == (TivoliStorageManager.maxRetries -1)) {
throw new Exception("Delete of " + depositId + " using " + optFilePath + " failed. ");
}
logger.info("Delete of " + depositId + " failed. Retrying in " + TivoliStorageManager.retryTime + " mins");
TimeUnit.MINUTES.sleep(TivoliStorageManager.retryTime);
} else {
logger.info("Delete of " + depositId + " is Successful.");
break;
}
}
}
} |
package main;
import java.util.Arrays;
import grid.GridGraph;
import main.AnyAnglePathfinding.AlgoFunction;
import algorithms.PathFindingAlgorithm;
public class Utility {
/**
* Compute the length of a given path. (Using euclidean distance)
*/
public static float computePathLength(GridGraph gridGraph, int[][] path) {
float pathLength = 0;
for (int i=0; i<path.length-1; i++) {
pathLength += gridGraph.distance(path[i][0], path[i][1],
path[i+1][0], path[i+1][1]);
}
return pathLength;
}
static int[][] generatePath(GridGraph gridGraph, int sx, int sy,
int ex, int ey) {
return generatePath(AnyAnglePathfinding.algoFunction, gridGraph, sx, sy, ex, ey);
}
static int[][] removeDuplicatesInPath(int[][] path) {
if (path.length <= 2) return path;
int[][] newPath = new int[path.length][];
int index = 0;
newPath[0] = path[0];
for (int i=1; i<path.length-1; ++i) {
if (isCollinear(path[i][0], path[i][1], path[i+1][0], path[i+1][1], newPath[index][0], newPath[index][1])) {
// skip
} else {
index++;
newPath[index] = path[i];
}
}
index++;
newPath[index] = path[path.length-1];
return Arrays.copyOf(newPath, index+1);
}
private static boolean isCollinear(int x1, int y1, int x2, int y2, int x3, int y3) {
return (y3-y1)*(x2-x1) == (x3-x1)*(y2-y1);
}
/**
* Generates a path between two points on a grid.
* @return an array of int[2] indicating the coordinates of the path.
*/
static int[][] generatePath(AlgoFunction algoFunction, GridGraph gridGraph,
int sx, int sy, int ex, int ey) {
PathFindingAlgorithm algo = algoFunction.getAlgo(gridGraph, sx, sy, ex, ey);
algo.computePath();
int[][] path = algo.getPath();
return path;
}
} |
package com.fishercoder.solutions;
/**
* 567. Permutation in String
*
* Given two strings s1 and s2, write a function to return true if s2 contains the permutation of s1.
* In other words, one of the first string's permutations is the substring of the second string.
Example 1:
Input:s1 = "ab" s2 = "eidbaooo"
Output:True
Explanation: s2 contains one permutation of s1 ("ba").
Example 2:
Input:s1= "ab" s2 = "eidboaoo"
Output: False
Note:
The input strings only contain lower case letters.
The length of both given strings is in range [1, 10,000].
*/
public class _567 {
/**1. How do we know string p is a permutation of string s? Easy, each character in p is in s too.
* So we can abstract all permutation strings of s to a map (Character -> Count). i.e. abba -> {a:2, b:2}.
* Since there are only 26 lower case letters in this problem, we can just use an array to represent the map.
2. How do we know string s2 contains a permutation of s1?
We just need to create a sliding window with length of s1,
move from beginning to the end of s2.
When a character moves in from right of the window,
we subtract 1 to that character count from the map.
When a character moves out from left of the window,
we add 1 to that character count. So once we see all zeros in the map,
meaning equal numbers of every characters between s1 and the substring in the sliding window, we know the answer is true.
*/
public boolean checkInclusion(String s1, String s2) {
int len1 = s1.length();
int len2 = s2.length();
if (len1 > len2) {
return false;
}
int[] count = new int[26];
for (int i = 0; i < len1; i++) {
count[s1.charAt(i) - 'a']++;
}
for (int i = 0; i < len1; i++) {
count[s2.charAt(i) - 'a']
}
if (allZeroes(count)) {
return true;
}
for (int i = len1; i < len2; i++) {
count[s2.charAt(i) - 'a']
count[s2.charAt(i - len1) - 'a']++;
if (allZeroes(count)) {
return true;
}
}
return false;
}
private boolean allZeroes(int[] count) {
for (int i : count) {
if (i != 0) {
return false;
}
}
return true;
}
} |
// Jupiter: A Ride-Sharing Network Generation and Analysis Application
package com.mshahrfar.jupiter;
import java.util.List;
/**
*
*
* @author Mariam Shahrabifarahani
*/
public interface Filter {
/**
*
*
* @param customer
* @param candidate
* @return
*/
public boolean pass(Customer customer, Customer candidate);
} |
//$HeadURL$
package org.deegree.portal.standard.digitizer.control;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.HttpSession;
import org.deegree.datatypes.QualifiedName;
import org.deegree.datatypes.Types;
import org.deegree.datatypes.UnknownTypeException;
import org.deegree.enterprise.control.ajax.AbstractListener;
import org.deegree.enterprise.control.ajax.ResponseHandler;
import org.deegree.enterprise.control.ajax.WebEvent;
import org.deegree.framework.log.ILogger;
import org.deegree.framework.log.LoggerFactory;
import org.deegree.framework.util.FileUtils;
import org.deegree.framework.util.HttpUtils;
import org.deegree.framework.util.TimeTools;
import org.deegree.framework.xml.XMLFragment;
import org.deegree.model.feature.Feature;
import org.deegree.model.feature.FeatureCollection;
import org.deegree.model.feature.FeatureFactory;
import org.deegree.model.feature.FeatureProperty;
import org.deegree.model.feature.schema.FeatureType;
import org.deegree.model.feature.schema.PropertyType;
import org.deegree.model.spatialschema.Geometry;
import org.deegree.model.spatialschema.GeometryException;
import org.deegree.model.spatialschema.WKTAdapter;
import org.deegree.ogcwebservices.wfs.XMLFactory;
import org.deegree.ogcwebservices.wfs.operation.transaction.Insert;
import org.deegree.ogcwebservices.wfs.operation.transaction.Insert.ID_GEN;
import org.deegree.ogcwebservices.wfs.operation.transaction.Transaction;
import org.deegree.ogcwebservices.wfs.operation.transaction.TransactionOperation;
import org.deegree.portal.Constants;
import org.deegree.portal.context.ViewContext;
/**
* TODO add class documentation here
*
* @author <a href="mailto:name@deegree.org">Andreas Poth</a>
* @author last edited by: $Author$
*
* @version $Revision$, $Date$
*/
public class SaveFeatureListener extends AbstractListener {
private static final ILogger LOG = LoggerFactory.getLogger( SaveFeatureListener.class );
/*
* (non-Javadoc)
*
* @see
* org.deegree.enterprise.control.ajax.AbstractListener#actionPerformed(org.deegree.enterprise.control.ajax.WebEvent
* , org.deegree.enterprise.control.ajax.ResponseHandler)
*/
@Override
public void actionPerformed( WebEvent event, ResponseHandler responseHandler )
throws IOException {
HttpSession session = event.getSession();
ViewContext vc = (ViewContext) session.getAttribute( Constants.CURRENTMAPCONTEXT );
List<Map<String, Object>> list = (List<Map<String, Object>>) event.getParameter().get( "featureMap" );
for ( Map<String, Object> map : list ) {
Map<String, Object> attributes = (Map<String, Object>) ( (List<Object>) map.get( "attributes" ) ).get( 0 );
LOG.logDebug( "attributes: ", attributes );
Map<String, Object> featureTypeMap = (Map<String, Object>) attributes.get( "$FEATURETYPE$" );
LOG.logDebug( "featureType: ", featureTypeMap );
FeatureType featureType;
try {
featureType = createFeatureType( featureTypeMap );
} catch ( Exception e ) {
handleException( responseHandler, e );
return;
}
LOG.logDebug( "geometry: ", map.get( "geometry" ) );
Geometry geometry;
try {
geometry = createGeometry( (String) map.get( "geometry" ), vc );
} catch ( Exception e ) {
handleException( responseHandler, e );
return;
}
Feature feature = null;
try {
feature = createFeature( attributes, geometry, featureType );
} catch ( Exception e ) {
handleException( responseHandler, e );
return;
}
FeatureCollection fc = FeatureFactory.createFeatureCollection( "UUID" + UUID.randomUUID().toString(),
new Feature[] { feature } );
URL url = new URL( (String) featureTypeMap.get( "wfsURL" ) );
if ( "INSERT".equalsIgnoreCase( (String) attributes.get( "$ACTION$" ) ) ) {
handleInsert( responseHandler, url, fc );
}
}
}
private void handleInsert( ResponseHandler responseHandler, URL url, FeatureCollection fc )
throws IOException {
Insert insert = new Insert( UUID.randomUUID().toString(), ID_GEN.GENERATE_NEW, null, fc );
List<TransactionOperation> tmp = new ArrayList<TransactionOperation>();
tmp.add( insert );
try {
performTransaction( url, tmp, null, null );
} catch ( Exception e ) {
handleException( responseHandler, e );
return;
}
}
private static XMLFragment performTransaction( URL wfsURL, List<TransactionOperation> list, String user,
String password )
throws Exception {
Transaction transaction = new Transaction( null, null, null, null, list, true, null );
XMLFragment xml = XMLFactory.export( transaction );
// HttpUtils.addAuthenticationForXML( xml, appCont.getUser(), appCont.getPassword(), //
// appCont.getCertificate( wfsURL.toURI().toASCIIString() ) );
if ( LOG.getLevel() == ILogger.LOG_DEBUG ) {
LOG.logDebug( "WFS Transaction: ", xml.getAsString() );
}
InputStream is = HttpUtils.performHttpPost( wfsURL.toURI().toASCIIString(), xml, timeout, user, password, null ).getResponseBodyAsStream();
if ( LOG.getLevel() == ILogger.LOG_DEBUG ) {
String st = FileUtils.readTextFile( is ).toString();
is = new ByteArrayInputStream( st.getBytes() );
LOG.logDebug( "WFS transaction result: ", st );
}
xml = new XMLFragment();
xml.load( is, wfsURL.toExternalForm() );
if ( "ExceptionReport".equalsIgnoreCase( xml.getRootElement().getLocalName() ) ) {
LOG.logError( "Transaction on: " + xml.getAsString() + " failed" );
// TODO // extract exception message
throw new Exception( xml.getAsString() );
}
return xml;
}
/**
* @param wkt
* @return
* @throws GeometryException
*/
private static Geometry createGeometry( String wkt, ViewContext vc )
throws GeometryException {
return WKTAdapter.wrap( wkt, vc.getGeneral().getBoundingBox()[0].getCoordinateSystem() );
}
/**
* @param attributes
* @param geometry
* @param featureType
* @return
*/
private static Feature createFeature( Map<String, Object> attributes, Geometry geometry, FeatureType featureType ) {
PropertyType[] pts = featureType.getProperties();
FeatureProperty[] fps = new FeatureProperty[pts.length];
for ( int i = 0; i < fps.length; i++ ) {
if ( pts[i].getType() == Types.GEOMETRY ) {
fps[i] = FeatureFactory.createFeatureProperty( pts[i].getName(), geometry );
continue;
}
if ( attributes.get( pts[i].getName().getFormattedString() ) == null ) {
fps[i] = FeatureFactory.createFeatureProperty( pts[i].getName(), null );
continue;
}
String value = attributes.get( pts[i].getName().getFormattedString() ).toString();
switch ( pts[i].getType() ) {
case Types.VARCHAR: {
fps[i] = FeatureFactory.createFeatureProperty( pts[i].getName(), value );
break;
}
case Types.FLOAT:
case Types.DOUBLE: {
fps[i] = FeatureFactory.createFeatureProperty( pts[i].getName(), Float.parseFloat( value ) );
break;
}
case Types.BIGINT:
case Types.TINYINT:
case Types.INTEGER:
case Types.SMALLINT: {
fps[i] = FeatureFactory.createFeatureProperty( pts[i].getName(), Integer.parseInt( value ) );
break;
}
case Types.BOOLEAN: {
fps[i] = FeatureFactory.createFeatureProperty( pts[i].getName(), "true".equalsIgnoreCase( value ) );
break;
}
case Types.TIMESTAMP:
case Types.DATE: {
Date date = TimeTools.createDate( value );
fps[i] = FeatureFactory.createFeatureProperty( pts[i].getName(), date );
break;
}
}
}
return FeatureFactory.createFeature( "UUID_" + UUID.randomUUID().toString(), featureType, fps );
}
private static FeatureType createFeatureType( Map<String, Object> featureType )
throws UnknownTypeException {
String featureTypeName = (String) featureType.get( "name" );
String featureTypeNamespace = (String) featureType.get( "namespace" );
String geoPropName = (String) featureType.get( "geomPropertyName" );
String geoPropNamespace = (String) featureType.get( "geomPropertyNamespace" );
List<PropertyType> propertyTypes = new ArrayList<PropertyType>();
QualifiedName qn = null;
List<Map<String, Object>> properties = (List<Map<String, Object>>) featureType.get( "properties" );
for ( Map<String, Object> map : properties ) {
int type = Types.getTypeCodeForSQLType( (String) map.get( "type" ) );
String name = (String) map.get( "name" );
URI nsp = URI.create( (String) map.get( "namespace" ) );
qn = new QualifiedName( name, nsp );
propertyTypes.add( FeatureFactory.createSimplePropertyType( qn, type, false ) );
}
qn = new QualifiedName( geoPropName, URI.create( geoPropNamespace ) );
propertyTypes.add( FeatureFactory.createSimplePropertyType( qn, Types.GEOMETRY, false ) );
qn = new QualifiedName( featureTypeName, URI.create( featureTypeNamespace ) );
return FeatureFactory.createFeatureType( qn, false,
propertyTypes.toArray( new PropertyType[propertyTypes.size()] ) );
}
} |
package com.fishercoder.solutions;
import com.fishercoder.common.utils.CommonUtils;
public class _672 {
public static class Solution1 {
public int flipLights(int n, int m) {
if (m < 1) {
return 1;
}
int[][] dp = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (j == 0) {
dp[i][j] = 2;
} else if (i == 0 && j == 1) {
dp[i][j] = 3;
} else if (i == 0) {
dp[i][j] = 4;
} else if (i == 1 && j == 1) {
dp[i][j] = 4;
} else if (i == 1 && j > 1) {
dp[i][j] = 7;
} else if (j == 1) {
dp[i][j] = 4;
} else if (i == 1) {
dp[i][j] = 7;
} else {
dp[i][j] = 8;
}
}
}
CommonUtils.print2DIntArray(dp);
return dp[m - 1][n - 1];
}
}
public static class Solution2 {
public int flipLights(int n, int m) {
if (n == 1 && m > 0) {
return 2;
} else if (n == 2 && m == 1) {
return 3;
} else if ((n > 2 && m == 1) || (n == 2 && m > 1)) {
return 4;
} else if (n > 2 && m == 2) {
return 7;
} else if (n > 2 && m > 2) {
return 8;
} else {
return 1;
}
}
}
} |
package be.ibridge.kettle.trans.step.tableoutput;
import java.sql.PreparedStatement;
import java.text.SimpleDateFormat;
import java.util.Iterator;
import be.ibridge.kettle.core.Const;
import be.ibridge.kettle.core.Row;
import be.ibridge.kettle.core.database.Database;
import be.ibridge.kettle.core.exception.KettleDatabaseBatchException;
import be.ibridge.kettle.core.exception.KettleDatabaseException;
import be.ibridge.kettle.core.exception.KettleException;
import be.ibridge.kettle.core.exception.KettleStepException;
import be.ibridge.kettle.core.util.StringUtil;
import be.ibridge.kettle.core.value.Value;
import be.ibridge.kettle.trans.Trans;
import be.ibridge.kettle.trans.TransMeta;
import be.ibridge.kettle.trans.step.BaseStep;
import be.ibridge.kettle.trans.step.StepDataInterface;
import be.ibridge.kettle.trans.step.StepInterface;
import be.ibridge.kettle.trans.step.StepMeta;
import be.ibridge.kettle.trans.step.StepMetaInterface;
/**
* Writes rows to a database table.
*
* @author Matt
* @since 6-apr-2003
*/
public class TableOutput extends BaseStep implements StepInterface
{
private TableOutputMeta meta;
private TableOutputData data;
public TableOutput(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans)
{
super(stepMeta, stepDataInterface, copyNr, transMeta, trans);
}
public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException
{
meta=(TableOutputMeta)smi;
data=(TableOutputData)sdi;
Row r;
r=getRow(); // this also waits for a previous step to be finished.
if (r==null) // no more input to be expected...
{
setOutputDone();
return false;
}
try
{
writeToTable(r);
putRow(r); // in case we want it go further...
if (checkFeedback(linesOutput)) logBasic("linenr "+linesOutput);
}
catch(KettleException e)
{
logError("Because of an error, this step can't continue: "+e.getMessage());
setErrors(1);
stopAll();
setOutputDone(); // signal end to receiver(s)
return false;
}
return true;
}
private boolean writeToTable(Row r) throws KettleException
{
if (r==null) // Stop: last line or error encountered
{
if (log.isDetailed()) logDetailed("Last line inserted: stop");
return false;
}
PreparedStatement insertStatement = null;
String tableName = null;
Value removedValue = null;
if ( meta.isTableNameInField() )
{
// Cache the position of the table name field
if (data.indexOfTableNameField<0)
{
data.indexOfTableNameField = r.searchValueIndex(meta.getTableNameField());
if (data.indexOfTableNameField<0)
{
String message = "Unable to find table name field ["+meta.getTableNameField()+"] in input row";
log.logError(toString(), message);
throw new KettleStepException(message);
}
}
tableName = r.getValue(data.indexOfTableNameField).getString();
if (!meta.isTableNameInTable())
{
removedValue = r.getValue(data.indexOfTableNameField);
r.removeValue(data.indexOfTableNameField);
}
}
else
if ( meta.isPartitioningEnabled() &&
( meta.isPartitioningDaily() || meta.isPartitioningMonthly()) &&
( meta.getPartitioningField()!=null && meta.getPartitioningField().length()>0 )
)
{
// Initialize some stuff!
if (data.indexOfPartitioningField<0)
{
data.indexOfPartitioningField = r.searchValueIndex(meta.getPartitioningField());
if (data.indexOfPartitioningField<0)
{
throw new KettleStepException("Unable to find field ["+meta.getPartitioningField()+"] in the input row!");
}
if (meta.isPartitioningDaily())
{
data.dateFormater = new SimpleDateFormat("yyyyMMdd");
}
else
{
data.dateFormater = new SimpleDateFormat("yyyyMM");
}
}
Value partitioningValue = r.getValue(data.indexOfPartitioningField);
if (!partitioningValue.isDate() || partitioningValue.isNull())
{
throw new KettleStepException("Sorry, the partitioning field needs to contain a data value and can't be empty!");
}
tableName=StringUtil.environmentSubstitute(meta.getTablename())+"_"+data.dateFormater.format(partitioningValue.getDate());
}
else
{
tableName = data.tableName;
}
if (Const.isEmpty(tableName))
{
throw new KettleStepException("The tablename is not defined (empty)");
}
insertStatement = (PreparedStatement) data.preparedStatements.get(tableName);
if (insertStatement==null)
{
String sql = data.db.getInsertStatement(meta.getSchemaName(), tableName, r);
if (log.isDetailed()) logDetailed("Prepared statement : "+sql);
insertStatement = data.db.prepareSQL(sql, meta.isReturningGeneratedKeys());
data.preparedStatements.put(tableName, insertStatement);
}
try
{
data.db.setValues(r, insertStatement);
data.db.insertRow(insertStatement, data.batchMode);
linesOutput++;
// See if we need to get back the keys as well...
if (meta.isReturningGeneratedKeys())
{
Row extra = data.db.getGeneratedKeys(insertStatement);
// Send out the good word!
// Only 1 key at the moment. (should be enough for now :-)
Value keyVal = extra.getValue(0);
keyVal.setName(meta.getGeneratedKeyField());
r.addValue(keyVal);
}
}
catch(KettleDatabaseBatchException be)
{
data.db.clearBatch(insertStatement);
data.db.rollback();
throw new KettleException("Error batch inserting rows into table ["+tableName+"]", be);
}
catch(KettleDatabaseException dbe)
{
if (meta.ignoreErrors())
{
if (data.warnings<20)
{
logBasic("WARNING: Couldn't insert row into table: "+r+Const.CR+dbe.getMessage());
}
else
if (data.warnings==20)
{
logBasic("FINAL WARNING (no more then 20 displayed): Couldn't insert row into table: "+r+Const.CR+dbe.getMessage());
}
data.warnings++;
}
else
{
setErrors(getErrors()+1);
data.db.rollback();
throw new KettleException("Error inserting row into table ["+tableName+"] with values: "+r, dbe);
}
}
if (meta.isTableNameInField() && !meta.isTableNameInTable())
{
r.addValue(data.indexOfTableNameField, removedValue);
}
return true;
}
public boolean init(StepMetaInterface smi, StepDataInterface sdi)
{
meta=(TableOutputMeta)smi;
data=(TableOutputData)sdi;
if (super.init(smi, sdi))
{
try
{
data.batchMode = meta.getCommitSize()>0 && meta.useBatchUpdate();
data.db=new Database(meta.getDatabaseMeta());
if (getTransMeta().isUsingUniqueConnections())
{
synchronized (getTrans()) { data.db.connect(getTrans().getThreadName(), getPartitionID()); }
}
else
{
data.db.connect(getPartitionID());
}
logBasic("Connected to database ["+meta.getDatabaseMeta()+"] (commit="+meta.getCommitSize()+")");
data.db.setCommit(meta.getCommitSize());
if (!meta.isPartitioningEnabled() && !meta.isTableNameInField())
{
data.tableName = StringUtil.environmentSubstitute( meta.getTablename());
// Only the first one truncates in a non-partitioned step copy
if (meta.truncateTable() && ( getCopy()==0 || !Const.isEmpty(getPartitionID())) )
{
data.db.truncateTable(data.tableName);
}
}
return true;
}
catch(KettleException e)
{
logError("An error occurred intialising this step: "+e.getMessage());
stopAll();
setErrors(1);
}
}
return false;
}
public void dispose(StepMetaInterface smi, StepDataInterface sdi)
{
meta=(TableOutputMeta)smi;
data=(TableOutputData)sdi;
try
{
Iterator preparedStatements = data.preparedStatements.values().iterator();
while (preparedStatements.hasNext())
{
PreparedStatement insertStatement = (PreparedStatement) preparedStatements.next();
data.db.insertFinished(insertStatement, data.batchMode);
}
}
catch(KettleDatabaseBatchException be)
{
logError("Unexpected batch update error committing the database connection: "+be.toString());
setErrors(1);
stopAll();
}
catch(Exception dbe)
{
// dbe.printStackTrace();
logError("Unexpected error committing the database connection: "+dbe.toString());
setErrors(1);
stopAll();
}
finally
{
if (getErrors()>0)
{
try
{
data.db.rollback();
}
catch(KettleDatabaseException e)
{
logError("Unexpected error rolling back the database connection: "+e.toString());
}
}
data.db.disconnect();
super.dispose(smi, sdi);
}
}
/**
* Run is were the action happens!
*/
public void run()
{
try
{
logBasic("Starting to run...");
while (processRow(meta, data) && !isStopped());
}
catch(Exception e)
{
logError("Unexpected error : "+e.toString());
logError(Const.getStackTracker(e));
setErrors(1);
stopAll();
}
finally
{
dispose(meta, data);
logSummary();
markStop();
}
}
} |
package org.apache.xml.security.utils;
import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;
import java.math.BigInteger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.*;
import org.apache.xml.security.c14n.*;
import org.apache.xml.security.exceptions.*;
import org.apache.xml.security.signature.XMLSignatureException;
import org.apache.xml.security.utils.Base64;
import org.apache.xml.security.utils.Constants;
import org.apache.xml.security.utils.HelperNodeList;
import org.apache.xpath.XPathAPI;
import org.apache.xpath.objects.XObject;
/**
* DOM and XML accessibility and comfort functions.
*
* @author Christian Geuer-Pollmann
*/
public class XMLUtils {
/** {@link org.apache.log4j} logging facility */
static org.apache.log4j.Category cat =
org.apache.log4j.Category.getInstance(XMLUtils.class.getName());
/**
* Constructor XMLUtils
*
*/
private XMLUtils() {
// we don't allow instantiation
}
/**
* Method getXalanVersion
*
*
*/
public static String getXalanVersion() {
String version = XMLUtils.getXalan1Version();
if (version != null) {
return version;
}
version = XMLUtils.getXalan20Version();
if (version != null) {
return version;
}
version = XMLUtils.getXalan2Version();
if (version != null) {
return version;
}
return "Apache Xalan not installed";
// return "Apache " + org.apache.xalan.processor.XSLProcessorVersion.S_VERSION;
// return "Apache " + org.apache.xalan.Version.getVersion();
}
/**
* Method getXercesVersion
*
*
*/
public static String getXercesVersion() {
String version = XMLUtils.getXerces1Version();
if (version != null) {
return version;
}
version = XMLUtils.getXerces2Version();
if (version != null) {
return version;
}
return "Apache Xerces not installed";
// return "Apache " + org.apache.xerces.impl.Version.fVersion;
// return "Apache " + org.apache.xerces.framework.Version.fVersion;
}
/**
* Method getXalan1Version
*
*
*/
private static String getXalan1Version() {
try {
final String XALAN1_VERSION_CLASS =
"org.apache.xalan.xslt.XSLProcessorVersion";
Class clazz = classForName(XALAN1_VERSION_CLASS);
// Found Xalan-J 1.x, grab it's version fields
StringBuffer buf = new StringBuffer();
Field f = clazz.getField("PRODUCT");
buf.append(f.get(null));
buf.append(';');
f = clazz.getField("LANGUAGE");
buf.append(f.get(null));
buf.append(';');
f = clazz.getField("S_VERSION");
buf.append(f.get(null));
buf.append(';');
return buf.toString();
} catch (Exception e1) {
return null;
}
}
/**
* Method getXalan20Version
*
*
*/
private static String getXalan20Version() {
try {
// NOTE: This is the new Xalan 2.2+ version class
final String XALAN2_2_VERSION_CLASS = "org.apache.xalan.Version";
final String XALAN2_2_VERSION_METHOD = "getVersion";
final Class noArgs[] = new Class[0];
Class clazz = classForName(XALAN2_2_VERSION_CLASS);
Method method = clazz.getMethod(XALAN2_2_VERSION_METHOD, noArgs);
Object returnValue = method.invoke(null, new Object[0]);
return (String) returnValue;
} catch (Exception e2) {
return null;
}
}
/**
* Method getXalan2Version
*
*
*/
private static String getXalan2Version() {
try {
// NOTE: This is the old Xalan 2.0, 2.1, 2.2 version class,
// is being replaced by class below
final String XALAN2_VERSION_CLASS =
"org.apache.xalan.processor.XSLProcessorVersion";
Class clazz = classForName(XALAN2_VERSION_CLASS);
// Found Xalan-J 2.x, grab it's version fields
StringBuffer buf = new StringBuffer();
Field f = clazz.getField("S_VERSION");
buf.append(f.get(null));
return buf.toString();
} catch (Exception e2) {
return null;
}
}
/**
* Method getXerces1Version
*
*
*/
private static String getXerces1Version() {
try {
final String XERCES1_VERSION_CLASS =
"org.apache.xerces.framework.Version";
Class clazz = classForName(XERCES1_VERSION_CLASS);
// Found Xerces-J 1.x, grab it's version fields
Field f = clazz.getField("fVersion");
String parserVersion = (String) f.get(null);
return parserVersion;
} catch (Exception e) {
return null;
}
}
/**
* Method getXerces2Version
*
*
*/
private static String getXerces2Version() {
try {
final String XERCES2_VERSION_CLASS = "org.apache.xerces.impl.Version";
Class clazz = classForName(XERCES2_VERSION_CLASS);
// Found Xerces-J 2.x, grab it's version fields
Field f = clazz.getField("fVersion");
String parserVersion = (String) f.get(null);
return parserVersion;
} catch (Exception e) {
return null;
}
}
/**
* Worker method to load a class.
* Factor out loading classes for future use and JDK differences.
* Copied from javax.xml.*.FactoryFinder
* @param className name of class to load from
* an appropriate classLoader
* @return the class asked for
* @throws ClassNotFoundException
*/
protected static Class classForName(String className)
throws ClassNotFoundException {
ClassLoader classLoader = findClassLoader();
if (classLoader == null) {
return Class.forName(className);
} else {
return classLoader.loadClass(className);
}
}
/**
* Worker method to figure out which ClassLoader to use.
* For JDK 1.2 and later use the context ClassLoader.
* Copied from javax.xml.*.FactoryFinder
* @return the appropriate ClassLoader
* @throws ClassNotFoundException
*/
protected static ClassLoader findClassLoader()
throws ClassNotFoundException {
ClassLoader classLoader = null;
Method m = null;
try {
m = Thread.class.getMethod("getContextClassLoader", null);
} catch (NoSuchMethodException e) {
// Assume that we are running JDK 1.1, use the current ClassLoader
return XMLUtils.class.getClassLoader();
}
try {
return (ClassLoader) m.invoke(Thread.currentThread(), null);
} catch (Exception e) {
throw new RuntimeException(e.toString());
}
}
/**
* Method spitOutVersions
*
* @param cat
*/
public static void spitOutVersions(org.apache.log4j.Category cat) {
cat.debug(XMLUtils.getXercesVersion());
cat.debug(XMLUtils.getXalanVersion());
}
/** Field nodeTypeString */
private static String[] nodeTypeString = new String[]{ "", "ELEMENT",
"ATTRIBUTE",
"TEXT_NODE",
"CDATA_SECTION",
"ENTITY_REFERENCE",
"ENTITY",
"PROCESSING_INSTRUCTION",
"COMMENT", "DOCUMENT",
"DOCUMENT_TYPE",
"DOCUMENT_FRAGMENT",
"NOTATION" };
/**
* Transforms <code>org.w3c.dom.Node.XXX_NODE</code> NodeType values into
* Strings.
*
* @param nodeType as taken from the {@link org.w3c.dom.Node#getNodeType} function
* @return the String value.
* @see org.w3c.dom.Node#getNodeType
*/
public static String getNodeTypeString(short nodeType) {
if ((nodeType > 0) && (nodeType < 13)) {
return nodeTypeString[nodeType];
} else {
return "";
}
}
/**
* Method getNodeTypeString
*
* @param n
*
*/
public static String getNodeTypeString(Node n) {
return getNodeTypeString(n.getNodeType());
}
/**
* Returns all ancestor elements of a given node up to the document element
*
* @param ctxNode
*
*/
public static Vector getAncestorElements(Node ctxNode) {
if (ctxNode.getNodeType() != Node.ELEMENT_NODE) {
return null;
}
Vector ancestorVector = new Vector();
Node parent = ctxNode;
while ((parent = parent.getParentNode()) != null
&& (parent.getNodeType() == Node.ELEMENT_NODE)) {
ancestorVector.add(parent);
}
ancestorVector.trimToSize();
return ancestorVector;
}
/**
* Returns all ancestor elements of a given node up to the given root element
*
* @param ctxNode
* @param rootElement
*
*/
public static Vector getAncestorElements(Node ctxNode, Node rootElement) {
Vector ancestorVector = new Vector();
if (ctxNode.getNodeType() != Node.ELEMENT_NODE) {
return ancestorVector;
}
Node parent = ctxNode;
Node parentOfRoot = rootElement.getParentNode();
while ((parent = parent.getParentNode()) != null
&& (parent.getNodeType() == Node.ELEMENT_NODE)
&& (parent != parentOfRoot)) {
ancestorVector.add(parent);
}
ancestorVector.trimToSize();
return ancestorVector;
}
/**
* Method getDirectChildrenElements
*
* @param parentElement
*
*/
public static NodeList getDirectChildrenElements(Element parentElement) {
NodeList allNodes = parentElement.getChildNodes();
HelperNodeList selectedNodes = new HelperNodeList();
for (int i = 0; i < allNodes.getLength(); i++) {
Node currentNode = allNodes.item(i);
if ((currentNode.getNodeType() == Node.ELEMENT_NODE)) {
selectedNodes.appendChild(currentNode);
}
}
return selectedNodes;
}
/**
* Method getDirectChild
*
* @param parentElement
* @param childLocalName
* @param childNamespaceURI
*
*/
public static Element getDirectChild(Element parentElement,
String childLocalName,
String childNamespaceURI) {
NodeList nl = parentElement.getChildNodes();
Vector results = new Vector();
for (int i = 0; i < nl.getLength(); i++) {
Node n = nl.item(i);
if (n.getNodeType() == Node.ELEMENT_NODE) {
if (((Element) n).getLocalName().equals(childLocalName)
&& ((Element) n).getNamespaceURI().equals(
childNamespaceURI)) {
results.add(n);
}
}
}
if (results.size() != 1) {
return null;
}
return (Element) results.elementAt(0);
}
/**
* Outputs a DOM tree to a file.
*
* @param contextNode root node of the DOM tree
* @param filename the file name
* @throws java.io.FileNotFoundException
*/
public static void outputDOM(Node contextNode, String filename)
throws java.io.FileNotFoundException {
OutputStream os = new FileOutputStream(filename);
XMLUtils.outputDOM(contextNode, os);
}
/**
* Outputs a DOM tree to an {@link OutputStream}.
*
* @param contextNode root node of the DOM tree
* @param os the {@link OutputStream}
*/
public static void outputDOM(Node contextNode, OutputStream os) {
XMLUtils.outputDOM(contextNode, os, false);
}
/**
* Outputs a DOM tree to an {@link OutputStream}. <I>If an Exception is
* thrown during execution, it's StackTrace is output to System.out, but the
* Exception is not re-thrown.</I>
*
* @param contextNode root node of the DOM tree
* @param os the {@link OutputStream}
* @param addPreamble
*/
public static void outputDOM(Node contextNode, OutputStream os,
boolean addPreamble) {
try {
if (addPreamble) {
os.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".getBytes());
}
os.write(
Canonicalizer.getInstance(
Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS).canonicalizeSubtree(
contextNode));
} catch (IOException ex) {}
catch (InvalidCanonicalizerException ex) {
ex.printStackTrace();
} catch (CanonicalizationException ex) {
ex.printStackTrace();
}
}
/**
* Serializes the <CODE>contextNode</CODE> into the OutputStream, <I>but
* supresses all Exceptions</I>.
* <BR />
* NOTE: <I>This should only be used for debugging purposes,
* NOT in a production environment; this method ignores all exceptions,
* so you won't notice if something goes wrong. If you're asking what is to
* be used in a production environment, simply use the code inside the
* <code>try{}</code> statement, but handle the Exceptions appropriately.</I>
*
* @param contextNode
* @param os
*/
public static void outputDOMc14nWithComments(Node contextNode,
OutputStream os) {
try {
os.write(
Canonicalizer.getInstance(
Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS).canonicalizeSubtree(
contextNode));
} catch (IOException ex) {
// throw new RuntimeException(ex.getMessage());
} catch (InvalidCanonicalizerException ex) {
// throw new RuntimeException(ex.getMessage());
} catch (CanonicalizationException ex) {
// throw new RuntimeException(ex.getMessage());
}
}
/**
* Converts a single {@link Node} into a {@link NodeList} which contains only that {@link Node}
*
* @param node the Node
* @return the NodeList
*/
public static NodeList elementToNodeList(Node node) {
HelperNodeList nl = new HelperNodeList();
nl.appendChild(node);
return (NodeList) nl;
}
/**
* Creates Attributes {@link org.w3c.dom.Attr} in the given namespace
* (if possible). If the namespace is empty, only the QName is used.
*
* @param doc the generator (factory) Document
* @param QName the QName of the Attr
* @param Value the String value of the Attr
* @param NamespaceURI the namespace for the Attr
* @return the Attr
*/
public static Attr createAttr(Document doc, String QName, String Value,
String NamespaceURI) {
Attr attr = doc.createAttributeNS(NamespaceURI, QName);
attr.setNodeValue(Value);
return attr;
}
/**
* Sets the Attribute QName with Value in Element elem.
*
* @param elem the Element which has to contain the Attribute
* @param QName the QName of the Attribute
* @param Value the value of the Attribute
*/
public static void setAttr(Element elem, String QName, String Value) {
Document doc = elem.getOwnerDocument();
Attr attr = doc.createAttributeNS(Constants.SignatureSpecNS, QName);
attr.setNodeValue(Value);
elem.setAttributeNode(attr);
}
public static Element createElementFromBigint(Document doc, String elementName, BigInteger bigInteger)
throws XMLSignatureException {
Element element = doc.createElementNS(Constants.SignatureSpecNS,
Constants.getSignatureSpecNSprefix()
+ ":" + elementName);
/* bigInteger must be positive */
if (bigInteger.signum() != 1) {
throw new XMLSignatureException("signature.Util.BignumNonPositive");
}
byte byteRepresentation[] = bigInteger.toByteArray();
while (byteRepresentation[0] == 0) {
byte oldByteRepresentation[] = byteRepresentation;
byteRepresentation = new byte[oldByteRepresentation.length - 1];
System.arraycopy(oldByteRepresentation, 1, byteRepresentation, 0,
oldByteRepresentation.length - 1);
}
Text text = doc.createTextNode(
org.apache.xml.security.utils.Base64.encode(byteRepresentation));
element.appendChild(text);
return element;
}
/**
* Method getFullTextChildrenFromElement
*
* @param element
*
*/
public static String getFullTextChildrenFromElement(Element element) {
StringBuffer sb = new StringBuffer();
NodeList children = element.getChildNodes();
int iMax = children.getLength();
for (int i = 0; i < iMax; i++) {
Node curr = children.item(i);
if (curr.getNodeType() == Node.TEXT_NODE) {
sb.append(((Text) curr).getData());
}
}
return sb.toString();
}
/**
* Fetches a base64-encoded BigInteger from an Element.
*
* @param element the Element
* @return the BigInteger
* @throws XMLSignatureException if Element has not exactly one Text child
*/
public static BigInteger getBigintFromElement(Element element)
throws XMLSignatureException {
try {
if (element.getChildNodes().getLength() != 1) {
throw new XMLSignatureException("signature.Util.TooManyChilds");
}
Node child = element.getFirstChild();
if ((child == null) || (child.getNodeType() != Node.TEXT_NODE)) {
throw new XMLSignatureException("signature.Util.NonTextNode");
}
Text text = (Text) child;
String textData = text.getData();
byte magnitude[] =
org.apache.xml.security.utils.Base64.decode(textData);
int signum = 1;
BigInteger bigInteger = new BigInteger(signum, magnitude);
return bigInteger;
} catch (Base64DecodingException ex) {
throw new XMLSignatureException("empty", ex);
}
}
/**
* Fetches base64-encoded byte[] data from an Element.
*
* @param element
* @return the byte[] data
* @throws XMLSignatureException if Element has not exactly one Text child
*/
public static byte[] getBytesFromElement(Element element)
throws XMLSignatureException {
try {
if (element.getChildNodes().getLength() != 1) {
throw new XMLSignatureException("signature.Util.TooManyChilds");
}
Node child = element.getFirstChild();
if ((child == null) || (child.getNodeType() != Node.TEXT_NODE)) {
throw new XMLSignatureException("signature.Util.NonTextNode");
}
Text text = (Text) child;
String textData = text.getData();
byte bytes[] = org.apache.xml.security.utils.Base64.decode(textData);
return bytes;
} catch (Base64DecodingException ex) {
throw new XMLSignatureException("empty", ex);
}
}
/**
* Creates an Element in the XML Signature specification namespace.
*
* @param doc the factory Document
* @param elementName the local name of the Element
* @return the Element
*/
public static Element createElementInSignatureSpace(Document doc,
String elementName) {
if (doc == null) {
throw new RuntimeException("Document is null");
}
String ds = Constants.getSignatureSpecNSprefix();
if ((ds == null) || (ds.length() == 0)) {
Element element = doc.createElementNS(Constants.SignatureSpecNS,
elementName);
element.setAttributeNS(Constants.NamespaceSpecNS, "xmlns",
Constants.SignatureSpecNS);
return element;
} else {
Element element = doc.createElementNS(Constants.SignatureSpecNS,
ds + ":" + elementName);
element.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:" + ds,
Constants.SignatureSpecNS);
return element;
}
}
/**
* Creates an Element in the XML Encryption specification namespace.
*
* @param doc the factory Document
* @param elementName the local name of the Element
* @return the Element
*/
public static Element createElementInEncryptionSpace(Document doc,
String elementName) {
if (doc == null) {
throw new RuntimeException("Document is null");
}
String xenc = EncryptionConstants.getEncryptionSpecNSprefix();
if ((xenc == null) || (xenc.length() == 0)) {
Element element =
doc.createElementNS(EncryptionConstants.EncryptionSpecNS,
elementName);
element.setAttributeNS(Constants.NamespaceSpecNS, "xmlns",
Constants.SignatureSpecNS);
return element;
} else {
Element element =
doc.createElementNS(EncryptionConstants.EncryptionSpecNS,
xenc + ":" + elementName);
element.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:" + xenc,
EncryptionConstants.EncryptionSpecNS);
return element;
}
}
/**
* Returns true if the element is in XML Signature namespace and the local
* name equals the supplied one.
*
* @param element
* @param localName
* @return true if the element is in XML Signature namespace and the local name equals the supplied one
*/
public static boolean elementIsInSignatureSpace(Element element,
String localName) {
if (element == null) {
return false;
}
if (element.getNamespaceURI() == null) {
return false;
}
if (!element.getNamespaceURI().equals(Constants.SignatureSpecNS)) {
return false;
}
if (!element.getLocalName().equals(localName)) {
return false;
}
return true;
}
/**
* Returns true if the element is in XML Encryption namespace and the local
* name equals the supplied one.
*
* @param element
* @param localName
* @return true if the element is in XML Encryption namespace and the local name equals the supplied one
*/
public static boolean elementIsInEncryptionSpace(Element element,
String localName) {
if (element == null) {
return false;
}
if (element.getNamespaceURI() == null) {
return false;
}
if (!element.getNamespaceURI().equals(
EncryptionConstants.EncryptionSpecNS)) {
return false;
}
if (!element.getLocalName().equals(localName)) {
return false;
}
return true;
}
/**
* Verifies that the given Element is in the XML Signature namespace
* {@link org.apache.xml.security.utils.Constants#SignatureSpecNS} and that the
* local name of the Element matches the supplied on.
*
* @param element Element to be checked
* @param localName
* @throws XMLSignatureException if element is not in Signature namespace or if the local name does not match
* @see org.apache.xml.security.utils.Constants#SignatureSpecNS
*/
public static void guaranteeThatElementInSignatureSpace(Element element, String localName)
throws XMLSignatureException {
/*
cat.debug("guaranteeThatElementInSignatureSpace(" + element + ", "
+ localName + ")");
*/
if (element == null) {
Object exArgs[] = { localName, null };
throw new XMLSignatureException("xml.WrongElement", exArgs);
}
if ((localName == null) || localName.equals("")
||!elementIsInSignatureSpace(element, localName)) {
Object exArgs[] = { localName, element.getLocalName() };
throw new XMLSignatureException("xml.WrongElement", exArgs);
}
}
/**
* Verifies that the given Element is in the XML Encryption namespace
* {@link org.apache.xml.security.utils.EncryptionConstants#EncryptionSpecNS} and that the
* local name of the Element matches the supplied on.
*
* @param element Element to be checked
* @param localName
* @throws XMLSecurityException if element is not in Encryption namespace or if the local name does not match
* @see org.apache.xml.security.utils.EncryptionConstants#EncryptionSpecNS
*/
public static void guaranteeThatElementInEncryptionSpace(Element element, String localName)
throws XMLSecurityException {
if (element == null) {
Object exArgs[] = { localName, null };
throw new XMLSecurityException("xml.WrongElement", exArgs);
}
if ((localName == null) || localName.equals("")
||!elementIsInEncryptionSpace(element, localName)) {
Object exArgs[] = { localName, element.getLocalName() };
throw new XMLSecurityException("xml.WrongElement", exArgs);
}
}
/**
* This method returns the owner document of a particular node.
* This method is necessary because it <I>always</I> returns a
* {@link Document}. {@link Node#getOwnerDocument} returns <CODE>null</CODE>
* if the {@link Node} is a {@link Document}.
*
* @param node
* @return the owner document of the node
*/
public static Document getOwnerDocument(Node node) {
if (node.getNodeType() == Node.DOCUMENT_NODE) {
return (Document) node;
} else {
try {
return node.getOwnerDocument();
} catch (NullPointerException npe) {
throw new NullPointerException(I18n.translate("endorsed.jdk1.4.0")
+ " Original message was \""
+ npe.getMessage() + "\"");
}
}
}
/** Field randomNS */
private static String randomNS = null;
/**
* Prefix for random namespaces.
*
* @see #getRandomNamespacePrefix
*/
public static final String randomNSprefix =
"http://www.xmlsecurity.org/NS#randomval";
public static String getRandomNamespacePrefix() {
if (XMLUtils.randomNS == null) {
byte[] randomData = new byte[21];
java.security.SecureRandom sr = new java.security.SecureRandom();
sr.nextBytes(randomData);
String prefix =
"xmlsecurityOrgPref"
+ org.apache.xml.security.utils.Base64.encode(randomData);
XMLUtils.randomNS = "";
for (int i = 0; i < prefix.length(); i++) {
if ((prefix.charAt(i) != '+') && (prefix.charAt(i) != '/')
&& (prefix.charAt(i) != '=')) {
XMLUtils.randomNS += prefix.charAt(i);
}
}
}
return XMLUtils.randomNS;
}
/**
* Method createDSctx
*
* @param doc
* @param prefix
* @param namespace
*
*/
public static Element createDSctx(Document doc, String prefix,
String namespace) {
if ((prefix == null) || (prefix.trim().length() == 0)) {
throw new IllegalArgumentException("You must supply a prefix");
}
Element ctx = doc.createElementNS(null, "namespaceContext");
ctx.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:" + prefix.trim(),
namespace);
return ctx;
}
/**
* Method createDSctx
*
* @param doc
* @param prefix
*
*/
public static Element createDSctx(Document doc, String prefix) {
return XMLUtils.createDSctx(doc, prefix, Constants.SignatureSpecNS);
}
/**
* Method addReturnToElement
*
* @param elementProxy
*/
public static void addReturnToElement(ElementProxy elementProxy) {
Document doc = elementProxy._doc;
elementProxy.getElement().appendChild(doc.createTextNode("\n"));
}
/**
* Method addReturnToElement
*
* @param e
*/
public static void addReturnToElement(Element e) {
Document doc = e.getOwnerDocument();
e.appendChild(doc.createTextNode("\n"));
}
/**
* Method addReturnToNode
*
* @param n
*/
public static void addReturnToNode(Node n) {
Document doc = n.getOwnerDocument();
n.appendChild(doc.createTextNode("\n"));
}
/**
* Method convertNodelistToSet
*
* @param xpathNodeSet
*
*/
public static Set convertNodelistToSet(NodeList xpathNodeSet) {
if (xpathNodeSet == null) {
return new HashSet();
}
int length = xpathNodeSet.getLength();
Set set = new HashSet(length);
for (int i = 0; i < length; i++) {
set.add(xpathNodeSet.item(i));
}
return set;
}
/**
* Method convertSetToNodelist
*
* @param set
*
*/
public static NodeList convertSetToNodelist(Set set) {
HelperNodeList result = new HelperNodeList();
Iterator it = set.iterator();
while (it.hasNext()) {
result.appendChild((Node) it.next());
}
return result;
}
public static void circumventBug2650(Document doc) {
Element documentElement = doc.getDocumentElement();
// if the document element has no xmlns definition, we add xmlns=""
Attr xmlnsAttr =
documentElement.getAttributeNodeNS(Constants.NamespaceSpecNS, "xmlns");
if (xmlnsAttr == null) {
documentElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", "");
}
XMLUtils.circumventBug2650recurse(doc);
}
private static void circumventBug2650recurse(Node node) {
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
NamedNodeMap attributes = element.getAttributes();
int attributesLength = attributes.getLength();
NodeList children = element.getChildNodes();
int childrenLength = children.getLength();
for (int j = 0; j < childrenLength; j++) {
Node child = children.item(j);
if (child.getNodeType() == Node.ELEMENT_NODE) {
Element childElement = (Element) child;
for (int i = 0; i < attributesLength; i++) {
Attr currentAttr = (Attr) attributes.item(i);
boolean isNamespace = Constants.NamespaceSpecNS.equals(
currentAttr.getNamespaceURI());
if (isNamespace) {
boolean mustBeDefinedInChild =
!childElement.hasAttributeNS(
Constants.NamespaceSpecNS,
currentAttr.getLocalName());
if (mustBeDefinedInChild) {
childElement.setAttributeNS(Constants.NamespaceSpecNS,
currentAttr.getName(),
currentAttr.getNodeValue());
}
}
}
}
}
}
for (Node child = node.getFirstChild(); child != null;
child = child.getNextSibling()) {
switch (child.getNodeType()) {
case Node.ELEMENT_NODE :
case Node.ENTITY_REFERENCE_NODE :
case Node.DOCUMENT_NODE :
circumventBug2650recurse(child);
}
}
}
/**
* Method getXPath
*
* @param n
* @param result
*
*/
private static String getXPath(Node n, String result) {
if (n == null) {
return result;
}
switch (n.getNodeType()) {
case Node.ATTRIBUTE_NODE :
return getXPath(((Attr) n).getOwnerElement(),
"/@" + ((Attr) n).getNodeName() + "=\""
+ ((Attr) n).getNodeValue() + "\"");
case Node.ELEMENT_NODE :
return getXPath(n.getParentNode(),
"/" + ((Element) n).getTagName() + result);
case Node.TEXT_NODE :
return getXPath(n.getParentNode(), "/#text");
case Node.DOCUMENT_NODE :
if (result.length() > 0) {
return result;
} else {
return "/";
}
}
return result;
}
/**
* Simple tool to return the position of a particular node in an XPath like String.
*
* @param n
*
*/
public static String getXPath(Node n) {
return getXPath(n, "");
}
} |
package org.owasp.dependencycheck.utils;
import java.io.File;
import org.owasp.dependencycheck.utils.Settings;
import org.owasp.dependencycheck.utils.Downloader;
import java.net.URL;
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 Jeremy Long (jeremy.long@owasp.org)
*/
public class DownloaderIntegrationTest {
@BeforeClass
public static void setUpClass() throws Exception {
}
@AfterClass
public static void tearDownClass() throws Exception {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
/**
* Test of fetchFile method, of class Downloader.
*
* @throws Exception thrown when an exception occurs.
*/
@Test
public void testFetchFile() throws Exception {
// Settings.setString(Settings.KEYS.CONNECTION_TIMEOUT, "1000");
// Settings.setString(Settings.KEYS.PROXY_PORT, "8080");
// Settings.setString(Settings.KEYS.PROXY_URL, "127.0.0.1");
// Removed as the actual CPE is no longer used.
// URL url = new URL(Settings.getString(Settings.KEYS.CPE_URL));
// String outputPath = "target/downloaded_cpe.xml";
// Downloader.fetchFile(url, outputPath, true);
URL url = new URL(Settings.getString(Settings.KEYS.CVE_MODIFIED_20_URL));
File outputPath = new File("target/downloaded_cve.xml");
Downloader.fetchFile(url, outputPath);
}
@Test
public void testGetLastModified() throws Exception {
URL url = new URL("http://nvd.nist.gov/download/nvdcve-2012.xml");
long timestamp = Downloader.getLastModified(url);
assertTrue("timestamp equal to zero?", timestamp > 0);
}
@Test
public void testGetLastModified_file() throws Exception {
File f = new File("target/test-classes/nvdcve-2.0-2012.xml");
URL url = new URL("file://" + f.getCanonicalPath());
long timestamp = Downloader.getLastModified(url);
assertTrue("timestamp equal to zero?", timestamp > 0);
}
} |
package com.gosimple.jpgagent;
import org.postgresql.ds.PGSimpleDataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public enum Database
{
INSTANCE;
private final PGSimpleDataSource data_source;
private int pid;
private Connection main_connection;
private Connection listener_connection;
private Database()
{
data_source = new PGSimpleDataSource();
data_source.setServerName(Config.INSTANCE.db_host);
data_source.setPortNumber(Config.INSTANCE.db_port);
data_source.setDatabaseName(Config.INSTANCE.db_database);
data_source.setUser(Config.INSTANCE.db_user);
data_source.setPassword(Config.INSTANCE.db_password);
data_source.setApplicationName("jpgAgent: " + Config.INSTANCE.hostname);
}
/**
* Returns the main connection used for all jpgAgent upkeep.
*
* @return
*/
public Connection getMainConnection()
{
if (main_connection == null)
{
resetMainConnection();
}
return main_connection;
}
/**
* Closes existing connection if necessary, and creates a new connection.
*/
public void resetMainConnection()
{
try
{
if (main_connection != null)
{
main_connection.close();
}
main_connection = Database.INSTANCE.getConnection(Config.INSTANCE.db_database);
String pid_sql = "SELECT pg_backend_pid();";
try (Statement statement = main_connection.createStatement())
{
try (ResultSet result = statement.executeQuery(pid_sql))
{
while (result.next())
{
pid = result.getInt("pg_backend_pid");
}
}
}
}
catch (final SQLException e)
{
Config.INSTANCE.logger.error(e.getMessage());
main_connection = null;
}
}
/**
* Returns the main connection used for all jpgAgent upkeep.
*
* @return
*/
public Connection getListenerConnection()
{
if (listener_connection == null)
{
resetListenerConnection();
}
return listener_connection;
}
/**
* Closes existing connection if necessary, and creates a new connection.
*/
public void resetListenerConnection()
{
try
{
if (listener_connection != null)
{
listener_connection.close();
}
listener_connection = Database.INSTANCE.getConnection(Config.INSTANCE.db_database);
String listen_sql = "LISTEN jpgagent_kill_job;";
try (Statement statement = listener_connection.createStatement())
{
statement.execute(listen_sql);
}
}
catch (final SQLException e)
{
Config.INSTANCE.logger.error(e.getMessage());
listener_connection = null;
}
}
/**
* Returns the pid of the main connection for jpgAgent.
*
* @return
*/
public int getPid()
{
return pid;
}
/**
* Returns a connection to the specified database with autocommit on.
*
* @param database
* @return
* @throws SQLException
*/
public synchronized Connection getConnection(final String database) throws SQLException
{
data_source.setDatabaseName(database);
return data_source.getConnection();
}
} |
import java.util.Arrays;
import static org.junit.Assert.*;
import org.junit.Test;
public class MakePiTest {
/*
* Testing makePi
*/
@Test
public void testMakePi() {
int[] x = { 3, 1, 4 };
int[] studentAnswer = Hw2pr8.makePi();
assertTrue(Arrays.equals(x, studentAnswer));
}
@Test
public void testMakePiFalse() {
int[] x = { 1, 2, 3 };
int[] studentAnswer = Hw2pr8.makePi();
assertFalse(Arrays.equals(x, studentAnswer));
}
} |
package org.bouncycastle.cms;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.ASN1Null;
import org.bouncycastle.asn1.ASN1OctetString;
import org.bouncycastle.asn1.ASN1OutputStream;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.ASN1Set;
import org.bouncycastle.asn1.DEREncodable;
import org.bouncycastle.asn1.DERNull;
import org.bouncycastle.asn1.DERObject;
import org.bouncycastle.asn1.DERObjectIdentifier;
import org.bouncycastle.asn1.DEROutputStream;
import org.bouncycastle.asn1.DERSet;
import org.bouncycastle.asn1.DERTags;
import org.bouncycastle.asn1.cms.Attribute;
import org.bouncycastle.asn1.cms.AttributeTable;
import org.bouncycastle.asn1.cms.CMSAttributes;
import org.bouncycastle.asn1.cms.IssuerAndSerialNumber;
import org.bouncycastle.asn1.cms.SignerIdentifier;
import org.bouncycastle.asn1.cms.SignerInfo;
import org.bouncycastle.asn1.cms.Time;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.asn1.x509.DigestInfo;
import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PublicKey;
import java.security.Signature;
import java.security.SignatureException;
import java.security.cert.CertificateExpiredException;
import java.security.cert.CertificateNotYetValidException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
/**
* an expanded SignerInfo block from a CMS Signed message
*/
public class SignerInformation
{
private SignerId sid;
private SignerInfo info;
private AlgorithmIdentifier digestAlgorithm;
private AlgorithmIdentifier encryptionAlgorithm;
private ASN1Set signedAttributes;
private ASN1Set unsignedAttributes;
private CMSProcessable content;
private byte[] signature;
private DERObjectIdentifier contentType;
private DigestCalculator digestCalculator;
private byte[] resultDigest;
SignerInformation(
SignerInfo info,
DERObjectIdentifier contentType,
CMSProcessable content,
DigestCalculator digestCalculator)
{
this.info = info;
this.sid = new SignerId();
this.contentType = contentType;
try
{
SignerIdentifier s = info.getSID();
if (s.isTagged())
{
ASN1OctetString octs = ASN1OctetString.getInstance(s.getId());
sid.setSubjectKeyIdentifier(octs.getOctets());
}
else
{
IssuerAndSerialNumber iAnds = IssuerAndSerialNumber.getInstance(s.getId());
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
ASN1OutputStream aOut = new ASN1OutputStream(bOut);
aOut.writeObject(iAnds.getName());
sid.setIssuer(bOut.toByteArray());
sid.setSerialNumber(iAnds.getSerialNumber().getValue());
}
}
catch (IOException e)
{
throw new IllegalArgumentException("invalid sid in SignerInfo");
}
this.digestAlgorithm = info.getDigestAlgorithm();
this.signedAttributes = info.getAuthenticatedAttributes();
this.unsignedAttributes = info.getUnauthenticatedAttributes();
this.encryptionAlgorithm = info.getDigestEncryptionAlgorithm();
this.signature = info.getEncryptedDigest().getOctets();
this.content = content;
this.digestCalculator = digestCalculator;
}
private byte[] encodeObj(
DEREncodable obj)
throws IOException
{
if (obj != null)
{
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
ASN1OutputStream aOut = new ASN1OutputStream(bOut);
aOut.writeObject(obj);
return bOut.toByteArray();
}
return null;
}
public SignerId getSID()
{
return sid;
}
/**
* return the version number for this objects underlying SignerInfo structure.
*/
public int getVersion()
{
return info.getVersion().getValue().intValue();
}
/**
* return the object identifier for the signature.
*/
public String getDigestAlgOID()
{
return digestAlgorithm.getObjectId().getId();
}
/**
* return the signature parameters, or null if there aren't any.
*/
public byte[] getDigestAlgParams()
{
try
{
return encodeObj(digestAlgorithm.getParameters());
}
catch (Exception e)
{
throw new RuntimeException("exception getting digest parameters " + e);
}
}
/**
* return the content digest that was calculated during verification.
*/
public byte[] getContentDigest()
{
if (resultDigest == null)
{
throw new IllegalStateException("method can only be called after verify.");
}
return (byte[])resultDigest.clone();
}
/**
* return the object identifier for the signature.
*/
public String getEncryptionAlgOID()
{
return encryptionAlgorithm.getObjectId().getId();
}
/**
* return the signature/encyrption algorithm parameters, or null if
* there aren't any.
*/
public byte[] getEncryptionAlgParams()
{
try
{
return encodeObj(encryptionAlgorithm.getParameters());
}
catch (Exception e)
{
throw new RuntimeException("exception getting encryption parameters " + e);
}
}
/**
* return a table of the signed attributes - indexed by
* the OID of the attribute.
*/
public AttributeTable getSignedAttributes()
{
if (signedAttributes == null)
{
return null;
}
return new AttributeTable(signedAttributes);
}
/**
* return a table of the unsigned attributes indexed by
* the OID of the attribute.
*/
public AttributeTable getUnsignedAttributes()
{
if (unsignedAttributes == null)
{
return null;
}
return new AttributeTable(unsignedAttributes);
}
/**
* return the encoded signature
*/
public byte[] getSignature()
{
return (byte[])signature.clone();
}
/**
* Return a SignerInformationStore containing the counter signatures attached to this
* signer. If no counter signatures are present an empty store is returned.
*/
public SignerInformationStore getCounterSignatures()
{
AttributeTable unsignedAttributeTable = getUnsignedAttributes();
if (unsignedAttributeTable == null)
{
return new SignerInformationStore(new ArrayList(0));
}
List counterSignatures = new ArrayList();
Attribute counterSignatureAttribute = unsignedAttributeTable.get(CMSAttributes.counterSignature);
if (counterSignatureAttribute != null)
{
ASN1Set values = counterSignatureAttribute.getAttrValues();
counterSignatures = new ArrayList(values.size());
for (Enumeration en = values.getObjects(); en.hasMoreElements();)
{
SignerInfo si = SignerInfo.getInstance(en.nextElement());
String digestName = CMSSignedHelper.INSTANCE.getDigestAlgName(si.getDigestAlgorithm().getObjectId().getId());
counterSignatures.add(new SignerInformation(si, CMSAttributes.counterSignature, null, new CounterSignatureDigestCalculator(digestName, null, getSignature())));
}
}
return new SignerInformationStore(counterSignatures);
}
/**
* return the DER encoding of the signed attributes.
* @throws IOException if an encoding error occurs.
*/
public byte[] getEncodedSignedAttributes()
throws IOException
{
if (signedAttributes != null)
{
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
DEROutputStream aOut = new DEROutputStream(bOut);
aOut.writeObject(signedAttributes);
return bOut.toByteArray();
}
return null;
}
private boolean doVerify(
PublicKey key,
AttributeTable signedAttrTable,
String sigProvider)
throws CMSException, NoSuchAlgorithmException, NoSuchProviderException
{
String digestName = CMSSignedHelper.INSTANCE.getDigestAlgName(this.getDigestAlgOID());
String signatureName = digestName + "with" + CMSSignedHelper.INSTANCE.getEncryptionAlgName(this.getEncryptionAlgOID());
Signature sig = CMSSignedHelper.INSTANCE.getSignatureInstance(signatureName, sigProvider);
MessageDigest digest = CMSSignedHelper.INSTANCE.getDigestInstance(digestName, sigProvider);
try
{
sig.initVerify(key);
if (signedAttributes == null)
{
if (content != null)
{
content.write(
new CMSSignedDataGenerator.SigOutputStream(sig));
content.write(
new CMSSignedDataGenerator.DigOutputStream(digest));
resultDigest = digest.digest();
}
else
{
resultDigest = digestCalculator.getDigest();
// need to decrypt signature and check message bytes
return verifyDigest(resultDigest, key, this.getSignature(), sigProvider);
}
}
else
{
byte[] hash;
if (content != null)
{
content.write(
new CMSSignedDataGenerator.DigOutputStream(digest));
hash = digest.digest();
}
else if (digestCalculator != null)
{
hash = digestCalculator.getDigest();
}
else
{
hash = null;
}
resultDigest = hash;
Attribute dig = signedAttrTable.get(
CMSAttributes.messageDigest);
Attribute type = signedAttrTable.get(
CMSAttributes.contentType);
if (dig == null)
{
throw new SignatureException("no hash for content found in signed attributes");
}
if (type == null && !contentType.equals(CMSAttributes.counterSignature))
{
throw new SignatureException("no content type id found in signed attributes");
}
DERObject hashObj = dig.getAttrValues().getObjectAt(0).getDERObject();
if (hashObj instanceof ASN1OctetString)
{
byte[] signedHash = ((ASN1OctetString)hashObj).getOctets();
if (!MessageDigest.isEqual(hash, signedHash))
{
throw new SignatureException("content hash found in signed attributes different");
}
}
else if (hashObj instanceof DERNull)
{
if (hash != null)
{
throw new SignatureException("NULL hash found in signed attributes when one expected");
}
}
if (type != null)
{
DERObjectIdentifier typeOID = (DERObjectIdentifier)type.getAttrValues().getObjectAt(0);
if (!typeOID.equals(contentType))
{
throw new SignatureException("contentType in signed attributes different");
}
}
sig.update(this.getEncodedSignedAttributes());
}
return sig.verify(this.getSignature());
}
catch (InvalidKeyException e)
{
throw new CMSException(
"key not appropriate to signature in message.", e);
}
catch (IOException e)
{
throw new CMSException(
"can't process mime object to create signature.", e);
}
catch (SignatureException e)
{
throw new CMSException(
"invalid signature format in message: " + e.getMessage(), e);
}
}
private boolean isNull(
DEREncodable o)
{
return (o instanceof ASN1Null) || (o == null);
}
private DigestInfo derDecode(
byte[] encoding)
throws IOException, CMSException
{
if (encoding[0] != (DERTags.CONSTRUCTED | DERTags.SEQUENCE))
{
throw new IOException("not a digest info object");
}
ASN1InputStream aIn = new ASN1InputStream(encoding);
DigestInfo digInfo = new DigestInfo((ASN1Sequence)aIn.readObject());
// length check to avoid Bleichenbacher vulnerability
if (digInfo.getEncoded().length != encoding.length)
{
throw new CMSException("malformed RSA signature");
}
return digInfo;
}
private boolean verifyDigest(
byte[] digest,
PublicKey key,
byte[] signature,
String sigProvider)
throws NoSuchAlgorithmException, NoSuchProviderException, CMSException
{
String algorithm = CMSSignedHelper.INSTANCE.getEncryptionAlgName(this.getEncryptionAlgOID());
try
{
if (algorithm.equals("RSA"))
{
Cipher c;
if (sigProvider != null)
{
c = Cipher.getInstance("RSA/ECB/PKCS1Padding", sigProvider);
}
else
{
c = Cipher.getInstance("RSA/ECB/PKCS1Padding");
}
c.init(Cipher.DECRYPT_MODE, key);
DigestInfo digInfo = derDecode(c.doFinal(signature));
if (!digInfo.getAlgorithmId().getObjectId().equals(digestAlgorithm.getObjectId()))
{
return false;
}
if (!isNull(digInfo.getAlgorithmId().getParameters()))
{
return false;
}
byte[] sigHash = digInfo.getDigest();
return MessageDigest.isEqual(digest, sigHash);
}
else if (algorithm.equals("DSA"))
{
Signature sig;
if (sigProvider != null)
{
sig = Signature.getInstance("NONEwithDSA", sigProvider);
}
else
{
sig = Signature.getInstance("NONEwithDSA", sigProvider);
}
sig.initVerify(key);
sig.update(digest);
return sig.verify(signature);
}
else
{
throw new CMSException("algorithm: " + algorithm + " not supported in base signatures.");
}
}
catch (NoSuchAlgorithmException e)
{
throw e;
}
catch (NoSuchProviderException e)
{
throw e;
}
catch (GeneralSecurityException e)
{
throw new CMSException("Exception processing signature: " + e, e);
}
catch (IOException e)
{
throw new CMSException("Exception decoding signature: " + e, e);
}
}
/**
* verify that the given public key succesfully handles and confirms the
* signature associated with this signer.
*/
public boolean verify(
PublicKey key,
String sigProvider)
throws NoSuchAlgorithmException, NoSuchProviderException, CMSException
{
return doVerify(key, this.getSignedAttributes(), sigProvider);
}
/**
* verify that the given certificate succesfully handles and confirms
* the signature associated with this signer and, if a signingTime
* attribute is available, that the certificate was valid at the time the
* signature was generated.
*/
public boolean verify(
X509Certificate cert,
String sigProvider)
throws NoSuchAlgorithmException, NoSuchProviderException,
CertificateExpiredException, CertificateNotYetValidException,
CMSException
{
AttributeTable attr = this.getSignedAttributes();
if (attr != null)
{
Attribute t = attr.get(CMSAttributes.signingTime);
if (t != null)
{
Time time = Time.getInstance(
t.getAttrValues().getObjectAt(0).getDERObject());
cert.checkValidity(time.getDate());
}
}
return doVerify(cert.getPublicKey(), attr, sigProvider);
}
/**
* Return the base ASN.1 CMS structure that this object contains.
*
* @return an object containing a CMS SignerInfo structure.
*/
public SignerInfo toSignerInfo()
{
return info;
}
/**
* Return a signer information object with the passed in unsigned
* attributes replacing the ones that are current associated with
* the object passed in.
*
* @param signerInformation the signerInfo to be used as the basis.
* @param unsignedAttributes the unsigned attributes to add.
* @return a copy of the original SignerInformationObject with the changed attributes.
*/
public static SignerInformation replaceUnsignedAttributes(
SignerInformation signerInformation,
AttributeTable unsignedAttributes)
{
SignerInfo sInfo = signerInformation.info;
ASN1Set unsignedAttr = null;
if (unsignedAttributes != null)
{
unsignedAttr = new DERSet(unsignedAttributes.toASN1EncodableVector());
}
return new SignerInformation(
new SignerInfo(sInfo.getSID(), sInfo.getDigestAlgorithm(),
sInfo.getAuthenticatedAttributes(), sInfo.getDigestEncryptionAlgorithm(), sInfo.getEncryptedDigest(), unsignedAttr),
signerInformation.contentType, signerInformation.content, null);
}
/**
* Return a signer information object with passed in SignerInformationStore representing counter
* signatures attached as an unsigned attribute.
*
* @param signerInformation the signerInfo to be used as the basis.
* @param counterSigners signer info objects carrying counter signature.
* @return a copy of the original SignerInformationObject with the changed attributes.
*/
public static SignerInformation addCounterSigners(
SignerInformation signerInformation,
SignerInformationStore counterSigners)
{
SignerInfo sInfo = signerInformation.info;
AttributeTable unsignedAttr = signerInformation.getUnsignedAttributes();
ASN1EncodableVector v;
if (unsignedAttr != null)
{
v = unsignedAttr.toASN1EncodableVector();
}
else
{
v = new ASN1EncodableVector();
}
ASN1EncodableVector sigs = new ASN1EncodableVector();
for (Iterator it = counterSigners.getSigners().iterator(); it.hasNext();)
{
sigs.add(((SignerInformation)it.next()).toSignerInfo());
}
v.add(new Attribute(CMSAttributes.counterSignature, new DERSet(sigs)));
return new SignerInformation(
new SignerInfo(sInfo.getSID(), sInfo.getDigestAlgorithm(),
sInfo.getAuthenticatedAttributes(), sInfo.getDigestEncryptionAlgorithm(), sInfo.getEncryptedDigest(), new DERSet(v)),
signerInformation.contentType, signerInformation.content, null);
}
} |
package com.timepath.hl2;
import com.timepath.steam.io.VDF;
import com.timepath.steam.io.VDFNode;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @author TimePath
*/
class VDFDiffTest extends JFrame {
private static final Logger LOG = Logger.getLogger(VDFDiffTest.class.getName());
private JTextArea text1, text2;
private VDFDiffTest() {
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setLayout(new BorderLayout());
add(new JSplitPane() {{
setResizeWeight(.5);
setLeftComponent(new JScrollPane(text1 = new JTextArea() {{
setTabSize(4);
setText("\"A\" {\n" +
"\t\"Modified\" {\n" +
"\t\t\"Same\"\t\"yes\"\n" +
"\t\t\"Similar\"\t\"one\"\n" +
"\t\t\"Removed\"\t\"yes\"\n" +
"\t}\n" +
"\t\"Removed\" {}\n" +
"\t\"Same\" {}\n" +
"}\n");
}}));
setRightComponent(new JScrollPane(text2 = new JTextArea() {{
setTabSize(4);
setText("\"B\" {\n" +
"\t\"Modified\" {\n" +
"\t\t\"Same\"\t\"yes\"\n" +
"\t\t\"Similar\"\t\"two\"\n" +
"\t\t\"Added\"\t\"yes\"\n" +
"\t}\n" +
"\t\"New\" {}\n" +
"\t\"Same\" {}\n" +
"}\n");
}}));
}});
add(new JButton("Diff") {{
addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
try {
VDFNode n1 = VDF.load(new ByteArrayInputStream(text1.getText().getBytes(StandardCharsets.UTF_8)));
VDFNode n2 = VDF.load(new ByteArrayInputStream(text2.getText().getBytes(StandardCharsets.UTF_8)));
n1.getNodes().get(0).rdiff2(n2.getNodes().get(0));
} catch(IOException ex) {
LOG.log(Level.SEVERE, null, ex);
}
}
});
}}, BorderLayout.SOUTH);
pack();
setLocationRelativeTo(null);
}
public static void main(String... args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new VDFDiffTest().setVisible(true);
}
});
}
} |
package com.algorithms.tree;
import com.algorithms.tree.RedBlackBST.Node;
/**
* 2-3-4tree
* @author altro
*
*/
public class LeftLeaningRedBlackTree <K extends Comparable<K>, V>/* implements Map<K, V>*/{
public static void main(String[] args) {
LeftLeaningRedBlackTree<Integer, Integer> tree = new LeftLeaningRedBlackTree<>();
tree.put(10, 10);
tree.put(7, 7);
tree.put(6, 6);
tree.put(8, 8);
tree.put(11, 11);
tree.put(15, 15);
tree.put(17, 17);
tree.put(0, 0);
tree.put(4, 4);
tree.put(19, 19);
System.out.println("tree.get(10) + " + tree.get(10));
System.out.println("tree.get(-1) + " + tree.get(-1));
System.out.println("tree.get(15) + " + tree.get(15));
tree.deleteMin();
tree.deleteMin();
System.out.println("hah");
}
private Node root = null;
public void put(K k, V v) {
root = put(root, k, v);
root.color = BLACK;
}
private Node put(Node cn, K k, V v) {
if (cn == null) return new Node(k, v, 1, RED);
if(isRed(cn.left) && isRed(cn.right)) split4Node(cn);
int cmp = k.compareTo(cn.k);
if (cmp > 0) cn.right = put(cn.right, k, v); // k > node.k go right
else if (cmp < 0) cn.left = put(cn.left, k, v);
else cn.v = v; //hit
//following code is to fix the tree on the way up
if (isRed(cn.right) && !isRed(cn.left)) cn = rotateLeft(cn);
if (isRed(cn.left) && isRed(cn.left.left)) cn = rotateRight(cn);
cn.size = size(cn.left) + size(cn.right) + 1;
return cn;
}
public V get(K k) {
return get(root, k);
}
//cn means currentNode
private V get(Node cn, K k) {
if (cn == null) return null; // not find the key
int cmp = k.compareTo(cn.k);
if(cmp > 0) return get(cn.right, k);
else if (cmp < 0) return get(cn.left, k);
else return cn.v; // hit
}
public void delete(K k) {
if (!isRed(root.left) && !isRed(root.right))
root.color = RED;
root = delete(root, k);
if (root != null)
root.color = BLACK;
}
private Node delete(Node cn, K k) {
if (cn == null) return null;
int cmp = k.compareTo(cn.k);
if (cmp < 0) { // k < node.k go left
if (!isRed(cn.left) && !isRed(cn.left.left))
cn = moveRedLeft(cn);
cn.left = delete(cn.left, k);
} else if (cmp > 0) { // k > node.k go right
if (isRed(cn.left) && !isRed(cn.right))
cn = rotateRight(cn);
if (!isRed(cn.right) && !isRed(cn.right.left))
cn = moveRedRight(cn);
cn.right = delete(cn.right, k);
} else { //hit
if (isRed(cn.left) && !isRed(cn.right))
cn = rotateRight(cn);
if (k.compareTo(cn.k) == 0 && (cn.right == null)) //find null just return null
return null;
if (!isRed(cn.right) && !isRed(cn.right.left))
cn = moveRedRight(cn);
if (k.compareTo(cn.k) == 0) {
Node x = min(cn.right);
cn.k = x.k;
cn.v = x.v;
cn.right = deleteMin(cn.right);
} else cn.right = delete(cn.right, k);
}
return fixup(cn);
}
private Node min(Node x) {
if (x.left == null) return x;
else return min(x.left);
}
public void deleteMin() {
if (!isRed(root.left) && !isRed(root.right))
root.color = RED;
root = deleteMin(root);
root.color = BLACK;
}
public Node deleteMin(Node cn) {
if (cn.left == null) return null;
if (!isRed(cn.left) && !isRed(cn.left.left))
cn = moveRedLeft(cn);
cn.left = deleteMin(cn.left);
return fixup(cn);
}
private Node moveRedLeft(Node cn) {
flipColors(cn);
if (isRed(cn.right.left)) {
cn.right = rotateRight(cn.right);
cn = rotateLeft(cn);
flipColors(cn);
}
return cn;
}
public void deleteMax() {
if (!isRed(root.left) && !isRed(root.right))
root.color = RED;
root = deleteMax(root);
root.color = BLACK;
}
//make sure currentNode is not a 2Node by make currentNode is red or currentNode.left is red
private Node deleteMax(Node cn) {
if (isRed(cn.left) && !isRed(cn.right) )
cn = rotateRight(cn);
if (cn.right == null) return null; // approach the end and find the currentNode's childNode is null then just return null;
if (!isRed(cn.right) && !isRed(cn.right.left)) {
cn = moveRedRight(cn);
}
cn.right = deleteMax(cn.right);
return fixup(cn);
}
//used when cn.left is not a 2Node
private Node moveRedRight(Node cn) {
flipColors(cn);
if (isRed(cn.left.left)) {
cn = rotateRight(cn);
flipColors(cn);
}
return cn;
}
private int size(Node node) {
if (node == null)
return 0;
return node.size;
}
private void split4Node(Node cn) {
flipColors(cn);
}
private void flipColors(Node h) {
assert(!isRed(h));
assert(isRed(h.right));
assert(isRed(h.left));
h.color = !h.color;
h.left.color = !h.left.color;
h.right.color = !h.right.color;
}
private Node rotateLeft(Node h) {
assert(isRed(h.right));
Node x = h.right; //changethe pointers
h.right = x.left;
x.left = h;
x.color = h.color; //change the colors
h.color = RED;
x.size = h.size; //change the sizes
h.size = size(h.left) + size(h.right) + 1;
return x;
}
private Node rotateRight(Node h) {
assert(isRed(h.left));
Node x = h.left;
h.left = x.right;
x.right = h;
x.color = h.color;
h.color = RED;
x.size = h.size; //size is the same
h.size = size(h.left) + size(h.right) + 1;
return x;
}
private Node fixup(Node h) {
if (isRed(h.right)) h = rotateLeft(h);
if (isRed(h.left) && isRed(h.left.left)) h = rotateRight(h);
// on the way up eliminate 4 nodes
h.size = size(h.left) + size(h.right) + 1; //right the size
return h;
}
private boolean isRed(Node x) {
if (x == null) return false;
return x.color == RED;
}
private static final boolean RED = true;
private static final boolean BLACK = false;
private class Node {
private K k;
private V v;
private Node left, right;
private int size;
private boolean color;
Node(K k, V v, int size, boolean color) {
this.k = k;
this.v = v;
this.size = size;
this.color = color;
}
@Override
public String toString() {
if (color) return "red" + v;
else return "black" + v;
}
}
} |
package org.javarosa.chatscreen;
import java.util.Enumeration;
import java.util.Vector;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.Displayable;
import minixpath.XPathExpression;
import org.javarosa.clforms.Controller;
import org.javarosa.clforms.MVCComponent;
import org.javarosa.clforms.api.Prompt;
import org.javarosa.clforms.api.ResponseEvent;
import org.javarosa.clforms.storage.Model;
import org.javarosa.clforms.util.J2MEUtil;
import org.javarosa.clforms.util.SimpleOrderedHashtable;
import org.javarosa.clforms.view.FormView;
import org.javarosa.clforms.view.IPrompter;
import org.javarosa.utils.ViewUtils;
import org.kxml2.kdom.Element;
import org.kxml2.kdom.Node;
import javax.microedition.lcdui.CommandListener;
/**
* The base container for the Chat Screen interface.
*
* The ChatScreenForm is responsible for containing and laying out frames,
* as well as the control logic used for navigation of protocols.
*
* It is the primary interface between the Protocol object and the View.
*
* @author ctsims
*
*/
public class ChatScreenForm extends DForm implements IPrompter, FormView, CommandListener {
private Vector frameSet = new Vector();
private Vector prompts;
int activeQuestion = -1;
int totalQuestions = 0;
int highestDisplayedQuestion = 0;
private String name;
private Model xmlModel;
private int recordId;
private Controller controller;
private boolean next = true;
private boolean prev = false;
Command exitCommand = new Command("Exit", Command.EXIT, 1);
Command nextCommand = new Command("Next", Command.ITEM, 1);
Command prevCommand = new Command("Prev", Command.ITEM, 1);
/**
* Creates a new ChatScreen Form
*/
public ChatScreenForm() {
addCommand(nextCommand);
addCommand(prevCommand);
addCommand(exitCommand);
this.setCommandListener(this);
setupComponents();
}
/**
* Lays out the static components for the form
*/
private void setupComponents() {
int width = this.getWidth();
int height = this.getHeight();
int frameCanvasHeight = height - (height / 11);
getContentComponent().setBackgroundColor(ViewUtils.GREY);
}
/**
* Pushes a new question onto the stack, setting all other
* questions to inactive status, and displaying the new question
* to the user.
*
* @param theQuestion The new question to be displayed
*/
public void addPrompt(Prompt p) {
System.out.println("ChatScreenForm.addPrompt() " + activeQuestion);
if (next) {
activeQuestion++;
// add a new question
if (activeQuestion == totalQuestions) {
totalQuestions++;
Frame newFrame = new Frame(p);
newFrame.setWidth(this.getWidth());
frameSet.addElement(newFrame);
getContentComponent().add(newFrame);
setupFrames();
this.repaint();
} else { // advance to question that's already there
getContentComponent().add((Frame)frameSet.elementAt(activeQuestion));
setupFrames();
}
next = false;
} else if (prev) {
System.out.println("goToPreviousPrompt()" + activeQuestion);
// Don't do anything if user hits prev command for first question
if (activeQuestion > 0) {
getContentComponent().remove((Frame)frameSet.elementAt(activeQuestion));
activeQuestion
setupFrames();
}
prev = false;
}
}
/**
* Goes back to the previous prompt
*/
public void goToPreviousPrompt() {
System.out.println("goToPreviousPrompt()" + activeQuestion);
// Don't do anything if user hits prev command for first question
if (activeQuestion > 0) {
getContentComponent().remove((Frame)frameSet.elementAt(activeQuestion));
activeQuestion
setupFrames();
}
}
/**
* Queries all frames for their optimal size, and then lays them out
* in a simple stack.
*/
private void setupFrames() {
int frameCanvasHeight = getContentComponent().getHeight()
- (getContentComponent().getHeight() / 11);
int frameStart = frameCanvasHeight;
for (int i=activeQuestion; i >=0; i
Frame aFrame = (Frame) frameSet.elementAt(i);
if ( i == activeQuestion ) {
aFrame.setActiveFrame(true);
} else {
aFrame.setActiveFrame(false);
}
frameStart -= aFrame.getHeight();
aFrame.setY(frameStart);
}
}
/**
* Sets the list of prompts for this Form
* @param prompts The prompts that this Form displays
*/
public void setPrompts(Vector prompts) {
this.prompts = prompts;
}
/** (non-Javadoc)
* @see org.javarosa.clforms.view.FormView#displayPrompt(Prompt)
*/
public void displayPrompt(Prompt prompt) {
this.showPrompt(prompt);
}
/** (non-Javadoc)
* @see org.javarosa.clforms.view.IPrompter#showPrompt(Prompt)
*/
public void showPrompt(Prompt prompt) {
System.out.println("ChatScreenForm.showPrompt(prompt)");
MVCComponent.display.setCurrent(this);
addPrompt(prompt);
}
/** (non-Javadoc)
* @see org.javarosa.clforms.view.IPrompter#showPrompt(Prompt,int,int)
*/
public void showPrompt(Prompt prompt, int screenIndex, int totalScreens) {
System.out.println("ChatScreenForm.showPrompt(screenIndex, totalScreens)");
displayPrompt(prompt);
}
/** (non-Javadoc)
* @see org.javarosa.clforms.view.FormView#registerController(Controller)
*/
public void registerController(Controller controller) {
System.out.println("ChatScreenForm.registerController(controller)");
this.controller = controller;
}
public void commandAction(Command command, Displayable s) {
try {
if (command == nextCommand) {
next = true;
controller.processEvent(new ResponseEvent(ResponseEvent.NEXT,
-1));
} else if (command == prevCommand) {
goToPreviousPrompt();
controller.processEvent(new ResponseEvent(
ResponseEvent.PREVIOUS, -1));
} else if (command == exitCommand) {
controller.processEvent(new ResponseEvent(ResponseEvent.EXIT,
-1));
}
} catch (Exception e) {
Alert a = new Alert("error.screen" + " 2"); //$NON-NLS-1$
a.setString(e.getMessage());
a.setTimeout(Alert.FOREVER);
MVCComponent.display.setCurrent(a);
}
}
} |
package com.xpn.xwiki;
// import com.xpn.xwiki.store.XWikiBatcher;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.velocity.exception.MethodInvocationException;
import org.hibernate.JDBCException;
import javax.servlet.ServletException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.MessageFormat;
public class XWikiException extends Exception {
private static final Log log = LogFactory.getLog(XWikiException.class);
private int module;
private int code;
private Throwable exception;
private Object[] args;
private String message;
// Module list
public static final int MODULE_XWIKI = 0;
public static final int MODULE_XWIKI_CONFIG = 1;
public static final int MODULE_XWIKI_DOC = 2;
public static final int MODULE_XWIKI_STORE = 3;
public static final int MODULE_XWIKI_RENDERING = 4;
public static final int MODULE_XWIKI_PLUGINS = 5;
public static final int MODULE_XWIKI_PERLPLUGINS = 6;
public static final int MODULE_XWIKI_CLASSES = 7;
public static final int MODULE_XWIKI_USER = 8;
public static final int MODULE_XWIKI_ACCESS = 9;
public static final int MODULE_XWIKI_EMAIL = 10;
public static final int MODULE_XWIKI_APP = 11;
public static final int MODULE_XWIKI_EXPORT = 12;
public static final int MODULE_XWIKI_DIFF = 13;
public static final int MODULE_XWIKI_GROOVY = 14;
public static final int MODULE_XWIKI_NOTIFICATION = 15;
public static final int MODULE_XWIKI_CACHE = 16;
public static final int MODULE_XWIKI_CONTENT = 17;
public static final int MODULE_XWIKI_XMLRPC = 18;
public static final int MODULE_XWIKI_GWT_API = 19;
public static final int MODULE_PLUGIN_LASZLO = 21;
// Error list
public static final int ERROR_XWIKI_UNKNOWN = 0;
public static final int ERROR_XWIKI_NOT_IMPLEMENTED = 1;
public static final int ERROR_XWIKI_DOES_NOT_EXIST = 2;
public static final int ERROR_XWIKI_INIT_FAILED = 3;
public static final int ERROR_XWIKI_MKDIR = 4;
public static final int ERROR_XWIKI_DOC_CUSTOMDOCINVOCATIONERROR = 5;
// Config
public static final int ERROR_XWIKI_CONFIG_FILENOTFOUND = 1001;
public static final int ERROR_XWIKI_CONFIG_FORMATERROR = 1002;
// Doc
public static final int ERROR_XWIKI_DOC_EXPORT = 2001;
public static final int ERROR_DOC_XML_PARSING = 2002;
public static final int ERROR_DOC_RCS_PARSING = 2003;
// Store
public static final int ERROR_XWIKI_STORE_CLASSINVOCATIONERROR = 3001;
public static final int ERROR_XWIKI_STORE_FILENOTFOUND = 3002;
public static final int ERROR_XWIKI_STORE_ARCHIVEFORMAT = 3003;
public static final int ERROR_XWIKI_STORE_ATTACHMENT_ARCHIVEFORMAT = 3004;
public static final int ERROR_XWIKI_STORE_MIGRATION = 3005;
public static final int ERROR_XWIKI_STORE_RCS_SAVING_FILE = 3101;
public static final int ERROR_XWIKI_STORE_RCS_READING_FILE = 3102;
public static final int ERROR_XWIKI_STORE_RCS_DELETING_FILE = 3103;
public static final int ERROR_XWIKI_STORE_RCS_READING_REVISIONS = 3103;
public static final int ERROR_XWIKI_STORE_RCS_READING_VERSION = 3104;
public static final int ERROR_XWIKI_STORE_RCS_SEARCH = 3111;
public static final int ERROR_XWIKI_STORE_RCS_LOADING_ATTACHMENT = 3221;
public static final int ERROR_XWIKI_STORE_RCS_SAVING_ATTACHMENT = 3222;
public static final int ERROR_XWIKI_STORE_RCS_SEARCHING_ATTACHMENT = 3223;
public static final int ERROR_XWIKI_STORE_RCS_DELETING_ATTACHMENT = 3224;
public static final int ERROR_XWIKI_STORE_HIBERNATE_SAVING_DOC = 3201;
public static final int ERROR_XWIKI_STORE_HIBERNATE_READING_DOC = 3202;
public static final int ERROR_XWIKI_STORE_HIBERNATE_DELETING_DOC = 3203;
public static final int ERROR_XWIKI_STORE_HIBERNATE_CANNOT_DELETE_UNLOADED_DOC = 3204;
public static final int ERROR_XWIKI_STORE_HIBERNATE_READING_REVISIONS = 3203;
public static final int ERROR_XWIKI_STORE_HIBERNATE_READING_VERSION = 3204;
public static final int ERROR_XWIKI_STORE_HIBERNATE_UNEXISTANT_VERSION = 3205;
public static final int ERROR_XWIKI_STORE_HIBERNATE_SAVING_OBJECT = 3211;
public static final int ERROR_XWIKI_STORE_HIBERNATE_LOADING_OBJECT = 3212;
public static final int ERROR_XWIKI_STORE_HIBERNATE_DELETING_OBJECT = 3213;
public static final int ERROR_XWIKI_STORE_HIBERNATE_SAVING_CLASS = 3221;
public static final int ERROR_XWIKI_STORE_HIBERNATE_LOADING_CLASS = 3222;
public static final int ERROR_XWIKI_STORE_HIBERNATE_SEARCH = 3223;
public static final int ERROR_XWIKI_STORE_HIBERNATE_LOADING_ATTACHMENT = 3231;
public static final int ERROR_XWIKI_STORE_HIBERNATE_SAVING_ATTACHMENT = 3232;
public static final int ERROR_XWIKI_STORE_HIBERNATE_DELETING_ATTACHMENT = 3233;
public static final int ERROR_XWIKI_STORE_HIBERNATE_SAVING_ATTACHMENT_LIST = 3234;
public static final int ERROR_XWIKI_STORE_HIBERNATE_SEARCHING_ATTACHMENT = 3235;
public static final int ERROR_XWIKI_STORE_HIBERNATE_CHECK_EXISTS_DOC = 3236;
public static final int ERROR_XWIKI_STORE_HIBERNATE_SWITCH_DATABASE = 3301;
public static final int ERROR_XWIKI_STORE_HIBERNATE_CREATE_DATABASE = 3401;
public static final int ERROR_XWIKI_STORE_JCR_SAVING_DOC = 3501;
public static final int ERROR_XWIKI_STORE_JCR_READING_DOC = 3502;
public static final int ERROR_XWIKI_STORE_JCR_DELETING_DOC = 3503;
public static final int ERROR_XWIKI_STORE_JCR_CANNOT_DELETE_UNLOADED_DOC = 3504;
public static final int ERROR_XWIKI_STORE_JCR_READING_REVISIONS = 3503;
public static final int ERROR_XWIKI_STORE_JCR_READING_VERSION = 3504;
public static final int ERROR_XWIKI_STORE_JCR_UNEXISTANT_VERSION = 3505;
public static final int ERROR_XWIKI_STORE_JCR_SAVING_OBJECT = 3511;
public static final int ERROR_XWIKI_STORE_JCR_LOADING_OBJECT = 3512;
public static final int ERROR_XWIKI_STORE_JCR_DELETING_OBJECT = 3513;
public static final int ERROR_XWIKI_STORE_JCR_SAVING_CLASS = 3521;
public static final int ERROR_XWIKI_STORE_JCR_LOADING_CLASS = 3522;
public static final int ERROR_XWIKI_STORE_JCR_SEARCH = 3523;
public static final int ERROR_XWIKI_STORE_JCR_LOADING_ATTACHMENT = 3531;
public static final int ERROR_XWIKI_STORE_JCR_SAVING_ATTACHMENT = 3532;
public static final int ERROR_XWIKI_STORE_JCR_DELETING_ATTACHMENT = 3533;
public static final int ERROR_XWIKI_STORE_JCR_SAVING_ATTACHMENT_LIST = 3534;
public static final int ERROR_XWIKI_STORE_JCR_SEARCHING_ATTACHMENT = 3535;
public static final int ERROR_XWIKI_STORE_JCR_CHECK_EXISTS_DOC = 3536;
public static final int ERROR_XWIKI_STORE_JCR_SWITCH_DATABASE = 3601;
public static final int ERROR_XWIKI_STORE_JCR_CREATE_DATABASE = 3701;
public static final int ERROR_XWIKI_RENDERING_VELOCITY_EXCEPTION = 4001;
public static final int ERROR_XWIKI_RENDERING_GROOVY_EXCEPTION = 4002;
public static final int ERROR_XWIKI_PERLPLUGIN_START_EXCEPTION = 6001;
public static final int ERROR_XWIKI_PERLPLUGIN_START = 6002;
public static final int ERROR_XWIKI_PERLPLUGIN_PERLSERVER_EXCEPTION = 6003;
public static final int ERROR_XWIKI_CLASSES_FIELD_DOES_NOT_EXIST = 7001;
public static final int ERROR_XWIKI_CLASSES_FIELD_INVALID = 7002;
public static final int ERROR_XWIKI_CLASSES_DIFF = 7003;
public static final int ERROR_XWIKI_CLASSES_CUSTOMCLASSINVOCATIONERROR = 7004;
public static final int ERROR_XWIKI_CLASSES_PROPERTY_CLASS_INSTANCIATION = 7005;
public static final int ERROR_XWIKI_CLASSES_PROPERTY_CLASS_IN_METACLASS = 7006;
public static final int ERROR_XWIKI_CLASSES_CANNOT_PREPARE_CUSTOM_DISPLAY = 7007;
public static final int ERROR_XWIKI_USER_INIT = 8001;
public static final int ERROR_XWIKI_USER_CREATE = 8002;
public static final int ERROR_XWIKI_USER_INACTIVE = 8003;
public static final int ERROR_XWIKI_ACCESS_DENIED = 9001;
public static final int ERROR_XWIKI_ACCESS_TOKEN_INVALID = 9002;
public static final int ERROR_XWIKI_ACCESS_EXO_EXCEPTION_USERS = 9003;
public static final int ERROR_XWIKI_ACCESS_EXO_EXCEPTION_GROUPS = 9004;
public static final int ERROR_XWIKI_ACCESS_EXO_EXCEPTION_ADDING_USERS = 9005;
public static final int ERROR_XWIKI_ACCESS_EXO_EXCEPTION_LISTING_USERS = 9006;
public static final int ERROR_XWIKI_EMAIL_CANNOT_GET_VALIDATION_CONFIG = 10001;
public static final int ERROR_XWIKI_EMAIL_CANNOT_PREPARE_VALIDATION_EMAIL = 10002;
public static final int ERROR_XWIKI_EMAIL_ERROR_SENDING_EMAIL = 10003;
public static final int ERROR_XWIKI_EMAIL_CONNECT_FAILED = 10004;
public static final int ERROR_XWIKI_EMAIL_LOGIN_FAILED = 10005;
public static final int ERROR_XWIKI_EMAIL_SEND_FAILED = 10006;
public static final int ERROR_XWIKI_APP_TEMPLATE_DOES_NOT_EXIST = 11001;
public static final int ERROR_XWIKI_APP_DOCUMENT_NOT_EMPTY = 11002;
public static final int ERROR_XWIKI_APP_ATTACHMENT_NOT_FOUND = 11003;
public static final int ERROR_XWIKI_APP_CREATE_USER = 11004;
public static final int ERROR_XWIKI_APP_VALIDATE_USER = 11005;
public static final int ERROR_XWIKI_APP_INVALID_CHARS = 11006;
public static final int ERROR_XWIKI_APP_URL_EXCEPTION = 11007;
public static final int ERROR_XWIKI_APP_UPLOAD_PARSE_EXCEPTION = 11008;
public static final int ERROR_XWIKI_APP_UPLOAD_FILE_EXCEPTION = 11009;
public static final int ERROR_XWIKI_APP_REDIRECT_EXCEPTION = 11010;
public static final int ERROR_XWIKI_APP_SEND_RESPONSE_EXCEPTION = 11011;
public static final int ERROR_XWIKI_APP_SERVICE_NOT_FOUND = 11012;
public static final int ERROR_XWIKI_APP_FILE_EXCEPTION_MAXSIZE = 11013;
public static final int ERROR_XWIKI_APP_JAVA_HEAP_SPACE = 11014;
public static final int ERROR_XWIKI_APP_EXPORT = 11015;
public static final int ERROR_XWIKI_EXPORT_XSL_FILE_NOT_FOUND = 12001;
public static final int ERROR_XWIKI_EXPORT_PDF_FOP_FAILED = 12002;
public static final int ERROR_XWIKI_EXPORT_XSL_FAILED = 12003;
public static final int ERROR_XWIKI_STORE_HIBERNATE_SAVING_LOCK = 13006;
public static final int ERROR_XWIKI_STORE_HIBERNATE_LOADING_LOCK = 13007;
public static final int ERROR_XWIKI_STORE_HIBERNATE_DELETING_LOCK = 13008;
public static final int ERROR_XWIKI_STORE_HIBERNATE_INVALID_MAPPING = 13009;
public static final int ERROR_XWIKI_STORE_HIBERNATE_MAPPING_INJECTION_FAILED = 13010;
public static final int ERROR_XWIKI_STORE_HIBERNATE_LOADING_LINKS = 13011;
public static final int ERROR_XWIKI_STORE_HIBERNATE_SAVING_LINKS = 13012;
public static final int ERROR_XWIKI_STORE_HIBERNATE_DELETING_LINKS = 13013;
public static final int ERROR_XWIKI_STORE_HIBERNATE_LOADING_BACKLINKS = 13014;
public static final int ERROR_XWIKI_DIFF_CONTENT_ERROR = 13021;
public static final int ERROR_XWIKI_DIFF_RENDERED_ERROR = 13022;
public static final int ERROR_XWIKI_DIFF_METADATA_ERROR = 13023;
public static final int ERROR_XWIKI_DIFF_CLASS_ERROR = 13024;
public static final int ERROR_XWIKI_DIFF_OBJECT_ERROR = 13025;
public static final int ERROR_XWIKI_DIFF_ATTACHMENT_ERROR = 13026;
public static final int ERROR_XWIKI_DIFF_XML_ERROR = 13027;
public static final int ERROR_XWIKI_STORE_JCR_SAVING_LOCK = 13106;
public static final int ERROR_XWIKI_STORE_JCR_LOADING_LOCK = 13107;
public static final int ERROR_XWIKI_STORE_JCR_DELETING_LOCK = 13108;
public static final int ERROR_XWIKI_STORE_JCR_INVALID_MAPPING = 13109;
public static final int ERROR_XWIKI_STORE_JCR_MAPPING_INJECTION_FAILED = 13110;
public static final int ERROR_XWIKI_STORE_JCR_LOADING_LINKS = 13111;
public static final int ERROR_XWIKI_STORE_JCR_SAVING_LINKS = 13112;
public static final int ERROR_XWIKI_STORE_JCR_DELETING_LINKS = 13113;
public static final int ERROR_XWIKI_STORE_JCR_LOADING_BACKLINKS = 13114;
public static final int ERROR_XWIKI_STORE_JCR_OTHER = 13130; // temporary
public static final int ERROR_XWIKI_STORE_SEARCH_NOTIMPL = 13200;
public static final int ERROR_XWIKI_GROOVY_COMPILE_FAILED = 14001;
public static final int ERROR_XWIKI_GROOVY_EXECUTION_FAILED = 14002;
public static final int ERROR_XWIKI_NOTIFICATION = 15001;
public static final int ERROR_CACHE_INITIALIZING = 16001;
public static final int ERROR_LASZLO_INVALID_XML = 21001;
public static final int ERROR_LASZLO_INVALID_DOTDOT = 21002;
// Content errors
public static final int ERROR_XWIKI_CONTENT_LINK_INVALID_TARGET = 22000;
public static final int ERROR_XWIKI_CONTENT_LINK_INVALID_URI = 22001;
public XWikiException(int module, int code, String message, Throwable e, Object[] args) {
setModule(module);
setCode(code);
setException(e);
setArgs(args);
setMessage(message);
if (log.isTraceEnabled())
log.trace(getMessage(), e);
}
public XWikiException(int module, int code, String message, Throwable e) {
this(module, code, message, e, null);
}
public XWikiException(int module, int code, String message) {
this(module, code, message, null, null);
}
public XWikiException() {
}
public int getModule() {
return module;
}
public String getModuleName() {
return "" + module;
}
public void setModule(int module) {
this.module = module;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public Throwable getException() {
return exception;
}
public void setException(Throwable exception) {
this.exception = exception;
}
public Object[] getArgs() {
return args;
}
public void setArgs(Object[] args) {
this.args = args;
}
public void setMessage(String message) {
this.message = message;
}
public String getMessage() {
StringBuffer buffer = new StringBuffer();
buffer.append("Error number ");
buffer.append(getCode());
buffer.append(" in ");
buffer.append(getModuleName());
buffer.append(": ");
if (message != null) {
if (args == null)
buffer.append(message);
else {
MessageFormat msgFormat = new MessageFormat(message);
try {
buffer.append(msgFormat.format(args));
}
catch (Exception e) {
buffer.append("Cannot format message " + message + " with args ");
for (int i = 0; i < args.length; i++) {
if (i != 0)
buffer.append(",");
buffer.append(args[i]);
}
}
}
}
if (exception != null) {
buffer.append("\nWrapped Exception: ");
buffer.append(exception.getMessage());
}
return buffer.toString();
}
public String getFullMessage() {
StringBuffer buffer = new StringBuffer(getMessage());
buffer.append("\n");
buffer.append(getStackTraceAsString());
buffer.append("\n");
/*
List list = XWikiBatcher.getSQLStats().getRecentSqlList();
if (list.size() > 0) {
buffer.append("Recent SQL:\n");
for (int i = 0; i < list.size(); i++) {
buffer.append(list.get(i));
buffer.append("\n");
}
}
*/
return buffer.toString();
}
public void printStackTrace(PrintWriter s) {
super.printStackTrace(s);
if (exception != null) {
s.write("\n\nWrapped Exception:\n\n");
if (exception.getCause()!=null)
exception.getCause().printStackTrace(s);
else if (exception instanceof org.hibernate.JDBCException) {
(((JDBCException) exception).getSQLException()).printStackTrace(s);
} else if (exception instanceof MethodInvocationException) {
(((MethodInvocationException) exception).getWrappedThrowable()).printStackTrace(s);
} else if (exception instanceof ServletException) {
(((ServletException) exception).getRootCause()).printStackTrace(s);
} else {
exception.printStackTrace(s);
}
}
}
public void printStackTrace(PrintStream s) {
super.printStackTrace(s);
if (exception != null) {
s.print("\n\nWrapped Exception:\n\n");
if (exception.getCause()!=null)
exception.getCause().printStackTrace(s);
else if (exception instanceof org.hibernate.JDBCException) {
(((JDBCException) exception).getSQLException()).printStackTrace(s);
} else if (exception instanceof MethodInvocationException) {
(((MethodInvocationException) exception).getWrappedThrowable()).printStackTrace(s);
} else if (exception instanceof ServletException) {
(((ServletException) exception).getRootCause()).printStackTrace(s);
} else {
exception.printStackTrace(s);
}
}
}
public String getStackTraceAsString() {
StringWriter swriter = new StringWriter();
PrintWriter pwriter = new PrintWriter(swriter);
printStackTrace(pwriter);
pwriter.flush();
return swriter.getBuffer().toString();
}
public String getStackTraceAsString(Throwable e) {
StringWriter swriter = new StringWriter();
PrintWriter pwriter = new PrintWriter(swriter);
e.printStackTrace(pwriter);
pwriter.flush();
return swriter.getBuffer().toString();
}
} |
package com.hearthsim.card.minion;
import com.hearthsim.card.CharacterIndex;
import com.hearthsim.card.weapon.WeaponCard;
import com.hearthsim.event.deathrattle.DeathrattleAction;
import com.hearthsim.exception.HSException;
import com.hearthsim.model.BoardModel;
import com.hearthsim.model.PlayerModel;
import com.hearthsim.model.PlayerSide;
import com.hearthsim.util.HearthAction;
import com.hearthsim.util.HearthAction.Verb;
import com.hearthsim.util.factory.BoardStateFactoryBase;
import com.hearthsim.util.tree.HearthTreeNode;
import org.json.JSONObject;
public abstract class Hero extends Minion implements MinionSummonedInterface {
protected static final byte HERO_ABILITY_COST = 2; // Assumed to be 2 for all heroes
private WeaponCard weapon;
private byte armor_;
public Hero() {
super();
}
@Deprecated
public byte getWeaponCharge() {
if (weapon == null) {
return 0;
} else {
return weapon.getWeaponCharge();
}
}
public void addArmor(byte armor) {
armor_ += armor;
}
public byte getArmor() {
return armor_;
}
public void setArmor(byte armor) {
armor_ = armor;
}
/**
*
* @return the class name of the hero, e.g. Hunter
*/
public String getHeroClass() {
return this.getClass().getSimpleName();
}
@Override
public boolean isHero() {
return true;
}
@Override
public Hero deepCopy() {
Hero copy = (Hero) super.deepCopy();
if (weapon != null) {
copy.weapon = weapon.deepCopy();
}
copy.armor_ = armor_;
return copy;
}
/**
* Attack with the hero
* <p>
* A hero can only attack if it has a temporary buff, such as weapons
*
* @param targetMinionPlayerSide
* @param targetMinion The target minion
* @param boardState The BoardState before this card has performed its action. It will be manipulated and returned.
* @return The boardState is manipulated and returned
*/
@Override
public HearthTreeNode attack(PlayerSide targetMinionPlayerSide, Minion targetMinion, HearthTreeNode boardState) throws HSException {
if (!this.canAttack()) {
return null;
}
WeaponCard attackingWeapon = this.getWeapon();
if (attackingWeapon != null) {
attackingWeapon.beforeAttack(targetMinionPlayerSide, targetMinion, boardState);
}
HearthTreeNode toRet = super.attack(targetMinionPlayerSide, targetMinion, boardState);
// TODO: weapon deathrattles should happen at the same time as the minion deathrattles
if (toRet != null && attackingWeapon != null) {
attackingWeapon.afterAttack(targetMinionPlayerSide, targetMinion, boardState);
DeathrattleAction weaponDeathrattle = this.checkForWeaponDeath();
if (weaponDeathrattle != null) {
toRet = weaponDeathrattle.performAction(attackingWeapon, PlayerSide.CURRENT_PLAYER, toRet);
toRet = BoardStateFactoryBase.handleDeadMinions(toRet);
}
}
return toRet;
}
@Override
public boolean canBeUsedOn(PlayerSide playerSide, Minion minion, BoardModel boardModel) {
if (this.hasBeenUsed()) {
return false;
}
if (boardModel.getCurrentPlayer().getMana() < HERO_ABILITY_COST) {
return false;
}
if (!minion.isHeroTargetable()) {
return false;
}
return true;
}
public final HearthTreeNode useHeroAbility(PlayerSide targetPlayerSide, CharacterIndex targetIndex,
HearthTreeNode boardState) throws HSException {
Minion targetMinion = boardState.data_.modelForSide(targetPlayerSide).getCharacter(targetIndex);
return this.useHeroAbility(targetPlayerSide, targetMinion, boardState);
}
/**
* Use the hero ability on a given target
*
* @param targetPlayerSide
* @param targetMinion The target minion
* @param boardState
* @return
*/
public final HearthTreeNode useHeroAbility(PlayerSide targetPlayerSide, Minion targetMinion, HearthTreeNode boardState) {
if (!this.canBeUsedOn(targetPlayerSide, targetMinion, boardState.data_)) {
return null;
}
PlayerModel targetPlayer = boardState.data_.modelForSide(targetPlayerSide);
HearthTreeNode toRet = this.useHeroAbility_core(targetPlayerSide, targetMinion, boardState);
if (toRet != null) {
CharacterIndex targetIndex = targetPlayer.getIndexForCharacter(targetMinion);
toRet.setAction(new HearthAction(Verb.HERO_ABILITY, PlayerSide.CURRENT_PLAYER, 0, targetPlayerSide,
targetIndex));
toRet = BoardStateFactoryBase.handleDeadMinions(toRet);
}
return toRet;
}
protected abstract HearthTreeNode useHeroAbility_core(PlayerSide targetPlayerSide, Minion targetMinion, HearthTreeNode boardState);
/**
* Called when this minion takes damage
* <p>
* Overridden from Minion. Need to handle armor.
*
* @param damage The amount of damage to take
* @param attackPlayerSide The player index of the attacker. This is needed to do things like +spell damage.
* @param thisPlayerSide
* @param boardState
* @param isSpellDamage
* @throws HSInvalidPlayerIndexException
*/
@Override
public byte takeDamage(byte damage, PlayerSide originSide, PlayerSide thisPlayerSide, BoardModel board, boolean isSpellDamage) {
byte totalDamage = damage;
if (isSpellDamage) {
totalDamage += board.modelForSide(originSide).getSpellDamage();
}
byte damageRemaining = (byte) (totalDamage - armor_);
if (damageRemaining > 0) {
armor_ = 0;
super.takeDamage(damageRemaining, originSide, thisPlayerSide, board, false);
} else {
armor_ = (byte) (armor_ - totalDamage);
}
return totalDamage;
}
/**
* Simpler version of take damage
* <p>
* For now, the Hero taking damage has no consequence to the board state. So, this version can be used as a way to simplify the code.
*
* @param damage The amount of damage taken by the hero
*/
public void takeDamage(byte damage) {
byte damageRemaining = (byte) (damage - armor_);
if (damageRemaining > 0) {
armor_ = 0;
health_ -= (byte) (damage - armor_);
} else {
armor_ = (byte) (armor_ - damage);
}
}
@Override
public JSONObject toJSON() {
JSONObject json = super.toJSON();
if (this.armor_ > 0) json.put("armor", this.armor_);
json.put("weapon", this.weapon);
return json;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
if (!super.equals(o))
return false;
Hero hero = (Hero) o;
if (armor_ != hero.armor_)
return false;
if (weapon != null ? !weapon.equals(hero.weapon) : hero.weapon != null)
return false;
return true;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (weapon != null ? weapon.hashCode() : 0);
result = 31 * result + armor_;
return result;
}
@Override
public byte getTotalAttack() {
byte attack = super.getTotalAttack();
if (this.getWeapon() != null) {
attack += this.getWeapon().getWeaponDamage();
}
return attack;
}
public DeathrattleAction setWeapon(WeaponCard weapon) {
if (weapon == null) {
throw new RuntimeException("use 'destroy weapon' method if trying to remove weapon.");
}
DeathrattleAction action = this.weapon != null && this.weapon.hasDeathrattle() ? this.weapon.getDeathrattle() : null;
this.weapon = weapon;
return action;
}
public WeaponCard getWeapon() {
return weapon;
}
public DeathrattleAction destroyWeapon() {
if (weapon != null) {
DeathrattleAction action = weapon.hasDeathrattle() ? weapon.getDeathrattle() : null;
weapon = null;
return action;
}
return null;
}
public DeathrattleAction checkForWeaponDeath() {
if (weapon != null && weapon.getWeaponCharge() == 0) {
return this.destroyWeapon();
}
return null;
}
@Override
public HearthTreeNode minionSummonEvent(PlayerSide thisMinionPlayerSide, PlayerSide summonedMinionPlayerSide, Minion summonedMinion, HearthTreeNode boardState) {
if (weapon != null) {
weapon.minionSummonedEvent(thisMinionPlayerSide, summonedMinionPlayerSide, summonedMinion, boardState);
}
return boardState;
}
} |
package org.jcryptool.visual.ssl.views;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.wb.swt.SWTResourceManager;
import org.jcryptool.core.util.fonts.FontService;
import org.jcryptool.visual.ssl.protocol.Message;
/**
* Represents the visual TLS-Plugin.
*
* @author Florian Stehrer
*/
public class SslView extends ViewPart
{
private Composite parent;
private ScrolledComposite scrolledComposite;
private Arrows arrow;
private Composite content;
private Composite mainContent;
private ClientHelloComposite clientHelloComposite;
private ServerHelloComposite serverHelloComposite;
private ServerCertificateComposite serverCertificateComposite;
private ClientCertificateComposite clientCertificateComposite;
private ServerChangeCipherSpecComposite serverChangeCipherSpecComposite;
private ClientChangeCipherSpecComposite clientChangeCipherSpecComposite;
private ClientFinishedComposite clientFinishedComposite;
private ServerFinishedComposite serverFinishedComposite;
private StyledText stxInformation;
private Group grp_serverComposites;
private Group grp_clientComposites;
private Button btnNextStep;
private Button btnPreviousStep;
public static final String ID = "org.jcryptool.visual.ssl.views.SslView"; //$NON-NLS-1$
public SslView() {
}
/**
* Create contents of the view part.
* @param parent
*/
@Override
public void createPartControl(final Composite parent)
{
this.parent = parent;
scrolledComposite = new ScrolledComposite(parent, SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
mainContent = new Composite(scrolledComposite, SWT.NONE);
scrolledComposite.setContent(mainContent);
scrolledComposite.setExpandHorizontal(true);
scrolledComposite.setExpandVertical(true);
scrolledComposite.setMinSize(mainContent.computeSize(1100, 900));
GridLayout gl = new GridLayout(1, false);
gl.verticalSpacing = 0;
mainContent.setLayout(gl);
Label headline = new Label(mainContent, SWT.NONE);
headline.setText(Messages.SslViewHeadline);
headline.setFont(FontService.getHeaderFont());
headline.setLayoutData(new GridData(SWT.LEFT, SWT.FILL, false, false, 1, 1));
content = new Composite(mainContent, SWT.NONE);
content.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1));
content.setLayout(new GridLayout(4, false));
createButtons();
createGui();
//Fuer die Hilfe:
//PlatformUI.getWorkbench().getHelpSystem().setHelp(parent.getShell(), SslPlugin.PLUGIN_ID + ".sslview");
}
/**
* Creates the Elements of the GUI.
*/
private void createGui()
{
//Client Composites
grp_clientComposites = new Group(content, SWT.NONE);
GridData gd_clientComposite = new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1);
gd_clientComposite.widthHint = 350;
grp_clientComposites.setLayoutData(gd_clientComposite);
grp_clientComposites.setLayout(new GridLayout());
grp_clientComposites.setText(Messages.SslViewLblClient);
clientHelloComposite = new ClientHelloComposite(grp_clientComposites, SWT.NONE, this);
clientHelloComposite.setLayout(new GridLayout(3, true));
clientHelloComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1));
clientCertificateComposite = new ClientCertificateComposite(grp_clientComposites, SWT.NONE, this);
clientCertificateComposite.setLayout(new GridLayout(3, true));
clientCertificateComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 2));
clientCertificateComposite.setVisible(false);
clientChangeCipherSpecComposite = new ClientChangeCipherSpecComposite(grp_clientComposites, SWT.NONE, this);
clientChangeCipherSpecComposite.setLayout(new GridLayout(3, true));
clientChangeCipherSpecComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 3));
clientChangeCipherSpecComposite.setVisible(false);
clientFinishedComposite = new ClientFinishedComposite(grp_clientComposites, SWT.NONE, this);
clientFinishedComposite.setLayout(new GridLayout(3, true));
clientFinishedComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 4));
clientFinishedComposite.setVisible(false);
//Draw Panel
Composite swtAwtComponent = new Composite(content, SWT.EMBEDDED);
GridData gd_drawPanel = new GridData(SWT.FILL, SWT.FILL, false, false, 1, 2);
gd_drawPanel.widthHint = 100;
gd_drawPanel.heightHint=760;
swtAwtComponent.setLayoutData(gd_drawPanel);
swtAwtComponent.setLayout(new GridLayout());
arrow = new Arrows(swtAwtComponent, SWT.NONE, new Color(Display.getCurrent(),0,0,0));
arrow.setLayoutData(gd_drawPanel);
arrow.setLayout(new GridLayout());
//Server Composites
grp_serverComposites = new Group(content, SWT.NONE);
GridData gd_serverComposite = new GridData(SWT.FILL, SWT.FILL, false, false, 1, 3);
gd_serverComposite.widthHint = 350;
grp_serverComposites.setLayoutData(gd_serverComposite);
grp_serverComposites.setLayout(new GridLayout());
grp_serverComposites.setText(Messages.SslViewLblServer);
serverHelloComposite = new ServerHelloComposite(grp_serverComposites, SWT.NONE, this);
serverHelloComposite.setLayout(new GridLayout(3, true));
serverHelloComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1));
serverHelloComposite.setVisible(false);
serverCertificateComposite = new ServerCertificateComposite(grp_serverComposites, SWT.NONE, this);
serverCertificateComposite.setLayout(new GridLayout(3, true));
serverCertificateComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 2));
serverCertificateComposite.setVisible(false);
serverChangeCipherSpecComposite = new ServerChangeCipherSpecComposite(grp_serverComposites, SWT.NONE, this);
serverChangeCipherSpecComposite.setLayout(new GridLayout(3, true));
serverChangeCipherSpecComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 3));
serverChangeCipherSpecComposite.setVisible(false);
serverFinishedComposite = new ServerFinishedComposite(grp_serverComposites, SWT.NONE, this);
serverFinishedComposite.setLayout(new GridLayout(3, true));
serverFinishedComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 4));
serverFinishedComposite.setVisible(false);
//Information Panel
Group grp_stxInfo = new Group(content, SWT.NONE);
grp_stxInfo.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 4));
grp_stxInfo.setLayout(new GridLayout());
grp_stxInfo.setText(Messages.SslViewLblInfo);
stxInformation = new StyledText(grp_stxInfo, SWT.READ_ONLY | SWT.MULTI | SWT.WRAP);
GridData gd_stxInfo = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1);
stxInformation.setLayoutData(gd_stxInfo);
stxInformation.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
stxInformation.setText(Messages.SslViewStxInformation);
stxInformation.setVisible(true);
}
/**
* Creates the Buttons of the GUI
*/
private void createButtons() {
Group grp_buttons = new Group(mainContent, SWT.NONE);
grp_buttons.setLayoutData(new GridData(SWT.CENTER, SWT.FILL, false, false, 3, 1));
grp_buttons.setLayout(new GridLayout(3, true));
btnPreviousStep = new Button(grp_buttons, SWT.PUSH);
btnPreviousStep.addMouseListener(new MouseAdapter() {
@Override
public void mouseUp(MouseEvent e) {
previousStep();
}
});
btnPreviousStep.setText(Messages.SslViewBtnPreviousStep);
btnPreviousStep.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1));
btnPreviousStep.setEnabled(false);
btnNextStep = new Button(grp_buttons, SWT.PUSH);
btnNextStep.addMouseListener(new MouseAdapter() {
@Override
public void mouseUp(MouseEvent e)
{
nextStep();
}
});
btnNextStep.setText(Messages.SslViewBtnNextStep);
btnNextStep.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1));
Button btnReset = new Button(grp_buttons, SWT.PUSH);
btnReset.addMouseListener(new MouseAdapter()
{
@Override
public void mouseUp(MouseEvent e)
{
resetStep();
}
});
btnReset.setText(Messages.SslViewBtnReset);
btnReset.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1));
}
/**
* Sets the text of the Information-Box.
* All other content of the Information-Box will be deleted.
* @param text
*/
public void setStxInformationText(String text)
{
if(stxInformation != null) {
stxInformation.setText(text);
}
}
/**
* Returns the text of the Information-Box.
* @return
*/
public String getStxInformationText()
{
return stxInformation.getText();
}
/**
* Adds text to the Information-Box.
* In contrast to the function "setStxInformationText()",
* all other content of the Information-Box will not be deleted.
* @param text
*/
public void addTextToStxInformationText(String text)
{
stxInformation.setText(stxInformation.getText()+text);
}
/**
* This method uses the "previousStep()"-function to
* move from ServerHelloComposite to ClientHelloComposite
*/
public void backToClientHello()
{
arrow.moveArrowsby(18);
arrow.nextArrow(100,75,0,75,0,0,0);
arrow.nextArrow(0,95,100,95,0,0,0);
previousStep();
}
/**
* Initializes the next Composite in the TLS-Handshake.
*/
public void nextStep()
{
if(serverHelloComposite.getVisible() == false || serverHelloComposite == null)
{
if(clientHelloComposite.checkParameters())
{
arrow.moveArrowsby(18);
serverHelloComposite.startStep();
serverHelloComposite.setVisible(true);
serverHelloComposite.enableControls();
clientHelloComposite.disableControls();
arrow.nextArrow(0,75,100,75,0,0,0);
btnPreviousStep.setEnabled(true);
}
}
else if(serverCertificateComposite.getVisible() == false || serverCertificateComposite == null)
{
if(serverHelloComposite.checkParameters())
{
serverCertificateComposite.startStep();
serverCertificateComposite.setVisible(true);
serverCertificateComposite.enableControls();
serverHelloComposite.disableControls();
}
}
else if(clientCertificateComposite.getVisible() == false || clientCertificateComposite == null)
{
if(serverCertificateComposite.checkParameters())
{
clientCertificateComposite.startStep();
clientCertificateComposite.setVisible(true);
clientCertificateComposite.enableControls();
serverCertificateComposite.disableControls();
clientCertificateComposite.refreshInformations();
arrow.nextArrow(100,275,0,275,0,0,0);
if (!Message.getServerCertificateServerCertificateRequest())
clientCertificateComposite.btnShow.setEnabled(false);
}
}
else if(serverChangeCipherSpecComposite.getVisible() == false || serverChangeCipherSpecComposite == null)
{
if(clientCertificateComposite.checkParameters())
{
serverChangeCipherSpecComposite.startStep();
serverChangeCipherSpecComposite.setVisible(true);
serverChangeCipherSpecComposite.enableControls();
serverFinishedComposite.startStep();
serverFinishedComposite.setVisible(true);
serverFinishedComposite.enableControls();
serverChangeCipherSpecComposite.refreshInformations();
clientCertificateComposite.disableControls();
arrow.nextArrow(0,325,100,450,0,0,0);
}
}
else if(clientChangeCipherSpecComposite.getVisible() == false || clientChangeCipherSpecComposite == null)
{
if(serverChangeCipherSpecComposite.checkParameters())
{
clientChangeCipherSpecComposite.startStep();
clientChangeCipherSpecComposite.setVisible(true);
clientChangeCipherSpecComposite.enableControls();
clientFinishedComposite.startStep();
clientFinishedComposite.setVisible(true);
clientFinishedComposite.enableControls();
clientChangeCipherSpecComposite.refreshInformations();
serverChangeCipherSpecComposite.disableControls();
serverFinishedComposite.disableControls();
btnNextStep.setEnabled(false);
arrow.nextArrow(100, 475, 0, 475, 0,0,0);
arrow.nextArrow(0, 500, 100, 500, 0, 0, 0);
arrow.nextArrow(100, 650, 0, 650, 0,180,0);
arrow.nextArrow(0, 675, 100, 675, 0, 180, 0);
}
}
}
/**
* Restarts the whole Plugin.
*/
public void resetStep()
{
clientFinishedComposite.setVisible(false);
clientFinishedComposite.resetStep();
clientChangeCipherSpecComposite.setVisible(false);
clientChangeCipherSpecComposite.resetStep();
serverFinishedComposite.setVisible(false);
serverFinishedComposite.resetStep();
serverChangeCipherSpecComposite.setVisible(false);
serverChangeCipherSpecComposite.resetStep();
clientCertificateComposite.setVisible(false);
clientCertificateComposite.resetStep();
serverCertificateComposite.setVisible(false);
serverCertificateComposite.resetStep();
serverHelloComposite.setVisible(false);
serverHelloComposite.resetStep();
clientHelloComposite.resetStep();
clientHelloComposite.enableControls();
arrow.resetArrows();
stxInformation.setText(Messages.SslViewStxInformation);
btnNextStep.setEnabled(true);
btnPreviousStep.setEnabled(false);
}
/**
* Removes the active Composite and goes back to the previous one.
* All selected options in the active Composite are set back.
*/
public void previousStep()
{
if(clientChangeCipherSpecComposite.getVisible() == true)
{
clientFinishedComposite.setVisible(false);
clientFinishedComposite.resetStep();
clientChangeCipherSpecComposite.setVisible(false);
clientChangeCipherSpecComposite.resetStep();
serverChangeCipherSpecComposite.enableControls();
serverFinishedComposite.enableControls();
arrow.removeLastArrow();
arrow.removeLastArrow();
arrow.removeLastArrow();
arrow.removeLastArrow();
btnNextStep.setEnabled(true);
}
else if(serverChangeCipherSpecComposite.getVisible() == true)
{
serverFinishedComposite.setVisible(false);
serverFinishedComposite.resetStep();
serverChangeCipherSpecComposite.setVisible(false);
serverChangeCipherSpecComposite.resetStep();
clientCertificateComposite.enableControls();
if (!Message.getServerCertificateServerCertificateRequest())
clientCertificateComposite.btnShow.setEnabled(false);
arrow.removeLastArrow();
}
else if(clientCertificateComposite.getVisible() == true)
{
clientCertificateComposite.setVisible(false);
clientCertificateComposite.resetStep();
serverCertificateComposite.enableControls();
arrow.removeLastArrow();
}
else if(serverCertificateComposite.getVisible() == true)
{
serverCertificateComposite.setVisible(false);
serverCertificateComposite.resetStep();
serverHelloComposite.enableControls();
serverHelloComposite.refreshInformations();
}
else if(serverHelloComposite.getVisible() == true)
{
serverHelloComposite.setVisible(false);
serverHelloComposite.resetStep();
clientHelloComposite.enableControls();
clientHelloComposite.refreshInformations();
arrow.removeLastArrow();
btnPreviousStep.setEnabled(false);
}
}
@Override
public void setFocus() {
// Set the focus
}
} |
package com.btmura.android.reddit;
import java.util.List;
import android.app.ListFragment;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.Loader;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;
public class ThingListFragment extends ListFragment implements LoaderCallbacks<List<Thing>>, OnScrollListener {
private static final String ARG_SUBREDDIT = "s";
private static final String ARG_FILTER = "f";
private static final String ARG_SINGLE_CHOICE = "c";
private static final String STATE_CHOSEN = "s";
private static final String LOADER_ARG_MORE_KEY = "m";
interface OnThingSelectedListener {
void onThingSelected(Thing thing, int position);
}
private ThingAdapter adapter;
private boolean scrollLoading;
public static ThingListFragment newInstance(Subreddit sr, int filter, boolean singleChoice) {
ThingListFragment frag = new ThingListFragment();
Bundle b = new Bundle(3);
b.putParcelable(ARG_SUBREDDIT, sr);
b.putInt(ARG_FILTER, filter);
b.putBoolean(ARG_SINGLE_CHOICE, singleChoice);
frag.setArguments(b);
return frag;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
adapter = new ThingAdapter(getActivity().getLayoutInflater(),
getArguments().getBoolean(ARG_SINGLE_CHOICE));
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = super.onCreateView(inflater, container, savedInstanceState);
ListView list = (ListView) view.findViewById(android.R.id.list);
list.setOnScrollListener(this);
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
adapter.setChosenPosition(savedInstanceState != null ? savedInstanceState.getInt(STATE_CHOSEN) : -1);
setListAdapter(adapter);
setListShown(false);
getLoaderManager().initLoader(0, null, this);
}
public Loader<List<Thing>> onCreateLoader(int id, Bundle args) {
Subreddit sr = getArguments().getParcelable(ARG_SUBREDDIT);
int filter = getArguments().getInt(ARG_FILTER);
String moreKey = args != null ? args.getString(LOADER_ARG_MORE_KEY) : null;
CharSequence url = Urls.subredditUrl(sr, filter, moreKey);
return new ThingLoader(getActivity(), sr.name, url, args != null ? adapter.getItems() : null);
}
public void onLoadFinished(Loader<List<Thing>> loader, List<Thing> things) {
scrollLoading = false;
adapter.swapData(things);
setEmptyText(getString(things != null ? R.string.empty : R.string.error));
setListShown(true);
}
public void onLoaderReset(Loader<List<Thing>> loader) {
adapter.swapData(null);
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
adapter.setChosenPosition(position);
adapter.notifyDataSetChanged();
Thing t = adapter.getItem(position);
switch (t.type) {
case Thing.TYPE_THING:
getListener().onThingSelected(adapter.getItem(position), position);
break;
}
}
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (scrollLoading) {
return;
}
if (firstVisibleItem + visibleItemCount * 2 >= totalItemCount) {
Loader<List<Thing>> loader = getLoaderManager().getLoader(0);
if (loader != null) {
if (!adapter.isEmpty()) {
Thing t = adapter.getItem(adapter.getCount() - 1);
if (t.type == Thing.TYPE_MORE) {
scrollLoading = true;
Bundle b = new Bundle(1);
b.putString(LOADER_ARG_MORE_KEY, t.moreKey);
getLoaderManager().restartLoader(0, b, this);
}
}
}
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_CHOSEN, adapter.getChosenPosition());
}
public void setChosenPosition(int position) {
if (position != adapter.getChosenPosition()) {
adapter.setChosenPosition(position);
adapter.notifyDataSetChanged();
}
}
@Override
public void onDestroyView() {
super.onDestroyView();
adapter.clearCache();
}
private OnThingSelectedListener getListener() {
return (OnThingSelectedListener) getActivity();
}
} |
package com.hearthsim.model;
import com.hearthsim.card.Card;
import com.hearthsim.card.Deck;
import com.hearthsim.card.minion.AuraTargetType;
import com.hearthsim.card.minion.Hero;
import com.hearthsim.card.minion.Minion;
import com.hearthsim.card.minion.MinionWithAura;
import com.hearthsim.card.minion.heroes.TestHero;
import com.hearthsim.exception.HSException;
import com.hearthsim.exception.HSInvalidPlayerIndexException;
import com.hearthsim.util.DeepCopyable;
import com.hearthsim.util.IdentityLinkedList;
import org.json.JSONObject;
import org.slf4j.MDC;
import java.util.ArrayList;
import java.util.EnumSet;
/**
* A class that represents the current state of the board (game)
*
*/
public class BoardModel implements DeepCopyable<BoardModel> {
// private final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(this.getClass());
private final PlayerModel currentPlayer;
private final PlayerModel waitingPlayer;
IdentityLinkedList<MinionPlayerPair> allMinionsFIFOList_;
public class MinionPlayerPair {
private Minion minion;
private PlayerSide playerSide;
public MinionPlayerPair(Minion minion, PlayerSide playerSide) {
this.minion = minion;
this.playerSide = playerSide;
}
public Minion getMinion() {
return minion;
}
public PlayerSide getPlayerSide() {
return playerSide;
}
public void setPlayerSide(PlayerSide playerSide) {
this.playerSide = playerSide;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MinionPlayerPair that = (MinionPlayerPair) o;
if (minion != null ? !minion.equals(that.minion) : that.minion != null) return false;
if (playerSide != null ? !playerSide.equals(that.playerSide) : that.playerSide != null) return false;
return true;
}
@Override
public int hashCode() {
int result = minion != null ? minion.hashCode() : 0;
result = 31 * result + (playerSide != null ? playerSide.hashCode() : 0);
return result;
}
}
public BoardModel() {
this(new PlayerModel((byte)0, "player0", new TestHero("hero0", (byte)30), new Deck()),
new PlayerModel((byte)1, "player1", new TestHero("hero1", (byte)30), new Deck()));
}
public BoardModel(Deck deckPlayer0, Deck deckPlayer1) {
this(new PlayerModel((byte)0, "player0", new TestHero("hero0", (byte)30), deckPlayer0),
new PlayerModel((byte)1, "player1", new TestHero("hero1", (byte)30), deckPlayer1));
}
public BoardModel(Hero p0_hero, Hero p1_hero) {
this(new PlayerModel((byte)0, "p0",p0_hero,new Deck()), new PlayerModel((byte)1, "p1",p1_hero,new Deck()));
}
public BoardModel(PlayerModel currentPlayerModel, PlayerModel waitingPlayerModel) {
this.currentPlayer = currentPlayerModel;
this.waitingPlayer = waitingPlayerModel;
buildModel();
}
public void buildModel() {
allMinionsFIFOList_ = new IdentityLinkedList<MinionPlayerPair>();
}
public IdentityLinkedList<Minion> getMinions(PlayerSide side) throws HSInvalidPlayerIndexException {
return modelForSide(side).getMinions();
}
public PlayerModel modelForSide(PlayerSide side){
PlayerModel model;
switch (side) {
case CURRENT_PLAYER: model = currentPlayer;
break;
case WAITING_PLAYER: model = waitingPlayer;
break;
default:
throw new RuntimeException("unexpected player side");
}
return model;
}
public Minion getMinion(PlayerSide side, int index) throws HSInvalidPlayerIndexException {
return modelForSide(side).getMinions().get(index);
}
public Card getCard_hand(PlayerSide playerSide, int index) throws HSInvalidPlayerIndexException {
return modelForSide(playerSide).getHand().get(index);
}
public Minion getCharacter(PlayerSide playerSide, int index) throws HSInvalidPlayerIndexException {
PlayerModel playerModel = modelForSide(playerSide);
return playerModel.getCharacter(index);
}
public Minion getMinionForCharacter(PlayerSide playerSide, int index) {
PlayerModel playerModel = modelForSide(playerSide);
return index == 0 ? playerModel.getHero() : playerModel.getMinions().get(index - 1);
}
// Various ways to put a minion onto board
/**
* Place a minion onto the board. Does not trigger any events, but applies all auras.
*
* This is a function to place a minion on the board. Use this function only if you
* want no events to be trigger upon placing the minion.
*
*
* @param playerSide
* @param minion The minion to be placed on the board.
* @param position The position to place the minion. The new minion goes to the "left" (lower index) of the postinion index.
* @throws HSInvalidPlayerIndexException
*/
public void placeMinion(PlayerSide playerSide, Minion minion, int position) throws HSInvalidPlayerIndexException {
PlayerModel playerModel = modelForSide(playerSide);
playerModel.getMinions().add(position, minion);
this.allMinionsFIFOList_.add(new MinionPlayerPair(minion, playerSide));
minion.isInHand(false);
//Apply the aura if any
applyAuraOfMinion(playerSide, minion);
applyOtherMinionsAura(playerSide, minion);
}
/**
* Place a minion onto the board. Does not trigger any events, but applies all auras.
*
* This is a function to place a minion on the board. Use this function only if you
* want no events to be trigger upon placing the minion.
*
*
* @param playerSide
* @param minion The minion to be placed on the board. The minion is placed on the right-most space.
* @throws HSInvalidPlayerIndexException
*/
public void placeMinion(PlayerSide playerSide, Minion minion) throws HSInvalidPlayerIndexException {
this.placeMinion(playerSide, minion, this.modelForSide(playerSide).getMinions().size());
}
public void placeCardHand(PlayerSide side, Card card){
modelForSide(side).placeCardHand(card);
}
public void removeCardFromHand(Card card, PlayerSide playerSide){
modelForSide(playerSide).getHand().remove(card);
}
public int getNumCards_hand(PlayerSide playerSide) throws HSInvalidPlayerIndexException {
return modelForSide(playerSide).getHand().size();
}
public void placeCardDeck(PlayerSide side, Card card){
modelForSide(side).placeCardDeck(card);
}
public Hero getHero(PlayerSide playerSide) {
return modelForSide(playerSide).getHero();
}
/**
* Draw a card from a deck and place it in the hand
*
* @param deck Deck from which to draw.
* @param numCards Number of cards to draw.
* @throws HSInvalidPlayerIndexException
*/
public void drawCardFromWaitingPlayerDeck(int numCards) {
//This minion is an enemy minion. Let's draw a card for the enemy. No need to use a StopNode for enemy card draws.
for (int indx = 0; indx < numCards; ++indx) {
this.getWaitingPlayer().drawNextCardFromDeck();
}
}
/**
* Draw a card from a deck and place it in the hand without using a CardDrawNode
*
* Note: It is almost always correct to use CardDrawNode instead of this function!!!!
*
* @param deck Deck from which to draw.
* @param numCards Number of cards to draw.
* @throws HSInvalidPlayerIndexException
*/
public void drawCardFromCurrentPlayerDeck(int numCards) throws HSInvalidPlayerIndexException {
for (int indx = 0; indx < numCards; ++indx) {
this.getCurrentPlayer().drawNextCardFromDeck();
}
}
/**
* Get the spell damage
*
* Returns the additional spell damage provided by buffs
* @return
* @param playerSide
*/
public byte getSpellDamage(PlayerSide playerSide) throws HSInvalidPlayerIndexException {
return modelForSide(playerSide).getSpellDamage();
}
public boolean removeMinion(MinionPlayerPair minionIdPair) throws HSInvalidPlayerIndexException {
this.allMinionsFIFOList_.remove(minionIdPair);
removeAuraOfMinion(minionIdPair.getPlayerSide(), minionIdPair.minion);
return this.modelForSide(minionIdPair.getPlayerSide()).getMinions().remove(minionIdPair.minion);
}
public boolean removeMinion(Minion minion) throws HSException {
MinionPlayerPair mP = null;
for (MinionPlayerPair minionIdPair : this.allMinionsFIFOList_) {
if (minionIdPair.minion == minion) {
mP = minionIdPair;
break;
}
}
return this.removeMinion(mP);
}
public boolean removeMinion(PlayerSide side, int minionIndex) throws HSException {
return removeMinion(getMinion(side, minionIndex));
}
// Overload support
public void addOverload(PlayerSide playerSide, byte overloadToAdd) throws HSException {
PlayerModel playerModel = modelForSide(playerSide);
playerModel.setOverload((byte) (playerModel.getOverload() + overloadToAdd));
}
// Aura Handling
// Aura handling is delegated to BoardModel rather than Minion class
/**
* Applies any aura that the given minion has
*
* @param side The PlayerSide of the minion
* @param minion
*/
public void applyAuraOfMinion(PlayerSide side, Minion minion) {
if (minion instanceof MinionWithAura && !minion.isSilenced()) {
EnumSet<AuraTargetType> targetTypes = ((MinionWithAura)minion).getAuraTargets();
for (AuraTargetType targetType : targetTypes) {
switch (targetType) {
case AURA_FRIENDLY_MINIONS:
for (Minion targetMinion : this.modelForSide(side).getMinions()) {
if (targetMinion != minion)
((MinionWithAura) minion).applyAura(side, targetMinion, this);
}
break;
case AURA_ENEMY_MINIONS:
for (Minion targetMinion : this.modelForSide(side.getOtherPlayer()).getMinions()) {
((MinionWithAura) minion).applyAura(side, targetMinion, this);
}
break;
default:
break;
}
}
}
}
/**
* Applies any aura effects that other minions on the board might have
*
* @param side The PlayerSide of the minion to apply the auras to
* @param minion
*/
public void applyOtherMinionsAura(PlayerSide side, Minion minion) {
for (Minion otherMinion : this.modelForSide(side).getMinions()) {
if (otherMinion instanceof MinionWithAura &&
minion != otherMinion &&
!otherMinion.isSilenced() &&
((MinionWithAura)otherMinion).getAuraTargets().contains(AuraTargetType.AURA_FRIENDLY_MINIONS)) {
((MinionWithAura)otherMinion).applyAura(side, minion, this);
}
}
for (Minion otherMinion : this.modelForSide(side.getOtherPlayer()).getMinions()) {
if (otherMinion instanceof MinionWithAura &&
minion != otherMinion &&
!otherMinion.isSilenced() &&
((MinionWithAura)otherMinion).getAuraTargets().contains(AuraTargetType.AURA_ENEMY_MINIONS)) {
((MinionWithAura)otherMinion).applyAura(side, minion, this);
}
}
}
/**
* Revomes any aura that the given minion might have
*
* @param side The PlayerSide of the minion
* @param minion
*/
public void removeAuraOfMinion(PlayerSide side, Minion minion) {
if (minion instanceof MinionWithAura && !minion.isSilenced()) {
EnumSet<AuraTargetType> targetTypes = ((MinionWithAura)minion).getAuraTargets();
for (AuraTargetType targetType : targetTypes) {
switch (targetType) {
case AURA_FRIENDLY_MINIONS:
for (Minion targetMinion : this.modelForSide(side).getMinions()) {
if (targetMinion != minion)
((MinionWithAura) minion).removeAura(side, targetMinion, this);
}
break;
case AURA_ENEMY_MINIONS:
for (Minion targetMinion : this.modelForSide(side.getOtherPlayer()).getMinions()) {
((MinionWithAura) minion).removeAura(side, targetMinion, this);
}
break;
default:
break;
}
}
}
}
public boolean isAlive(PlayerSide playerSide) {
return modelForSide(playerSide).getHero().getHealth() > 0;
}
public boolean isLethalState() {
return !this.isAlive(PlayerSide.CURRENT_PLAYER) || !this.isAlive(PlayerSide.WAITING_PLAYER);
}
@SuppressWarnings("unused")
public ArrayList<Integer> getAttackableMinions() {
ArrayList<Integer> toRet = new ArrayList<Integer>();
boolean hasTaunt = false;
for (final Minion minion : waitingPlayer.getMinions()) {
hasTaunt = hasTaunt || minion.getTaunt();
}
if (!hasTaunt) {
toRet.add(0);
int counter = 1;
for (Minion ignored : waitingPlayer.getMinions()) {
toRet.add(counter);
counter++;
}
return toRet;
} else {
int counter = 1;
for (Minion aP1_minions_ : waitingPlayer.getMinions()) {
if (aP1_minions_.getTaunt())
toRet.add(counter);
counter++;
}
return toRet;
}
}
//Dead minion check
/**
* Checks to see if there are dead minions
* @return
*/
public boolean hasDeadMinions() {
for (Minion minion : currentPlayer.getMinions()) {
if (minion.getTotalHealth() <= 0)
return true;
}
for (Minion minion : getWaitingPlayer().getMinions()) {
if (minion.getTotalHealth() <= 0) {
return true;
}
}
return false;
}
public IdentityLinkedList<MinionPlayerPair> getAllMinionsFIFOList() {
return allMinionsFIFOList_;
}
public void resetMana() {
currentPlayer.resetMana();
waitingPlayer.resetMana();
}
@Override
public boolean equals(Object other) {
if (other == null) {
return false;
}
if (this.getClass() != other.getClass()) {
return false;
}
BoardModel bOther = (BoardModel)other;
if (!currentPlayer.equals(bOther.currentPlayer)) return false;
if (!waitingPlayer.equals(bOther.waitingPlayer)) return false;
if (!allMinionsFIFOList_.equals(bOther.allMinionsFIFOList_)) return false;
return true;
}
@Override
public int hashCode() {
int hash = 1;
hash = hash * 31 + currentPlayer.hashCode();
hash = hash * 31 + waitingPlayer.hashCode();
hash = hash * 31 + allMinionsFIFOList_.hashCode();
return hash;
}
/**
* Reset all minions to clear their has_attacked state.
*
* Call this function at the beginning of each turn
*
*/
public void resetMinions() {
currentPlayer.getHero().hasAttacked(false);
currentPlayer.getHero().hasBeenUsed(false);
waitingPlayer.getHero().hasAttacked(false);
waitingPlayer.getHero().hasBeenUsed(false);
for (Minion minion : currentPlayer.getMinions()) {
minion.hasAttacked(false);
minion.hasBeenUsed(false);
}
for (Minion minion : waitingPlayer.getMinions()) {
minion.hasAttacked(false);
minion.hasBeenUsed(false);
}
}
/**
* Reset the has_been_used state of the cards in hand
*/
public void resetHand() {
for (Card card : currentPlayer.getHand()) {
card.hasBeenUsed(false);
}
}
public BoardModel flipPlayers() {
BoardModel newBoard = new BoardModel(waitingPlayer.deepCopy(), currentPlayer.deepCopy());
for (MinionPlayerPair minionPlayerPair : allMinionsFIFOList_) {
PlayerModel oldPlayerModel = this.modelForSide(minionPlayerPair.getPlayerSide());
Minion oldMinion = minionPlayerPair.getMinion();
int indexOfOldMinion = oldPlayerModel.getMinions().indexOf(oldMinion);
PlayerModel newPlayerModel = newBoard.modelForSide(minionPlayerPair.getPlayerSide().getOtherPlayer());
newBoard.allMinionsFIFOList_.add(new MinionPlayerPair(newPlayerModel.getMinions().get(indexOfOldMinion), minionPlayerPair.getPlayerSide().getOtherPlayer()));
}
return newBoard;
}
@Override
public BoardModel deepCopy() {
BoardModel newBoard = new BoardModel(currentPlayer.deepCopy(), waitingPlayer.deepCopy());
for (MinionPlayerPair minionPlayerPair : allMinionsFIFOList_) {
PlayerModel oldPlayerModel = this.modelForSide(minionPlayerPair.getPlayerSide());
Minion oldMinion = minionPlayerPair.getMinion();
int indexOfOldMinion = oldPlayerModel.getMinions().indexOf(oldMinion);
PlayerModel newPlayerModel = newBoard.modelForSide(minionPlayerPair.getPlayerSide());
newBoard.allMinionsFIFOList_.add(new MinionPlayerPair(newPlayerModel.getMinions().get(indexOfOldMinion), minionPlayerPair.getPlayerSide()));
}
return newBoard;
}
public JSONObject toJSON() {
JSONObject json = new JSONObject();
json.put("currentPlayer", currentPlayer.toJSON());
json.put("waitingPlayer", waitingPlayer.toJSON());
return json;
}
@Override
public String toString() {
String boardFormat = MDC.get("board_format");
if (boardFormat != null && boardFormat.equals("simple")) {
return simpleString();
} else {
return jsonString();
}
}
private String simpleString() {
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("[");
stringBuffer.append("P0_health:").append(currentPlayer.getHero().getHealth()).append(", ");
stringBuffer.append("P0_mana:").append(currentPlayer.getMana()).append(", ");
stringBuffer.append("P1_health:").append(waitingPlayer.getHero().getHealth()).append(", ");
stringBuffer.append("P1_mana:").append(waitingPlayer.getMana()).append(", ");
stringBuffer.append("]");
return stringBuffer.toString();
}
private String jsonString() {
return this.toJSON().toString();
}
public PlayerModel getCurrentPlayer() {
return currentPlayer;
}
public PlayerModel getWaitingPlayer() {
return waitingPlayer;
}
// TODO: remove asap, simply to aid in refactoring
public int getIndexOfPlayer(PlayerSide playerSide) {
if (playerSide == PlayerSide.CURRENT_PLAYER){
return 0;
} else {
return 1;
}
}
// TODO: remove asap, simply to aid in refactoring
public PlayerSide getPlayerByIndex(int index) {
if (index == 0){
return PlayerSide.CURRENT_PLAYER;
} else {
return PlayerSide.WAITING_PLAYER;
}
}
@Deprecated
public IdentityLinkedList<Card> getCurrentPlayerHand() {
return currentPlayer.getHand();
}
@Deprecated
public IdentityLinkedList<Card> getWaitingPlayerHand() {
return waitingPlayer.getHand();
}
@Deprecated
public PlayerSide sideForModel(PlayerModel model) {
if (model.equals(currentPlayer)) {
return PlayerSide.CURRENT_PLAYER;
} else if (model.equals(waitingPlayer)) {
return PlayerSide.WAITING_PLAYER;
} else {
throw new RuntimeException("unexpected player model");
}
}
@Deprecated
public Card getCurrentPlayerCardHand(int index) {
return currentPlayer.getHand().get(index);
}
@Deprecated
public Card getWaitingPlayerCardHand(int index) {
return waitingPlayer.getHand().get(index);
}
@Deprecated
public Minion getCurrentPlayerCharacter(int index) {
return getMinionForCharacter(PlayerSide.CURRENT_PLAYER, index);
}
@Deprecated
public Minion getWaitingPlayerCharacter(int index) {
return getMinionForCharacter(PlayerSide.WAITING_PLAYER, index);
}
@Deprecated
public void placeCard_hand(PlayerSide playerSide, Card card) throws HSInvalidPlayerIndexException {
card.isInHand(true);
modelForSide(playerSide).getHand().add(card);
}
@Deprecated
public void placeCardHandCurrentPlayer(int cardIndex) {
currentPlayer.placeCardHand(cardIndex);
}
@Deprecated
public void placeCardHandCurrentPlayer(Card card) {
currentPlayer.placeCardHand(card);
}
@Deprecated
public void placeCardHandWaitingPlayer(int cardIndex) {
waitingPlayer.placeCardHand(cardIndex);
}
@Deprecated
public void placeCardHandWaitingPlayer(Card card) {
waitingPlayer.placeCardHand(card);
}
@Deprecated
public void removeCard_hand(Card card) {
currentPlayer.getHand().remove(card);
}
@Deprecated
public int getNumCards_hand() {
return currentPlayer.getHand().size();
}
@Deprecated
public int getNumCardsHandCurrentPlayer() {
return currentPlayer.getHand().size();
}
@Deprecated
public int getNumCardsHandWaitingPlayer() {
return waitingPlayer.getHand().size();
}
@Deprecated
public Hero getCurrentPlayerHero() {
return currentPlayer.getHero();
}
@Deprecated
public Hero getWaitingPlayerHero() {
return waitingPlayer.getHero();
}
} |
package com.example.reader.texttospeech;
import java.util.HashMap;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.preference.PreferenceManager;
import android.speech.tts.TextToSpeech;
import android.speech.tts.UtteranceProgressListener;
import android.widget.Toast;
import com.example.reader.interfaces.OnTextToSpeechComplete;
import com.example.reader.interfaces.TTSHighlightCallback;
import com.example.reader.interfaces.TTSReadingCallback;
public class TextToSpeechIdDriven extends TextToSpeechBase {
private final TTSHighlightCallback cbHighlight;
private final TTSReadingCallback cbReading;
private int position;
private int startedPosition;
private final String SENTENCE_TAG;
public TextToSpeechIdDriven(Context context, OnTextToSpeechComplete listener, String sentTag,
TTSHighlightCallback highlight, TTSReadingCallback reading,
int requestCode, int resultCode, Intent data) {
super(context, listener, requestCode, resultCode, data);
this.cbHighlight = highlight;
this.cbReading = reading;
SENTENCE_TAG = sentTag;
final SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
if(Build.VERSION.SDK_INT >= 15){
tts.setOnUtteranceProgressListener(new UtteranceProgressListener() {
@Override
public void onStart(String utteranceId) {
startedPosition = position;
if(!utteranceId.equals("rehighlight"))
cbReading.OnStartedReading();
if(utteranceId.equals("speakWithId")){
cbHighlight.OnHighlight(position);
sp.edit().putInt(SENTENCE_TAG, position).commit();
} else if(utteranceId.equals("lastSpeakWithId")){
cbHighlight.OnHighlight(position);
sp.edit().putInt(SENTENCE_TAG, 0).commit();
}
}
@Override
public void onError(String utteranceId) {}
@Override
public void onDone(String utteranceId) {
boolean isStepping = sp.getBoolean("readerStepping", false);
if(isStepping){
sp.edit().putBoolean("readerStepping", false).commit();
return;
}
if(startedPosition != position){
return;
}
if(utteranceId.equals("speakWithId")){
cbHighlight.OnRemoveHighlight(position, true);
}else if(utteranceId.equals("lastSpeakWithId")){
cbHighlight.OnRemoveHighlight(position, false);
cbReading.OnFinishedReading();
} else if(utteranceId.equals("rehighlight")){
cbHighlight.OnHighlight(sp.getInt(SENTENCE_TAG, 0));
cbReading.OnFinishedReading();
}
}
});
} else {
// TODO: Should we handle devices older than VER: 4.0.3 - 4.0.4
// Then we need to handle the speaking differently
//tts.setOnUtteranceCompletedListener(listener)
}
}
public void speak(String text, int position, boolean isFinal){
if(text==null || text.isEmpty()){
Toast.makeText(context, "TTS: Speak: No data to speak", Toast.LENGTH_LONG).show();
return;
}
this.position = position;
HashMap<String, String> params = new HashMap<String, String>();
String value = !isFinal ? "speakWithId" : "lastSpeakWithId";
params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, value);
tts.speak(text, TextToSpeech.QUEUE_FLUSH, params);
}
public void rehighlight(){
HashMap<String, String> params = new HashMap<String, String>();
params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "rehighlight");
tts.speak("", TextToSpeech.QUEUE_FLUSH, params);
}
} |
package de.targodan.usb.ui;
import de.targodan.usb.data.Case;
import de.targodan.usb.data.CaseManager;
import de.targodan.usb.data.Client;
import de.targodan.usb.data.Platform;
import de.targodan.usb.data.Rat;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;
import java.util.Set;
import java.util.stream.Stream;
import javax.swing.AbstractCellEditor;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableModel;
/**
*
* @author Luca Corbatto
*/
public class CaseTable extends JTable {
private static class Model implements TableModel, Observer {
private static String[] COLUMNS = new String[] {
"Case", "CMDR Name", "Lang", "Plat", "System", "Rats", "Notes"
};
private static Class<?>[] COLUMN_CLASSES = new Class<?>[] {
Integer.class, Client.class, Client.class, Client.class, de.targodan.usb.data.System.class, Set.class, List.class
};
private CaseManager cm;
private Set<TableModelListener> listeners;
public Model(CaseManager cm) {
this.cm = cm;
this.cm.addObserver(this);
this.listeners = new HashSet<>();
}
@Override
public int getRowCount() {
return this.cm.getOpenCases().size() + this.cm.getClosedCases().size();
}
@Override
public int getColumnCount() {
return COLUMNS.length;
}
@Override
public String getColumnName(int columnIndex) {
return COLUMNS[columnIndex];
}
@Override
public Class<?> getColumnClass(int columnIndex) {
return COLUMN_CLASSES[columnIndex];
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return columnIndex == 6;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
switch(columnIndex) {
case 0:
return new Pair<>(this.getCase(rowIndex).getNumber(), this.getCase(rowIndex));
case 1:
case 2:
case 3:
return this.getCase(rowIndex).getClient();
case 4:
return this.getCase(rowIndex).getSystem();
case 5:
return this.getCase(rowIndex).getRats();
case 6:
return this.getCase(rowIndex).getNotes();
}
throw new IllegalArgumentException("Requested column "+columnIndex+" but only 7 columns supported.");
}
@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
if(columnIndex == 6) {
String val = aValue.toString();
this.getCase(rowIndex).setNotes(val.split("\n"));
}
}
@Override
public void addTableModelListener(TableModelListener l) {
this.listeners.add(l);
}
@Override
public void removeTableModelListener(TableModelListener l) {
this.listeners.remove(l);
}
private void notifyListeners() {
this.listeners.forEach(l -> {
l.tableChanged(new TableModelEvent(this));
});
}
private Case getCase(int rowIndex) {
if(rowIndex < this.cm.getClosedCases().size()) {
return this.cm.getClosedCases().get(rowIndex);
}
return this.cm.getOpenCases().get(rowIndex - this.cm.getClosedCases().size());
}
@Override
public void update(Observable o, Object arg) {
this.notifyListeners();
}
}
@SuppressWarnings("unchecked")
private static class CaseNumberRenderer implements TableCellRenderer {
private static final Color CR_BACKGROUND_COLOR = Color.RED;
private static final Color CR_FOREGROUND_COLOR = Color.WHITE;
private static final Color CLOSED_BACKGROUND_COLOR = Color.GREEN;
private static final Color CLOSED_FOREGROUND_COLOR = Color.BLACK;
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
Pair<Integer, Case> pair = (Pair<Integer, Case>)value;
TextPanel panel = new TextPanel("#"+pair.getLeft().toString());
if(pair.getRight().isClosed()) {
panel.setBackground(CLOSED_BACKGROUND_COLOR);
panel.getLabel().setForeground(CLOSED_FOREGROUND_COLOR);
panel.getLabel().setFont(new Font(panel.getLabel().getFont().getFamily(), Font.PLAIN, panel.getLabel().getFont().getSize()));
} else if(pair.getRight().isCodeRed()) {
panel.setBackground(CR_BACKGROUND_COLOR);
panel.getLabel().setForeground(CR_FOREGROUND_COLOR);
panel.getLabel().setFont(new Font(panel.getLabel().getFont().getFamily(), Font.BOLD, panel.getLabel().getFont().getSize()));
} else if(!pair.getRight().isActive()) {
panel.setText("("+panel.getText()+")");
}
int height = panel.getPreferredSize().height;
if(height > 0) {
table.setRowHeight(row, height);
}
return panel;
}
}
private static class ClientRenderer implements TableCellRenderer {
protected String platformToString(Platform platform) {
switch(platform) {
case PC:
return "PC";
case PS4:
return "PS4";
case XBOX:
return "XBox";
}
throw new IllegalArgumentException("Platform \""+platform.toString()+"\" is not supported.");
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
Client client = (Client)value;
switch(column) {
case 1:
return new CopyableTextPanel(client.getCMDRName());
case 2:
return new TextPanel(client.getLanguage().toUpperCase());
case 3:
return new TextPanel(this.platformToString(client.getPlatform()));
}
throw new IllegalArgumentException("Requested rendering for column "+column+" on ClientRenderer but only columns 1, 2 and 3 are suported.");
}
}
private static class SystemRenderer implements TableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
de.targodan.usb.data.System system = (de.targodan.usb.data.System)value;
return new CopyableTextPanel(system.getName());
}
}
@SuppressWarnings("unchecked")
private static class RatsRenderer implements TableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
Set<Rat> rats = (Set<Rat>)value;
JPanel panel = new JPanel(new GridLayout(rats.size(), 1));
rats.stream()
.sorted((r1, r2) -> r1.getCMDRName().compareTo(r2.getCMDRName()))
.forEach(rat -> {
panel.add(new RatView(rat));
});
int height = Stream.of(panel.getComponents())
.mapToInt(c -> c.getPreferredSize().height)
.sum();
if(height > 0) {
table.setRowHeight(row, height);
}
return panel;
}
}
@SuppressWarnings("unchecked")
private static class NotesRenderer implements TableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
List<String> notes = (List<String>)value;
return new MultiTextPanel(String.join("\n", notes));
}
}
private static class NotesEditor extends AbstractCellEditor implements TableCellEditor {
private Map<Pair<Integer, Integer>, Component> cells;
private MultiTextPanel panel;
public NotesEditor(Map<Pair<Integer, Integer>, Component> cells) {
this.cells = cells;
}
@Override
public Object getCellEditorValue() {
return this.panel.getText();
}
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
if(column == 6) {
this.panel = (MultiTextPanel)this.cells.get(new Pair<>(row, column));
return this.panel;
}
return null;
}
}
private class MouseHandler extends MouseAdapter {
private void relayEvent(MouseEvent e) {
int row = CaseTable.this.rowAtPoint(e.getPoint());
int column = CaseTable.this.columnAtPoint(e.getPoint());
Component c = CaseTable.this.cells.get(new Pair<>(row, column));
if(c == null) {
return;
}
Rectangle pos = CaseTable.this.getCellRect(row, column, true);
e.translatePoint(-(int)pos.getX(), -(int)pos.getY());
c.dispatchEvent(e);
}
@Override
public void mouseMoved(MouseEvent e) {
this.relayEvent(e);
}
@Override
public void mouseReleased(MouseEvent e) {
this.relayEvent(e);
}
@Override
public void mousePressed(MouseEvent e) {
this.relayEvent(e);
}
@Override
public void mouseClicked(MouseEvent e) {
this.relayEvent(e);
}
}
public CaseTable(CaseManager cm) {
super(new Model(cm));
this.cells = new HashMap<>();
this.setDefaultRenderer(Integer.class, new CaseNumberRenderer());
this.setDefaultRenderer(Client.class, new ClientRenderer());
this.setDefaultRenderer(de.targodan.usb.data.System.class, new SystemRenderer());
this.setDefaultRenderer(Set.class, new RatsRenderer());
this.setDefaultRenderer(List.class, new NotesRenderer());
this.setDefaultEditor(List.class, new NotesEditor(this.cells));
this.addMouseListener(new MouseHandler());
this.addMouseMotionListener(new MouseHandler());
// Case number
this.getColumnModel().getColumn(0).setMaxWidth(45);
// Language
this.getColumnModel().getColumn(2).setMaxWidth(45);
// Platform
this.getColumnModel().getColumn(3).setMaxWidth(45);
}
@Override
public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
Component c = super.prepareRenderer(renderer, row, column);
this.cells.put(new Pair<>(row, column), c);
return c;
}
private final Map<Pair<Integer, Integer>, Component> cells;
} |
package com.intel.alex.Utils;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import jxl.write.*;
import jxl.write.Number;
import java.io.*;
public class ExcelUtil {
private final String logDir;
public ExcelUtil(String logDir) {
this.logDir = logDir;
}
public void createExcel() {
File excFile = new File("BigBenchTimes.xls");
if (createRawDataSheet(excFile)) {
createPhaseSheet(excFile);
createPowerSheet(excFile);
createThroughputSheet(excFile);
}
}
private boolean createRawDataSheet(File excFile) {
try {
WritableWorkbook book;
book = Workbook.createWorkbook(excFile);
int num = book.getNumberOfSheets();
WritableSheet sheet = book.createSheet("BigBenchTimes", num);
FileReader fileReader = new FileReader(new File(logDir + "/run-logs/BigBenchTimes.csv"));
BufferedReader br = new BufferedReader(fileReader);
int i = 0;
String line;
while ((line = br.readLine()) != null) {
String s[] = line.split(";");
if (s.length > 3) {
for (int j = 0; j < s.length; j++) {
if (i == 0) {
Label title = new Label(j, i, s[j]);
sheet.addCell(title);
} else if (j == 0 || j == 2 || j == 3 || j == 4 | j == 5 | j == 8) {
if (s[j] != null && !s[j].equals("")) {
Number ints = new Number(j, i, Long.parseLong(s[j]));
sheet.addCell(ints);
} else {
Label label = new Label(j, i, s[j]);
sheet.addCell(label);
}
} else if (j == 9) {
Number doubles = new Number(j, i, Double.parseDouble(s[j]));
sheet.addCell(doubles);
} else {
Label label = new Label(j, i, s[j]);
sheet.addCell(label);
}
}
}
i++;
}
br.close();
fileReader.close();
book.write();
book.close();
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
private void createPowerSheet(File excFile) {
try {
FileInputStream fin = new FileInputStream(excFile);
Workbook wb = Workbook.getWorkbook(fin);
WritableWorkbook wwb = Workbook.createWorkbook(excFile, wb);
int num = wwb.getNumberOfSheets();
Sheet sheet = wwb.getSheet(0);
WritableSheet newSheet = wwb.createSheet("PowerTest", num);
Label queryNumber = new Label(0, 0, "QueryNumber");
Label queryTime = new Label(1, 0, "QueryTime(s)");
newSheet.addCell(queryNumber);
newSheet.addCell(queryTime);
int i = 1;
for (int r = 0; r < sheet.getRows(); r++) {
if (sheet.getCell(1, r).getContents().equals("POWER_TEST") && !sheet.getCell(3, r).getContents().equals("")) {
Number ints = new Number(0, i, Integer.parseInt(sheet.getCell(3, r).getContents()));
newSheet.addCell(ints);
Number doubles = new Number(1, i, Double.parseDouble(sheet.getCell(9, r).getContents()));
newSheet.addCell(doubles);
i++;
}
}
wwb.write();
wwb.close();
} catch (IOException e) {
e.printStackTrace();
} catch (BiffException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
}
private void createThroughputSheet(File excFile) {
try {
FileInputStream fin = new FileInputStream(excFile);
Workbook wb = Workbook.getWorkbook(fin);
WritableWorkbook wwb = Workbook.createWorkbook(excFile, wb);
int num = wwb.getNumberOfSheets();
Sheet sheet = wwb.getSheet(0);
WritableSheet newSheet = wwb.createSheet("Throughput", num);
Label queryNumber = new Label(0, 0, "QueryNumber");
newSheet.addCell(queryNumber);
for(int i =1 ; i<=30;i++){
Number queries = new Number(0, i, i);
newSheet.addCell(queries);
}
for (int r = 0; r < sheet.getRows(); r++) {
if (sheet.getCell(1, r).getContents().equals("THROUGHPUT_TEST_1") && !sheet.getCell(3, r).getContents().equals("")) {
int stream = Integer.parseInt(sheet.getCell(2, r).getContents());
Label streamNumber = new Label(stream + 1, 0, "Stream" + stream);
newSheet.addCell(streamNumber);
Number doubles = new Number(stream + 1, Integer.parseInt(sheet.getCell(3, r).getContents()), Double.parseDouble(sheet.getCell(9, r).getContents()));
newSheet.addCell(doubles);
}
}
wwb.write();
wwb.close();
} catch (IOException e) {
e.printStackTrace();
} catch (BiffException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
}
private void createPhaseSheet(File excFile) {
try {
FileInputStream fin = new FileInputStream(excFile);
Workbook wb = Workbook.getWorkbook(fin);
WritableWorkbook wwb = Workbook.createWorkbook(excFile, wb);
int num = wwb.getNumberOfSheets();
Sheet sheet = wwb.getSheet(0);
WritableSheet newSheet = wwb.createSheet("PhaseTime", num);
Label queryNumber = new Label(0, 0, "Phase");
Label queryTime = new Label(1, 0, "ElapsedTimes(s)");
newSheet.addCell(queryNumber);
newSheet.addCell(queryTime);
int i = 1;
for (int r = 0; r < sheet.getRows(); r++) {
if (sheet.getCell(2, r).getContents().equals("")) {
Label phase = new Label(0, i, (sheet.getCell(1, r).getContents()));
newSheet.addCell(phase);
Number doubles = new Number(1, i, Double.parseDouble(sheet.getCell(9, r).getContents()));
newSheet.addCell(doubles);
i++;
}
}
wwb.write();
wwb.close();
} catch (IOException e) {
e.printStackTrace();
} catch (BiffException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
}
} |
package eu.amidst.scai2015;
import eu.amidst.core.datastream.*;
import eu.amidst.core.distribution.Multinomial;
import eu.amidst.core.inference.InferenceAlgorithmForBN;
import eu.amidst.core.inference.messagepassing.VMP;
import eu.amidst.core.io.DataStreamLoader;
import eu.amidst.core.learning.StreamingVariationalBayesVMP;
import eu.amidst.core.models.BayesianNetwork;
import eu.amidst.core.models.DAG;
import eu.amidst.core.utils.Utils;
import eu.amidst.core.variables.StaticVariables;
import eu.amidst.core.variables.Variable;
import weka.classifiers.evaluation.NominalPrediction;
import weka.classifiers.evaluation.Prediction;
import weka.classifiers.evaluation.ThresholdCurve;
import weka.core.Instances;
import java.io.IOException;
import java.util.*;
public class wrapperBN {
int seed = 0;
Variable classVariable;
Variable classVariable_PM;
Attribute SEQUENCE_ID;
Attribute TIME_ID;
static int DEFAULTER_VALUE_INDEX = 1;
static int NON_DEFAULTER_VALUE_INDEX = 0;
int NbrClients= 50000;
HashMap<Integer, Multinomial> posteriorsGlobal = new HashMap<>();
static boolean usePRCArea = false; //By default ROCArea is used
static boolean dynamicNB = false;
static boolean onlyPrediction = false;
public static boolean isDynamicNB() {
return dynamicNB;
}
public static void setDynamicNB(boolean dynamicNB) {
wrapperBN.dynamicNB = dynamicNB;
}
public static boolean isOnlyPrediction() {
return onlyPrediction;
}
public static void setOnlyPrediction(boolean onlyPrediction) {
wrapperBN.onlyPrediction = onlyPrediction;
}
HashMap<Integer, Integer> defaultingClients = new HashMap<>();
public static boolean isUsePRCArea() {
return usePRCArea;
}
public static void setUsePRCArea(boolean usePRCArea) {
wrapperBN.usePRCArea = usePRCArea;
}
public Attribute getSEQUENCE_ID() {
return SEQUENCE_ID;
}
public void setSEQUENCE_ID(Attribute SEQUENCE_ID) {
this.SEQUENCE_ID = SEQUENCE_ID;
}
public Attribute getTIME_ID() {
return TIME_ID;
}
public void setTIME_ID(Attribute TIME_ID) {
this.TIME_ID = TIME_ID;
}
public Variable getClassVariable_PM() {
return classVariable_PM;
}
public void setClassVariable_PM(Variable classVariable_PM) {
this.classVariable_PM = classVariable_PM;
}
public int getSeed() {
return seed;
}
public void setSeed(int seed) {
this.seed = seed;
}
public Variable getClassVariable() {
return classVariable;
}
public void setClassVariable(Variable classVariable) {
this.classVariable = classVariable;
}
public BayesianNetwork wrapperBNOneMonthNB(DataOnMemory<DataInstance> data){
StaticVariables Vars = new StaticVariables(data.getAttributes());
//Split the whole data into training and testing
List<DataOnMemory<DataInstance>> splitData = this.splitTrainAndTest(data,66.0);
DataOnMemory<DataInstance> trainingData = splitData.get(0);
DataOnMemory<DataInstance> testData = splitData.get(1);
List<Variable> NSF = new ArrayList<>(Vars.getListOfVariables()); // NSF: non selected features
NSF.remove(classVariable); //remove C
NSF.remove(classVariable_PM); // remove C'
int nbrNSF = NSF.size();
List<Variable> SF = new ArrayList(); // SF:selected features
Boolean stop = false;
//Learn the initial BN with training data including only the class variable
BayesianNetwork bNet = train(trainingData, Vars, SF,false);
System.out.println(bNet.toString());
//Evaluate the initial BN with testing data including only the class variable, i.e., initial score or initial auc
double score = testFS(testData, bNet);
int cont=0;
//iterate until there is no improvement in score
while (nbrNSF > 0 && stop == false ){
System.out.print("Iteration: " + cont + ", Score: "+score +", Number of selected variables: "+ SF.size() + ", ");
SF.stream().forEach(v -> System.out.print(v.getName() + ", "));
System.out.println();
Map<Variable, Double> scores = new HashMap<>(); //scores for each considered feature
for(Variable V:NSF) {
//if (V.getVarID()>5)
// break;
System.out.println("Testing "+V.getName());
SF.add(V);
//train
bNet = train(trainingData, Vars, SF, false);
//evaluate
scores.put(V, testFS(testData, bNet));
SF.remove(V);
}
//determine the Variable V with max score
double maxScore = (Collections.max(scores.values())); //returns max value in the Hashmap
if (maxScore - score > 0.001){
score = maxScore;
//Variable with best score
for (Map.Entry<Variable, Double> entry : scores.entrySet()) {
if (entry.getValue()== maxScore){
Variable SelectedV = entry.getKey();
SF.add(SelectedV);
NSF.remove(SelectedV);
break;
}
}
nbrNSF = nbrNSF - 1;
}
else{
stop = true;
}
cont++;
}
//Final training with the winning SF and the full initial data
bNet = train(data, Vars, SF, true);
System.out.println(bNet.getDAG().toString());
return bNet;
}
List<DataOnMemory<DataInstance>> splitTrainAndTest(DataOnMemory<DataInstance> data, double trainPercentage) {
Random random = new Random(this.seed);
DataOnMemoryListContainer<DataInstance> train = new DataOnMemoryListContainer(data.getAttributes());
DataOnMemoryListContainer<DataInstance> test = new DataOnMemoryListContainer(data.getAttributes());
for (DataInstance dataInstance : data) {
if (dataInstance.getValue(classVariable) == DEFAULTER_VALUE_INDEX)
continue;
if (random.nextDouble()<trainPercentage/100.0)
train.add(dataInstance);
else
test.add(dataInstance);
}
for (DataInstance dataInstance : data) {
if (dataInstance.getValue(classVariable) != DEFAULTER_VALUE_INDEX)
continue;
if (random.nextDouble()<trainPercentage/100.0)
train.add(dataInstance);
else
test.add(dataInstance);
}
Collections.shuffle(train.getList(), random);
Collections.shuffle(test.getList(), random);
return Arrays.asList(train, test);
}
public BayesianNetwork train(DataOnMemory<DataInstance> data, StaticVariables allVars, List<Variable> SF, boolean includeClassVariablePM){
DAG dag = new DAG(allVars);
if(includeClassVariablePM)
dag.getParentSet(classVariable).addParent(classVariable_PM);
/* Add classVariable to all SF*/
dag.getParentSets().stream()
.filter(parent -> SF.contains(parent.getMainVar()))
.filter(w -> w.getMainVar().getVarID() != classVariable.getVarID())
.forEach(w -> w.addParent(classVariable));
StreamingVariationalBayesVMP vmp = new StreamingVariationalBayesVMP();
vmp.setDAG(dag);
vmp.setDataStream(data);
vmp.setWindowsSize(100);
vmp.runLearning();
return vmp.getLearntBayesianNetwork();
}
public BayesianNetwork train(DataOnMemory<DataInstance> data, StaticVariables allVars, List<Variable> SF){
DAG dag = new DAG(allVars);
if(data.getDataInstance(0).getValue(TIME_ID)!=0)
dag.getParentSet(classVariable).addParent(classVariable_PM);
/* Add classVariable to all SF*/
dag.getParentSets().stream()
.filter(parent -> SF.contains(parent.getMainVar()))
.filter(w -> w.getMainVar().getVarID() != classVariable.getVarID())
.forEach(w -> w.addParent(classVariable));
StreamingVariationalBayesVMP vmp = new StreamingVariationalBayesVMP();
vmp.setDAG(dag);
vmp.setDataStream(data);
vmp.setWindowsSize(100);
vmp.runLearning();
return vmp.getLearntBayesianNetwork();
}
public double testFS(DataOnMemory<DataInstance> data, BayesianNetwork bn){
InferenceAlgorithmForBN vmp = new VMP();
ArrayList<Prediction> predictions = new ArrayList<>();
int currentMonthIndex = (int)data.getDataInstance(0).getValue(TIME_ID);
for (DataInstance instance : data) {
int clientID = (int) instance.getValue(SEQUENCE_ID);
double classValue = instance.getValue(classVariable);
Prediction prediction;
Multinomial posterior;
vmp.setModel(bn);
instance.setValue(classVariable, Utils.missingValue());
vmp.setEvidence(instance);
vmp.runInference();
posterior = vmp.getPosterior(classVariable);
instance.setValue(classVariable, classValue);
prediction = new NominalPrediction(classValue, posterior.getProbabilities());
predictions.add(prediction);
}
ThresholdCurve thresholdCurve = new ThresholdCurve();
Instances tcurve = thresholdCurve.getCurve(predictions);
if(usePRCArea)
return ThresholdCurve.getPRCArea(tcurve);
else
return ThresholdCurve.getROCArea(tcurve);
}
public double test(DataOnMemory<DataInstance> data, BayesianNetwork bn, HashMap<Integer, Multinomial> posteriors, boolean updatePosteriors){
InferenceAlgorithmForBN vmp = new VMP();
ArrayList<Prediction> predictions = new ArrayList<>();
int currentMonthIndex = (int)data.getDataInstance(0).getValue(TIME_ID);
for (DataInstance instance : data) {
int clientID = (int) instance.getValue(SEQUENCE_ID);
double classValue = instance.getValue(classVariable);
Prediction prediction;
Multinomial posterior;
/*Propagates*/
bn.setConditionalDistribution(classVariable_PM, posteriors.get(clientID));
/*
Multinomial_MultinomialParents distClass = bn.getConditionalDistribution(classVariable);
Multinomial deterministic = new Multinomial(classVariable);
deterministic.setProbabilityOfState(DEFAULTER_VALUE_INDEX, 1.0);
deterministic.setProbabilityOfState(NON_DEFAULTER_VALUE_INDEX, 0.0);
distClass.setMultinomial(DEFAULTER_VALUE_INDEX, deterministic);
*/
vmp.setModel(bn);
double classValue_PM = instance.getValue(classVariable_PM);
instance.setValue(classVariable, Utils.missingValue());
instance.setValue(classVariable_PM, Utils.missingValue());
vmp.setEvidence(instance);
vmp.runInference();
posterior = vmp.getPosterior(classVariable);
instance.setValue(classVariable, classValue);
instance.setValue(classVariable_PM, classValue_PM);
prediction = new NominalPrediction(classValue, posterior.getProbabilities());
predictions.add(prediction);
if (classValue == DEFAULTER_VALUE_INDEX) {
defaultingClients.putIfAbsent(clientID, currentMonthIndex);
}
if(updatePosteriors) {
Multinomial multi_PM = posterior.toEFUnivariateDistribution().deepCopy(classVariable_PM).toUnivariateDistribution();
if (classValue == DEFAULTER_VALUE_INDEX) {
multi_PM.setProbabilityOfState(DEFAULTER_VALUE_INDEX, 1.0);
multi_PM.setProbabilityOfState(NON_DEFAULTER_VALUE_INDEX, 0);
}
posteriors.put(clientID, multi_PM);
}
}
ThresholdCurve thresholdCurve = new ThresholdCurve();
Instances tcurve = thresholdCurve.getCurve(predictions);
if(usePRCArea)
return ThresholdCurve.getPRCArea(tcurve);
else
return ThresholdCurve.getROCArea(tcurve);
}
public double propagateAndTest(Queue<DataOnMemory<DataInstance>> data, BayesianNetwork bn){
HashMap<Integer, Multinomial> posteriors = new HashMap<>();
InferenceAlgorithmForBN vmp = new VMP();
ArrayList<Prediction> predictions = new ArrayList<>();
/*
for (int i = 0; i < NbrClients ; i++){
Multinomial uniform = new Multinomial(classVariable_PM);
uniform.setProbabilityOfState(DEFAULTER_VALUE_INDEX, 0.5);
uniform.setProbabilityOfState(NON_DEFAULTER_VALUE_INDEX, 0.5);
posteriors.put(i, uniform);
}
*/
boolean firstMonth = true;
Iterator<DataOnMemory<DataInstance>> iterator = data.iterator();
while(iterator.hasNext()){
Prediction prediction = null;
Multinomial posterior = null;
DataOnMemory<DataInstance> batch = iterator.next();
int currentMonthIndex = (int)batch.getDataInstance(0).getValue(TIME_ID);
for (DataInstance instance : batch) {
int clientID = (int) instance.getValue(SEQUENCE_ID);
double classValue = instance.getValue(classVariable);
/*Propagates*/
double classValue_PM = -1;
if(!firstMonth){
bn.setConditionalDistribution(classVariable_PM, posteriors.get(clientID));
classValue_PM = instance.getValue(classVariable_PM);
instance.setValue(classVariable_PM, Utils.missingValue());
}
vmp.setModel(bn);
instance.setValue(classVariable, Utils.missingValue());
vmp.setEvidence(instance);
vmp.runInference();
posterior = vmp.getPosterior(classVariable);
instance.setValue(classVariable, classValue);
if(!firstMonth) {
instance.setValue(classVariable_PM, classValue_PM);
}
if(!iterator.hasNext()) { //Last month or present
prediction = new NominalPrediction(classValue, posterior.getProbabilities());
predictions.add(prediction);
}
Multinomial multi_PM = posterior.toEFUnivariateDistribution().deepCopy(classVariable_PM).toUnivariateDistribution();
posteriors.put(clientID, multi_PM);
}
firstMonth = false;
if(!iterator.hasNext()) {//Last month or present time
ThresholdCurve thresholdCurve = new ThresholdCurve();
Instances tcurve = thresholdCurve.getCurve(predictions);
if(usePRCArea)
return ThresholdCurve.getPRCArea(tcurve);
else
return ThresholdCurve.getROCArea(tcurve);
}
}
throw new UnsupportedOperationException("Something went wrong: The method should have stopped at some point in the loop.");
}
void learnCajamarModel(DataStream<DataInstance> data) {
StaticVariables Vars = new StaticVariables(data.getAttributes());
classVariable = Vars.getVariableById(Vars.getNumberOfVars()-1);
classVariable_PM = Vars.getVariableById(Vars.getNumberOfVars()-2);
TIME_ID = data.getAttributes().getAttributeByName("TIME_ID");
SEQUENCE_ID = data.getAttributes().getAttributeByName("SEQUENCE_ID");
int count = 0;
double averageAUC = 0;
/*
for (int i = 0; i < NbrClients ; i++){
Multinomial uniform = new Multinomial(classVariable_PM);
uniform.setProbabilityOfState(DEFAULTER_VALUE_INDEX, 0.5);
uniform.setProbabilityOfState(NON_DEFAULTER_VALUE_INDEX, 0.5);
posteriorsGlobal.put(i, uniform);
}
*/
Iterable<DataOnMemory<DataInstance>> iteratable = data.iterableOverBatches(NbrClients);
Iterator<DataOnMemory<DataInstance>> iterator = iteratable.iterator();
Queue<DataOnMemory<DataInstance>> monthsMinus12to0 = new LinkedList<>();
iterator.next(); //First month is discarded
//Take 13 batches at a time - 1 for training and 12 for testing
//for (int i = 0; i < 12; i++) {
for (int i = 0; i < 2; i++) {
monthsMinus12to0.add(iterator.next());
}
while(iterator.hasNext()){
DataOnMemory<DataInstance> currentMonth = iterator.next();
monthsMinus12to0.add(currentMonth);
int idMonthMinus12 = (int)monthsMinus12to0.peek().getDataInstance(0).getValue(TIME_ID);
BayesianNetwork bn = null;
if(isOnlyPrediction()){
DataOnMemory<DataInstance> batch = monthsMinus12to0.poll();
StaticVariables vars = new StaticVariables(batch.getAttributes());
bn = train(batch, vars, vars.getListOfVariables(),this.isDynamicNB());
}
else
bn = wrapperBNOneMonthNB(monthsMinus12to0.poll());
double auc = propagateAndTest(monthsMinus12to0, bn);
System.out.println( idMonthMinus12 + "\t" + auc);
averageAUC += auc;
count += NbrClients;
}
System.out.println("Average Accuracy: " + averageAUC / (count / NbrClients));
}
public static void main(String[] args) throws IOException {
//DataStream<DataInstance> data = DataStreamLoader.loadFromFile("datasets/BankArtificialDataSCAI2015_DEFAULTING_PM.arff");
DataStream<DataInstance> data = DataStreamLoader.loadFromFile(args[0]);
for (int i = 1; i < args.length ; i++) {
if(args[i].equalsIgnoreCase("PRCArea"))
setUsePRCArea(true);
if(args[i].equalsIgnoreCase("onlyPrediction"))
setOnlyPrediction(true);
if(args[i].equalsIgnoreCase("dynamic"))
setDynamicNB(true);
}
wrapperBN wbnet = new wrapperBN();
wbnet.learnCajamarModel(data);
}
} |
package com.ecyrd.jspwiki.providers;
import java.lang.ref.SoftReference;
import java.util.Properties;
import java.util.Collection;
import java.util.HashMap;
import java.util.TreeSet;
import java.util.Date;
import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;
import java.io.IOException;
import org.apache.log4j.Category;
import com.ecyrd.jspwiki.*;
import com.ecyrd.jspwiki.util.ClassUtil;
/**
* Provides a caching page provider. This class rests on top of a
* real provider class and provides a cache to speed things up. Only
* if the cache copy of the page text has expired, we fetch it from
* the provider.
* <p>
* This class also detects if someone has modified the page
* externally, not through JSPWiki routines, and throws the proper
* RepositoryModifiedException.
*
* Heavily based on ideas by Chris Brooking.
*
* @author Janne Jalkanen
* @since 1.6.4
* @see RepositoryModifiedException
*/
// FIXME: Keeps a list of all WikiPages in memory - should cache them too.
// FIXME: Synchronization is a bit inconsistent in places.
public class CachingProvider
implements WikiPageProvider
{
private static final Category log = Category.getInstance(CachingProvider.class);
private WikiPageProvider m_provider;
private HashMap m_cache = new HashMap();
private long m_cacheMisses = 0;
private long m_cacheHits = 0;
private long m_milliSecondsBetweenChecks = 5000;
public void initialize( Properties properties )
throws NoRequiredPropertyException,
IOException
{
log.debug("Initing CachingProvider");
String classname = WikiEngine.getRequiredProperty( properties,
PageManager.PROP_PAGEPROVIDER );
try
{
Class providerclass = ClassUtil.findClass( "com.ecyrd.jspwiki.providers",
classname );
m_provider = (WikiPageProvider)providerclass.newInstance();
log.debug("Initializing real provider class "+m_provider);
m_provider.initialize( properties );
}
catch( ClassNotFoundException e )
{
log.error("Unable to locate provider class "+classname,e);
throw new IllegalArgumentException("no provider class");
}
catch( InstantiationException e )
{
log.error("Unable to create provider class "+classname,e);
throw new IllegalArgumentException("faulty provider class");
}
catch( IllegalAccessException e )
{
log.error("Illegal access to provider class "+classname,e);
throw new IllegalArgumentException("illegal provider class");
}
}
public boolean pageExists( String page )
{
CacheItem item = (CacheItem)m_cache.get( page );
if( checkIfPageChanged( item ) )
{
try
{
revalidatePage( item.m_page );
}
catch( ProviderException e ) {} // FIXME: Should do something!
return m_provider.pageExists( page );
}
// A null item means that the page either does not
// exist, or has not yet been cached; a non-null
// means that the page does exist.
if( item != null )
{
return true;
}
// We could add the page to the cache here as well,
// but in order to understand whether that is a
// good thing or not we would need to analyze
// the JSPWiki calling patterns extensively. Presumably
// it would be a good thing if pageExists() is called
// many times before the first getPageText() is called,
// and the whole page is cached.
return m_provider.pageExists( page );
}
/**
* @throws RepositoryModifiedException If the page has been externally modified.
*/
public String getPageText( String page, int version )
throws ProviderException
{
String result = null;
if( version == WikiPageProvider.LATEST_VERSION )
{
if( pageExists( page ) )
{
result = getTextFromCache( page );
}
}
else
{
CacheItem item = (CacheItem)m_cache.get( page );
// Or is this the latest version fetched by version number?
if( item != null && item.m_page.getVersion() == version )
{
result = getTextFromCache( page );
}
else
{
result = m_provider.getPageText( page, version );
}
}
return result;
}
/**
* Returns true, if the page has been changed outside of JSPWiki.
*/
private boolean checkIfPageChanged( CacheItem item )
{
if( item == null ) return false;
long currentTime = System.currentTimeMillis();
if( currentTime - item.m_lastChecked > m_milliSecondsBetweenChecks )
{
// log.debug("Consistency check: has page "+item.m_page.getName()+" been changed?");
try
{
WikiPage cached = item.m_page;
WikiPage current = m_provider.getPageInfo( cached.getName(),
LATEST_VERSION );
// Page has been deleted.
if( current == null )
{
log.debug("Page "+cached.getName()+" has been removed externally.");
return true;
}
item.m_lastChecked = currentTime;
long epsilon = 1000L; // FIXME: This should be adjusted according to provider granularity.
Date curDate = current.getLastModified();
Date cacDate = cached.getLastModified();
// log.debug("cached date = "+cacDate+", current date = "+curDate);
if( curDate != null && cacDate != null &&
curDate.getTime() - cacDate.getTime() > epsilon )
{
log.debug("Page "+current.getName()+" has been externally modified, refreshing contents.");
return true;
}
}
catch( ProviderException e )
{
log.error("While checking cache, got error: ",e);
}
}
return false;
}
/**
* Removes the page from cache, and attempts to reload all information.
*/
private synchronized void revalidatePage( WikiPage page )
throws ProviderException
{
m_cache.remove( page.getName() );
addPage( page.getName(), null ); // If fetch fails, we want info to go directly to user
}
/**
* @throws RepositoryModifiedException If the page has been externally modified.
*/
private String getTextFromCache( String page )
throws ProviderException
{
CacheItem item;
synchronized(this)
{
item = (CacheItem)m_cache.get( page );
}
// Check if page has been changed externally. If it has, then
// we need to refresh all of the information.
if( checkIfPageChanged( item ) )
{
revalidatePage( item.m_page );
throw new RepositoryModifiedException( page );
}
if( item == null )
{
// Page has never been seen.
// log.debug("Page "+page+" never seen.");
String text = m_provider.getPageText( page, WikiPageProvider.LATEST_VERSION );
addPage( page, text );
m_cacheMisses++;
return text;
}
else
{
String text = (String)item.m_text.get();
if( text == null )
{
// Oops, expired already
// log.debug("Page "+page+" expired.");
text = m_provider.getPageText( page, WikiPageProvider.LATEST_VERSION );
item.m_text = new SoftReference( text );
m_cacheMisses++;
return text;
}
// log.debug("Page "+page+" found in cache.");
m_cacheHits++;
return text;
}
}
public void putPageText( WikiPage page, String text )
throws ProviderException
{
synchronized(this)
{
m_provider.putPageText( page, text );
revalidatePage( page );
}
}
// FIXME: This MUST be cached somehow.
private boolean m_gotall = false;
public Collection getAllPages()
throws ProviderException
{
Collection all;
if( m_gotall == false )
{
all = m_provider.getAllPages();
// Make sure that all pages are in the cache.
// FIXME: This has the unfortunate side effect of clearing
// the cache.
synchronized(this)
{
for( Iterator i = all.iterator(); i.hasNext(); )
{
CacheItem item = new CacheItem();
item.m_page = (WikiPage) i.next();
item.m_text = new SoftReference( null );
m_cache.put( item.m_page.getName(), item );
}
m_gotall = true;
}
}
else
{
all = new ArrayList();
for( Iterator i = m_cache.values().iterator(); i.hasNext(); )
{
all.add( ((CacheItem)i.next()).m_page );
}
}
return all;
}
// Null text for no page
// Returns null if no page could be found.
private synchronized CacheItem addPage( String pageName, String text )
throws ProviderException
{
CacheItem item = null;
WikiPage newpage = m_provider.getPageInfo( pageName, WikiPageProvider.LATEST_VERSION );
if( newpage != null )
{
item = new CacheItem();
item.m_page = newpage;
item.m_text = new SoftReference( text );
m_cache.put( pageName, item );
}
return item;
}
public Collection getAllChangedSince( Date date )
{
return m_provider.getAllChangedSince( date );
}
public int getPageCount()
throws ProviderException
{
return m_provider.getPageCount();
}
public Collection findPages( QueryItem[] query )
{
TreeSet res = new TreeSet( new SearchResultComparator() );
SearchMatcher matcher = new SearchMatcher( query );
Collection allPages = null;
try
{
allPages = getAllPages();
}
catch( ProviderException pe )
{
log.error( "Unable to retrieve page list", pe );
return( null );
}
Iterator it = allPages.iterator();
while( it.hasNext() )
{
try
{
WikiPage page = (WikiPage) it.next();
String pageName = page.getName();
String pageContent = getTextFromCache( pageName );
SearchResult comparison = matcher.matchPageContent( pageName, pageContent );
if( comparison != null )
{
res.add( comparison );
}
}
catch( RepositoryModifiedException rme )
{
// FIXME: What to do in this case???
}
catch( ProviderException pe )
{
log.error( "Unable to retrieve page from cache", pe );
}
catch( IOException ioe )
{
log.error( "Failed to search page", ioe );
}
}
return( res );
}
public WikiPage getPageInfo( String page, int version )
throws ProviderException
{
CacheItem item = (CacheItem)m_cache.get( page );
int latestcached = (item != null) ? item.m_page.getVersion() : Integer.MIN_VALUE;
if( version == WikiPageProvider.LATEST_VERSION ||
version == latestcached )
{
if( item == null )
{
item = addPage( page, null );
if( item == null )
{
return null;
}
}
return item.m_page;
}
else
{
// We do not cache old versions.
return m_provider.getPageInfo( page, version );
}
}
public List getVersionHistory( String page )
throws ProviderException
{
return m_provider.getVersionHistory( page );
}
public synchronized String getProviderInfo()
{
int cachedPages = 0;
long totalSize = 0;
for( Iterator i = m_cache.values().iterator(); i.hasNext(); )
{
CacheItem item = (CacheItem) i.next();
String text = (String) item.m_text.get();
if( text != null )
{
cachedPages++;
totalSize += text.length()*2;
}
}
totalSize = (totalSize+512)/1024L;
return("Real provider: "+m_provider.getClass().getName()+
"<br />Cache misses: "+m_cacheMisses+
"<br />Cache hits: "+m_cacheHits+
"<br />Cached pages: "+cachedPages+
"<br />Total cache size (kBytes): "+totalSize+
"<br />Cache consistency checks: "+m_milliSecondsBetweenChecks+"ms");
}
public void deleteVersion( String pageName, int version )
throws ProviderException
{
// Luckily, this is such a rare operation it is okay
// to synchronize against the whole thing.
synchronized( this )
{
CacheItem item = (CacheItem)m_cache.get( pageName );
int latestcached = (item != null) ? item.m_page.getVersion() : Integer.MIN_VALUE;
// If we have this version cached, remove from cache.
if( version == WikiPageProvider.LATEST_VERSION ||
version == latestcached )
{
m_cache.remove( pageName );
}
m_provider.deleteVersion( pageName, version );
}
}
public void deletePage( String pageName )
throws ProviderException
{
// See note in deleteVersion().
synchronized(this)
{
m_cache.remove( pageName );
m_provider.deletePage( pageName );
}
}
/**
* Returns the actual used provider.
* @since 2.0
*/
public WikiPageProvider getRealProvider()
{
return m_provider;
}
private class CacheItem
{
WikiPage m_page;
long m_lastChecked = 0L;
SoftReference m_text;
}
} |
package com.jaamsim.BasicObjects;
import java.util.ArrayList;
import com.jaamsim.Graphics.DisplayEntity;
import com.jaamsim.Samples.SampleConstant;
import com.jaamsim.Samples.SampleExpInput;
import com.jaamsim.basicsim.Entity;
import com.jaamsim.datatypes.DoubleVector;
import com.jaamsim.events.EventHandle;
import com.jaamsim.events.EventManager;
import com.jaamsim.events.ProcessTarget;
import com.jaamsim.input.BooleanInput;
import com.jaamsim.input.IntegerInput;
import com.jaamsim.input.Keyword;
import com.jaamsim.input.Output;
import com.jaamsim.input.ValueInput;
import com.jaamsim.math.Vec3d;
import com.jaamsim.units.DimensionlessUnit;
import com.jaamsim.units.DistanceUnit;
import com.jaamsim.units.TimeUnit;
public class Queue extends LinkedComponent {
@Keyword(description = "The priority for positioning the received entity in the queue.\n" +
"Priority is integer valued and a lower numerical value indicates a higher priority.\n" +
"For example, priority 3 is higher than 4, and priorities 3, 3.2, and 3.8 are equivalent.",
example = "Queue1 Priority { this.obj.Attrib1 }")
private final SampleExpInput priority;
@Keyword(description = "An expression that returns a dimensionless integer value that can be used to "
+ "match entities in separate queues. The expression is evaluated when the entity "
+ "first arrives at the queue. Since Match is integer valued, a value of 3.2 for one "
+ "queue and 3.6 for another queue are considered to be equal.",
example = "Queue1 Match { this.obj.Attrib1 }")
private final SampleExpInput match;
@Keyword(description = "Determines the order in which entities are placed in the queue (FIFO or LIFO):\n" +
"TRUE = first in first out (FIFO) order (the default setting)," +
"FALSE = last in first out (LIFO) order.",
example = "Queue1 FIFO { FALSE }")
private final BooleanInput fifo;
@Keyword(description = "The amount of graphical space shown between DisplayEntity objects in the queue.",
example = "Queue1 Spacing { 1 m }")
private final ValueInput spacing;
@Keyword(description = "The number of queuing entities in each row.",
example = "Queue1 MaxPerLine { 4 }")
protected final IntegerInput maxPerLine; // maximum items per sub line-up of queue
protected ArrayList<QueueEntry> itemList;
private final ArrayList<QueueUser> userList; // other objects that use this queue
// Statistics
protected double timeOfLastUpdate; // time at which the statistics were last updated
protected double startOfStatisticsCollection; // time at which statistics collection was started
protected int minElements; // minimum observed number of entities in the queue
protected int maxElements; // maximum observed number of entities in the queue
protected double elementSeconds; // total time that entities have spent in the queue
protected double squaredElementSeconds; // total time for the square of the number of elements in the queue
protected DoubleVector queueLengthDist; // entry at position n is the total time the queue has had length n
{
testEntity.setHidden(true);
nextComponent.setHidden(true);
priority = new SampleExpInput("Priority", "Key Inputs", new SampleConstant(0));
priority.setUnitType(DimensionlessUnit.class);
priority.setEntity(this);
priority.setValidRange(0.0d, Double.POSITIVE_INFINITY);
this.addInput(priority);
match = new SampleExpInput("Match", "Key Inputs", new SampleConstant(0));
match.setUnitType(DimensionlessUnit.class);
match.setEntity(this);
this.addInput(match);
fifo = new BooleanInput("FIFO", "Key Inputs", true);
this.addInput(fifo);
spacing = new ValueInput("Spacing", "Key Inputs", 0.0d);
spacing.setUnitType(DistanceUnit.class);
spacing.setValidRange(0.0d, Double.POSITIVE_INFINITY);
this.addInput(spacing);
maxPerLine = new IntegerInput("MaxPerLine", "Key Inputs", Integer.MAX_VALUE);
maxPerLine.setValidRange(1, Integer.MAX_VALUE);
this.addInput(maxPerLine);
}
@Override
public void validate() {
super.validate();
priority.validate();
}
public Queue() {
itemList = new ArrayList<>();
queueLengthDist = new DoubleVector(10,10);
userList = new ArrayList<>();
}
@Override
public void earlyInit() {
super.earlyInit();
// Clear the entries in the queue
itemList.clear();
// Clear statistics
this.clearStatistics();
// Identify the objects that use this queue
userList.clear();
for (Entity each : Entity.getAll()) {
if (each instanceof QueueUser) {
QueueUser u = (QueueUser)each;
if (u.getQueues().contains(this))
userList.add(u);
}
}
}
private static class QueueEntry {
DisplayEntity entity;
double timeAdded;
int priority;
int match;
}
private final DoQueueChanged userUpdate = new DoQueueChanged(this);
private final EventHandle userUpdateHandle = new EventHandle();
private static class DoQueueChanged extends ProcessTarget {
private final Queue queue;
public DoQueueChanged(Queue q) {
queue = q;
}
@Override
public void process() {
for (QueueUser each : queue.userList)
each.queueChanged();
}
@Override
public String getDescription() {
return queue.getName() + ".UpdateAllQueueUsers";
}
}
// QUEUE HANDLING METHODS
@Override
public void addEntity(DisplayEntity ent) {
super.addEntity(ent);
// Determine the entity's priority and match values
int pri = (int) priority.getValue().getNextSample(getSimTime());
int mtch = (int) match.getValue().getNextSample(getSimTime());
// Insert the entity in the correct position in the queue
// FIFO ordering
int pos = 0;
if (fifo.getValue()) {
for (int i=itemList.size()-1; i>=0; i
if (itemList.get(i).priority <= pri) {
pos = i+1;
break;
}
}
}
// LIFO ordering
else {
pos = itemList.size();
for (int i=0; i<itemList.size(); i++) {
if (itemList.get(i).priority >= pri) {
pos = i;
break;
}
}
}
this.add(pos, ent, pri, mtch);
// Notify the users of this queue
if (!userUpdateHandle.isScheduled())
EventManager.scheduleTicks(0, 2, false, userUpdate, userUpdateHandle);
}
/**
* Inserts the specified element at the specified position in this Queue.
* Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices).
*/
private void add(int i, DisplayEntity ent, int pri, int mtch) {
int queueSize = itemList.size(); // present number of entities in the queue
this.updateStatistics(queueSize, queueSize+1);
QueueEntry entry = new QueueEntry();
entry.entity = ent;
entry.timeAdded = this.getSimTime();
entry.priority = pri;
entry.match = mtch;
itemList.add(i, entry);
}
public void add(int i, DisplayEntity ent) {
int pri = (int) priority.getValue().getNextSample(getSimTime());
int mtch = (int) match.getValue().getNextSample(getSimTime());
this.add(i, ent, pri, mtch);
}
/**
* Add an entity to the end of the queue
*/
public void addLast(DisplayEntity ent) {
int pri = (int) priority.getValue().getNextSample(getSimTime());
int mtch = (int) match.getValue().getNextSample(getSimTime());
this.add(itemList.size(), ent, pri, mtch);
}
/**
* Removes the entity at the specified position in the queue
*/
public DisplayEntity remove(int i) {
if (i >= itemList.size() || i < 0)
error("Index: %d is beyond the end of the queue.", i);
int queueSize = itemList.size(); // present number of entities in the queue
this.updateStatistics(queueSize, queueSize-1);
QueueEntry entry = itemList.remove(i);
DisplayEntity ent = entry.entity;
this.incrementNumberProcessed();
return ent;
}
/**
* Removes the first entity from the queue
*/
public DisplayEntity removeFirst() {
return this.remove(0);
}
/**
* Returns the first entity in the queue.
* @return first entity in the queue.
*/
public DisplayEntity getFirst() {
return itemList.get(0).entity;
}
/**
* Number of entities in the queue
*/
public int getCount() {
return itemList.size();
}
/**
* Returns the number of seconds spent by the first object in the queue
*/
public double getQueueTime() {
return this.getSimTime() - itemList.get(0).timeAdded;
}
/**
* Update the position of all entities in the queue. ASSUME that entities
* will line up according to the orientation of the queue.
*/
@Override
public void updateGraphics(double simTime) {
Vec3d queueOrientation = getOrientation();
Vec3d qSize = this.getSize();
Vec3d tmp = new Vec3d();
double distanceX = 0.5d * qSize.x;
double distanceY = 0;
double maxWidth = 0;
// find widest vessel
if (itemList.size() > maxPerLine.getValue()){
for (QueueEntry entry : itemList) {
maxWidth = Math.max(maxWidth, entry.entity.getSize().y);
}
}
// update item locations
for (int i = 0; i < itemList.size(); i++) {
// if new row is required, set reset distanceX and move distanceY up one row
if( i > 0 && i % maxPerLine.getValue() == 0 ){
distanceX = 0.5d * qSize.x;
distanceY += spacing.getValue() + maxWidth;
}
DisplayEntity item = itemList.get(i).entity;
// Rotate each transporter about its center so it points to the right direction
item.setOrientation(queueOrientation);
Vec3d itemSize = item.getSize();
distanceX += spacing.getValue() + 0.5d * itemSize.x;
tmp.set3(-distanceX / qSize.x, distanceY/qSize.y, 0.0d);
// increment total distance
distanceX += 0.5d * itemSize.x;
// Set Position
Vec3d itemCenter = this.getGlobalPositionForAlignment(tmp);
item.setGlobalPositionForAlignment(new Vec3d(), itemCenter);
}
}
// STATISTICS
/**
* Clear queue statistics
*/
@Override
public void clearStatistics() {
double simTime = this.getSimTime();
startOfStatisticsCollection = simTime;
timeOfLastUpdate = simTime;
minElements = itemList.size();
maxElements = itemList.size();
elementSeconds = 0.0;
squaredElementSeconds = 0.0;
queueLengthDist.clear();
}
private void updateStatistics(int oldValue, int newValue) {
minElements = Math.min(newValue, minElements);
maxElements = Math.max(newValue, maxElements);
// Add the necessary number of additional bins to the queue length distribution
int n = newValue + 1 - queueLengthDist.size();
for (int i = 0; i < n; i++) {
queueLengthDist.add(0.0);
}
double simTime = this.getSimTime();
double dt = simTime - timeOfLastUpdate;
if (dt > 0.0) {
elementSeconds += dt * oldValue;
squaredElementSeconds += dt * oldValue * oldValue;
queueLengthDist.addAt(dt,oldValue); // add dt to the entry at index queueSize
timeOfLastUpdate = simTime;
}
}
// OUTPUT METHODS
@Output(name = "QueueLength",
description = "The present number of entities in the queue.",
unitType = DimensionlessUnit.class)
public double getQueueLength(double simTime) {
return itemList.size();
}
@Output(name = "QueueTimes",
description = "The waiting time for each entity in the queue.",
unitType = TimeUnit.class)
public ArrayList<Double> getQueueTimes(double simTime) {
ArrayList<Double> ret = new ArrayList<>(itemList.size());
for (QueueEntry item : itemList) {
ret.add(simTime - item.timeAdded);
}
return ret;
}
@Output(name = "PriorityValues",
description = "The Priority expression value for each entity in the queue.",
unitType = DimensionlessUnit.class)
public ArrayList<Integer> getPriorityValues(double simTime) {
ArrayList<Integer> ret = new ArrayList<>();
for (QueueEntry item : itemList) {
ret.add(item.priority);
}
return ret;
}
@Output(name = "MatchValues",
description = "The Match expression value for each entity in the queue.",
unitType = DimensionlessUnit.class)
public ArrayList<Integer> getMatchValues(double simTime) {
ArrayList<Integer> ret = new ArrayList<>();
for (QueueEntry item : itemList) {
ret.add(item.match);
}
return ret;
}
@Output(name = "QueueLengthAverage",
description = "The average number of entities in the queue.",
unitType = DimensionlessUnit.class,
reportable = true)
public double getQueueLengthAverage(double simTime) {
double dt = simTime - timeOfLastUpdate;
int queueSize = itemList.size();
double totalTime = simTime - startOfStatisticsCollection;
if (totalTime > 0.0) {
return (elementSeconds + dt*queueSize)/totalTime;
}
return 0.0;
}
@Output(name = "QueueLengthStandardDeviation",
description = "The standard deviation of the number of entities in the queue.",
unitType = DimensionlessUnit.class,
reportable = true)
public double getQueueLengthStandardDeviation(double simTime) {
double dt = simTime - timeOfLastUpdate;
int queueSize = itemList.size();
double mean = this.getQueueLengthAverage(simTime);
double totalTime = simTime - startOfStatisticsCollection;
if (totalTime > 0.0) {
return Math.sqrt( (squaredElementSeconds + dt*queueSize*queueSize)/totalTime - mean*mean );
}
return 0.0;
}
@Output(name = "QueueLengthMinimum",
description = "The minimum number of entities in the queue.",
unitType = DimensionlessUnit.class,
reportable = true)
public Integer getQueueLengthMinimum(double simTime) {
return minElements;
}
@Output(name = "QueueLengthMaximum",
description = "The maximum number of entities in the queue.",
unitType = DimensionlessUnit.class,
reportable = true)
public Integer getQueueLengthMaximum(double simTime) {
// An entity that is added to an empty queue and removed immediately
// does not count as a non-zero queue length
if (maxElements == 1 && queueLengthDist.get(1) == 0.0)
return 0;
return maxElements;
}
@Output(name = "QueueLengthDistribution",
description = "The fraction of time that the queue has length 0, 1, 2, etc.",
unitType = DimensionlessUnit.class,
reportable = true)
public DoubleVector getQueueLengthDistribution(double simTime) {
DoubleVector ret = new DoubleVector(queueLengthDist);
double dt = simTime - timeOfLastUpdate;
int queueSize = itemList.size();
double totalTime = simTime - startOfStatisticsCollection;
if (totalTime > 0.0) {
if (ret.size() == 0)
ret.add(0.0);
ret.addAt(dt, queueSize); // adds dt to the entry at index queueSize
for (int i = 0; i < ret.size(); i++) {
ret.set(i, ret.get(i)/totalTime);
}
}
else {
ret.clear();
}
return ret;
}
@Output(name = "AverageQueueTime",
description = "The average time each entity waits in the queue. Calculated as total queue time to date divided " +
"by the total number of entities added to the queue.",
unitType = TimeUnit.class,
reportable = true)
public double getAverageQueueTime(double simTime) {
int n = this.getNumberAdded();
if (n == 0)
return 0.0;
double dt = simTime - timeOfLastUpdate;
int queueSize = itemList.size();
return (elementSeconds + dt*queueSize)/n;
}
} |
package org.mtransit.android.commons;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import java.util.WeakHashMap;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.mtransit.android.commons.data.POIStatus;
import org.mtransit.android.commons.data.Schedule;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.text.style.RelativeSizeSpan;
import android.util.Pair;
public class TimeUtils implements MTLog.Loggable {
private static final String TAG = TimeUtils.class.getSimpleName();
@Override
public String getLogTag() {
return TAG;
}
public static final long RECENT_IN_MILLIS = DateUtils.HOUR_IN_MILLIS;
public static IntentFilter TIME_CHANGED_INTENT_FILTER;
static {
TIME_CHANGED_INTENT_FILTER = new IntentFilter();
TIME_CHANGED_INTENT_FILTER.addAction(Intent.ACTION_TIME_TICK);
TIME_CHANGED_INTENT_FILTER.addAction(Intent.ACTION_TIMEZONE_CHANGED);
TIME_CHANGED_INTENT_FILTER.addAction(Intent.ACTION_TIME_CHANGED);
}
private static final String FORMAT_HOUR_12_PATTERN = "h a";
private static final String FORMAT_TIME_12_PATTERN = "h:mm a";
private static final String FORMAT_TIME_12_W_TZ_PATTERN = "h:mm a z";
private static final String FORMAT_TIME_12_PRECISE_PATTERN = "h:mm:ss a";
private static final String FORMAT_TIME_12_PRECISE_W_TZ_PATTERN = "h:mm:ss a z";
private static final String FORMAT_HOUR_24_PATTERN = "HH";
private static final String FORMAT_TIME_24_PATTERN = "HH:mm";
private static final String FORMAT_TIME_24_W_TZ_PATTERN = "HH:mm z";
private static final String FORMAT_TIME_24_PRECISE_PATTERN = "HH:mm:ss";
private static final String FORMAT_TIME_24_PRECISE_W_TZ_PATTERN = "HH:mm:ss z";
private static ThreadSafeDateFormatter formatTime;
private static ThreadSafeDateFormatter getFormatTime(Context context) {
if (formatTime == null) {
formatTime = getNewFormatTime(context);
}
return formatTime;
}
private static WeakHashMap<String, ThreadSafeDateFormatter> formatTimeTZ = new WeakHashMap<String, ThreadSafeDateFormatter>();
private static ThreadSafeDateFormatter getFormatTimeTZ(Context context, TimeZone timeZone) {
if (!formatTimeTZ.containsKey(timeZone.getID())) {
ThreadSafeDateFormatter formatTime = getNewFormatTime(context);
formatTime.setTimeZone(timeZone);
formatTimeTZ.put(timeZone.getID(), formatTime);
}
return formatTimeTZ.get(timeZone.getID());
}
private static ThreadSafeDateFormatter getNewFormatTime(Context context) {
if (is24HourFormat(context)) {
return new ThreadSafeDateFormatter(FORMAT_TIME_24_PATTERN);
} else {
return new ThreadSafeDateFormatter(FORMAT_TIME_12_PATTERN);
}
}
private static ThreadSafeDateFormatter formatTimePrecise;
private static ThreadSafeDateFormatter getFormatTimePrecise(Context context) {
if (formatTimePrecise == null) {
formatTimePrecise = getNewFormatTimePrecise(context);
}
return formatTimePrecise;
}
private static WeakHashMap<String, ThreadSafeDateFormatter> formatTimePreciseTZ = new WeakHashMap<String, ThreadSafeDateFormatter>();
private static ThreadSafeDateFormatter getFormatTimePreciseTZ(Context context, TimeZone timeZone) {
if (!formatTimePreciseTZ.containsKey(timeZone.getID())) {
ThreadSafeDateFormatter formatTimePrecise = getNewFormatTimePrecise(context);
formatTimePrecise.setTimeZone(timeZone);
formatTimePreciseTZ.put(timeZone.getID(), formatTimePrecise);
}
return formatTimePreciseTZ.get(timeZone.getID());
}
private static ThreadSafeDateFormatter getNewFormatTimePrecise(Context context) {
if (is24HourFormat(context)) {
return new ThreadSafeDateFormatter(FORMAT_TIME_24_PRECISE_PATTERN);
} else {
return new ThreadSafeDateFormatter(FORMAT_TIME_12_PRECISE_PATTERN);
}
}
public static ThreadSafeDateFormatter getNewHourFormat(Context context) {
if (is24HourFormat(context)) {
return new ThreadSafeDateFormatter(FORMAT_HOUR_24_PATTERN);
} else {
return new ThreadSafeDateFormatter(FORMAT_HOUR_12_PATTERN);
}
}
public static int millisToSec(long millis) {
return (int) (millis / 1000l);
}
public static int currentTimeSec() {
return millisToSec(currentTimeMillis());
}
public static long currentTimeToTheMinuteMillis() {
long currentTime = currentTimeMillis();
return timeToTheMinuteMillis(currentTime);
}
public static long timeToTheMinuteMillis(long time) {
time -= time % DateUtils.MINUTE_IN_MILLIS;
return time;
}
private static final long TO_THE_TENS_SECONDS = TimeUnit.SECONDS.toMillis(10);
public static long timeToTheTensSecondsMillis(long time) {
time -= time % TO_THE_TENS_SECONDS;
return time;
}
public static long currentTimeMillis() { // USEFUL FOR DEBUG
return System.currentTimeMillis();
}
public static long getBeginningOfTodayInMs() {
return getBeginningOfTodayCal().getTimeInMillis();
}
public static Calendar getBeginningOfTodayCal() {
Calendar today = getNewCalendarInstance(currentTimeMillis());
today.set(Calendar.HOUR_OF_DAY, 0);
today.set(Calendar.MINUTE, 0);
today.set(Calendar.SECOND, 0);
today.set(Calendar.MILLISECOND, 0);
return today;
}
public static boolean isMorePreciseThanMinute(long timeInMs) {
return timeInMs % DateUtils.MINUTE_IN_MILLIS > 0;
}
public static CharSequence formatRelativeTime(Context context, long timeInThePastInMs) {
return formatRelativeTime(context, timeInThePastInMs, currentTimeMillis());
}
public static CharSequence formatRelativeTime(Context context, long timeInThePastInMs, long nowInMs) {
return DateUtils.getRelativeTimeSpanString(timeInThePastInMs, nowInMs, DateUtils.MINUTE_IN_MILLIS, DateUtils.FORMAT_ABBREV_RELATIVE);
}
public static String formatTime(Context context, long timeInMs) {
return getFormatTime(context, timeInMs).formatThreadSafe(timeInMs);
}
public static String formatTime(Context context, long timeInMs, String timeZone) {
return formatTime(context, timeInMs, TimeZone.getTimeZone(timeZone));
}
public static String formatTime(Context context, long timeInMs, TimeZone timeZone) {
return getFormatTimeTZ(context, timeInMs, timeZone).formatThreadSafe(timeInMs);
}
private static ThreadSafeDateFormatter getFormatTime(Context context, long timeInMs) {
if (isMorePreciseThanMinute(timeInMs)) {
return getFormatTimePrecise(context);
}
return getFormatTime(context);
}
private static ThreadSafeDateFormatter getFormatTimeTZ(Context context, long timeInMs, TimeZone timeZone) {
if (isMorePreciseThanMinute(timeInMs)) {
return getFormatTimePreciseTZ(context, timeZone);
}
return getFormatTimeTZ(context, timeZone);
}
public static String formatTimeWithTZ(Context context, long timeInMs, TimeZone timeZone) {
return getFormatTimeWithTZ(context, timeInMs, timeZone).formatThreadSafe(timeInMs);
}
private static ThreadSafeDateFormatter getFormatTimeWithTZ(Context context, long timeInMs, TimeZone timeZone) {
if (isMorePreciseThanMinute(timeInMs)) {
return getFormatTimePreciseWithTZ(context, timeZone);
}
return getFormatTimeWithTZ(context, timeZone);
}
private static WeakHashMap<String, ThreadSafeDateFormatter> formatTimePreciseWithTZ = new WeakHashMap<String, ThreadSafeDateFormatter>();
private static ThreadSafeDateFormatter getFormatTimePreciseWithTZ(Context context, TimeZone timeZone) {
if (!formatTimePreciseWithTZ.containsKey(timeZone.getID())) {
ThreadSafeDateFormatter formatTimePrecise = getNewFormatTimePreciseWithTZ(context);
formatTimePrecise.setTimeZone(timeZone);
formatTimePreciseWithTZ.put(timeZone.getID(), formatTimePrecise);
}
return formatTimePreciseWithTZ.get(timeZone.getID());
}
private static ThreadSafeDateFormatter getNewFormatTimePreciseWithTZ(Context context) {
if (is24HourFormat(context)) {
return new ThreadSafeDateFormatter(FORMAT_TIME_24_PRECISE_W_TZ_PATTERN);
} else {
return new ThreadSafeDateFormatter(FORMAT_TIME_12_PRECISE_W_TZ_PATTERN);
}
}
private static WeakHashMap<String, ThreadSafeDateFormatter> formatTimeWithTZ = new WeakHashMap<String, ThreadSafeDateFormatter>();
private static ThreadSafeDateFormatter getFormatTimeWithTZ(Context context, TimeZone timeZone) {
if (!formatTimeWithTZ.containsKey(timeZone.getID())) {
ThreadSafeDateFormatter formatTime = getNewFormatTimeWithTZ(context);
formatTime.setTimeZone(timeZone);
formatTimeWithTZ.put(timeZone.getID(), formatTime);
}
return formatTimeWithTZ.get(timeZone.getID());
}
private static ThreadSafeDateFormatter getNewFormatTimeWithTZ(Context context) {
if (is24HourFormat(context)) {
return new ThreadSafeDateFormatter(FORMAT_TIME_24_W_TZ_PATTERN);
} else {
return new ThreadSafeDateFormatter(FORMAT_TIME_12_W_TZ_PATTERN);
}
}
public static String formatTime(Context context, Date date) {
return getFormatTime(context, date.getTime()).formatThreadSafe(date);
}
public static boolean isToday(long timeInMs) {
return timeInMs >= getBeginningOfTodayCal().getTimeInMillis() && timeInMs < getBeginningOfTomorrowCal().getTimeInMillis();
}
public static boolean isTomorrow(long timeInMs) {
return timeInMs >= getBeginningOfTomorrowCal().getTimeInMillis() && timeInMs < getBeginningOfDayRelativeToTodayCal(+2).getTimeInMillis();
}
public static boolean isYesterday(long timeInMs) {
return timeInMs >= getBeginningOfYesterdayCal().getTimeInMillis() && timeInMs < getBeginningOfTodayCal().getTimeInMillis();
}
public static Calendar getBeginningOfDayRelativeToTodayCal(int nbDays) {
Calendar today = getBeginningOfTodayCal();
today.add(Calendar.DATE, nbDays);
return today;
}
public static int getHourOfTheDay(long timeInMs) {
Calendar time = getNewCalendar(timeInMs);
return time.get(Calendar.HOUR_OF_DAY);
}
public static Calendar getBeginningOfYesterdayCal() {
return getBeginningOfDayRelativeToTodayCal(-1);
}
public static Calendar getBeginningOfTomorrowCal() {
return getBeginningOfDayRelativeToTodayCal(+1);
}
public static Calendar getNewCalendarInstance(long timeInMs) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(timeInMs);
return cal;
}
public static Calendar getNewCalendar(long timestamp) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(timestamp);
return calendar;
}
private static final String AM = "am";
private static final String PM = "pm";
private static final Pattern TIME_W_SECONDS = Pattern.compile("([0-9]{1,2}\\:[0-9]{2}:[0-9]{2})", Pattern.CASE_INSENSITIVE);
public static void cleanTimes(SpannableStringBuilder ssb) {
cleanTimes(ssb.toString(), ssb);
}
public static void cleanTimes(String input, SpannableStringBuilder output) {
String word = input.toLowerCase(Locale.ENGLISH);
for (int index = word.indexOf(AM); index >= 0; index = word.indexOf(AM, index + 1)) { // TODO i18n
if (index <= 0) {
break;
}
SpanUtils.set(output, new RelativeSizeSpan(0.1f), index - 1, index); // remove space hack
SpanUtils.set(output, new RelativeSizeSpan(0.25f), index, index + 2);
}
for (int index = word.indexOf(PM); index >= 0; index = word.indexOf(PM, index + 1)) { // TODO i18n
if (index <= 0) {
break;
}
SpanUtils.set(output, new RelativeSizeSpan(0.1f), index - 1, index); // remove space hack
SpanUtils.set(output, new RelativeSizeSpan(0.25f), index, index + 2);
}
Matcher rMatcher = TIME_W_SECONDS.matcher(word);
while (rMatcher.find()) {
int end = rMatcher.end();
SpanUtils.set(output, new RelativeSizeSpan(0.50f), end - 3, end);
}
}
private static final String M = "m";
public static ThreadSafeDateFormatter removeMinutes(ThreadSafeDateFormatter input) {
String pattern = input == null ? null : input.toPattern();
if (pattern == null) {
return null;
}
if (pattern.contains(M)) {
pattern = pattern.replace(M, StringUtils.EMPTY);
}
return new ThreadSafeDateFormatter(pattern);
}
public static boolean is24HourFormat(Context context) {
return android.text.format.DateFormat.is24HourFormat(context);
}
public static final long FREQUENT_SERVICE_TIMESPAN_IN_MS_DEFAULT = TimeUnit.MINUTES.toMillis(5);
public static final long FREQUENT_SERVICE_MIN_DURATION_IN_MS_DEFAULT = TimeUnit.MINUTES.toMillis(30);
public static final long FREQUENT_SERVICE_MIN_SERVICE = 2;
public static boolean isFrequentService(ArrayList<Schedule.Timestamp> timestamps, long providerFSMinDuractionInMs, long providerFSTimespanInMs) {
if (CollectionUtils.getSize(timestamps) < FREQUENT_SERVICE_MIN_SERVICE) {
return false; // NOT FREQUENT (no service at all)
}
long fsMinDuractionMs = providerFSMinDuractionInMs > 0 ? providerFSMinDuractionInMs : FREQUENT_SERVICE_MIN_DURATION_IN_MS_DEFAULT;
long fsTimespanMs = providerFSTimespanInMs > 0 ? providerFSTimespanInMs : FREQUENT_SERVICE_TIMESPAN_IN_MS_DEFAULT;
long firstTimestamp = timestamps.get(0).t;
long previousTimestamp = firstTimestamp;
long currentTimestamp;
long diffInMs;
for (int i = 1; i < timestamps.size(); i++) {
currentTimestamp = timestamps.get(i).t;
diffInMs = currentTimestamp - previousTimestamp;
if (diffInMs > fsTimespanMs) {
return false; // NOT FREQUENT
}
previousTimestamp = currentTimestamp;
if (previousTimestamp - firstTimestamp >= fsMinDuractionMs) {
return true; // NOT FREQUENT (for long enough)
}
}
if (previousTimestamp - firstTimestamp < fsMinDuractionMs) {
return false; // NOT FREQUENT (for long enough)
}
return true; // FREQUENT
}
private static final ThreadSafeDateFormatter STANDALONE_DAY_OF_THE_WEEK_LONG = new ThreadSafeDateFormatter("cccc");
private static final ThreadSafeDateFormatter STANDALONE_MONTH_LONG = new ThreadSafeDateFormatter("LLLL");
public static final long MAX_DURATION_DISPLAYED_IN_MS = TimeUnit.HOURS.toMillis(6);
public static final int URGENT_SCHEDULE_IN_MIN = 10;
public static final long URGENT_SCHEDULE_IN_MS = TimeUnit.MINUTES.toMillis(URGENT_SCHEDULE_IN_MIN);
public static final long MAX_DURATION_SHOW_NUMBER_IN_MS = TimeUnit.MINUTES.toMillis(100) - 1; // 99 minutes 59 seconds 999 milliseconds
public static Pair<CharSequence, CharSequence> getShortTimeSpan(Context context, long diffInMs, long targetedTimestamp, long precisionInMs) {
if (diffInMs > MAX_DURATION_DISPLAYED_IN_MS) {
Pair<CharSequence, CharSequence> timeS = getShortTimeSpanString(context, diffInMs, targetedTimestamp);
return getShortTimeSpanStringStyle(context, timeS);
} else {
return getShortTimeSpanNumber(context, diffInMs, precisionInMs);
}
}
private static final int MILLIS_IN_SEC = 1000;
private static final int SEC_IN_MIN = 60;
private static final int MIN_IN_HOUR = 60;
private static final int HOUR_IN_DAY = 24;
private static Pair<CharSequence, CharSequence> getShortTimeSpanNumber(Context context, long diffInMs, long precisionInMs) {
int diffInSec = (int) Math.floor(diffInMs / MILLIS_IN_SEC);
if (diffInMs - (diffInSec * MILLIS_IN_SEC) > (MILLIS_IN_SEC / 2)) {
diffInSec++;
}
int diffInMin = (int) Math.floor(diffInSec / SEC_IN_MIN);
if (diffInSec - (diffInMin * SEC_IN_MIN) > (SEC_IN_MIN / 2)) {
diffInMin++;
}
int diffInHour = (int) Math.floor(diffInMin / MIN_IN_HOUR);
if (diffInMin - (diffInHour * MIN_IN_HOUR) > (MIN_IN_HOUR / 2)) {
diffInHour++;
}
int diffInDay = (int) Math.floor(diffInHour / HOUR_IN_DAY);
if (diffInHour - (diffInDay * HOUR_IN_DAY) > (HOUR_IN_DAY / 2)) {
diffInDay++;
}
int startUrgentTimeLine1 = -1;
int endUrgentTimeLine1 = -1;
int startTimeUnitLine2 = -1;
int endTimeUnitLine2 = -1;
int startUrgentTimeLine2 = -1;
int endUrgentTimeLine2 = -1;
SpannableStringBuilder shortTimeSpanLine1SSB = new SpannableStringBuilder();
SpannableStringBuilder shortTimeSpanLine2SSB = new SpannableStringBuilder();
boolean isShortTimeSpanString = false;
if (diffInDay > 0 && diffInHour > 99) {
shortTimeSpanLine1SSB.append(getNumberInLetter(context, diffInDay));
isShortTimeSpanString = true;
shortTimeSpanLine2SSB.append(context.getResources().getQuantityText(R.plurals.days_capitalized, diffInDay));
} else if (diffInHour > 0 && diffInMin > 99) {
shortTimeSpanLine1SSB.append(getNumberInLetter(context, diffInHour));
isShortTimeSpanString = true;
shortTimeSpanLine2SSB.append(context.getResources().getQuantityText(R.plurals.hours_capitalized, diffInHour));
} else if (diffInMs <= precisionInMs && diffInMs >= -precisionInMs) {
startUrgentTimeLine1 = shortTimeSpanLine1SSB.length();
shortTimeSpanLine1SSB.append(String.valueOf(diffInMin));
endUrgentTimeLine1 = shortTimeSpanLine1SSB.length();
startUrgentTimeLine2 = shortTimeSpanLine2SSB.length();
startTimeUnitLine2 = shortTimeSpanLine2SSB.length();
shortTimeSpanLine2SSB.append(context.getResources().getQuantityString(R.plurals.minutes_capitalized, Math.abs(diffInMin)));
endTimeUnitLine2 = shortTimeSpanLine2SSB.length();
endUrgentTimeLine2 = shortTimeSpanLine2SSB.length();
} else {
if (diffInMin < URGENT_SCHEDULE_IN_MIN) {
startUrgentTimeLine1 = shortTimeSpanLine1SSB.length();
}
shortTimeSpanLine1SSB.append(String.valueOf(diffInMin));
if (diffInMin < URGENT_SCHEDULE_IN_MIN) {
endUrgentTimeLine1 = shortTimeSpanLine1SSB.length();
startUrgentTimeLine2 = shortTimeSpanLine2SSB.length();
}
startTimeUnitLine2 = shortTimeSpanLine2SSB.length();
shortTimeSpanLine2SSB.append(context.getResources().getQuantityString(R.plurals.minutes_capitalized, diffInMin));
endTimeUnitLine2 = shortTimeSpanLine2SSB.length();
if (diffInMin < URGENT_SCHEDULE_IN_MIN) {
endUrgentTimeLine2 = shortTimeSpanLine2SSB.length();
}
}
if (startUrgentTimeLine1 < endUrgentTimeLine1) {
SpanUtils.set(shortTimeSpanLine1SSB, SpanUtils.getLargeTextAppearance(context), startUrgentTimeLine1, endUrgentTimeLine1);
}
if (startUrgentTimeLine2 < endUrgentTimeLine2) {
SpanUtils.set(shortTimeSpanLine2SSB, SpanUtils.getLargeTextAppearance(context), startUrgentTimeLine2, endUrgentTimeLine2);
}
if (startTimeUnitLine2 < endTimeUnitLine2) {
SpanUtils.set(shortTimeSpanLine2SSB, SpanUtils.FIFTY_PERCENT_SIZE_SPAN, startTimeUnitLine2, endTimeUnitLine2);
SpanUtils.set(shortTimeSpanLine2SSB, POIStatus.STATUS_TEXT_FONT, startTimeUnitLine2, endTimeUnitLine2);
}
if (isShortTimeSpanString) {
return getNewShortTimeSpan(getShortTimeSpanStringStyle(context, shortTimeSpanLine1SSB), getShortTimeSpanStringStyle(context, shortTimeSpanLine2SSB));
}
return getNewShortTimeSpan(shortTimeSpanLine1SSB, shortTimeSpanLine2SSB);
}
public static CharSequence getNumberInLetter(Context context, int number) {
switch (number) {
case 0:
return context.getString(R.string.zero_capitalized);
case 1:
return context.getString(R.string.one_capitalized);
case 2:
return context.getString(R.string.two_capitalized);
case 3:
return context.getString(R.string.three_capitalized);
case 4:
return context.getString(R.string.four_capitalized);
case 5:
return context.getString(R.string.five_capitalized);
case 6:
return context.getString(R.string.six_capitalized);
case 7:
return context.getString(R.string.seven_capitalized);
case 8:
return context.getString(R.string.eight_capitalized);
case 9:
return context.getString(R.string.nine_capitalized);
case 10:
return context.getString(R.string.ten_capitalized);
case 11:
return context.getString(R.string.eleven_capitalized);
case 12:
return context.getString(R.string.twelve_capitalized);
case 13:
return context.getString(R.string.thirteen_capitalized);
case 14:
return context.getString(R.string.fourteen_capitalized);
case 15:
return context.getString(R.string.fifteen_capitalized);
case 16:
return context.getString(R.string.sixteen_capitalized);
case 17:
return context.getString(R.string.seventeen_capitalized);
case 18:
return context.getString(R.string.eighteen_capitalized);
case 19:
return context.getString(R.string.nineteen_capitalized);
default:
return String.valueOf(number); // 2 characters number almost equal world
}
}
private static Pair<CharSequence, CharSequence> getShortTimeSpanString(Context context, long diffInMs, long targetedTimestamp) {
long now = targetedTimestamp - diffInMs;
Calendar today = Calendar.getInstance();
today.setTimeInMillis(now);
today.set(Calendar.HOUR_OF_DAY, 0);
today.set(Calendar.MINUTE, 0);
today.set(Calendar.SECOND, 0);
today.set(Calendar.MILLISECOND, 0);
Calendar todayMorningStarts = (Calendar) today.clone();
todayMorningStarts.set(Calendar.HOUR_OF_DAY, 6);
Calendar todayAfterNoonStarts = (Calendar) today.clone();
todayAfterNoonStarts.set(Calendar.HOUR_OF_DAY, 12);
if (targetedTimestamp >= todayMorningStarts.getTimeInMillis() && targetedTimestamp < todayAfterNoonStarts.getTimeInMillis()) {
return getNewShortTimeSpan(context, R.string.this_morning_part_1, R.string.this_morning_part_2); // MORNING
}
Calendar todayEveningStarts = (Calendar) today.clone();
todayEveningStarts.set(Calendar.HOUR_OF_DAY, 18);
if (targetedTimestamp >= todayAfterNoonStarts.getTimeInMillis() && targetedTimestamp < todayEveningStarts.getTimeInMillis()) {
return getNewShortTimeSpan(context, R.string.this_afternoon_part_1, R.string.this_afternoon_part_2); // AFTERNOON
}
Calendar tonightStarts = (Calendar) today.clone();
tonightStarts.set(Calendar.HOUR_OF_DAY, 22);
if (targetedTimestamp >= todayEveningStarts.getTimeInMillis() && targetedTimestamp < tonightStarts.getTimeInMillis()) {
return getNewShortTimeSpan(context, R.string.this_evening_part_1, R.string.this_evening_part_2); // EVENING
}
Calendar tomorrow = (Calendar) today.clone();
tomorrow.add(Calendar.DATE, +1);
Calendar tomorrowStarts = (Calendar) tomorrow.clone();
tomorrowStarts.set(Calendar.HOUR_OF_DAY, 5);
if (targetedTimestamp >= tonightStarts.getTimeInMillis() && targetedTimestamp < tomorrowStarts.getTimeInMillis()) {
return getNewShortTimeSpan(context, R.string.tonight_part_1, R.string.tonight_part_2); // NIGHT
}
Calendar afterTomorrow = (Calendar) today.clone();
afterTomorrow.add(Calendar.DATE, +2);
if (targetedTimestamp >= tomorrowStarts.getTimeInMillis() && targetedTimestamp < afterTomorrow.getTimeInMillis()) {
return getNewShortTimeSpan(context, R.string.tomorrow_part_1, R.string.tomorrow_part_2); // TOMORROW
}
Calendar nextWeekStarts = (Calendar) today.clone();
nextWeekStarts.add(Calendar.DATE, +7);
if (targetedTimestamp >= afterTomorrow.getTimeInMillis() && targetedTimestamp < nextWeekStarts.getTimeInMillis()) {
return getNewShortTimeSpan(STANDALONE_DAY_OF_THE_WEEK_LONG.formatThreadSafe(targetedTimestamp), null); // THIS WEEK (Monday-Sunday)
}
Calendar nextWeekEnds = (Calendar) today.clone();
nextWeekEnds.add(Calendar.DATE, +14);
if (targetedTimestamp >= nextWeekStarts.getTimeInMillis() && targetedTimestamp < nextWeekEnds.getTimeInMillis()) {
return getNewShortTimeSpan(context, R.string.next_week_part_1, R.string.next_week_part_2); // NEXT WEEK
}
Calendar thisMonthStarts = (Calendar) today.clone();
thisMonthStarts.set(Calendar.DAY_OF_MONTH, 1);
Calendar nextMonthStarts = (Calendar) thisMonthStarts.clone();
nextMonthStarts.add(Calendar.MONTH, +1);
if (targetedTimestamp >= thisMonthStarts.getTimeInMillis() && targetedTimestamp < nextMonthStarts.getTimeInMillis()) {
return getNewShortTimeSpan(context, R.string.this_month_part_1, R.string.this_month_part_2); // THIS MONTH
}
Calendar nextNextMonthStarts = (Calendar) nextMonthStarts.clone();
nextNextMonthStarts.add(Calendar.MONTH, +1);
if (targetedTimestamp >= nextMonthStarts.getTimeInMillis() && targetedTimestamp < nextNextMonthStarts.getTimeInMillis()) {
return getNewShortTimeSpan(context, R.string.next_month_part_1, R.string.next_month_part_2); // NEXT MONTH
}
Calendar next12MonthsStart = (Calendar) today.clone();
next12MonthsStart.add(Calendar.MONTH, +1);
Calendar next12MonthsEnd = (Calendar) today.clone();
next12MonthsEnd.add(Calendar.MONTH, +6);
if (targetedTimestamp >= next12MonthsStart.getTimeInMillis() && targetedTimestamp < next12MonthsEnd.getTimeInMillis()) {
return getNewShortTimeSpan(STANDALONE_MONTH_LONG.formatThreadSafe(targetedTimestamp), null); // LESS THAN 12 MONTHS (January-December)
}
Calendar thisYearStarts = (Calendar) thisMonthStarts.clone();
thisYearStarts.set(Calendar.MONTH, Calendar.JANUARY);
Calendar nextYearStarts = (Calendar) thisYearStarts.clone();
nextYearStarts.add(Calendar.YEAR, +1);
Calendar nextNextYearStarts = (Calendar) nextYearStarts.clone();
nextNextYearStarts.add(Calendar.YEAR, +1);
if (targetedTimestamp >= nextYearStarts.getTimeInMillis() && targetedTimestamp < nextNextYearStarts.getTimeInMillis()) {
return getNewShortTimeSpan(context, R.string.next_year_part_1, R.string.next_year_part_2); // NEXT YEAR
}
CharSequence defaultDate = DateUtils.formatSameDayTime(targetedTimestamp, now, ThreadSafeDateFormatter.MEDIUM, ThreadSafeDateFormatter.SHORT);
return getNewShortTimeSpan(defaultDate, null); // DEFAULT
}
private static Pair<CharSequence, CharSequence> getNewShortTimeSpan(Context context, int resId1, int resId2) {
return getNewShortTimeSpan(context.getString(resId1), context.getString(resId2));
}
private static Pair<CharSequence, CharSequence> getNewShortTimeSpan(CharSequence cs1, CharSequence cs2) {
return new Pair<CharSequence, CharSequence>(cs1, cs2);
}
private static CharSequence getShortTimeSpanStringStyle(Context context, CharSequence timeSpan) {
if (TextUtils.isEmpty(timeSpan)) {
return timeSpan;
}
SpannableStringBuilder fsSSB = new SpannableStringBuilder(timeSpan);
SpanUtils.set(fsSSB, SpanUtils.getSmallTextAppearance(context));
SpanUtils.set(fsSSB, POIStatus.STATUS_TEXT_FONT);
return fsSSB;
}
private static Pair<CharSequence, CharSequence> getShortTimeSpanStringStyle(Context context, Pair<CharSequence, CharSequence> timeSpans) {
if (timeSpans == null) {
return null;
}
return getNewShortTimeSpan(getShortTimeSpanStringStyle(context, timeSpans.first), getShortTimeSpanStringStyle(context, timeSpans.second));
}
public static boolean isSameDay(Long timeInMillis1, Long timeInMillis2) {
if (timeInMillis1 == null || timeInMillis2 == null) {
throw new IllegalArgumentException("The date must not be null");
}
Calendar cal1 = Calendar.getInstance();
cal1.setTimeInMillis(timeInMillis1);
Calendar cal2 = Calendar.getInstance();
cal2.setTimeInMillis(timeInMillis2);
return isSameDay(cal1, cal2);
}
public static boolean isSameDay(Calendar cal1, Calendar cal2) {
if (cal1 == null || cal2 == null) {
throw new IllegalArgumentException("The date must not be null");
}
return (cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA)
&& cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR)
&& cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR));
}
public static boolean isSameDay(Date date1, Date date2) {
if (date1 == null || date2 == null) {
throw new IllegalArgumentException("The date must not be null");
}
Calendar cal1 = Calendar.getInstance();
cal1.setTime(date1);
Calendar cal2 = Calendar.getInstance();
cal2.setTime(date2);
return isSameDay(cal1, cal2);
}
public static class TimeChangedReceiver extends BroadcastReceiver {
private WeakReference<TimeChangedListener> listenerWR;
public TimeChangedReceiver(TimeChangedListener listener) {
this.listenerWR = new WeakReference<TimeChangedListener>(listener);
}
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (Intent.ACTION_TIME_TICK.equals(action) || Intent.ACTION_TIME_CHANGED.equals(action) || Intent.ACTION_TIMEZONE_CHANGED.equals(action)) {
TimeChangedListener listener = this.listenerWR == null ? null : this.listenerWR.get();
if (listener != null) {
listener.onTimeChanged();
}
}
}
public interface TimeChangedListener {
void onTimeChanged();
}
}
} |
package com.rackspace.flewton.backend.cassandra;
import com.rackspace.flewton.AbstractRecord;
import com.rackspace.flewton.ConfigError;
import com.rackspace.flewton.Flow;
import com.rackspace.flewton.backend.AbstractBackend;
import com.rackspace.flewton.util.HostResolver;
import static com.rackspace.flewton.util.HostResolver.int2ByteBuffer;
import static com.eaio.uuid.UUIDGen.createTime;
import static com.eaio.uuid.UUIDGen.getClockSeqAndNode;
import org.apache.cassandra.thrift.Cassandra;
import org.apache.cassandra.thrift.Column;
import org.apache.cassandra.thrift.ColumnOrSuperColumn;
import org.apache.cassandra.thrift.ConsistencyLevel;
import org.apache.cassandra.thrift.InvalidRequestException;
import org.apache.cassandra.thrift.Mutation;
import org.apache.cassandra.thrift.TimedOutException;
import org.apache.cassandra.thrift.UnavailableException;
import org.apache.commons.configuration.HierarchicalConfiguration;
import org.apache.thrift.TException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class UsageBackend extends AbstractBackend {
protected static final int DEFAULT_TTL = 7 * 24 * 60 * 60;
private static final Logger logger = LoggerFactory.getLogger(UsageBackend.class);
protected final String localColFam;
protected final String ingressColFam;
protected final String egressColFam;
protected final int colTTL;
protected HostResolver resolver;
private ThriftClientPool clientPool;
private String getRequiredString(HierarchicalConfiguration config, String key) throws ConfigError {
String value = config.getString(key);
if (value == null)
throw new ConfigError("missing required config property: " + key);
return value;
}
public UsageBackend(HierarchicalConfiguration config) throws ConfigError {
super(config);
final String keyspace = getRequiredString(config, "keyspace");
localColFam = getRequiredString(config, "lanCf");
ingressColFam = getRequiredString(config, "wanInCf");
egressColFam = getRequiredString(config, "wanOutCf");
colTTL = config.getInt("columnTTLSecs", DEFAULT_TTL);
resolver = new HostResolver(config);
clientPool = new ThriftClientPool(keyspace, config.getStringArray("storageNode"));
}
/**
* attempts to write the record. will retry once if there is a time out or unavailable error. all other errors
* are treated as unrecoverable and the data is dropped.
*/
public void write(AbstractRecord record) {
final long ts = System.currentTimeMillis();
final Map<ByteBuffer, Map<String, List<Mutation>>> mutations = makeMutations(record, resolver, ts);
long retry = 0; // indicates how many MS to sleep before retrying.
// first try.
try {
write(mutations);
} catch (TimedOutException ex) {
retry = 1;
} catch (UnavailableException ex) {
retry = 1000;
} catch (InvalidRequestException e) {
logger.error("DROPPING DATA " + e.getMessage(), e);
} catch (TException e) {
logger.error("DROPPING DATA " + e.getMessage(), e);
}
// maybe second try.
if (retry > 0) {
try { Thread.sleep(retry); } catch (InterruptedException ignore) { }
try {
write(mutations);
} catch (TimedOutException ex) {
logger.error("DROPPING DATA " + ex.getMessage(), ex);
} catch (UnavailableException ex) {
logger.error("DROPPING DATA " + ex.getMessage(), ex);
} catch (InvalidRequestException ex) {
logger.error("DROPPING DATA " + ex.getMessage(), ex);
} catch (TException ex) {
logger.error("DROPPING DATA " + ex.getMessage(), ex);
}
}
}
// convert record to a mapped list of mutations suitable for batch_mutate.
private Map<ByteBuffer, Map<String, List<Mutation>>> makeMutations(AbstractRecord record, HostResolver resolver, long ts) {
Map<ByteBuffer, Map<String, List<Mutation>>> mutations = new HashMap<ByteBuffer, Map<String, List<Mutation>>>();
for (Flow flow : record.flows) {
boolean srcInternal = resolver.isInternal(flow.sourceAddr);
boolean dstInternal = resolver.isInternal(flow.destAddr);
if (srcInternal && dstInternal) {
// src
Mutation m = new Mutation();
m.column_or_supercolumn = new ColumnOrSuperColumn();
m.column_or_supercolumn.column = new Column(getTimeUUIDByteBuffer(flow.timestampCalculated),
int2ByteBuffer(flow.numOctets), ts);
m.column_or_supercolumn.column.ttl = colTTL;
mutationsForKeyAndCf(ByteBuffer.wrap(flow.sourceAddr.getAddress()), localColFam, mutations).add(m);
// dst
m = new Mutation();
m.column_or_supercolumn = new ColumnOrSuperColumn();
m.column_or_supercolumn.column = new Column(getTimeUUIDByteBuffer(flow.timestampCalculated),
int2ByteBuffer(flow.numOctets), ts);
m.column_or_supercolumn.column.ttl = colTTL;
mutationsForKeyAndCf(ByteBuffer.wrap(flow.destAddr.getAddress()), localColFam, mutations).add(m);
} else if (srcInternal) { // inbound
Mutation m = new Mutation();
m.column_or_supercolumn = new ColumnOrSuperColumn();
m.column_or_supercolumn.column = new Column(getTimeUUIDByteBuffer(flow.timestampCalculated),
int2ByteBuffer(flow.numOctets), ts);
m.column_or_supercolumn.column.ttl = colTTL;
mutationsForKeyAndCf(ByteBuffer.wrap(flow.sourceAddr.getAddress()), ingressColFam, mutations).add(m);
} else if (dstInternal) { // outbound
Mutation m = new Mutation();
m.column_or_supercolumn = new ColumnOrSuperColumn();
m.column_or_supercolumn.column = new Column(getTimeUUIDByteBuffer(flow.timestampCalculated),
int2ByteBuffer(flow.numOctets), ts);
m.column_or_supercolumn.column.ttl = colTTL;
mutationsForKeyAndCf(ByteBuffer.wrap(flow.destAddr.getAddress()), egressColFam, mutations).add(m);
} else {
// FIXME: can actually happen.
logger.error("{} nor {} belong to us, how can this be?", flow.sourceAddr.getCanonicalHostName(),
flow.destAddr.getCanonicalHostName());
continue;
}
}
return mutations;
}
protected void write(Map<ByteBuffer, Map<String, List<Mutation>>> mutations)
throws TimedOutException, UnavailableException, InvalidRequestException, TException {
Cassandra.Client client = borrowClient();
boolean reuseClient = true;
try {
client.batch_mutate(mutations, ConsistencyLevel.ONE);
} catch (TException texcep) {
reuseClient = false;
invalidateClient(client);
throw texcep;
} finally {
// Return the client to the pool, unless a TException was thrown.
if (reuseClient)
returnClient(client);
}
}
// ensures integrity of the map while handling the null cases.
protected static List<Mutation> mutationsForKeyAndCf(ByteBuffer key, String cfName, Map<ByteBuffer, Map<String, List<Mutation>>> map) {
Map<String, List<Mutation>> cfMap = map.get(key);
if (cfMap == null) {
cfMap = new HashMap<String, List<Mutation>>();
map.put(key, cfMap);
}
List<Mutation> mutations = cfMap.get(cfName);
if (mutations == null) {
mutations = new ArrayList<Mutation>();
cfMap.put(cfName, mutations);
}
return mutations;
}
/**
* Converts a milliseconds-since-epoch timestamp into the 16 byte representation
* of a type 1 UUID (a time-based UUID).
*
* @param timeMillis
* @return a type 1 UUID represented as a byte[]
*/
protected static byte[] getTimeUUIDBytes(long timeMillis) {
long msb = createTime(timeMillis), lsb = getClockSeqAndNode();
byte[] uuidBytes = new byte[16];
for (int i = 0; i < 8; i++) {
uuidBytes[i] = (byte) (msb >>> 8 * (7 - i));
}
for (int i = 8; i < 16; i++) {
uuidBytes[i] = (byte) (lsb >>> 8 * (7 - i));
}
return uuidBytes;
}
/**
* Converts a milliseconds-since-epoch timestamp into the 16 byte representation
* of a type 1 UUID (a time-based UUID).
*
* @param timeMillis
* @return a type 1 UUID represented as a ByteBuffer
*/
protected static ByteBuffer getTimeUUIDByteBuffer(long timeMillis) {
return ByteBuffer.wrap(getTimeUUIDBytes(timeMillis));
}
private Cassandra.Client borrowClient() {
try {
return (Cassandra.Client)clientPool.borrowObject();
} catch (Exception error) {
throw new RuntimeException(error);
}
}
private void returnClient(Object obj) {
try {
clientPool.returnObject(obj);
} catch (Exception error) {
throw new RuntimeException(error);
}
}
private void invalidateClient(Object obj) {
try {
clientPool.invalidateObject(obj);
} catch (Exception error) {
throw new RuntimeException(error);
}
}
} |
package com.ecyrd.jspwiki.providers;
import java.io.File;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.ArrayList;
import java.util.List;
import java.util.Date;
import java.util.Iterator;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import org.apache.log4j.Logger;
import org.apache.oro.text.regex.*;
import com.ecyrd.jspwiki.*;
/**
* This class implements a simple RCS file provider. NOTE: You MUST
* have the RCS package installed for this to work. They must also
* be in your path...
*
* <P>
* The RCS file provider extends from the FileSystemProvider, which
* means that it provides the pages in the same way. The only difference
* is that it implements the version history commands, and also in each
* checkin it writes the page to the RCS repository as well.
* <p>
* If you decide to dabble with the default commands, please make sure
* that you do not check the default archive suffix ",v". File deletion
* depends on it.
*
* @author Janne Jalkanen
*/
// FIXME: Not all commands read their format from the property file yet.
public class RCSFileProvider
extends AbstractFileProvider
{
private String m_checkinCommand = "ci -q -m\"author=%u\" -l -t-none %s";
private String m_checkoutCommand = "co -l %s";
private String m_logCommand = "rlog -zLT -r %s";
private String m_fullLogCommand = "rlog -zLT %s";
private String m_checkoutVersionCommand = "co -p -r1.%v %s";
private String m_deleteVersionCommand = "rcs -o1.%v %s";
private static final Logger log = Logger.getLogger(RCSFileProvider.class);
public static final String PROP_CHECKIN = "jspwiki.rcsFileProvider.checkinCommand";
public static final String PROP_CHECKOUT = "jspwiki.rcsFileProvider.checkoutCommand";
public static final String PROP_LOG = "jspwiki.rcsFileProvider.logCommand";
public static final String PROP_FULLLOG = "jspwiki.rcsFileProvider.fullLogCommand";
public static final String PROP_CHECKOUTVERSION = "jspwiki.rcsFileProvider.checkoutVersionCommand";
private static final String PATTERN_DATE = "^date:\\s*(.*\\d);";
private static final String PATTERN_AUTHOR = "^\"?author=([\\w\\.\\s\\+\\.\\%]*)\"?";
private static final String PATTERN_REVISION = "^revision \\d+\\.(\\d+)";
private static final String RCSFMT_DATE = "yyyy-MM-dd HH:mm:ss";
private static final String RCSFMT_DATE_UTC = "yyyy/MM/dd HH:mm:ss";
// Date format parsers, placed here to save on object creation
private SimpleDateFormat m_rcsdatefmt = new SimpleDateFormat( RCSFMT_DATE );
private SimpleDateFormat m_rcsdatefmt_utc = new SimpleDateFormat( RCSFMT_DATE_UTC );
public void initialize( WikiEngine engine, Properties props )
throws NoRequiredPropertyException,
IOException
{
log.debug("Initing RCS");
super.initialize( engine, props );
m_checkinCommand = props.getProperty( PROP_CHECKIN, m_checkinCommand );
m_checkoutCommand = props.getProperty( PROP_CHECKOUT, m_checkoutCommand );
m_logCommand = props.getProperty( PROP_LOG, m_logCommand );
m_fullLogCommand = props.getProperty( PROP_FULLLOG, m_fullLogCommand );
m_checkoutVersionCommand = props.getProperty( PROP_CHECKOUTVERSION, m_checkoutVersionCommand );
File rcsdir = new File( getPageDirectory(), "RCS" );
if( !rcsdir.exists() )
{
rcsdir.mkdirs();
}
log.debug("checkin="+m_checkinCommand);
log.debug("checkout="+m_checkoutCommand);
log.debug("log="+m_logCommand);
log.debug("fulllog="+m_fullLogCommand);
log.debug("checkoutversion="+m_checkoutVersionCommand);
}
// NB: This is a very slow method.
public WikiPage getPageInfo( String page, int version )
throws ProviderException
{
PatternMatcher matcher = new Perl5Matcher();
PatternCompiler compiler = new Perl5Compiler();
BufferedReader stdout = null;
WikiPage info = super.getPageInfo( page, version );
if( info == null ) return null;
try
{
String cmd = m_fullLogCommand;
cmd = TextUtil.replaceString( cmd, "%s", mangleName(page)+FILE_EXT );
Process process = Runtime.getRuntime().exec( cmd, null, new File(getPageDirectory()) );
// FIXME: Should this use encoding as well?
stdout = new BufferedReader( new InputStreamReader(process.getInputStream() ) );
String line;
Pattern headpattern = compiler.compile( PATTERN_REVISION );
// This complicated pattern is required, since on Linux RCS adds
// quotation marks, but on Windows, it does not.
Pattern userpattern = compiler.compile( PATTERN_AUTHOR );
Pattern datepattern = compiler.compile( PATTERN_DATE );
boolean found = false;
while( (line = stdout.readLine()) != null )
{
if( matcher.contains( line, headpattern ) )
{
MatchResult result = matcher.getMatch();
try
{
int vernum = Integer.parseInt( result.group(1) );
if( vernum == version || version == WikiPageProvider.LATEST_VERSION )
{
info.setVersion( vernum );
found = true;
}
}
catch( NumberFormatException e )
{
log.info("Failed to parse version number from RCS log: ",e);
// Just continue reading through
}
}
else if( matcher.contains( line, datepattern ) && found )
{
MatchResult result = matcher.getMatch();
Date d = parseDate( result.group(1) );
if( d != null )
{
info.setLastModified( d );
}
else
{
log.info("WikiPage "+info.getName()+
" has null modification date for version "+
version);
}
}
else if( matcher.contains( line, userpattern ) && found )
{
MatchResult result = matcher.getMatch();
info.setAuthor( TextUtil.urlDecodeUTF8(result.group(1)) );
}
else if( found && line.startsWith("
{
// End of line sign from RCS
break;
}
}
// Especially with certain versions of RCS on Windows,
// process.waitFor() hangs unless you read all of the
// standard output. So we make sure it's all emptied.
while( (line = stdout.readLine()) != null )
{
}
process.waitFor();
process.getInputStream().close();
process.getOutputStream().close();
process.getErrorStream().close();
}
catch( Exception e )
{
// This also occurs when 'info' was null.
log.warn("Failed to read RCS info",e);
}
finally
{
try
{
if( stdout != null ) stdout.close();
}
catch( IOException e ) {}
}
return info;
}
public String getPageText( String page, int version )
throws ProviderException
{
String result = null;
InputStream stdout = null;
// Let parent handle latest fetches, since the FileSystemProvider
// can do the file reading just as well.
if( version == WikiPageProvider.LATEST_VERSION )
return super.getPageText( page, version );
log.debug("Fetching specific version "+version+" of page "+page);
try
{
PatternMatcher matcher = new Perl5Matcher();
PatternCompiler compiler = new Perl5Compiler();
int checkedOutVersion = -1;
String line;
String cmd = m_checkoutVersionCommand;
cmd = TextUtil.replaceString( cmd, "%s", mangleName(page)+FILE_EXT );
cmd = TextUtil.replaceString( cmd, "%v", Integer.toString(version ) );
log.debug("Command = '"+cmd+"'");
Process process = Runtime.getRuntime().exec( cmd, null, new File(getPageDirectory()) );
stdout = process.getInputStream();
result = FileUtil.readContents( stdout, m_encoding );
BufferedReader stderr = new BufferedReader(new InputStreamReader(process.getErrorStream()));
Pattern headpattern = compiler.compile( PATTERN_REVISION );
while( (line = stderr.readLine()) != null )
{
if( matcher.contains( line, headpattern ) )
{
MatchResult mr = matcher.getMatch();
checkedOutVersion = Integer.parseInt( mr.group(1) );
}
}
process.waitFor();
int exitVal = process.exitValue();
process.getInputStream().close();
process.getOutputStream().close();
process.getErrorStream().close();
log.debug("Done, returned = "+exitVal);
// If fetching failed, assume that this is because of the user
// has just migrated from FileSystemProvider, and check
// if he's getting version 1. Else he might be trying to find
// a version that has been deleted.
if( exitVal != 0 || checkedOutVersion == -1 )
{
if( version == 1 )
{
System.out.println("Migrating, fetching super.");
result = super.getPageText( page, WikiProvider.LATEST_VERSION );
}
else
{
throw new NoSuchVersionException( "Page: "+page+", version="+version);
}
}
else
{
// Check which version we actually got out!
if( checkedOutVersion != version )
{
throw new NoSuchVersionException( "Page: "+page+", version="+version);
}
}
}
catch( MalformedPatternException e )
{
throw new InternalWikiException("Malformed pattern in RCSFileProvider!");
}
catch( InterruptedException e )
{
// This is fine, we'll just log it.
log.info("RCS process was interrupted, we'll just return whatever we found.");
}
catch( IOException e )
{
log.error("RCS checkout failed",e);
}
finally
{
try
{
if( stdout != null ) stdout.close();
}
catch( Exception e ) {}
}
return result;
}
/**
* Puts the page into RCS and makes sure there is a fresh copy in
* the directory as well.
*/
public void putPageText( WikiPage page, String text )
throws ProviderException
{
String pagename = page.getName();
// Writes it in the dir.
super.putPageText( page, text );
log.debug( "Checking in text..." );
try
{
String cmd = m_checkinCommand;
String author = page.getAuthor();
if( author == null ) author = "unknown";
cmd = TextUtil.replaceString( cmd, "%s", mangleName(pagename)+FILE_EXT );
cmd = TextUtil.replaceString( cmd, "%u", TextUtil.urlEncodeUTF8(author) );
log.debug("Command = '"+cmd+"'");
Process process = Runtime.getRuntime().exec( cmd, null, new File(getPageDirectory()) );
process.waitFor();
log.debug("Done, returned = "+process.exitValue());
process.getInputStream().close();
process.getOutputStream().close();
process.getErrorStream().close();
}
catch( Exception e )
{
log.error("RCS checkin failed",e);
}
}
// FIXME: Put the rcs date formats into properties as well.
public List getVersionHistory( String page )
{
PatternMatcher matcher = new Perl5Matcher();
PatternCompiler compiler = new Perl5Compiler();
BufferedReader stdout = null;
log.debug("Getting RCS version history");
ArrayList list = new ArrayList();
try
{
Pattern revpattern = compiler.compile( PATTERN_REVISION );
Pattern datepattern = compiler.compile( PATTERN_DATE );
// This complicated pattern is required, since on Linux RCS adds
// quotation marks, but on Windows, it does not.
Pattern userpattern = compiler.compile( PATTERN_AUTHOR );
String cmd = TextUtil.replaceString( m_fullLogCommand,
"%s",
mangleName(page)+FILE_EXT );
Process process = Runtime.getRuntime().exec( cmd, null, new File(getPageDirectory()) );
// FIXME: Should this use encoding as well?
stdout = new BufferedReader( new InputStreamReader(process.getInputStream()) );
String line;
WikiPage info = null;
while( (line = stdout.readLine()) != null )
{
if( matcher.contains( line, revpattern ) )
{
info = new WikiPage( m_engine, page );
MatchResult result = matcher.getMatch();
int vernum = Integer.parseInt( result.group(1) );
info.setVersion( vernum );
list.add( info );
}
if( matcher.contains( line, datepattern ) )
{
MatchResult result = matcher.getMatch();
Date d = parseDate( result.group(1) );
info.setLastModified( d );
}
if( matcher.contains( line, userpattern ) )
{
MatchResult result = matcher.getMatch();
info.setAuthor( TextUtil.urlDecodeUTF8(result.group(1)) );
}
}
process.waitFor();
process.getInputStream().close();
process.getOutputStream().close();
process.getErrorStream().close();
// FIXME: This is very slow
for( Iterator i = list.iterator(); i.hasNext(); )
{
WikiPage p = (WikiPage) i.next();
String content = getPageText( p.getName(), p.getVersion() );
p.setSize( content.length() );
}
}
catch( Exception e )
{
log.error( "RCS log failed", e );
}
finally
{
try
{
if( stdout != null ) stdout.close();
}
catch( IOException e ) {}
}
return list;
}
/**
* Removes the page file and the RCS archive from the repository.
* This method assumes that the page archive ends with ",v".
*/
public void deletePage( String page )
throws ProviderException
{
log.debug( "Deleting page "+page );
super.deletePage( page );
File rcsdir = new File( getPageDirectory(), "RCS" );
if( rcsdir.exists() && rcsdir.isDirectory() )
{
File rcsfile = new File( rcsdir, mangleName(page)+FILE_EXT+",v" );
if( rcsfile.exists() )
{
if( rcsfile.delete() == false )
{
log.warn( "Deletion of RCS file "+rcsfile.getAbsolutePath()+" failed!" );
}
}
else
{
log.info( "RCS file does not exist for page: "+page );
}
}
else
{
log.info( "No RCS directory at "+rcsdir.getAbsolutePath() );
}
}
public void deleteVersion( String page, int version )
{
String line = "<rcs not run>";
BufferedReader stderr;
boolean success = false;
String cmd = m_deleteVersionCommand;
log.debug("Deleting version "+version+" of page "+page);
cmd = TextUtil.replaceString( cmd, "%s", mangleName(page)+FILE_EXT );
cmd = TextUtil.replaceString( cmd, "%v", Integer.toString( version ) );
log.debug("Running command "+cmd);
try
{
Process process = Runtime.getRuntime().exec( cmd, null, new File(getPageDirectory()) );
// 'rcs' command outputs to stderr methinks.
// FIXME: Should this use encoding as well?
stderr = new BufferedReader( new InputStreamReader(process.getErrorStream() ) );
while( (line = stderr.readLine()) != null )
{
log.debug( "LINE="+line );
if( line.equals("done") )
{
success = true;
}
}
}
catch( IOException e )
{
log.error("Page deletion failed: ",e);
}
if( !success )
{
log.error("Version deletion failed. Last info from RCS is: "+line);
}
}
/**
* util method to parse a date string in Local and UTC formats
*/
private Date parseDate( String str )
{
Date d = null;
try
{
d = m_rcsdatefmt.parse( str );
return d;
}
catch ( ParseException pe ) { }
try
{
d = m_rcsdatefmt_utc.parse( str );
return d;
}
catch ( ParseException pe ) { }
return d;
}
public void movePage( String from,
String to )
throws ProviderException
{
// XXX: Error checking could be better throughout this method.
File fromFile = findPage( from );
File toFile = findPage( to );
fromFile.renameTo( toFile );
String fromRCSName = "RCS/"+mangleName( from )+FILE_EXT+",v";
String toRCSName = "RCS/"+mangleName( to )+FILE_EXT+",v";
File fromRCSFile = new File( getPageDirectory(), fromRCSName );
File toRCSFile = new File( getPageDirectory(), toRCSName );
fromRCSFile.renameTo( toRCSFile );
}
} |
package com.jaamsim.BasicObjects;
import java.util.ArrayList;
import com.jaamsim.Graphics.DisplayEntity;
import com.jaamsim.datatypes.IntegerVector;
import com.jaamsim.input.EntityInput;
import com.jaamsim.input.EntityListInput;
import com.jaamsim.input.InputErrorException;
import com.jaamsim.input.IntegerListInput;
import com.jaamsim.input.Keyword;
public class Seize extends LinkedComponent {
@Keyword(description = "The Resource(s) to be seized.",
example = "Seize1 Resource { Resource1 Resource2 }")
private final EntityListInput<Resource> resourceList;
@Keyword(description = "The number of units to seize from the Resource(s).",
example = "Seize1 NumberOfUnits { 2 1 }")
private final IntegerListInput numberOfUnitsList;
@Keyword(description = "The queue in which the waiting DisplayEntities will be placed.",
example = "Seize1 WaitQueue { Queue1 }")
private final EntityInput<Queue> waitQueue;
{
resourceList = new EntityListInput<>(Resource.class, "Resource", "Key Inputs", null);
this.addInput(resourceList);
IntegerVector defNum = new IntegerVector();
defNum.add(1);
numberOfUnitsList = new IntegerListInput("NumberOfUnits", "Key Inputs", defNum);
this.addInput(numberOfUnitsList);
waitQueue = new EntityInput<>(Queue.class, "WaitQueue", "Key Inputs", null);
this.addInput(waitQueue);
}
@Override
public void validate() {
super.validate();
// Confirm that the target queue has been specified
if (waitQueue.getValue() == null) {
throw new InputErrorException("The keyword WaitQueue must be set.");
}
// Confirm that the resource has been specified
if (resourceList.getValue() == null) {
throw new InputErrorException("The keyword Resource must be set.");
}
}
@Override
public void addEntity(DisplayEntity ent) {
super.addEntity(ent);
Queue queue = waitQueue.getValue();
// If other entities are queued already or insufficient units are available, then add the entity to the queue
if (queue.getCount() > 0 || !this.checkResources()) {
queue.addEntity(ent);
return;
}
// If sufficient units are available, then seize them and pass the entity to the next component
this.seizeResources();
this.sendToNextComponent(ent);
}
/**
* Determine whether the required Resources are available.
* @return = TRUE if all the resources are available
*/
public boolean checkResources() {
ArrayList<Resource> resList = resourceList.getValue();
IntegerVector numberList = numberOfUnitsList.getValue();
for (int i=0; i<resList.size(); i++) {
if (resList.get(i).getAvailableUnits() < numberList.get(i))
return false;
}
return true;
}
/**
* Seize the required Resources.
* @return
*/
public void seizeResources() {
ArrayList<Resource> resList = resourceList.getValue();
IntegerVector numberList = numberOfUnitsList.getValue();
for (int i=0; i<resList.size(); i++) {
resList.get(i).seize(numberList.get(i));
}
}
/**
* Remove an object from the queue, seize the specified resources, and pass to the next component
* @param i = position in the queue of the object to be removed
*/
public void processQueuedEntity(int i) {
if (this.checkResources()) {
this.seizeResources();
DisplayEntity ent = waitQueue.getValue().remove(i);
this.sendToNextComponent(ent);
}
}
public Queue getQueue() {
return waitQueue.getValue();
}
/**
* Is the specified Resource required by this Seize object?
* @param res = the specified Resource.
* @return = TRUE if the Resource is required.
*/
public boolean requiresResource(Resource res) {
return resourceList.getValue().contains(res);
}
} |
package agentgui.core.update;
import javax.swing.JOptionPane;
import org.agentgui.gui.AwbProgressMonitor;
import org.agentgui.gui.UiBridge;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.equinox.p2.operations.UpdateOperation;
import agentgui.core.application.Application;
import agentgui.core.application.Language;
import agentgui.core.config.GlobalInfo;
import agentgui.core.config.GlobalInfo.ExecutionEnvironment;
import agentgui.core.config.GlobalInfo.ExecutionMode;
import agentgui.core.gui.options.UpdateOptions;
import de.enflexit.common.p2.P2OperationsHandler;
/**
* The Class AWBUpdater provides a thread that can be used to update
* Agent.Workbench and its features.
*
* @author Christian Derksen - DAWIS - ICB - University of Duisburg - Essen
* @author Nils Loose - DAWIS - ICB - University of Duisburg - Essen
*/
public class AWBUpdater extends Thread {
public static final long UPDATE_CHECK_PERIOD = 1000 * 60 * 60 * 24; // - once a day -
private boolean debuggingInIDE = false;
private boolean debug = false;
private boolean updateDone = false;
private GlobalInfo globalInfo;
private ExecutionMode executionMode;
private Integer updateAutoConfiguration;
private long updateDateLastChecked = 0;
private boolean manualyExecutedByUser = false;
private boolean enforceUpdate = false;
private boolean doUpdateProcedure = true;
private boolean askBeforeDownload = false;
private boolean doUpdateCheckOnly = false;
private Object synchronizationObject;
private AwbProgressMonitor progressMonitor;
/**
* Instantiates a new Agent.Workbench updater process.
*/
public AWBUpdater() {
this(false);
}
/**
* Instantiates a new Agent.Workbench updater process.
* @param userExecuted indicates that execution was manually chosen by user
*/
public AWBUpdater(boolean userExecuted) {
this(userExecuted, false);
}
/**
* Instantiates a new Agent.Workbench updater process.
* @param userExecuted indicates that execution was manually chosen by user
* @param enforceUpdate the enforce update
*/
public AWBUpdater(boolean userExecuted, boolean enforceUpdate) {
this.manualyExecutedByUser = userExecuted;
this.enforceUpdate = enforceUpdate;
this.initialize();
}
/**
* Initialize and set needed local variables.
*/
private void initialize() {
this.synchronizationObject = new Object();
this.setName(Application.getGlobalInfo().getApplicationTitle() + "-Updater");
this.globalInfo = Application.getGlobalInfo();
this.executionMode = this.globalInfo.getExecutionMode();
this.updateAutoConfiguration = this.globalInfo.getUpdateAutoConfiguration();
this.updateDateLastChecked = this.globalInfo.getUpdateDateLastChecked();
this.setUpdateConfiguration();
}
/**
* Sets the update configuration.
*/
private void setUpdateConfiguration() {
if (this.manualyExecutedByUser==false) {
long timeNow = System.currentTimeMillis();
long time4NextCheck = this.updateDateLastChecked + AWBUpdater.UPDATE_CHECK_PERIOD;
if (this.enforceUpdate==false && timeNow < time4NextCheck) {
this.doUpdateProcedure = false;
return;
} else {
Application.getGlobalInfo().setUpdateDateLastChecked(timeNow);
Application.getGlobalInfo().doSaveConfiguration();
}
}
switch (this.executionMode) {
case APPLICATION:
switch (this.updateAutoConfiguration) {
case UpdateOptions.UPDATE_MODE_AUTOMATIC:
this.askBeforeDownload = false;
break;
case UpdateOptions.UPDATE_MODE_ASK:
this.askBeforeDownload = true;
break;
default:
doUpdateProcedure = false;
break;
}
break;
case SERVER:
case SERVER_MASTER:
case SERVER_SLAVE:
case DEVICE_SYSTEM:
switch (this.updateAutoConfiguration) {
case UpdateOptions.UPDATE_MODE_AUTOMATIC:
this.askBeforeDownload = false;
break;
default:
System.out.println("[" + this.getClass().getSimpleName() + "] Automatic updates are disabled.");
doUpdateProcedure = false;
break;
}
break;
}
if (this.manualyExecutedByUser==true) {
this.askBeforeDownload=true;
this.doUpdateProcedure=true;
}
if (this.globalInfo.getExecutionEnvironment()==ExecutionEnvironment.ExecutedOverIDE) {
this.askBeforeDownload = true;
this.doUpdateProcedure = false; // set to 'true' for further developments of the AgentGuiUpdater class
this.doUpdateCheckOnly = true;
System.out.println("[" + this.getClass().getSimpleName() + "] P2 updates are not possible when starting from the IDE.");
}
if (this.debuggingInIDE == true) {
this.doUpdateProcedure = true;
this.askBeforeDownload = true;
}
}
/*
* (non-Javadoc)
* @see java.lang.Thread#run()
*/
@Override
public void run() {
super.run();
synchronized (this.getSynchronizationObject()) {
if (this.doUpdateProcedure==true) {
this.debugPrint("Doing full update procedure");
this.waitForTheEndOfBenchmark();
this.startP2Updates();
} else if (this.doUpdateCheckOnly==true) {
this.debugPrint("Doing update check only");
this.waitForTheEndOfBenchmark();
this.checkForAvailableUpdates(); // Disabled due to strange results
}
this.debugPrint("Update done, notifying");
this.updateDone = true;
this.getSynchronizationObject().notify();
}
}
/**
* Checks if updates for the locally installed software components are available.
*/
private void checkForAvailableUpdates() {
boolean updatesAvailable = P2OperationsHandler.getInstance().checkForNewerBundles();
if (updatesAvailable==true) {
String infoString = "Newer versions of local AWB components are available, please update your local AWB installation (if working against one) and the Target Platform!";
System.err.println("[" + this.getClass().getSimpleName() + "] " + infoString);
//TODO Activate when sure everything works
// if (Application.isOperatingHeadless()==false) {
// JOptionPane.showMessageDialog(Application.getMainWindow(), infoString, "Updates available!", JOptionPane.WARNING_MESSAGE);
}
}
/**
* Wait for the end of the benchmark.
*/
private void waitForTheEndOfBenchmark() {
while (Application.isBenchmarkRunning()==true) {
try {
sleep(250);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
/**
* Starts a p2-based update procedure
*/
public void startP2Updates() {
System.out.println("[" + this.getClass().getSimpleName() + "] P2 Update: Check for updates ...");
if (Application.isOperatingHeadless() == false) {
this.getProgressMonitor().setVisible(true);
P2OperationsHandler.getInstance().setProgressMonitor(this.getProgressMonitor());
}
IStatus status = P2OperationsHandler.getInstance().checkForUpdates();
if (status.getSeverity()!=IStatus.ERROR) {
if (status.getCode()==UpdateOperation.STATUS_NOTHING_TO_UPDATE) {
System.out.println("[" + this.getClass().getSimpleName() + "] P2 Update: No updates found!");
if (Application.isOperatingHeadless() == false) {
this.getProgressMonitor().setProgress(100);
this.getProgressMonitor().setVisible(false);
this.getProgressMonitor().dispose();
}
if (Application.isOperatingHeadless()==false && this.manualyExecutedByUser==true) {
JOptionPane.showMessageDialog(null, Language.translate("Keine Updates gefunden") + "!", Language.translate("Keine Updates gefunden"), JOptionPane.INFORMATION_MESSAGE);
}
} else {
boolean installUpdates = true;
if (this.askBeforeDownload==true) {
if (this.executionMode == ExecutionMode.APPLICATION) {
this.getProgressMonitor().setVisible(false);
}
int userAnswer = JOptionPane.showConfirmDialog(null, Language.translate("Updates verfügbar, installieren?"), Application.getGlobalInfo().getApplicationTitle() + " Update", JOptionPane.YES_NO_OPTION);
if (userAnswer == JOptionPane.NO_OPTION) {
installUpdates = false;
System.out.println("[" + this.getClass().getSimpleName() + "] P2 Update: Update canceled by user.");
if (Application.isOperatingHeadless() == false) {
this.getProgressMonitor().setVisible(false);
this.getProgressMonitor().dispose();
}
}
}
if (installUpdates==true) {
if (Application.isOperatingHeadless() == false) {
this.getProgressMonitor().setHeaderText(Language.translate("Installiere Updates"));
this.getProgressMonitor().setProgressText(Language.translate("Installiere") + "...");
this.getProgressMonitor().setVisible(true);
P2OperationsHandler.getInstance().setProgressMonitor(this.getProgressMonitor());
}
status = P2OperationsHandler.getInstance().installAvailableUpdates();
if (status.isOK()) {
System.out.println("[" + this.getClass().getSimpleName() + "] P2 Update: Updates sucessfully installed, restarting...");
Application.restart();
} else {
System.err.println("[" + this.getClass().getSimpleName() + "] P2 Update: Error installing updates.");
}
}
if (Application.isOperatingHeadless() == false) {
this.getProgressMonitor().setProgress(100);
this.getProgressMonitor().setVisible(false);
this.getProgressMonitor().dispose();
}
}
}
P2OperationsHandler.getInstance().setProgressMonitor(null);
}
/**
* Gets the progress monitor.
* @return the progress monitor
*/
private AwbProgressMonitor getProgressMonitor() {
if (this.progressMonitor == null) {
String title = Language.translate("Aktualisierung");
String header = Language.translate("Suche nach Updates");
String progress = Language.translate("Suche") + "...";
this.progressMonitor = UiBridge.getInstance().getProgressMonitor(title, header, progress);
}
return this.progressMonitor;
}
/**
* Checks if the update is done.
* @return true, if is update done
*/
public boolean isUpdateDone() {
return updateDone;
}
/**
* Wait until the update is done.
*/
public void waitForUpdate() {
if (this.isUpdateDone()==false) {
synchronized (this.getSynchronizationObject()) {
try {
this.debugPrint("Waiting for the update process");
this.getSynchronizationObject().wait();
this.debugPrint("Update process finished, proceeding");
} catch (InterruptedException e) {
System.err.println("Waiting for update interrupted");
e.printStackTrace();
}
}
} else {
this.debugPrint("Update already done, no need to wait");
}
}
/**
* Check for updates.
*/
// private void checkForUpdates() {
// P2OperationsHandler.getInstance().checkMetadataRepos();
// IStatus status = P2OperationsHandler.getInstance().checkForUpdates();
// if (status.getSeverity()!=IStatus.ERROR) {
// if (status.getCode()==UpdateOperation.STATUS_NOTHING_TO_UPDATE) {
// System.out.println("[" + this.getClass().getSimpleName() + "] All installed features are up to date.");
// } else {
// JOptionPane.showMessageDialog(null, "Newer Versions of installed features are available, please update your target platform!", "Updates available", JOptionPane.WARNING_MESSAGE);
// System.out.println("[" + this.getClass().getSimpleName() + "] Newer Versions of installed features are available, please update your target platform!");
/**
* Gets the synchronization object.
* @return the synchronization object
*/
private Object getSynchronizationObject() {
if (this.synchronizationObject==null) {
this.synchronizationObject = new Object();
}
return this.synchronizationObject;
}
private void debugPrint(String text) {
if (this.debug==true) {
System.out.println("[" + this.getClass().getSimpleName() + "] " + text);
}
}
} |
package org.myrobotlab.service;
import org.myrobotlab.framework.Service;
import org.myrobotlab.logging.Level;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.logging.Logging;
import org.myrobotlab.logging.LoggingFactory;
import org.slf4j.Logger;
import org.wikidata.wdtk.datamodel.interfaces.EntityDocument;
import org.wikidata.wdtk.datamodel.interfaces.ItemDocument;
import org.wikidata.wdtk.datamodel.interfaces.ItemIdValue;
import org.wikidata.wdtk.datamodel.interfaces.MonolingualTextValue;
import org.wikidata.wdtk.datamodel.interfaces.PropertyIdValue;
import org.wikidata.wdtk.datamodel.interfaces.Snak;
import org.wikidata.wdtk.datamodel.interfaces.Statement;
import org.wikidata.wdtk.datamodel.interfaces.StatementGroup;
import org.wikidata.wdtk.wikibaseapi.WikibaseDataFetcher;
import org.wikidata.wdtk.wikibaseapi.apierrors.MediaWikiApiErrorException;
import org.wikidata.wdtk.datamodel.interfaces.TimeValue;
import org.wikidata.wdtk.datamodel.interfaces.Value;
import org.wikidata.wdtk.datamodel.interfaces.ValueSnak;
import org.wikidata.wdtk.datamodel.interfaces.SomeValueSnak;
import org.wikidata.wdtk.datamodel.interfaces.DataObjectFactory;
import org.wikidata.wdtk.datamodel.helpers.ToString;
import org.wikidata.wdtk.datamodel.json.jackson.*;
import org.wikidata.wdtk.datamodel.json.jackson.JacksonItemDocument;
import org.wikidata.wdtk.datamodel.json.jackson.datavalues.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class WikiDataFetcher extends Service {
private static final long serialVersionUID = 1L;
public final static Logger log = LoggerFactory.getLogger(WikiDataFetcher.class);
String language = "en";
String website = "enwiki";
public static void main(String[] args) {
LoggingFactory.getInstance().configure();
LoggingFactory.getInstance().setLevel(Level.INFO);
try {
WikiDataFetcher wdf = (WikiDataFetcher) Runtime.start("wikiDataFetcher", "WikiDataFetcher");
Runtime.start("gui", "GUIService");
} catch (Exception e) {
Logging.logError(e);
}
}
public WikiDataFetcher(String n) {
super(n);
}
@Override
public String[] getCategories() {
return new String[] { "general" };
}
@Override
public String getDescription() {
return "used as a general template";
}
public void setLanguage(String lang){
language = lang;
}
public void setWebSite(String site){
website = site;
}
private EntityDocument getWiki(String query) throws MediaWikiApiErrorException{
WikibaseDataFetcher wbdf = WikibaseDataFetcher.getWikidataDataFetcher();
EntityDocument wiki = wbdf.getEntityDocumentByTitle(website,query);
if (wiki == null) {
System.out.println("ERROR ! Can't get the document : " + query);
}
return wiki;
}
private EntityDocument getWikiById(String query) throws MediaWikiApiErrorException{
WikibaseDataFetcher wbdf = WikibaseDataFetcher.getWikidataDataFetcher();
EntityDocument wiki = wbdf.getEntityDocument(query);
if (wiki == null) {
System.out.println("ERROR ! Can't get the document : " + query);
}
return wiki;
}
public String getDescription(String query) throws MediaWikiApiErrorException{
EntityDocument document = getWiki(query);
if (document instanceof ValueSnak) {
System.out.println("MainSnak Value : ");
}
try {
String answer = ((ItemDocument) document).getDescriptions().get(language).getText();
return answer;
}
catch (Exception e){return " Description not found";}
}
public String getLabel(String query) throws MediaWikiApiErrorException{
EntityDocument document = getWiki(query);
try {
String answer = ((ItemDocument) document).getLabels().get(language).getText();
return answer;
}
catch (Exception e){return "Label not found";}
}
public String getId(String query) throws MediaWikiApiErrorException{
EntityDocument document = getWiki(query);
try {
String answer = document.getEntityId().getId();
return answer;
}
catch (Exception e){return "ID not found";}
}
public String getDescriptionById(String query) throws MediaWikiApiErrorException{
EntityDocument document = getWikiById(query);
try {
String answer = ((ItemDocument) document).getDescriptions().get(language).getText();
return answer;
}
catch (Exception e){return "Description by ID not found";}
}
public String getLabelById(String query) throws MediaWikiApiErrorException{
EntityDocument document = getWikiById(query);
try {
String answer = ((ItemDocument) document).getLabels().get(language).getText();
return answer;
}
catch (Exception e){return "Label by ID not found";}
}
public String cutStart(String sentence) throws MediaWikiApiErrorException{
try {
String answer = sentence.substring(sentence.indexOf(" ")+1);
return answer;
}
catch (Exception e){return sentence;}
}
public String grabStart(String sentence) throws MediaWikiApiErrorException{
try {
String answer = sentence.substring(0,sentence.indexOf(" "));
return answer;
}
catch (Exception e){return sentence;}
}
// TODO add other dataType
public Value getSnak(String query, String ID) throws MediaWikiApiErrorException{
EntityDocument document = getWiki(query);
String dataType = "error";
Value data = (Value)document.getEntityId();// If property is not found, return the value of document ID
for (StatementGroup sg : ((ItemDocument) document).getStatementGroups()) {
if (ID.equals(sg.getProperty().getId())) { // Check if this ID exist for this document
for (Statement s : sg.getStatements()) {
if (s.getClaim().getMainSnak() instanceof ValueSnak) {
dataType = ((JacksonValueSnak) s.getClaim().getMainSnak()).getDatatype().toString();
switch (dataType) {
case "wikibase-item":
data = ((JacksonValueSnak) s.getClaim().getMainSnak()).getValue();
break;
case "time":
data = (TimeValue)(((JacksonValueSnak) s.getClaim().getMainSnak()).getDatavalue());
break;
}
}
}
}
}
return data;
}
public String getProperty(String query, String ID)throws MediaWikiApiErrorException{
String info = (getSnak(query,ID)).toString();
int beginIndex = info.indexOf('Q');
int endIndex = info.indexOf("(") ;
info = info.substring(beginIndex , endIndex-1);
return getLabelById(info);
}
public String getTime(String query, String ID, String what)throws MediaWikiApiErrorException{
try {
TimeValue date = (TimeValue)(getSnak(query,ID));
String data ="";
switch (what) {
case "year":
data = String.valueOf(date.getYear());
break;
case "month":
data = String.valueOf(date.getMonth());
break;
case "day":
data = String.valueOf(date.getDay());
break;
case "hour":
data = String.valueOf(date.getHour());
break;
case "minute":
data = String.valueOf(date.getMinute());
break;
case "second":
data = String.valueOf(date.getSecond());
break;
case "before":
data = String.valueOf(date.getBeforeTolerance());
break;
case "after":
data = String.valueOf(date.getAfterTolerance());
break;
default:
data = "ERROR";
}
return data;
}
catch (Exception e){return "Not a TimeValue !";}
}
} |
package fr.adbonnin.cz2128.json;
import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import fr.adbonnin.cz2128.json.provider.FileProvider;
import fr.adbonnin.cz2128.json.provider.MemoryProvider;
import fr.adbonnin.cz2128.json.repository.*;
import java.nio.file.Path;
import java.util.function.BiFunction;
import java.util.function.Function;
import static java.util.Objects.requireNonNull;
public class Json {
private final ObjectMapper mapper;
public Json(ObjectMapper mapper) {
this.mapper = requireNonNull(mapper);
}
public ObjectMapper getMapper() {
return mapper;
}
public ProviderFactory fileProvider(Path file) {
return new ProviderFactory(new FileProvider(file, mapper.getFactory()));
}
public ProviderFactory fileProvider(Path file, JsonEncoding encoding) {
return new ProviderFactory(new FileProvider(file, encoding, mapper.getFactory()));
}
public ProviderFactory fileProvider(Path file, Path tempFile, JsonEncoding encoding) {
return new ProviderFactory(new FileProvider(file, tempFile, encoding, mapper.getFactory()));
}
public ProviderFactory fileProvider(Path file, Function<Path, Path> tempFileProvider, JsonEncoding encoding) {
return new ProviderFactory(new FileProvider(file, tempFileProvider, encoding, mapper.getFactory()));
}
public ProviderFactory memoryProvider() {
return new ProviderFactory(new MemoryProvider(mapper.getFactory()));
}
public ProviderFactory memoryProvider(String content) {
return new ProviderFactory(new MemoryProvider(content, mapper.getFactory()));
}
public ProviderFactory provider(JsonProvider provider) {
return new ProviderFactory(provider);
}
public class ProviderFactory implements JsonProvider {
private final JsonProvider provider;
public ProviderFactory(JsonProvider provider) {
this.provider = requireNonNull(provider);
}
public JsonProvider getProvider() {
return provider;
}
@Override
public <R> R withParser(Function<JsonParser, ? extends R> function) {
return provider.withParser(function);
}
@Override
public <R> R withGenerator(BiFunction<JsonParser, JsonGenerator, ? extends R> function) {
return provider.withGenerator(function);
}
@Override
public JsonNode readJsonNode() {
return provider.readJsonNode();
}
@Override
public void writeJsonNode(JsonNode node) {
provider.writeJsonNode(node);
}
@Override
public ProviderFactory at(String name) {
return new ProviderFactory(provider.at(name));
}
@Override
public ProviderFactory at(int index) {
return new ProviderFactory(provider.at(index));
}
@Override
public ProviderFactory concurrent(long lockTimeout) {
return new ProviderFactory(provider.concurrent(lockTimeout));
}
public NodeRepositoryFactory node() {
return new NodeRepositoryFactory(provider);
}
public ValueRepositoryFactory value() {
return new ValueRepositoryFactory(provider);
}
}
public abstract class RepositoryFactory extends ProviderFactory {
public RepositoryFactory(JsonProvider provider) {
super(provider);
}
public abstract <U> SetRepository<U> setRepository(Class<U> type);
public abstract <U> SetRepository<U> setRepository(TypeReference<U> type);
public abstract <U> SetRepository<U> setRepository(ObjectReader reader);
public abstract <U> MapRepository<U> mapRepository(Class<U> type);
public abstract <U> MapRepository<U> mapRepository(TypeReference<U> type);
public abstract <U> MapRepository<U> mapRepository(ObjectReader reader);
public abstract <U> ElementRepository<U> elementRepository(Class<U> type);
public abstract <U> ElementRepository<U> elementRepository(TypeReference<U> type);
public abstract <U> ElementRepository<U> elementRepository(ObjectReader reader);
}
public class NodeRepositoryFactory extends RepositoryFactory {
private final JsonProvider provider;
public NodeRepositoryFactory(JsonProvider provider) {
super(provider);
this.provider = provider;
}
@Override
public <U> NodeSetRepository<U> setRepository(Class<U> type) {
return new NodeSetRepository<>(type, provider, mapper);
}
@Override
public <U> NodeSetRepository<U> setRepository(TypeReference<U> type) {
return new NodeSetRepository<>(type, provider, mapper);
}
@Override
public <U> NodeSetRepository<U> setRepository(ObjectReader reader) {
return new NodeSetRepository<>(reader, provider, mapper);
}
@Override
public <U> NodeMapRepository<U> mapRepository(Class<U> type) {
return new NodeMapRepository<>(type, provider, mapper);
}
@Override
public <U> NodeMapRepository<U> mapRepository(TypeReference<U> type) {
return new NodeMapRepository<>(type, provider, mapper);
}
@Override
public <U> NodeMapRepository<U> mapRepository(ObjectReader reader) {
return new NodeMapRepository<>(reader, provider, mapper);
}
@Override
public <U> NodeElementRepository<U> elementRepository(Class<U> type) {
return new NodeElementRepository<>(type, provider, mapper);
}
@Override
public <U> NodeElementRepository<U> elementRepository(TypeReference<U> type) {
return new NodeElementRepository<>(type, provider, mapper);
}
@Override
public <U> NodeElementRepository<U> elementRepository(ObjectReader reader) {
return new NodeElementRepository<>(reader, provider, mapper);
}
}
public class ValueRepositoryFactory extends RepositoryFactory {
private final JsonProvider provider;
public ValueRepositoryFactory(JsonProvider provider) {
super(provider);
this.provider = provider;
}
@Override
public <U> ValueSetRepository<U> setRepository(Class<U> type) {
return new ValueSetRepository<>(type, provider, mapper);
}
@Override
public <U> ValueSetRepository<U> setRepository(TypeReference<U> type) {
return new ValueSetRepository<>(type, provider, mapper);
}
@Override
public <U> ValueSetRepository<U> setRepository(ObjectReader reader) {
return new ValueSetRepository<>(reader, provider, mapper);
}
@Override
public <U> ValueMapRepository<U> mapRepository(Class<U> type) {
return new ValueMapRepository<>(type, provider, mapper);
}
@Override
public <U> ValueMapRepository<U> mapRepository(TypeReference<U> type) {
return new ValueMapRepository<>(type, provider, mapper);
}
@Override
public <U> ValueMapRepository<U> mapRepository(ObjectReader reader) {
return new ValueMapRepository<>(reader, provider, mapper);
}
@Override
public <U> ValueElementRepository<U> elementRepository(Class<U> type) {
return new ValueElementRepository<>(type, provider, mapper);
}
@Override
public <U> ValueElementRepository<U> elementRepository(TypeReference<U> type) {
return new ValueElementRepository<>(type, provider, mapper);
}
@Override
public <U> ValueElementRepository<U> elementRepository(ObjectReader reader) {
return new ValueElementRepository<>(reader, provider, mapper);
}
}
} |
package com.ecyrd.jspwiki.providers;
import java.io.File;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.Properties;
import java.util.Collection;
import java.util.ArrayList;
import java.util.Date;
import java.text.SimpleDateFormat;
import org.apache.log4j.Category;
import org.apache.oro.text.*;
import org.apache.oro.text.regex.*;
import com.ecyrd.jspwiki.*;
/**
* This class implements a simple RCS file provider. NOTE: You MUST
* have the RCS package installed for this to work. They must also
* be in your path...
*
* <P>
* The RCS file provider extends from the FileSystemProvider, which
* means that it provides the pages in the same way. The only difference
* is that it implements the version history commands, and also in each
* checkin it writes the page to the RCS repository as well.
*
* @author Janne Jalkanen
*/
// FIXME: Not all commands read their format from the property file yet.
public class RCSFileProvider
extends FileSystemProvider
{
private String m_checkinCommand = "ci -q -m\"author=%u\" -l -t-none %s";
private String m_checkoutCommand = "co -l %s";
private String m_logCommand = "rlog -zLT -r %s";
private String m_fullLogCommand = "rlog -zLT %s";
private String m_checkoutVersionCommand = "co -p -r1.%v %s";
private static final Category log = Category.getInstance(RCSFileProvider.class);
public static final String PROP_CHECKIN = "jspwiki.rcsFileProvider.checkinCommand";
public static final String PROP_CHECKOUT = "jspwiki.rcsFileProvider.checkoutCommand";
public static final String PROP_LOG = "jspwiki.rcsFileProvider.logCommand";
public static final String PROP_FULLLOG = "jspwiki.rcsFileProvider.fullLogCommand";
public static final String PROP_CHECKOUTVERSION = "jspwiki.rcsFileProvider.checkoutVersionCommand";
private static final String PATTERN_DATE = "^date:\\s*(.*)[\\+\\-;]\\d+;";
private static final String PATTERN_AUTHOR = "^\"?author=([\\w\\.\\s\\+\\.\\%]*)\"?";
private static final String PATTERN_REVISION = "^revision \\d+\\.(\\d+)";
private static final String RCSFMT_DATE = "yyyy-MM-dd HH:mm:ss";
public void initialize( Properties props )
throws NoRequiredPropertyException,
IOException
{
log.debug("Initing RCS");
super.initialize( props );
m_checkinCommand = props.getProperty( PROP_CHECKIN, m_checkinCommand );
m_checkoutCommand = props.getProperty( PROP_CHECKOUT, m_checkoutCommand );
m_logCommand = props.getProperty( PROP_LOG, m_logCommand );
m_fullLogCommand = props.getProperty( PROP_FULLLOG, m_fullLogCommand );
m_checkoutVersionCommand = props.getProperty( PROP_CHECKOUTVERSION, m_checkoutVersionCommand );
File rcsdir = new File( getPageDirectory(), "RCS" );
if( !rcsdir.exists() )
rcsdir.mkdirs();
log.debug("checkin="+m_checkinCommand);
log.debug("checkout="+m_checkoutCommand);
log.debug("log="+m_logCommand);
log.debug("fulllog="+m_fullLogCommand);
log.debug("checkoutversion="+m_checkoutVersionCommand);
}
// NB: This is a very slow method.
public WikiPage getPageInfo( String page, int version )
throws ProviderException
{
PatternMatcher matcher = new Perl5Matcher();
PatternCompiler compiler = new Perl5Compiler();
PatternMatcherInput input;
WikiPage info = super.getPageInfo( page, version );
try
{
String cmd = m_fullLogCommand;
cmd = TextUtil.replaceString( cmd, "%s", mangleName(page)+FILE_EXT );
Process process = Runtime.getRuntime().exec( cmd, null, new File(getPageDirectory()) );
// FIXME: Should this use encoding as well?
BufferedReader stdout = new BufferedReader( new InputStreamReader(process.getInputStream() ) );
String line;
Pattern headpattern = compiler.compile( PATTERN_REVISION );
// This complicated pattern is required, since on Linux RCS adds
// quotation marks, but on Windows, it does not.
Pattern userpattern = compiler.compile( PATTERN_AUTHOR );
Pattern datepattern = compiler.compile( PATTERN_DATE );
SimpleDateFormat rcsdatefmt = new SimpleDateFormat( RCSFMT_DATE );
boolean found = false;
while( (line = stdout.readLine()) != null )
{
if( matcher.contains( line, headpattern ) )
{
MatchResult result = matcher.getMatch();
int vernum = Integer.parseInt( result.group(1) );
if( vernum == version || version == WikiPageProvider.LATEST_VERSION )
{
info.setVersion( vernum );
found = true;
}
}
else if( matcher.contains( line, datepattern ) && found )
{
MatchResult result = matcher.getMatch();
Date d = rcsdatefmt.parse( result.group(1) );
if( d != null )
{
info.setLastModified( d );
}
else
{
log.info("WikiPage "+info.getName()+
" has null modification date for version "+
version);
}
}
else if( matcher.contains( line, userpattern ) && found )
{
MatchResult result = matcher.getMatch();
info.setAuthor( TextUtil.urlDecodeUTF8(result.group(1)) );
}
else if( found && line.startsWith("
{
// End of line sign from RCS
break;
}
}
// Especially with certain versions of RCS on Windows,
// process.waitFor() hangs unless you read all of the
// standard output. So we make sure it's all emptied.
while( (line = stdout.readLine()) != null )
{
}
process.waitFor();
}
catch( Exception e )
{
// This also occurs when 'info' was null.
log.warn("Failed to read RCS info",e);
}
return info;
}
public String getPageText( String page, int version )
throws ProviderException
{
String result = null;
// Let parent handle latest fetches, since the FileSystemProvider
// can do the file reading just as well.
if( version == WikiPageProvider.LATEST_VERSION )
return super.getPageText( page, version );
log.debug("Fetching specific version "+version+" of page "+page);
try
{
String cmd = m_checkoutVersionCommand;
cmd = TextUtil.replaceString( cmd, "%s", mangleName(page)+FILE_EXT );
cmd = TextUtil.replaceString( cmd, "%v", Integer.toString(version ) );
log.debug("Command = '"+cmd+"'");
Process process = Runtime.getRuntime().exec( cmd, null, new File(getPageDirectory()) );
result = FileUtil.readContents( process.getInputStream(),
m_encoding );
process.waitFor();
log.debug("Done, returned = "+process.exitValue());
}
catch( Exception e )
{
log.error("RCS checkout failed",e);
}
return result;
}
/**
* Puts the page into RCS and makes sure there is a fresh copy in
* the directory as well.
*/
public void putPageText( WikiPage page, String text )
{
String pagename = page.getName();
// Writes it in the dir.
super.putPageText( page, text );
log.debug( "Checking in text..." );
try
{
String cmd = m_checkinCommand;
String author = page.getAuthor();
if( author == null ) author = "unknown";
cmd = TextUtil.replaceString( cmd, "%s", mangleName(pagename)+FILE_EXT );
cmd = TextUtil.replaceString( cmd, "%u", TextUtil.urlEncodeUTF8(author) );
log.debug("Command = '"+cmd+"'");
Process process = Runtime.getRuntime().exec( cmd, null, new File(getPageDirectory()) );
process.waitFor();
log.debug("Done, returned = "+process.exitValue());
}
catch( Exception e )
{
log.error("RCS checkin failed",e);
}
}
// FIXME: Put the rcs date formats into properties as well.
public Collection getVersionHistory( String page )
{
PatternMatcher matcher = new Perl5Matcher();
PatternCompiler compiler = new Perl5Compiler();
PatternMatcherInput input;
log.debug("Getting RCS version history");
ArrayList list = new ArrayList();
SimpleDateFormat rcsdatefmt = new SimpleDateFormat( RCSFMT_DATE );
try
{
Pattern revpattern = compiler.compile( PATTERN_REVISION );
Pattern datepattern = compiler.compile( PATTERN_DATE );
// This complicated pattern is required, since on Linux RCS adds
// quotation marks, but on Windows, it does not.
Pattern userpattern = compiler.compile( PATTERN_AUTHOR );
String cmd = TextUtil.replaceString( m_fullLogCommand,
"%s",
mangleName(page)+FILE_EXT );
Process process = Runtime.getRuntime().exec( cmd, null, new File(getPageDirectory()) );
// FIXME: Should this use encoding as well?
BufferedReader stdout = new BufferedReader( new InputStreamReader(process.getInputStream()) );
String line;
WikiPage info = null;
while( (line = stdout.readLine()) != null )
{
if( matcher.contains( line, revpattern ) )
{
info = new WikiPage( page );
MatchResult result = matcher.getMatch();
int vernum = Integer.parseInt( result.group(1) );
info.setVersion( vernum );
list.add( info );
}
if( matcher.contains( line, datepattern ) )
{
MatchResult result = matcher.getMatch();
Date d = rcsdatefmt.parse( result.group(1) );
info.setLastModified( d );
}
if( matcher.contains( line, userpattern ) )
{
MatchResult result = matcher.getMatch();
info.setAuthor( TextUtil.urlDecodeUTF8(result.group(1)) );
}
}
process.waitFor();
}
catch( Exception e )
{
log.error( "RCS log failed", e );
}
return list;
}
} |
package com.jbion.riseoflords;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import com.jbion.riseoflords.config.Account;
import com.jbion.riseoflords.config.AttackParams;
import com.jbion.riseoflords.config.Config;
import com.jbion.riseoflords.config.PlayerFilter;
import com.jbion.riseoflords.model.AccountState;
import com.jbion.riseoflords.model.Player;
import com.jbion.riseoflords.network.RoLAdapter;
import com.jbion.riseoflords.util.Format;
import com.jbion.riseoflords.util.Log;
import com.jbion.riseoflords.util.Sleeper;
import com.jbion.riseoflords.util.Sleeper.Speed;
public class Sequence {
private static final String TAG = Sequence.class.getSimpleName();
private static final Comparator<Player> richestFirst = Comparator.comparingInt(Player::getGold).reversed();
private final Log log = Log.get();
private final Sleeper fakeTime = new Sleeper(Speed.INHUMAN);
private final RoLAdapter rol;
private final Config config;
public Sequence(Config config) {
this.config = config;
this.rol = new RoLAdapter();
}
public AccountState getCurrentState() {
return rol.getCurrentState();
}
public void start() {
log.i(TAG, "Starting attack session...");
final Account account = config.getAccount();
login(account.getLogin(), account.getPassword());
attackRichest(config.getPlayerFilter(), config.getAttackParams());
fakeTime.changePageLong();
log.i(TAG, "");
logout();
log.i(TAG, "End of session.");
}
/**
* Logs in with the specified credentials, and wait for standard time.
*
* @param username
* the login to connect with
* @param password
* the password to connect with
*/
private void login(String username, String password) {
log.d(TAG, "Logging in with username ", username, "...");
final boolean success = rol.login(username, password);
if (success) {
log.i(TAG, "Logged in with username: ", username);
log.i(TAG, "");
log.i(TAG, "Faking redirection page delay... (this takes a few seconds)");
log.i(TAG, "");
} else {
throw new RuntimeException("Login failure.");
}
fakeTime.waitAfterLogin();
rol.homePage();
fakeTime.actionInPage();
}
/**
* Logs out.
*/
private void logout() {
log.d(TAG, "Logging out...");
final boolean success = rol.logout();
if (success) {
log.i(TAG, "Logout successful");
} else {
log.e(TAG, "Logout failure");
}
}
/**
* Attacks the richest players matching the filter.
*
* @param filter
* the {@link PlayerFilter} to use to choose players
* @param params
* the {@link AttackParams} to use for attacks/actions sequencing
* @return the total gold stolen
*/
private int attackRichest(PlayerFilter filter, AttackParams params) {
final int maxTurns = Math.min(rol.getCurrentState().turns, params.getMaxTurns());
if (maxTurns <= 0) {
log.i(TAG, "No more turns to spend, aborting attack.");
return 0;
}
log.i(TAG,
String.format("Starting attack on players ranked %d to %d richer than %s gold (%d attacks max)",
filter.getMinRank(), filter.getMaxRank(), Format.gold(filter.getGoldThreshold()), maxTurns));
log.i(TAG, "");
log.i(TAG, "Searching players matching the config filter...");
log.indent();
final List<Player> matchingPlayers = new ArrayList<>();
int startRank = filter.getMinRank();
while (startRank < filter.getMaxRank()) {
log.d(TAG, "Reading page of players ranked ", startRank, " to ", startRank + 98, "...");
final List<Player> filteredPage = rol.listPlayers(startRank).stream() // stream players
.filter(p -> p.getGold() >= filter.getGoldThreshold()) // above gold threshold
.filter(p -> p.getRank() <= filter.getMaxRank()) // below max rank
.sorted(richestFirst) // richest first
.limit(params.getMaxTurns()) // limit to max turns
.limit(rol.getCurrentState().turns) // limit to available turns
.collect(Collectors.toList());
int pageMaxRank = Math.min(startRank + 98, filter.getMaxRank());
int nbMatchingPlayers = matchingPlayers.size();
matchingPlayers.addAll(filteredPage);
System.out.print("\r");
System.out.print(String.format(
" %s matching player%s found so far, ranked %d to %d (%d/%d players scanned) ",
nbMatchingPlayers > 0 ? nbMatchingPlayers : "No", nbMatchingPlayers > 1 ? "s" : "",
filter.getMinRank(), pageMaxRank, pageMaxRank - filter.getMinRank() + 1,
filter.getNbPlayersToScan()));
fakeTime.readPage();
startRank += 99;
}
System.out.println();
System.out.println();
log.deindent(1);
final int nbMatchingPlayers = matchingPlayers.size();
if (nbMatchingPlayers > maxTurns) {
log.i(TAG, String.format(
"only %d out of the %d matching players can be attacked, filtering only the richest of them...",
maxTurns, matchingPlayers.size()));
// too many players, select only the richest
final List<Player> playersToAttack = matchingPlayers.stream() // stream players
.sorted(richestFirst) // richest first
.limit(params.getMaxTurns()) // limit to max turns
.limit(rol.getCurrentState().turns) // limit to available turns
.collect(Collectors.toList());
return attackAll(playersToAttack, params);
} else {
return attackAll(matchingPlayers, params);
}
}
/**
* Attacks all the specified players, following the given parameters.
*
* @param playersToAttack
* the filtered list of players to attack. They must verify the thresholds specified
* by the given {@link PlayerFilter}.
* @param params
* the parameters to follow. In particular the storing and repair frequencies are
* used.
* @return the total gold stolen
*/
private int attackAll(List<Player> playersToAttack, AttackParams params) {
log.i(TAG, playersToAttack.size(), " players to attack");
if (rol.getCurrentState().turns == 0) {
log.e(TAG, "No turns available, impossible to attack.");
return 0;
} else if (rol.getCurrentState().turns < playersToAttack.size()) {
log.e(TAG, "Not enough turns to attack this many players, attack aborted.");
return 0;
}
int totalGoldStolen = 0;
int nbConsideredPlayers = 0;
int nbAttackedPlayers = 0;
for (final Player player : playersToAttack) {
nbConsideredPlayers++;
// attack player
final int goldStolen = attack(player);
if (goldStolen < 0) {
// error, player not attacked
continue;
}
totalGoldStolen += goldStolen;
nbAttackedPlayers++;
final boolean isLastPlayer = nbConsideredPlayers == playersToAttack.size();
// repair weapons as specified
if (nbAttackedPlayers % params.getRepairPeriod() == 0 || isLastPlayer) {
fakeTime.changePage();
repairWeapons();
}
// store gold as specified
if (nbAttackedPlayers % params.getStoragePeriod() == 0 || isLastPlayer) {
fakeTime.changePage();
storeGoldIntoChest();
fakeTime.pauseWhenSafe();
} else {
fakeTime.changePageLong();
}
}
log.i(TAG, Format.gold(totalGoldStolen), " total gold stolen from ", nbAttackedPlayers, " players.");
log.i(TAG, "The chest now contains ", Format.gold(rol.getCurrentState().chestGold), " gold.");
return totalGoldStolen;
}
/**
* Attacks the specified player.
*
* @param player
* the player to attack
* @return the gold stolen from that player
*/
private int attack(Player player) {
log.d(TAG, "Attacking player ", player.getName(), "...");
log.indent();
log.v(TAG, "Displaying player page...");
final int playerGold = rol.displayPlayer(player.getName());
log.indent();
if (playerGold == RoLAdapter.ERROR_REQUEST) {
log.e(TAG, "Something's wrong: request failed");
log.deindent(2);
return -1;
} else if (playerGold != player.getGold()) {
log.w(TAG, "Something's wrong: the player does not have the expected gold");
log.deindent(2);
return -1;
}
log.deindent(1);
fakeTime.actionInPage();
log.v(TAG, "Attacking...");
final int goldStolen = rol.attack(player.getName());
log.deindent(1);
if (goldStolen > 0) {
log.i(TAG, "Victory! ", Format.gold(goldStolen), " gold stolen from player ", player.getName(),
", current gold: ", Format.gold(rol.getCurrentState().gold));
} else if (goldStolen == RoLAdapter.ERROR_STORM_ACTIVE) {
log.e(TAG, "Cannot attack: a storm is raging upon your kingdom!");
} else if (goldStolen == RoLAdapter.ERROR_REQUEST) {
log.e(TAG, "Attack request failed, something went wrong");
} else {
log.w(TAG, "Defeat! Ach, player ", player.getName(), " was too sronk! Current gold: ",
rol.getCurrentState().gold);
}
return goldStolen;
}
private int storeGoldIntoChest() {
log.v(TAG, "Storing gold into the chest...");
log.indent();
log.v(TAG, "Displaying chest page...");
final int amount = rol.displayChestPage();
log.v(TAG, Format.gold(amount) + " gold to store");
fakeTime.actionInPage();
log.v(TAG, "Storing everything...");
log.indent();
final boolean success = rol.storeInChest(amount);
if (success) {
log.v(TAG, "The gold is safe!");
} else {
log.v(TAG, "Something went wrong!");
}
log.deindent(2);
log.i(TAG, Format.gold(amount), " gold stored in chest, total: " + Format.gold(rol.getCurrentState().chestGold));
return amount;
}
private void repairWeapons() {
log.v(TAG, "Repairing weapons...");
log.indent();
log.v(TAG, "Displaying weapons page...");
final int wornness = rol.displayWeaponsPage();
log.v(TAG, "Weapons worn at ", wornness, "%");
fakeTime.actionInPage();
log.v(TAG, "Repair request...");
final boolean success = rol.repairWeapons();
log.deindent(1);
if (!success) {
log.e(TAG, "Couldn't repair weapons, is there enough gold?");
} else {
log.i(TAG, "Weapons repaired");
}
}
} |
package org.hibernate.validator.internal.metadata.aggregated;
import java.lang.annotation.ElementType;
import java.lang.reflect.Type;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import javax.validation.ElementKind;
import javax.validation.metadata.ReturnValueDescriptor;
import org.hibernate.validator.internal.engine.path.PathImpl;
import org.hibernate.validator.internal.metadata.core.MetaConstraint;
import org.hibernate.validator.internal.metadata.descriptor.ReturnValueDescriptorImpl;
import org.hibernate.validator.internal.metadata.facets.Cascadable;
import org.hibernate.validator.internal.metadata.facets.Validatable;
import org.hibernate.validator.internal.util.stereotypes.Immutable;
/**
* Represents the constraint related meta data of the return value of a method
* or constructor.
*
* @author Gunnar Morling
*/
public class ReturnValueMetaData extends AbstractConstraintMetaData
implements Validatable, Cascadable {
private static final String RETURN_VALUE_NODE_NAME = null;
@Immutable
private final List<Cascadable> cascadables;
private final CascadingMetaData cascadingMetaData;
public ReturnValueMetaData(Type type,
Set<MetaConstraint<?>> constraints,
Set<MetaConstraint<?>> containerElementsConstraints,
CascadingMetaData cascadingMetaData) {
super(
RETURN_VALUE_NODE_NAME,
type,
constraints,
containerElementsConstraints,
cascadingMetaData.isMarkedForCascadingOnElementOrContainerElements(),
!constraints.isEmpty() || containerElementsConstraints.isEmpty() || cascadingMetaData.isMarkedForCascadingOnElementOrContainerElements()
);
this.cascadables = isCascading() ? Collections.singletonList( this ) : Collections.emptyList();
this.cascadingMetaData = cascadingMetaData;
this.cascadingMetaData.validateGroupConversions( this.toString() );
}
@Override
public Iterable<Cascadable> getCascadables() {
return cascadables;
}
@Override
public ElementType getElementType() {
return ElementType.METHOD;
}
@Override
public ReturnValueDescriptor asDescriptor(boolean defaultGroupSequenceRedefined, List<Class<?>> defaultGroupSequence) {
return new ReturnValueDescriptorImpl(
getType(),
asDescriptors( getDirectConstraints() ),
asContainerElementTypeDescriptors( getContainerElementsConstraints(), cascadingMetaData, defaultGroupSequenceRedefined, defaultGroupSequence ),
cascadingMetaData.isCascading(),
defaultGroupSequenceRedefined,
defaultGroupSequence,
cascadingMetaData.getGroupConversionDescriptors()
);
}
@Override
public Object getValue(Object parent) {
return parent;
}
@Override
public Type getCascadableType() {
return getType();
}
@Override
public void appendTo(PathImpl path) {
path.addReturnValueNode();
}
@Override
public CascadingMetaData getCascadingMetaData() {
return cascadingMetaData;
}
@Override
public ElementKind getKind() {
return ElementKind.RETURN_VALUE;
}
} |
package org.opencms.ui.components;
import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_CACHE;
import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_COPYRIGHT;
import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_DATE_CREATED;
import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_DATE_EXPIRED;
import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_DATE_MODIFIED;
import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_DATE_RELEASED;
import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_INSIDE_PROJECT;
import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_IS_FOLDER;
import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_NAVIGATION_TEXT;
import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_PERMISSIONS;
import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_PROJECT;
import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_RELEASED_NOT_EXPIRED;
import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_RESOURCE_NAME;
import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_RESOURCE_TYPE;
import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_SIZE;
import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_STATE;
import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_STATE_NAME;
import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_TITLE;
import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_TYPE_ICON;
import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_USER_CREATED;
import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_USER_LOCKED;
import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_USER_MODIFIED;
import org.opencms.db.CmsResourceState;
import org.opencms.file.CmsObject;
import org.opencms.file.CmsResource;
import org.opencms.file.CmsResourceFilter;
import org.opencms.file.CmsVfsResourceNotFoundException;
import org.opencms.file.types.CmsResourceTypePlain;
import org.opencms.file.types.CmsResourceTypeXmlContainerPage;
import org.opencms.file.types.CmsResourceTypeXmlContent;
import org.opencms.jsp.CmsJspTagEnableAde;
import org.opencms.main.CmsException;
import org.opencms.main.CmsLog;
import org.opencms.main.OpenCms;
import org.opencms.ui.A_CmsUI;
import org.opencms.ui.CmsVaadinUtils;
import org.opencms.ui.I_CmsDialogContext;
import org.opencms.ui.actions.CmsEditDialogAction;
import org.opencms.ui.apps.CmsFileExplorerSettings;
import org.opencms.ui.apps.I_CmsContextProvider;
import org.opencms.ui.contextmenu.CmsContextMenu;
import org.opencms.ui.contextmenu.I_CmsContextMenuBuilder;
import org.opencms.util.CmsStringUtil;
import org.opencms.util.CmsUUID;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import com.google.common.collect.Lists;
import com.vaadin.data.Container;
import com.vaadin.data.Item;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.data.Property.ValueChangeListener;
import com.vaadin.data.util.DefaultItemSorter;
import com.vaadin.data.util.filter.Or;
import com.vaadin.data.util.filter.SimpleStringFilter;
import com.vaadin.event.FieldEvents.BlurEvent;
import com.vaadin.event.FieldEvents.BlurListener;
import com.vaadin.event.ItemClickEvent;
import com.vaadin.event.ItemClickEvent.ItemClickListener;
import com.vaadin.event.ShortcutAction.KeyCode;
import com.vaadin.event.ShortcutListener;
import com.vaadin.shared.MouseEventDetails.MouseButton;
import com.vaadin.ui.AbstractTextField.TextChangeEventMode;
import com.vaadin.ui.Component;
import com.vaadin.ui.DefaultFieldFactory;
import com.vaadin.ui.Field;
import com.vaadin.ui.Table;
import com.vaadin.ui.TextField;
import com.vaadin.ui.themes.ValoTheme;
/**
* Table for displaying resources.<p>
*/
public class CmsFileTable extends CmsResourceTable {
/**
* File edit handler.<p>
*/
public class FileEditHandler implements BlurListener {
/** The serial version id. */
private static final long serialVersionUID = -2286815522247807054L;
/**
* @see com.vaadin.event.FieldEvents.BlurListener#blur(com.vaadin.event.FieldEvents.BlurEvent)
*/
public void blur(BlurEvent event) {
stopEdit();
}
}
/**
* Field factory to enable inline editing of individual file properties.<p>
*/
public class FileFieldFactory extends DefaultFieldFactory {
/** The serial version id. */
private static final long serialVersionUID = 3079590603587933576L;
/**
* @see com.vaadin.ui.DefaultFieldFactory#createField(com.vaadin.data.Container, java.lang.Object, java.lang.Object, com.vaadin.ui.Component)
*/
@Override
public Field<?> createField(Container container, Object itemId, Object propertyId, Component uiContext) {
Field<?> result = null;
if (itemId.equals(getEditItemId()) && isEditProperty((CmsResourceTableProperty)propertyId)) {
result = super.createField(container, itemId, propertyId, uiContext);
result.addStyleName(OpenCmsTheme.INLINE_TEXTFIELD);
result.addValidator(m_editHandler);
if (result instanceof TextField) {
((TextField)result).setComponentError(null);
((TextField)result).addShortcutListener(new ShortcutListener("Cancel edit", KeyCode.ESCAPE, null) {
private static final long serialVersionUID = 1L;
@Override
public void handleAction(Object sender, Object target) {
cancelEdit();
}
});
((TextField)result).addShortcutListener(new ShortcutListener("Save", KeyCode.ENTER, null) {
private static final long serialVersionUID = 1L;
@Override
public void handleAction(Object sender, Object target) {
stopEdit();
}
});
((TextField)result).addBlurListener(m_fileEditHandler);
((TextField)result).setTextChangeEventMode(TextChangeEventMode.LAZY);
((TextField)result).addTextChangeListener(m_editHandler);
}
result.focus();
}
return result;
}
}
/**
* Extends the default sorting to differentiate between files and folder when sorting by name.<p>
*/
public static class FileSorter extends DefaultItemSorter {
/** The serial version id. */
private static final long serialVersionUID = 1L;
/**
* @see com.vaadin.data.util.DefaultItemSorter#compareProperty(java.lang.Object, boolean, com.vaadin.data.Item, com.vaadin.data.Item)
*/
@Override
protected int compareProperty(Object propertyId, boolean sortDirection, Item item1, Item item2) {
if (CmsResourceTableProperty.PROPERTY_RESOURCE_NAME.equals(propertyId)) {
Boolean isFolder1 = (Boolean)item1.getItemProperty(
CmsResourceTableProperty.PROPERTY_IS_FOLDER).getValue();
Boolean isFolder2 = (Boolean)item2.getItemProperty(
CmsResourceTableProperty.PROPERTY_IS_FOLDER).getValue();
if (!isFolder1.equals(isFolder2)) {
int result = isFolder1.booleanValue() ? -1 : 1;
if (!sortDirection) {
result = result * (-1);
}
return result;
}
}
return super.compareProperty(propertyId, sortDirection, item1, item2);
}
}
/**
* Handles folder selects in the file table.<p>
*/
public interface I_FolderSelectHandler {
/**
* Called when the folder name is left clicked.<p>
*
* @param folderId the selected folder id
*/
void onFolderSelect(CmsUUID folderId);
}
/** The logger instance for this class. */
static final Log LOG = CmsLog.getLog(CmsFileTable.class);
/** The serial version id. */
private static final long serialVersionUID = 5460048685141699277L;
/** The selected resources. */
protected List<CmsResource> m_currentResources = new ArrayList<CmsResource>();
/** The current file property edit handler. */
I_CmsFilePropertyEditHandler m_editHandler;
/** File edit event handler. */
FileEditHandler m_fileEditHandler = new FileEditHandler();
/** The context menu. */
CmsContextMenu m_menu;
/** The context menu builder. */
I_CmsContextMenuBuilder m_menuBuilder;
/** The edited item id. */
private CmsUUID m_editItemId;
/** The edited property id. */
private CmsResourceTableProperty m_editProperty;
/** The original edit value. */
private String m_originalEditValue;
/** The dialog context provider. */
private I_CmsContextProvider m_contextProvider;
/** The folder select handler. */
private I_FolderSelectHandler m_folderSelectHandler;
/**
* Default constructor.<p>
*
* @param contextProvider the dialog context provider
*/
public CmsFileTable(I_CmsContextProvider contextProvider) {
super();
m_contextProvider = contextProvider;
m_container.setItemSorter(new FileSorter());
m_fileTable.addStyleName(ValoTheme.TABLE_BORDERLESS);
m_fileTable.addStyleName(OpenCmsTheme.SIMPLE_DRAG);
m_fileTable.setSizeFull();
m_fileTable.setColumnCollapsingAllowed(true);
m_fileTable.setSelectable(true);
m_fileTable.setMultiSelect(true);
m_fileTable.setTableFieldFactory(new FileFieldFactory());
new ColumnBuilder() {
{
column(PROPERTY_TYPE_ICON);
column(PROPERTY_PROJECT, COLLAPSED);
column(PROPERTY_RESOURCE_NAME);
column(PROPERTY_TITLE);
column(PROPERTY_NAVIGATION_TEXT, COLLAPSED);
column(PROPERTY_COPYRIGHT, COLLAPSED);
column(PROPERTY_CACHE, COLLAPSED);
column(PROPERTY_RESOURCE_TYPE);
column(PROPERTY_SIZE);
column(PROPERTY_PERMISSIONS, COLLAPSED);
column(PROPERTY_DATE_MODIFIED);
column(PROPERTY_USER_MODIFIED, COLLAPSED);
column(PROPERTY_DATE_CREATED, COLLAPSED);
column(PROPERTY_USER_CREATED, COLLAPSED);
column(PROPERTY_DATE_RELEASED);
column(PROPERTY_DATE_EXPIRED);
column(PROPERTY_STATE_NAME);
column(PROPERTY_USER_LOCKED);
column(PROPERTY_IS_FOLDER, INVISIBLE);
column(PROPERTY_STATE, INVISIBLE);
column(PROPERTY_INSIDE_PROJECT, INVISIBLE);
column(PROPERTY_RELEASED_NOT_EXPIRED, INVISIBLE);
}
}.buildColumns();
m_fileTable.setSortContainerPropertyId(CmsResourceTableProperty.PROPERTY_RESOURCE_NAME);
m_menu = new CmsContextMenu();
m_fileTable.addValueChangeListener(new ValueChangeListener() {
private static final long serialVersionUID = 1L;
public void valueChange(ValueChangeEvent event) {
@SuppressWarnings("unchecked")
Set<CmsUUID> selectedIds = (Set<CmsUUID>)event.getProperty().getValue();
List<CmsResource> selectedResources = new ArrayList<CmsResource>();
for (CmsUUID id : selectedIds) {
try {
CmsResource resource = A_CmsUI.getCmsObject().readResource(id, CmsResourceFilter.ALL);
selectedResources.add(resource);
} catch (CmsException e) {
LOG.error(e.getLocalizedMessage(), e);
}
}
m_currentResources = selectedResources;
if (!selectedIds.isEmpty() && (m_menuBuilder != null)) {
m_menu.removeAllItems();
m_menuBuilder.buildContextMenu(getContextProvider().getDialogContext(), m_menu);
}
}
});
m_fileTable.addItemClickListener(new ItemClickListener() {
private static final long serialVersionUID = 1L;
public void itemClick(ItemClickEvent event) {
handleFileItemClick(event);
}
});
m_fileTable.setCellStyleGenerator(new Table.CellStyleGenerator() {
private static final long serialVersionUID = 1L;
public String getStyle(Table source, Object itemId, Object propertyId) {
return getStateStyle(m_container.getItem(itemId))
+ (CmsResourceTableProperty.PROPERTY_RESOURCE_NAME == propertyId
? " " + OpenCmsTheme.HOVER_COLUMN
: "");
}
});
m_menu.setAsTableContextMenu(m_fileTable);
}
/**
* Returns the resource state specific style name.<p>
*
* @param resourceItem the resource item
*
* @return the style name
*/
public static String getStateStyle(Item resourceItem) {
String result = "";
if (resourceItem != null) {
if ((resourceItem.getItemProperty(PROPERTY_INSIDE_PROJECT) == null)
|| ((Boolean)resourceItem.getItemProperty(PROPERTY_INSIDE_PROJECT).getValue()).booleanValue()) {
CmsResourceState state = (CmsResourceState)resourceItem.getItemProperty(
CmsResourceTableProperty.PROPERTY_STATE).getValue();
result = getStateStyle(state);
} else {
result = OpenCmsTheme.PROJECT_OTHER;
}
if ((resourceItem.getItemProperty(PROPERTY_RELEASED_NOT_EXPIRED) != null)
&& !((Boolean)resourceItem.getItemProperty(PROPERTY_RELEASED_NOT_EXPIRED).getValue()).booleanValue()) {
result += " " + OpenCmsTheme.EXPIRED;
}
if ((resourceItem.getItemProperty(CmsResourceTableProperty.PROPERTY_DISABLED) != null)
&& ((Boolean)resourceItem.getItemProperty(
CmsResourceTableProperty.PROPERTY_DISABLED).getValue()).booleanValue()) {
result += " " + OpenCmsTheme.DISABLED;
}
}
return result;
}
/**
* Filters the displayed resources.<p>
* Only resources where either the resource name, the title or the nav-text contains the given substring are shown.<p>
*
* @param search the search term
*/
public void filterTable(String search) {
m_container.removeAllContainerFilters();
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(search)) {
m_container.addContainerFilter(
new Or(
new SimpleStringFilter(CmsResourceTableProperty.PROPERTY_RESOURCE_NAME, search, true, false),
new SimpleStringFilter(CmsResourceTableProperty.PROPERTY_NAVIGATION_TEXT, search, true, false),
new SimpleStringFilter(CmsResourceTableProperty.PROPERTY_TITLE, search, true, false)));
}
}
/**
* Returns the index of the first visible item.<p>
*
* @return the first visible item
*/
public int getFirstVisibleItemIndex() {
return m_fileTable.getCurrentPageFirstItemIndex();
}
/**
* Gets the selected structure ids.<p>
*
* @return the set of selected structure ids
*/
@SuppressWarnings("unchecked")
public Set<CmsUUID> getSelectedIds() {
return (Set<CmsUUID>)m_fileTable.getValue();
}
/**
* Gets the list of selected resources.<p>
*
* @return the list of selected resources
*/
public List<CmsResource> getSelectedResources() {
return m_currentResources;
}
/**
* Returns the current table state.<p>
*
* @return the table state
*/
public CmsFileExplorerSettings getTableSettings() {
CmsFileExplorerSettings fileTableState = new CmsFileExplorerSettings();
fileTableState.setSortAscending(m_fileTable.isSortAscending());
fileTableState.setSortColumnId((CmsResourceTableProperty)m_fileTable.getSortContainerPropertyId());
List<CmsResourceTableProperty> collapsedCollumns = new ArrayList<CmsResourceTableProperty>();
Object[] visibleCols = m_fileTable.getVisibleColumns();
for (int i = 0; i < visibleCols.length; i++) {
if (m_fileTable.isColumnCollapsed(visibleCols[i])) {
collapsedCollumns.add((CmsResourceTableProperty)visibleCols[i]);
}
}
fileTableState.setCollapsedColumns(collapsedCollumns);
return fileTableState;
}
/**
* Handles the item selection.<p>
*
* @param itemId the selected item id
*/
public void handleSelection(CmsUUID itemId) {
Set<CmsUUID> selection = getSelectedIds();
if (selection == null) {
m_fileTable.select(itemId);
} else if (!selection.contains(itemId)) {
m_fileTable.setValue(null);
m_fileTable.select(itemId);
}
}
/**
* Returns if a file property is being edited.<p>
* @return <code>true</code> if a file property is being edited
*/
public boolean isEditing() {
return m_editItemId != null;
}
/**
* Returns if the given property is being edited.<p>
*
* @param propertyId the property id
*
* @return <code>true</code> if the given property is being edited
*/
public boolean isEditProperty(CmsResourceTableProperty propertyId) {
return (m_editProperty != null) && m_editProperty.equals(propertyId);
}
/**
* Opens the context menu.<p>
*
* @param event the click event
*/
public void openContextMenu(ItemClickEvent event) {
m_menu.openForTable(event, m_fileTable);
}
/**
* Sets the first visible item index.<p>
*
* @param i the item index
*/
public void setFirstVisibleItemIndex(int i) {
m_fileTable.setCurrentPageFirstItemIndex(i);
}
/**
* Sets the folder select handler.<p>
*
* @param folderSelectHandler the folder select handler
*/
public void setFolderSelectHandler(I_FolderSelectHandler folderSelectHandler) {
m_folderSelectHandler = folderSelectHandler;
}
/**
* Sets the menu builder.<p>
*
* @param builder the menu builder
*/
public void setMenuBuilder(I_CmsContextMenuBuilder builder) {
m_menuBuilder = builder;
}
/**
* Sets the table state.<p>
*
* @param state the table state
*/
public void setTableState(CmsFileExplorerSettings state) {
if (state != null) {
m_fileTable.setSortContainerPropertyId(state.getSortColumnId());
m_fileTable.setSortAscending(state.isSortAscending());
Object[] visibleCols = m_fileTable.getVisibleColumns();
for (int i = 0; i < visibleCols.length; i++) {
m_fileTable.setColumnCollapsed(visibleCols[i], state.getCollapsedColumns().contains(visibleCols[i]));
}
}
}
/**
* Starts inline editing of the given file property.<p>
*
* @param itemId the item resource structure id
* @param propertyId the property to edit
* @param editHandler the edit handler
*/
public void startEdit(
CmsUUID itemId,
CmsResourceTableProperty propertyId,
I_CmsFilePropertyEditHandler editHandler) {
m_editItemId = itemId;
m_editProperty = propertyId;
m_originalEditValue = (String)m_container.getItem(m_editItemId).getItemProperty(m_editProperty).getValue();
m_editHandler = editHandler;
m_fileTable.setEditable(true);
}
/**
* Stops the current edit process to save the changed property value.<p>
*/
public void stopEdit() {
if (m_editHandler != null) {
String value = (String)m_container.getItem(m_editItemId).getItemProperty(m_editProperty).getValue();
if (!value.equals(m_originalEditValue)) {
m_editHandler.validate(value);
m_editHandler.save(value);
} else {
// call cancel to ensure unlock
m_editHandler.cancel();
}
}
clearEdit();
}
/**
* Updates all items with ids from the given list.<p>
*
* @param id the resource structure id to update
* @param remove true if the item should be removed only
*/
public void update(CmsUUID id, boolean remove) {
updateItem(id, remove);
}
/**
* Updates the column widths.<p>
*
* The reason this is needed is that the Vaadin table does not support minimum widths for columns,
* so expanding columns get squished when most of the horizontal space is used by other columns.
* So we try to determine whether the expanded columns would have enough space, and if not, give them a
* fixed width.
*
* @param estimatedSpace the estimated horizontal space available for the table.
*/
public void updateColumnWidths(int estimatedSpace) {
Object[] cols = m_fileTable.getVisibleColumns();
List<CmsResourceTableProperty> expandCols = Lists.newArrayList();
int nonExpandWidth = 0;
int totalExpandMinWidth = 0;
for (Object colObj : cols) {
if (m_fileTable.isColumnCollapsed(colObj)) {
continue;
}
CmsResourceTableProperty prop = (CmsResourceTableProperty)colObj;
if (0 < m_fileTable.getColumnExpandRatio(prop)) {
expandCols.add(prop);
totalExpandMinWidth += getAlternativeWidthForExpandingColumns(prop);
} else {
nonExpandWidth += prop.getColumnWidth();
}
}
if (estimatedSpace < (totalExpandMinWidth + nonExpandWidth)) {
for (CmsResourceTableProperty expandCol : expandCols) {
m_fileTable.setColumnWidth(expandCol, getAlternativeWidthForExpandingColumns(expandCol));
}
}
}
/**
* Updates the file table sorting.<p>
*/
public void updateSorting() {
m_fileTable.sort();
}
/**
* Sets the dialog context provider.<p>
*
* @param provider the dialog context provider
*/
protected void setContextProvider(I_CmsContextProvider provider) {
m_contextProvider = provider;
}
/**
* Cancels the current edit process.<p>
*/
void cancelEdit() {
if (m_editHandler != null) {
m_editHandler.cancel();
}
clearEdit();
}
/**
* Returns the dialog context provider.<p>
*
* @return the dialog context provider
*/
I_CmsContextProvider getContextProvider() {
return m_contextProvider;
}
/**
* Returns the edit item id.<p>
*
* @return the edit item id
*/
CmsUUID getEditItemId() {
return m_editItemId;
}
/**
* Returns the edit property id.<p>
*
* @return the edit property id
*/
CmsResourceTableProperty getEditProperty() {
return m_editProperty;
}
/**
* Handles the file table item click.<p>
*
* @param event the click event
*/
void handleFileItemClick(ItemClickEvent event) {
if (isEditing()) {
stopEdit();
} else if (!event.isCtrlKey() && !event.isShiftKey()) {
CmsUUID itemId = (CmsUUID)event.getItemId();
boolean openedFolder = false;
// don't interfere with multi-selection using control key
if (event.getButton().equals(MouseButton.RIGHT)) {
handleSelection(itemId);
openContextMenu(event);
} else {
if ((event.getPropertyId() == null)
|| CmsResourceTableProperty.PROPERTY_TYPE_ICON.equals(event.getPropertyId())) {
openContextMenu(event);
} else if (CmsResourceTableProperty.PROPERTY_RESOURCE_NAME.equals(event.getPropertyId())) {
Boolean isFolder = (Boolean)event.getItem().getItemProperty(
CmsResourceTableProperty.PROPERTY_IS_FOLDER).getValue();
if ((isFolder != null) && isFolder.booleanValue()) {
if (m_folderSelectHandler != null) {
m_folderSelectHandler.onFolderSelect(itemId);
}
openedFolder = true;
} else {
try {
CmsObject cms = A_CmsUI.getCmsObject();
CmsResource res = cms.readResource(itemId, CmsResourceFilter.IGNORE_EXPIRATION);
if (((CmsResourceTypePlain.getStaticTypeId() == res.getTypeId())
|| (CmsResourceTypeXmlContent.isXmlContent(res)
&& !CmsResourceTypeXmlContainerPage.isContainerPage(res)))
&& !res.getName().endsWith(".html")
&& !res.getName().endsWith(".htm")) {
m_currentResources = Collections.singletonList(res);
CmsEditDialogAction action = new CmsEditDialogAction();
I_CmsDialogContext context = m_contextProvider.getDialogContext();
if (action.getVisibility(context).isActive()) {
action.executeAction(context);
return;
}
}
String link = OpenCms.getLinkManager().substituteLink(cms, res);
HttpServletRequest req = CmsVaadinUtils.getRequest();
CmsJspTagEnableAde.removeDirectEditFlagFromSession(req.getSession());
if (cms.getRequestContext().getCurrentProject().isOnlineProject()) {
A_CmsUI.get().openPageOrWarn(link, "_blank");
} else {
A_CmsUI.get().getPage().setLocation(link);
}
return;
} catch (CmsVfsResourceNotFoundException e) {
LOG.info(e.getLocalizedMessage(), e);
} catch (CmsException e) {
LOG.error(e.getLocalizedMessage(), e);
}
}
}
}
// update the item on click to show any available changes
if (!openedFolder) {
update(itemId, false);
}
}
}
/**
* Clears the current edit process.<p>
*/
private void clearEdit() {
m_fileTable.setEditable(false);
if (m_editItemId != null) {
updateItem(m_editItemId, false);
}
m_editItemId = null;
m_editProperty = null;
m_editHandler = null;
updateSorting();
}
/**
* Gets alternative width for expanding table columns which is used when there is not enough space for
* all visible columns.<p>
*
* @param prop the table property
* @return the alternative column width
*/
private int getAlternativeWidthForExpandingColumns(CmsResourceTableProperty prop) {
if (prop.getId().equals(CmsResourceTableProperty.PROPERTY_RESOURCE_NAME.getId())) {
return 200;
}
if (prop.getId().equals(CmsResourceTableProperty.PROPERTY_TITLE.getId())) {
return 300;
}
if (prop.getId().equals(CmsResourceTableProperty.PROPERTY_NAVIGATION_TEXT.getId())) {
return 200;
}
return 200;
}
/**
* Updates the given item in the file table.<p>
*
* @param itemId the item id
* @param remove true if the item should be removed only
*/
private void updateItem(CmsUUID itemId, boolean remove) {
if (remove) {
m_container.removeItem(itemId);
return;
}
CmsObject cms = A_CmsUI.getCmsObject();
try {
CmsResource resource = cms.readResource(itemId, CmsResourceFilter.ALL);
fillItem(cms, resource, OpenCms.getWorkplaceManager().getWorkplaceLocale(cms));
} catch (CmsVfsResourceNotFoundException e) {
m_container.removeItem(itemId);
LOG.debug("Failed to update file table item, removing it from view.", e);
} catch (CmsException e) {
LOG.error(e.getLocalizedMessage(), e);
}
}
} |
package me.legrange.swap;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.logging.Level;
import java.util.logging.Logger;
public final class SerialModem implements SwapModem {
public SerialModem(String port, int baud) {
this.port = port;
this.baud = baud;
}
@Override
public void open() throws SwapException {
com = ComPort.open(port, baud);
running = true;
reader = new Reader();
reader.setDaemon(true);
reader.setName(String.format("%s Reader Thread", getClass().getSimpleName()));
reader.start();
if (setup != null) {
setSetup(setup);
}
}
@Override
public void close() throws SerialException {
running = false;
com.close();
}
@Override
public boolean isOpen() {
return running;
}
@Override
public synchronized void send(SwapMessage msg) throws SerialException {
send(msg.getText() + "\r");
fireEvent(msg, ReceiveTask.Direction.OUT);
}
@Override
public void addListener(MessageListener l) {
synchronized (listeners) {
listeners.add(l);
}
}
@Override
public void removeListener(MessageListener l) {
synchronized (listeners) {
listeners.remove(l);
}
}
@Override
public ModemSetup getSetup() throws SerialException {
if (setup == null) {
if (running) {
synchronized (this) {
enterCommandMode();
setup = new ModemSetup(readATasInt("ATCH?"), readATasHex("ATSW?"),
readATasHex("ATDA?"));
leaveCommandMode();
}
} else {
setup = new ModemSetup(0, 0, 0);
}
}
return setup;
}
@Override
public void setSetup(ModemSetup setup) throws SerialException {
synchronized (this) {
if (running) {
enterCommandMode();
sendATCommand(String.format("ATCH=%2d", setup.getChannel()));
sendATCommand(String.format("ATSW=%4h", setup.getNetworkID()));
sendATCommand(String.format("ATDA=%2d", setup.getDeviceAddress()));
leaveCommandMode();
}
this.setup = setup;
}
}
@Override
public Type getType() {
return Type.SERIAL;
}
/**
* Get the name of the serial port used by this modem.
*
* @return The name of the serial port
*/
public String getPort() {
return port;
}
/**
* Get the serial speed this modem connects at
*
* @return The serial speed
*/
public int getBaud() {
return baud;
}
private int readATasInt(String cmd) throws SerialException {
String res = readAT(cmd);
try {
return Integer.parseInt(res);
} catch (NumberFormatException e) {
throw new SerialException(String.format("Malformed integer response '%s' (%s) to %s commamnd", res, asHex(res), cmd), e);
}
}
private int readATasHex(String cmd) throws SerialException {
String res = readAT(cmd);
try {
return Integer.parseInt(res, 16);
} catch (NumberFormatException e) {
throw new SerialException(String.format("Malformed hex response '%s' (%s) to %s commamnd", res, asHex(res), cmd), e);
}
}
private String readAT(String cmd) throws SerialException {
String res = sendATCommand(cmd);
switch (res) {
case "ERROR":
throw new SerialException(String.format("Error received on %s command", cmd));
case "OK":
throw new SerialException(String.format("Unexpected OK in %s command", cmd));
default:
return res;
}
}
private void enterCommandMode() throws SerialException {
if (mode == Mode.COMMAND) {
return;
}
while (mode == Mode.INIT) {
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
logger.log(Level.SEVERE, null, ex);
}
}
int count = 3;
while (count > 0) {
if (tryCommandMode()) {
return;
}
count
}
throw new SerialException("Timed out waiting for command mode");
}
private boolean tryCommandMode() throws SerialException {
int count = 0;
send("+++");
while ((mode != Mode.COMMAND) && (count < 15)) {
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
if (!running) {
throw new SerialException("Modem stopped while entering command mode");
}
}
count++;
}
return (mode == Mode.COMMAND);
}
private void leaveCommandMode() throws SerialException {
if (mode == Mode.DATA) {
return;
}
send("ATO\r");
while (mode != Mode.DATA) {
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
}
}
}
private String sendATCommand(String cmd) throws SerialException {
send(cmd + "\r");
try {
return results.take();
} catch (InterruptedException ex) {
throw new SerialException("Interruped waiting for AT response");
}
}
private void send(String cmd) throws SerialException {
log("SEND: '" + cmd.replace("\r", "") + "'");
com.send(cmd);
}
private String read() throws SerialException {
String in = com.read();
log("RECV: '" + in + "'");
return in.trim();
}
private void log(String msg) {
logger.finest(msg);
}
/**
* send the received message to listeners
*/
private void fireEvent(SwapMessage msg, ReceiveTask.Direction dir) {
synchronized (listeners) {
for (MessageListener l : listeners) {
pool.submit(new ReceiveTask(l, msg, dir));
}
}
}
private enum Mode {
INIT, DATA, COMMAND
};
private ComPort com;
private Mode mode = Mode.DATA;
private ModemSetup setup;
private final BlockingQueue<String> results = new LinkedBlockingQueue<>();
private Reader reader;
private boolean running;
private final List<MessageListener> listeners = new CopyOnWriteArrayList<>();
private final int baud;
private final String port;
private final ExecutorService pool = Executors.newCachedThreadPool(new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r, "SWAP Listener Notification");
t.setDaemon(true);
return t;
}
});
private static final Logger logger = Logger.getLogger(SerialModem.class.getName());
/**
* The reader thread that receives data from the modem, unpacks it into
* messages and send the messages to the listeners.
*/
private class Reader extends Thread {
private static final String OK_COMMAND = "OK-Command mode";
private static final String OK_DATA = "OK-Data mode";
private static final String MODEM_READY = "Modem ready!";
private boolean isSwapMessage(String in) {
return !in.isEmpty() && (in.charAt(0) == '(') && in.length() >= 12;
}
@Override
public void run() {
while (running) {
try {
String in = read();
if (in.isEmpty()) {
continue; // discard empty lines
}
if (isSwapMessage(in)) {
mode = Mode.DATA;
fireEvent(new SerialMessage(in), ReceiveTask.Direction.IN);
} else {
switch (in) {
case OK_COMMAND:
mode = Mode.COMMAND;
break;
case MODEM_READY:
case OK_DATA:
mode = Mode.DATA;
break;
default:
if (mode == Mode.COMMAND) {
results.add(in);
}
}
}
} catch (SerialException | DecodingException ex) {
logger.log(Level.SEVERE, null, ex);
} catch (Throwable ex) {
logger.log(Level.SEVERE, null, ex);
}
}
}
}
private String asHex(String text) {
byte[] bytes = text.getBytes();
StringBuilder buf = new StringBuilder();
for (byte b : bytes) {
buf.append(String.format("%2x", b));
}
return buf.toString();
}
private static class ReceiveTask implements Runnable {
private enum Direction {
IN, OUT;
}
private ReceiveTask(MessageListener listener, SwapMessage msg, Direction dir) {
this.msg = msg;
this.l = listener;
this.dir = dir;
}
@Override
public void run() {
try {
if (dir == Direction.IN) {
l.messageReceived(msg);
} else {
l.messageSent(msg);
}
} catch (Throwable e) {
logger.log(Level.SEVERE, null, e);
}
}
private final SwapMessage msg;
private final MessageListener l;
private final Direction dir;
}
} |
/**
* @file ExampleString.java
* @author Valery Samovich
* @version 1.0.0
* @date 11/5/2014
*
* Example of logger class with LOGGER object which is used to log messages.
*/
package com.valerysamovich.java.basics.strings;
public class ExapmleString {
public static void main(String[] args) {
//[0]J [1]a [2]m [3]e [4]s [5]_ [6]D [7]e [8]a [9]n
String x = "James Dean";
// String methods
System.out.println("Hello " + x);
System.out.println(x.toUpperCase());
System.out.println(x.substring(2));
System.out.println(x.substring(2, 7));
System.out.println(x.charAt(3));
String age = "37";
String salary = "78965.83";
//Wrapper classes
int a = Integer.parseInt(age) + 2;
System.out.println(a);
double s = Double.parseDouble(salary) * .15;
System.out.println(s);
}
} |
package mil.dds.anet.beans;
import java.util.LinkedList;
import java.util.List;
import org.joda.time.DateTime;
import mil.dds.anet.emails.AnetEmailAction;
public class AnetEmail {
private Integer id;
private AnetEmailAction action;
private List<String> toAddresses;
private DateTime createdAt;
private String comment;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public AnetEmailAction getAction() {
return action;
}
public void setAction(AnetEmailAction action) {
this.action = action;
}
public List<String> getToAddresses() {
return toAddresses;
}
public void setToAddresses(List<String> toAddresses) {
this.toAddresses = toAddresses;
}
public void addToAddress(String toAddress) {
if (toAddresses == null) { toAddresses = new LinkedList<String>(); }
toAddresses.add(toAddress);
}
public DateTime getCreatedAt() {
return createdAt;
}
public void setCreatedAt(DateTime createdAt) {
this.createdAt = createdAt;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
} |
package models;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.TimeZone;
public class OrgConfig {
public String name;
public String short_name;
public String people_url;
public String str_manual_title;
public String str_manual_title_short;
public String str_res_plan_short;
public String str_res_plan;
public String str_res_plan_cap;
public String str_res_plans;
public String str_res_plans_cap;
public String str_committee_name = "Judicial Committee";
public String str_findings = "Findings";
public boolean show_no_contest_plea = false;
public boolean show_severity = false;
public boolean use_minor_referrals = false;
public boolean show_checkbox_for_res_plan = true;
public boolean track_writer = true;
public boolean filter_no_charge_cases = false;
public Organization org;
public TimeZone time_zone = TimeZone.getTimeZone("US/Eastern");
public static OrgConfig get() {
Organization org = Organization.getByHost();
OrgConfig result = configs.get(org.name);
result.org = org;
return result;
}
public String getReferralDestination(Charge c) {
return "School Meeting";
}
static HashMap<String, OrgConfig> configs = new HashMap<String, OrgConfig>();
static void register(String name, OrgConfig config) {
configs.put(name, config);
}
public String getCaseNumberPrefix(Meeting m) {
return new SimpleDateFormat("MM-dd-").format(m.date);
}
}
class ThreeRiversVillageSchool extends OrgConfig {
private static final ThreeRiversVillageSchool INSTANCE = new ThreeRiversVillageSchool();
public ThreeRiversVillageSchool() {
name = "Three Rivers Village School";
short_name = "TRVS";
people_url = "http://trvs.demschooltools.com";
str_manual_title = "Management Manual";
str_manual_title_short = "Manual";
str_res_plan_short = "RP";
str_res_plan = "resolution plan";
str_res_plan_cap = "Resolution plan";
str_res_plans = "resolution plans";
str_res_plans_cap = "Resolution plans";
str_committee_name = "Justice Committee";
show_checkbox_for_res_plan = false;
OrgConfig.register(name, this);
}
public static ThreeRiversVillageSchool getInstance() {
return INSTANCE;
}
}
class PhillyFreeSchool extends OrgConfig {
private static final PhillyFreeSchool INSTANCE = new PhillyFreeSchool();
public PhillyFreeSchool() {
name = "Philly Free School";
short_name = "PFS";
people_url = "http://pfs.demschooltools.com";
str_manual_title = "Lawbook";
str_manual_title_short = "Lawbook";
str_res_plan_short = "Sentence";
str_res_plan = "sentence";
str_res_plan_cap = "Sentence";
str_res_plans = "sentences";
str_res_plans_cap = "Sentences";
show_no_contest_plea = true;
show_severity = true;
use_minor_referrals = true;
OrgConfig.register(name, this);
}
public static PhillyFreeSchool getInstance() {
return INSTANCE;
}
}
class Fairhaven extends OrgConfig {
private static final Fairhaven INSTANCE = new Fairhaven();
public Fairhaven() {
name = "Fairhaven School";
short_name = "Fairhaven";
people_url = "http://fairhaven.demschooltools.com";
str_manual_title = "Lawbook";
str_manual_title_short = "Lawbook";
str_res_plan_short = "Sentence";
str_res_plan = "sentence";
str_res_plan_cap = "Sentence";
str_res_plans = "sentences";
str_res_plans_cap = "Sentences";
str_findings = "JC Report";
use_minor_referrals = true;
OrgConfig.register(name, this);
}
public static Fairhaven getInstance() {
return INSTANCE;
}
}
class TheCircleSchool extends OrgConfig {
private static final TheCircleSchool INSTANCE = new TheCircleSchool();
public TheCircleSchool() {
name = "The Circle School";
short_name = "TCS";
people_url = "http://tcs.demschooltools.com";
str_manual_title = "Management Manual";
str_manual_title_short = "Mgmt. Man.";
str_res_plan_short = "Sentence";
str_res_plan = "sentence";
str_res_plan_cap = "Sentence";
str_res_plans = "sentences";
str_res_plans_cap = "Sentences";
str_findings = "Findings";
use_minor_referrals = true;
track_writer = false;
filter_no_charge_cases = true;
OrgConfig.register(name, this);
}
@Override
public String getReferralDestination(Charge c) {
if (c.plea.equals("Not Guilty")) {
return "trial";
} else {
return "School Meeting";
}
}
public static TheCircleSchool getInstance() {
return INSTANCE;
}
@Override
public String getCaseNumberPrefix(Meeting m) {
return new SimpleDateFormat("yyyyMMdd").format(m.date);
}
}
class MakariosLearningCommunity extends OrgConfig {
private static final MakariosLearningCommunity INSTANCE =
new MakariosLearningCommunity();
public MakariosLearningCommunity() {
name = "Makarios Learning Community";
short_name = "MLC";
people_url = "http://mlc.demschooltools.com";
time_zone = TimeZone.getTimeZone("US/Central");
str_manual_title = "Management Manual";
str_manual_title_short = "Mgmt. Man.";
str_res_plan_short = "Sentence";
str_res_plan = "sentence";
str_res_plan_cap = "Sentence";
str_res_plans = "sentences";
str_res_plans_cap = "Sentences";
str_findings = "Findings";
use_minor_referrals = true;
OrgConfig.register(name, this);
}
public static MakariosLearningCommunity getInstance() {
return INSTANCE;
}
} |
package com.molina.cvmfs.common;
/**
* @author Jose Molina Colmenero
*/
public class Common {
public static final String REPO_CONFIG_PATH = "/etc/cvmfs/repositories.d";
public static final String SERVER_CONFIG_NAME = "server.conf";
public static final String REST_CONNECTOR = "control";
public static final String MANIFEST_NAME = ".cvmfspublished";
public static final String LAST_REPLICATION_NAME = ".cvmfs_last_snapshot";
public static final String REPLICATING_NAME = ".cvmfs_is_snapshotting";
public static String binaryBufferToHexString(byte[] binaryBuffer) {
StringBuilder sb = new StringBuilder();
for (byte b : binaryBuffer)
sb.append(String.format("%02X ", b));
return sb.toString().toLowerCase();
}
} |
package org.sugr.gearshift;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Locale;
import org.sugr.gearshift.TorrentComparator.SortBy;
import org.sugr.gearshift.TorrentComparator.SortOrder;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.Loader;
import android.text.Html;
import android.text.Spanned;
import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AbsListView.MultiChoiceModeListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.Filter.FilterListener;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
/**
* A list fragment representing a list of Torrents. This fragment
* also supports tablet devices by allowing list items to be given an
* 'activated' state upon selection. This helps indicate which item is
* currently being viewed in a {@link TorrentDetailFragment}.
* <p>
* Activities containing this fragment MUST implement the {@link Callbacks}
* interface.
*/
public class TorrentListFragment extends ListFragment {
/**
* The serialization (saved instance state) Bundle key representing the
* activated item position. Only used on tablets.
*/
private static final String STATE_ACTIVATED_POSITION = "activated_position";
/**
* The fragment's current callback object, which is notified of list item
* clicks.
*/
private Callbacks mCallbacks = sDummyCallbacks;
/**
* The current activated item position. Only used on tablets.
*/
private int mActivatedPosition = ListView.INVALID_POSITION;
private boolean mAltSpeed = false;
private boolean mRefreshing = true;
private boolean mIsCABDestroyed = false;
private int mChoiceMode = ListView.CHOICE_MODE_NONE;
private TransmissionProfileListAdapter mProfileAdapter;
private TorrentListAdapter mTorrentListAdapter;
private TransmissionProfile mCurrentProfile;
private TransmissionSession mSession = new TransmissionSession();
private TransmissionSessionStats mSessionStats;
/**
* A callback interface that all activities containing this fragment must
* implement. This mechanism allows activities to be notified of item
* selections.
*/
public interface Callbacks {
/**
* Callback for when an item has been selected.
*/
public void onItemSelected(Torrent torrent);
}
/**
* A dummy implementation of the {@link Callbacks} interface that does
* nothing. Used only when this fragment is not attached to an activity.
*/
private static Callbacks sDummyCallbacks = new Callbacks() {
@Override
public void onItemSelected(Torrent torrent) {
}
};
private LoaderCallbacks<TransmissionProfile[]> mProfileLoaderCallbacks = new LoaderCallbacks<TransmissionProfile[]>() {
@Override
public android.support.v4.content.Loader<TransmissionProfile[]> onCreateLoader(
int id, Bundle args) {
return new TransmissionProfileSupportLoader(getActivity());
}
@Override
public void onLoadFinished(
android.support.v4.content.Loader<TransmissionProfile[]> loader,
TransmissionProfile[] profiles) {
mProfileAdapter.clear();
if (profiles.length > 0) {
mProfileAdapter.addAll(profiles);
} else {
mProfileAdapter.add(TransmissionProfileListAdapter.EMPTY_PROFILE);
setEmptyText(R.string.no_profiles_empty_list);
mRefreshing = false;
getActivity().invalidateOptionsMenu();
}
String currentId = TransmissionProfile.getCurrentProfileId(getActivity());
int index = 0;
for (TransmissionProfile prof : profiles) {
if (prof.getId().equals(currentId)) {
ActionBar actionBar = getActivity().getActionBar();
if (actionBar != null)
actionBar.setSelectedNavigationItem(index);
mCurrentProfile = prof;
break;
}
index++;
}
if (mCurrentProfile == null && profiles.length > 0)
mCurrentProfile = profiles[0];
getActivity().getSupportLoaderManager().initLoader(TorrentListActivity.SESSION_LOADER_ID, null, mTorrentLoaderCallbacks);
}
@Override
public void onLoaderReset(
android.support.v4.content.Loader<TransmissionProfile[]> loader) {
mProfileAdapter.clear();
}
};
private LoaderCallbacks<TransmissionSessionData> mTorrentLoaderCallbacks = new LoaderCallbacks<TransmissionSessionData>() {
@Override
public android.support.v4.content.Loader<TransmissionSessionData> onCreateLoader(
int id, Bundle args) {
TorrentListActivity.logD("Starting the torrents loader with profile " + mCurrentProfile);
if (mCurrentProfile == null) return null;
TransmissionSessionLoader loader = new TransmissionSessionLoader(getActivity(), mCurrentProfile);
return loader;
}
@Override
public void onLoadFinished(
android.support.v4.content.Loader<TransmissionSessionData> loader,
TransmissionSessionData data) {
if (data.session != null)
mSession = data.session;
if (data.stats != null)
mSessionStats = data.stats;
boolean invalidateMenu = false;
if (mAltSpeed != mSession.isAltSpeedEnabled()) {
mAltSpeed = mSession.isAltSpeedEnabled();
invalidateMenu = true;
}
if (data.torrents.size() > 0 || data.error > 0
|| mTorrentListAdapter.getUnfilteredCount() > 0) {
/* The notifyDataSetChanged method sets this to true */
mTorrentListAdapter.setNotifyOnChange(false);
boolean notifyChange = true;
if (data.error == 0) {
if (data.hasRemoved || data.hasAdded || mTorrentListAdapter.getUnfilteredCount() == 0) {
notifyChange = false;
mTorrentListAdapter.clear();
mTorrentListAdapter.addAll(data.torrents);
mTorrentListAdapter.repeatFilter();
}
setEmptyText(null);
} else {
mTorrentListAdapter.clear();
if (data.error == TransmissionSessionData.Errors.NO_CONNECTIVITY) {
setEmptyText(R.string.no_connectivity_empty_list);
} else if (data.error == TransmissionSessionData.Errors.ACCESS_DENIED) {
setEmptyText(R.string.access_denied_empty_list);
} else if (data.error == TransmissionSessionData.Errors.NO_JSON) {
setEmptyText(R.string.no_json_empty_list);
} else if (data.error == TransmissionSessionData.Errors.NO_CONNECTION) {
setEmptyText(R.string.no_connection_empty_list);
}
}
if (data.torrents.size() > 0) {
if (notifyChange) {
mTorrentListAdapter.notifyDataSetChanged();
}
} else {
mTorrentListAdapter.notifyDataSetInvalidated();
}
FragmentManager manager = getActivity().getSupportFragmentManager();
TorrentListMenuFragment menu = (TorrentListMenuFragment) manager.findFragmentById(R.id.torrent_list_menu);
if (menu != null) {
menu.notifyTorrentListUpdate(mTorrentListAdapter.getItems(), data.session);
}
TorrentDetailFragment detail = (TorrentDetailFragment) manager.findFragmentByTag(
TorrentDetailFragment.TAG);
if (detail != null) {
detail.notifyTorrentListChanged(data.hasRemoved, data.hasAdded);
}
}
if (data.error == 0) {
/* TODO: Move this code to the filter, since it's asyncronous */
if (mTorrentListAdapter.getUnfilteredCount() == 0) {
setEmptyText(R.string.no_torrents_empty_list);
} else if (mTorrentListAdapter.getCount() == 0) {
((TransmissionSessionInterface) getActivity())
.setTorrents(null);
setEmptyText(R.string.no_filtered_torrents_empty_list);
}
}
if (mRefreshing) {
mRefreshing = false;
invalidateMenu = true;
}
if (invalidateMenu)
getActivity().invalidateOptionsMenu();
}
@Override
public void onLoaderReset(
android.support.v4.content.Loader<TransmissionSessionData> loader) {
}
};
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public TorrentListFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mTorrentListAdapter = new TorrentListAdapter(getActivity());
setListAdapter(mTorrentListAdapter);
setHasOptionsMenu(true);
getActivity().requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
getActivity().setProgressBarIndeterminateVisibility(true);
ActionBar actionBar = getActivity().getActionBar();
if (actionBar != null) {
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
mProfileAdapter = new TransmissionProfileListAdapter(getActivity());
actionBar.setListNavigationCallbacks(mProfileAdapter, new ActionBar.OnNavigationListener() {
@Override
public boolean onNavigationItemSelected(int pos, long id) {
TransmissionProfile profile = mProfileAdapter.getItem(pos);
if (profile != TransmissionProfileListAdapter.EMPTY_PROFILE)
TransmissionProfile.setCurrentProfile(profile, getActivity());
return false;
}
});
actionBar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE);
}
getActivity().getSupportLoaderManager().initLoader(TorrentListActivity.PROFILES_LOADER_ID, null, mProfileLoaderCallbacks);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// Restore the previously serialized activated item position.
if (savedInstanceState != null
&& savedInstanceState.containsKey(STATE_ACTIVATED_POSITION)) {
setActivatedPosition(savedInstanceState.getInt(STATE_ACTIVATED_POSITION));
}
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
final ListView list = getListView();
list.setChoiceMode(mChoiceMode);
list.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
if (!((TorrentListActivity) getActivity()).isDetailsPanelShown()) {
list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
mIsCABDestroyed = false;
setActivatedPosition(position);
return true;
}
return false;
}});
list.setMultiChoiceModeListener(new MultiChoiceModeListener() {
private HashSet<Integer> mSelectedTorrentIds;
@Override
public boolean onActionItemClicked(ActionMode mode, final MenuItem item) {
final Loader<TransmissionSessionData> loader = getActivity().getSupportLoaderManager()
.getLoader(TorrentListActivity.SESSION_LOADER_ID);
if (loader == null)
return false;
final int[] ids = new int[mSelectedTorrentIds.size()];
int index = 0;
for (Integer id : mSelectedTorrentIds)
ids[index++] = id;
switch (item.getItemId()) {
case R.id.remove:
case R.id.delete:
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity())
.setCancelable(false)
.setNegativeButton(android.R.string.no, null);
builder.setPositiveButton(android.R.string.yes,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
((TransmissionSessionLoader) loader).setTorrentsRemove(ids, item.getItemId() == R.id.delete);
}
})
.setMessage(item.getItemId() == R.id.delete
? R.string.delete_selected_confirmation
: R.string.remove_selected_confirmation)
.show();
break;
case R.id.resume:
((TransmissionSessionLoader) loader).setTorrentsAction("torrent-start", ids);
break;
case R.id.pause:
((TransmissionSessionLoader) loader).setTorrentsAction("torrent-stop", ids);
break;
default:
return true;
}
mRefreshing = true;
getActivity().invalidateOptionsMenu();
mode.finish();
return true;
}
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.torrent_list_multiselect, menu);
mSelectedTorrentIds = new HashSet<Integer>();
return true;
}
@Override
public void onDestroyActionMode(ActionMode mode) {
TorrentListActivity.logD("Destroying context menu");
mIsCABDestroyed = true;
mSelectedTorrentIds = null;
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
@Override
public void onItemCheckedStateChanged(ActionMode mode,
int position, long id, boolean checked) {
if (checked)
mSelectedTorrentIds.add(mTorrentListAdapter.getItem(position).getId());
else
mSelectedTorrentIds.remove(mTorrentListAdapter.getItem(position).getId());
ArrayList<Torrent> torrents = ((TransmissionSessionInterface) getActivity()).getTorrents();
boolean hasPaused = false;
boolean hasRunning = false;
for (Torrent t : torrents) {
if (mSelectedTorrentIds.contains(t.getId())) {
if (t.getStatus() == Torrent.Status.STOPPED) {
hasPaused = true;
} else {
hasRunning = true;
}
}
}
Menu menu = mode.getMenu();
MenuItem item = menu.findItem(R.id.resume);
item.setVisible(hasPaused).setEnabled(hasPaused);
item = menu.findItem(R.id.pause);
item.setVisible(hasRunning).setEnabled(hasRunning);
}});
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// Activities containing this fragment must implement its callbacks.
if (!(activity instanceof Callbacks)) {
throw new IllegalStateException("Activity must implement fragment's callbacks.");
}
mCallbacks = (Callbacks) activity;
}
@Override
public void onDetach() {
super.onDetach();
// Reset the active callbacks interface to the dummy implementation.
mCallbacks = sDummyCallbacks;
}
@Override
public void onListItemClick(ListView listView, View view, int position, long id) {
super.onListItemClick(listView, view, position, id);
if (mIsCABDestroyed)
listView.setChoiceMode(mChoiceMode);
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
mCallbacks.onItemSelected(mTorrentListAdapter.getItem(position));
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mActivatedPosition != ListView.INVALID_POSITION) {
// Serialize and persist the activated item position.
outState.putInt(STATE_ACTIVATED_POSITION, mActivatedPosition);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_torrent_list, container, false);
return rootView;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.torrent_list_options, menu);
MenuItem item = menu.findItem(R.id.menu_refresh);
if (mRefreshing)
item.setActionView(R.layout.action_progress_bar);
else
item.setActionView(null);
item = menu.findItem(R.id.menu_alt_speed);
if (mAltSpeed) {
item.setIcon(R.drawable.ic_menu_alt_speed_on);
item.setTitle(R.string.alt_speed_label_off);
} else {
item.setIcon(R.drawable.ic_menu_alt_speed_off);
item.setTitle(R.string.alt_speed_label_on);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Loader<TransmissionSessionData> loader;
switch (item.getItemId()) {
case R.id.menu_alt_speed:
loader = getActivity().getSupportLoaderManager()
.getLoader(TorrentListActivity.SESSION_LOADER_ID);
if (loader != null) {
mAltSpeed = !mAltSpeed;
mSession.setAltSpeedEnabled(mAltSpeed);
((TransmissionSessionLoader) loader).setSession(mSession, "alt-speed-enabled");
getActivity().invalidateOptionsMenu();
}
return true;
case R.id.menu_refresh:
loader = getActivity().getSupportLoaderManager()
.getLoader(TorrentListActivity.SESSION_LOADER_ID);
if (loader != null) {
loader.onContentChanged();
mRefreshing = !mRefreshing;
getActivity().invalidateOptionsMenu();
}
return true;
case R.id.menu_settings:
Intent i = new Intent(getActivity(), SettingsActivity.class);
getActivity().startActivity(i);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void setEmptyText(int stringId) {
Spanned text = Html.fromHtml(getString(stringId));
((TextView) getListView().getEmptyView()).setText(text);
}
public void setEmptyText(String text) {
((TextView) getListView().getEmptyView()).setText(text);
}
/**
* Turns on activate-on-click mode. When this mode is on, list items will be
* given the 'activated' state when touched.
*/
public void setActivateOnItemClick(boolean activateOnItemClick) {
// When setting CHOICE_MODE_SINGLE, ListView will automatically
// give items the 'activated' state when touched.
mChoiceMode = activateOnItemClick
? ListView.CHOICE_MODE_SINGLE
: ListView.CHOICE_MODE_NONE;
getListView().setChoiceMode(mChoiceMode);
}
public void setListFilter(CharSequence constraint) {
mTorrentListAdapter.filter(constraint);
}
public SortBy getSortBy() {
return mTorrentListAdapter.getSortBy();
}
public SortOrder getSortOrder() {
return mTorrentListAdapter.getSortOrder();
}
private void setActivatedPosition(int position) {
if (position == ListView.INVALID_POSITION) {
getListView().setItemChecked(mActivatedPosition, false);
} else {
getListView().setItemChecked(position, true);
}
mActivatedPosition = position;
}
private static class TransmissionProfileListAdapter extends ArrayAdapter<TransmissionProfile> {
public static final TransmissionProfile EMPTY_PROFILE = new TransmissionProfile();
public TransmissionProfileListAdapter(Context context) {
super(context, 0);
add(EMPTY_PROFILE);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
TransmissionProfile profile = getItem(position);
if (rowView == null) {
LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = vi.inflate(R.layout.torrent_profile_selector, null);
}
TextView name = (TextView) rowView.findViewById(R.id.name);
TextView summary = (TextView) rowView.findViewById(R.id.summary);
if (profile == EMPTY_PROFILE) {
name.setText(R.string.no_profiles);
if (summary != null)
summary.setText(R.string.create_profile_in_settings);
} else {
name.setText(profile.getName());
if (summary != null)
summary.setText((profile.getUsername().length() > 0 ? profile.getUsername() + "@" : "")
+ profile.getHost() + ":" + profile.getPort());
}
return rowView;
}
@Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
if (rowView == null) {
LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = vi.inflate(R.layout.torrent_profile_selector_dropdown, null);
}
return getView(position, rowView, parent);
}
}
private class TorrentListAdapter extends ArrayAdapter<Torrent> {
private final Object mLock = new Object();
private ArrayList<Torrent> mObjects = new ArrayList<Torrent>();
private ArrayList<Torrent> mOriginalValues;
private TorrentFilter mFilter;
private CharSequence mCurrentConstraint;
private FilterListener mCurrentFilterListener;
private TorrentComparator mTorrentComparator = new TorrentComparator();
private SortBy mSortBy = mTorrentComparator.getSortBy();
private SortOrder mSortOrder = mTorrentComparator.getSortOrder();
public TorrentListAdapter(Context context) {
super(context, R.layout.torrent_list_item, R.id.name);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
Torrent torrent = getItem(position);
if (rowView == null) {
LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = vi.inflate(R.layout.torrent_list_item, parent, false);
}
TextView name = (TextView) rowView.findViewById(R.id.name);
TextView traffic = (TextView) rowView.findViewById(R.id.traffic);
ProgressBar progress = (ProgressBar) rowView.findViewById(R.id.progress);
TextView status = (TextView) rowView.findViewById(R.id.status);
name.setText(torrent.getName());
if (torrent.getMetadataPercentComplete() < 1) {
progress.setSecondaryProgress((int) (torrent.getMetadataPercentComplete() * 100));
} else if (torrent.getPercentDone() < 1) {
progress.setSecondaryProgress((int) (torrent.getPercentDone() * 100));
} else {
progress.setSecondaryProgress(100);
float limit = torrent.getActiveSeedRatioLimit();
float current = torrent.getUploadRatio();
if (limit == -1) {
progress.setProgress(100);
} else {
if (current >= limit) {
progress.setProgress(100);
} else {
progress.setProgress((int) (current / limit * 100));
}
}
}
traffic.setText(torrent.getTrafficText());
status.setText(torrent.getStatusText());
int color;
switch(torrent.getStatus()) {
case Torrent.Status.STOPPED:
case Torrent.Status.CHECK_WAITING:
case Torrent.Status.DOWNLOAD_WAITING:
case Torrent.Status.SEED_WAITING:
color = getContext().getResources().getColor(android.R.color.darker_gray);
break;
default:
color = getContext().getResources().getColor(android.R.color.primary_text_light);
break;
}
name.setTextColor(color);
traffic.setTextColor(color);
status.setTextColor(color);
return rowView;
}
@Override
public void addAll(Collection<? extends Torrent> collection) {
synchronized (mLock) {
if (mOriginalValues != null) {
mOriginalValues.addAll(collection);
} else {
mObjects.addAll(collection);
}
super.addAll(collection);
}
}
@Override
public void clear() {
synchronized (mLock) {
if (mOriginalValues != null) {
mOriginalValues.clear();
} else {
mObjects.clear();
}
super.clear();
}
}
@Override
public int getCount() {
synchronized(mLock) {
return mObjects == null ? 0 : mObjects.size();
}
}
public int getUnfilteredCount() {
synchronized(mLock) {
if (mOriginalValues != null) {
return mOriginalValues.size();
} else {
return mObjects.size();
}
}
}
@Override
public Torrent getItem(int position) {
return mObjects.get(position);
}
@Override
public int getPosition(Torrent item) {
return mObjects.indexOf(item);
}
@Override
public Filter getFilter() {
if (mFilter == null)
mFilter = new TorrentFilter();
return mFilter;
}
public void filter(CharSequence constraint) {
filter(constraint, null);
}
public void filter(CharSequence constraint, FilterListener listener) {
String prefix = constraint.toString().toLowerCase(Locale.getDefault());
if (prefix.startsWith("sortby:")) {
if (prefix.equals("sortby:name")) {
mSortBy = SortBy.NAME;
} else if (prefix.equals("sortby:size")) {
mSortBy = SortBy.SIZE;
} else if (prefix.equals("sortby:status")) {
mSortBy = SortBy.STATUS;
} else if (prefix.equals("sortby:activity")) {
mSortBy = SortBy.ACTIVITY;
} else if (prefix.equals("sortby:age")) {
mSortBy = SortBy.AGE;
} else if (prefix.equals("sortby:progress")) {
mSortBy = SortBy.PROGRESS;
} else if (prefix.equals("sortby:ratio")) {
mSortBy = SortBy.RATIO;
} else if (prefix.equals("sortby:location")) {
mSortBy = SortBy.LOCATION;
} else if (prefix.equals("sortby:peers")) {
mSortBy = SortBy.PEERS;
} else if (prefix.equals("sortby:rate_download")) {
mSortBy = SortBy.RATE_DOWNLOAD;
} else if (prefix.equals("sortby:rate_upload")) {
mSortBy = SortBy.RATE_UPLOAD;
} else if (prefix.equals("sortby:queue")) {
mSortBy = SortBy.QUEUE;
}
mTorrentComparator.setSortingMethod(mSortBy, mSortOrder);
} else if (prefix.startsWith("sortorder:")) {
mSortOrder = prefix.equals("sortorder:descending")
? SortOrder.DESCENDING : SortOrder.ASCENDING;
mTorrentComparator.setSortingMethod(mSortBy, mSortOrder);
} else {
mCurrentConstraint = constraint;
}
mCurrentFilterListener = listener;
getFilter().filter(mCurrentConstraint, listener);
}
public void repeatFilter() {
getFilter().filter(mCurrentConstraint, mCurrentFilterListener);
}
public ArrayList<Torrent> getItems() {
return mObjects;
}
public SortBy getSortBy() {
return mSortBy;
}
public SortOrder getSortOrder() {
return mSortOrder;
}
private class TorrentFilter extends Filter {
private boolean mChanged;
@Override
protected FilterResults performFiltering(CharSequence prefix) {
FilterResults results = new FilterResults();
ArrayList<Torrent> resultList;
if (mOriginalValues == null) {
synchronized (mLock) {
mOriginalValues = new ArrayList<Torrent>(mObjects);
}
}
String prefixString = prefix == null
? "" : prefix.toString().toLowerCase(Locale.getDefault());
if (prefixString.length() == 0 || prefixString.equals("filter:all")) {
ArrayList<Torrent> list;
synchronized (mLock) {
list = new ArrayList<Torrent>(mOriginalValues);
}
resultList = list;
} else {
ArrayList<Torrent> values;
synchronized (mLock) {
values = new ArrayList<Torrent>(mOriginalValues);
}
final int count = values.size();
final ArrayList<Torrent> newValues = new ArrayList<Torrent>();
for (int i = 0; i < count; i++) {
final Torrent torrent = values.get(i);
if (prefixString.equals("filter:downloading")) {
if (torrent.getStatus() == Torrent.Status.DOWNLOADING)
newValues.add(torrent);
} else if (prefixString.equals("filter:seeding")) {
if (torrent.getStatus() == Torrent.Status.SEEDING)
newValues.add(torrent);
} else if (prefixString.equals("filter:paused")) {
if (torrent.getStatus() == Torrent.Status.STOPPED)
newValues.add(torrent);
} else if (prefixString.equals("filter:complete")) {
if (torrent.getPercentDone() == 1)
newValues.add(torrent);
} else if (prefixString.equals("filter:incomplete")) {
if (torrent.getPercentDone() < 1)
newValues.add(torrent);
} else if (prefixString.equals("filter:active")) {
if (!torrent.isStalled() && !torrent.isFinished() && (
torrent.getStatus() == Torrent.Status.DOWNLOADING
|| torrent.getStatus() == Torrent.Status.SEEDING
))
newValues.add(torrent);
} else if (prefixString.equals("filter:checking")) {
if (torrent.getStatus() == Torrent.Status.CHECKING)
newValues.add(torrent);
} else {
final String valueText = torrent.getName().toLowerCase(Locale.getDefault());
// First match against the whole, non-splitted value
if (valueText.startsWith(prefixString)) {
newValues.add(torrent);
} else {
final String[] words = valueText.split(" ");
final int wordCount = words.length;
// Start at index 0, in case valueText starts with space(s)
for (int k = 0; k < wordCount; k++) {
if (words[k].startsWith(prefixString)) {
newValues.add(torrent);
break;
}
}
}
}
}
resultList = newValues;
}
Collections.sort(resultList, mTorrentComparator);
mChanged = !((TransmissionSessionInterface) getActivity())
.getTorrents().equals(resultList);
results.values = resultList;
results.count = resultList.size();
return results;
}
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
mObjects = (ArrayList<Torrent>) results.values;
if (results.count > 0) {
if (mChanged) {
((TransmissionSessionInterface) getActivity()).setTorrents((ArrayList<Torrent>) results.values);
FragmentManager manager = getActivity().getSupportFragmentManager();
TorrentDetailFragment detail = (TorrentDetailFragment) manager.findFragmentByTag(
TorrentDetailFragment.TAG);
if (detail != null) {
detail.notifyTorrentListChanged(true, true);
}
}
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
}
}
} |
package me.nallar.patched.storage;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import cpw.mods.fml.common.FMLLog;
import me.nallar.patched.annotation.FakeExtend;
import me.nallar.tickthreading.Log;
import me.nallar.tickthreading.minecraft.TickThreading;
import me.nallar.tickthreading.minecraft.storage.RegionFileCache;
import me.nallar.tickthreading.patcher.Declare;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityList;
import net.minecraft.nbt.CompressedStreamTools;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.LongHashMap;
import net.minecraft.world.ChunkCoordIntPair;
import net.minecraft.world.NextTickListEntry;
import net.minecraft.world.World;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.chunk.NibbleArray;
import net.minecraft.world.chunk.storage.AnvilChunkLoader;
import net.minecraft.world.chunk.storage.AnvilChunkLoaderPending;
import net.minecraft.world.chunk.storage.ExtendedBlockStorage;
import net.minecraft.world.chunk.storage.IChunkLoader;
import net.minecraft.world.storage.IThreadedFileIO;
import net.minecraft.world.storage.ThreadedFileIOBase;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.world.ChunkDataEvent;
@FakeExtend
public abstract class ThreadedChunkLoader extends AnvilChunkLoader implements IThreadedFileIO, IChunkLoader {
private final java.util.LinkedHashMap<ChunkCoordIntPair, AnvilChunkLoaderPending> pendingSaves = new java.util.LinkedHashMap<ChunkCoordIntPair, AnvilChunkLoaderPending>(); // Spigot
private final LongHashMap inProgressSaves = new LongHashMap();
private final Object syncLockObject = new Object();
public final File chunkSaveLocation;
private final Cache<Long, NBTTagCompound> chunkCache;
public final RegionFileCache regionFileCache;
private int cacheSize;
@Override
@Declare
public boolean isChunkSavedPopulated(int x, int z) {
DataInputStream dataInputStream = regionFileCache.getChunkInputStream(x, z);
if (dataInputStream == null) {
return false;
}
try {
NBTTagCompound rootCompound = CompressedStreamTools.read(dataInputStream);
NBTTagCompound levelCompound = (NBTTagCompound) rootCompound.getTag("Level");
return levelCompound != null && levelCompound.getBoolean("TerrainPopulated");
} catch (IOException e) {
Log.severe("Failed to check if chunk " + x + ',' + z + " is populated.", e);
return false;
}
}
public ThreadedChunkLoader(File file) {
super(file);
this.chunkSaveLocation = file;
if (file == null) {
Log.severe("Null chunk save location set for ThreadedChunkLoader", new Throwable());
}
chunkCache = CacheBuilder.newBuilder().maximumSize(cacheSize = TickThreading.instance.chunkCacheSize).build();
regionFileCache = new RegionFileCache(chunkSaveLocation);
}
public boolean chunkExists(World world, int i, int j) {
ChunkCoordIntPair chunkcoordintpair = new ChunkCoordIntPair(i, j);
synchronized (this.syncLockObject) {
if (pendingSaves.containsKey(chunkcoordintpair)) {
return true;
}
}
return regionFileCache.get(i, j).isChunkSaved(i & 31, j & 31);
}
@Override
@Declare
public int getCachedChunks() {
return (int) chunkCache.size();
}
@Override
@Declare
public boolean isChunkCacheFull() {
return chunkCache.size() >= cacheSize;
}
@Override
@Declare
public void cacheChunk(World world, int x, int z) {
DataInputStream dataInputStream = regionFileCache.getChunkInputStream(x, z);
if (dataInputStream == null) {
return;
}
NBTTagCompound nbttagcompound;
try {
nbttagcompound = CompressedStreamTools.read(dataInputStream);
} catch (Throwable t) {
Log.severe("Failed to cache chunk " + Log.pos(world, x, z), t);
return;
}
chunkCache.put(hash(x, z), nbttagcompound);
}
@Override
public Chunk loadChunk(World world, int x, int z) {
NBTTagCompound nbttagcompound;
ChunkCoordIntPair chunkcoordintpair = new ChunkCoordIntPair(x, z);
synchronized (this.syncLockObject) {
AnvilChunkLoaderPending pendingchunktosave = pendingSaves.get(chunkcoordintpair);
long hash = hash(x, z);
if (pendingchunktosave == null) {
nbttagcompound = (NBTTagCompound) inProgressSaves.getValueByKey(hash);
if (nbttagcompound == null) {
nbttagcompound = chunkCache.getIfPresent(hash);
}
} else {
nbttagcompound = pendingchunktosave.nbtTags;
}
if (nbttagcompound != null) {
chunkCache.invalidate(hash);
}
}
if (nbttagcompound == null) {
DataInputStream dataInputStream = regionFileCache.getChunkInputStream(x, z);
if (dataInputStream == null) {
return null;
}
try {
nbttagcompound = CompressedStreamTools.read(dataInputStream);
} catch (Throwable t) {
Log.severe("Failed to load chunk " + Log.pos(world, x, z), t);
return null;
}
}
return this.checkedReadChunkFromNBT(world, x, z, nbttagcompound);
}
@Override
@Declare
public Chunk loadChunk__Async_CB(World world, int x, int z) {
throw new UnsupportedOperationException();
}
@Override
protected Chunk checkedReadChunkFromNBT(World world, int x, int z, NBTTagCompound chunkTagCompound) {
NBTTagCompound levelTag = (NBTTagCompound) chunkTagCompound.getTag("Level");
if (levelTag == null) {
FMLLog.severe("Chunk file at " + x + ',' + z + " is missing level data, skipping");
return null;
} else if (!levelTag.hasKey("Sections")) {
FMLLog.severe("Chunk file at " + x + ',' + z + " is missing block data, skipping");
return null;
} else {
int cX = levelTag.getInteger("xPos");
int cZ = levelTag.getInteger("zPos");
if (cX != x || cZ != z) {
FMLLog.warning("Chunk file at " + x + ',' + z + " is in the wrong location; relocating. (Expected " + x + ", " + z + ", got " + cX + ", " + cZ + ')');
levelTag.setInteger("xPos", x);
levelTag.setInteger("zPos", z);
}
Chunk chunk = this.readChunkFromNBT(world, levelTag);
try {
MinecraftForge.EVENT_BUS.post(new ChunkDataEvent.Load(chunk, chunkTagCompound));
} catch (Throwable t) {
FMLLog.log(Level.SEVERE, t, "A mod failed to handle a ChunkDataEvent.Load event for " + x + ',' + z);
}
return chunk;
}
}
protected Object[] a(World world, int x, int z, NBTTagCompound chunkTagCompound) {
throw new UnsupportedOperationException();
}
@Override
public void saveChunk(World world, Chunk chunk) {
try {
NBTTagCompound nbttagcompound = new NBTTagCompound();
NBTTagCompound nbttagcompound1 = new NBTTagCompound();
nbttagcompound.setTag("Level", nbttagcompound1);
this.writeChunkToNBT(chunk, world, nbttagcompound1);
try {
MinecraftForge.EVENT_BUS.post(new ChunkDataEvent.Save(chunk, nbttagcompound));
} catch (Throwable t) {
FMLLog.log(Level.SEVERE, t, "A mod failed to handle a ChunkDataEvent.Save event for " + chunk.xPosition + ',' + chunk.zPosition);
}
this.addToSaveQueue(chunk.getChunkCoordIntPair(), nbttagcompound, chunk.alreadySavedAfterUnload || chunk.partiallyUnloaded || !chunk.isChunkLoaded);
} catch (Exception exception) {
Log.severe("Failed to save chunk " + Log.pos(world, chunk.xPosition, chunk.zPosition));
}
}
void addToSaveQueue(ChunkCoordIntPair par1ChunkCoordIntPair, NBTTagCompound par2NBTTagCompound, boolean unloading) {
synchronized (this.syncLockObject) {
AnvilChunkLoaderPending pending = new AnvilChunkLoaderPending(par1ChunkCoordIntPair, par2NBTTagCompound);
pending.unloading = unloading;
if (this.pendingSaves.put(par1ChunkCoordIntPair, pending) == null) {
ThreadedFileIOBase.threadedIOInstance.queueIO(this);
}
}
}
/**
* Returns a boolean stating if the write was unsuccessful.
*/
@Override
public boolean writeNextIO() {
AnvilChunkLoaderPending anvilchunkloaderpending;
long hash;
synchronized (this.syncLockObject) {
if (this.pendingSaves.isEmpty()) {
return false;
}
anvilchunkloaderpending = this.pendingSaves.values().iterator().next();
this.pendingSaves.remove(anvilchunkloaderpending.chunkCoordinate);
hash = hash(anvilchunkloaderpending.chunkCoordinate.chunkXPos, anvilchunkloaderpending.chunkCoordinate.chunkZPos);
if (anvilchunkloaderpending.unloading) {
chunkCache.put(hash, anvilchunkloaderpending.nbtTags);
}
inProgressSaves.add(hash, anvilchunkloaderpending.nbtTags);
}
try {
this.writeChunkNBTTags(anvilchunkloaderpending);
} catch (Exception exception) {
Log.severe("Failed to write chunk data to disk " + Log.pos(anvilchunkloaderpending.chunkCoordinate.chunkXPos, anvilchunkloaderpending.chunkCoordinate.chunkZPos));
}
inProgressSaves.remove(hash);
return true;
}
@Override
public void writeChunkNBTTags(AnvilChunkLoaderPending par1AnvilChunkLoaderPending) throws java.io.IOException // CraftBukkit - public -> private, added throws
{
DataOutputStream dataoutputstream = regionFileCache.getChunkOutputStream(par1AnvilChunkLoaderPending.chunkCoordinate.chunkXPos, par1AnvilChunkLoaderPending.chunkCoordinate.chunkZPos);
CompressedStreamTools.write(par1AnvilChunkLoaderPending.nbtTags, dataoutputstream);
dataoutputstream.close();
}
@Override
public void saveExtraChunkData(World par1World, Chunk par2Chunk) {
}
@Override
public void chunkTick() {
}
@Override
public void saveExtraData() {
}
@Override
protected void writeChunkToNBT(Chunk par1Chunk, World par2World, NBTTagCompound par3NBTTagCompound) {
par3NBTTagCompound.setInteger("xPos", par1Chunk.xPosition);
par3NBTTagCompound.setInteger("zPos", par1Chunk.zPosition);
par3NBTTagCompound.setLong("LastUpdate", par2World.getTotalWorldTime());
par3NBTTagCompound.setIntArray("HeightMap", par1Chunk.heightMap);
par3NBTTagCompound.setBoolean("TerrainPopulated", par1Chunk.isTerrainPopulated);
ExtendedBlockStorage[] aextendedblockstorage = par1Chunk.getBlockStorageArray();
NBTTagList nbttaglist = new NBTTagList("Sections");
boolean flag = !par2World.provider.hasNoSky;
int i = aextendedblockstorage.length;
NBTTagCompound nbttagcompound1;
for (int j = 0; j < i; ++j) {
ExtendedBlockStorage extendedblockstorage = aextendedblockstorage[j];
if (extendedblockstorage != null) {
nbttagcompound1 = new NBTTagCompound();
nbttagcompound1.setByte("Y", (byte) (extendedblockstorage.getYLocation() >> 4 & 255));
nbttagcompound1.setByteArray("Blocks", extendedblockstorage.getBlockLSBArray());
if (extendedblockstorage.getBlockMSBArray() != null) {
nbttagcompound1.setByteArray("Add", extendedblockstorage.getBlockMSBArray().getValueArray()); // Spigot
}
nbttagcompound1.setByteArray("Data", extendedblockstorage.getMetadataArray().getValueArray()); // Spigot
nbttagcompound1.setByteArray("BlockLight", extendedblockstorage.getBlocklightArray().getValueArray()); // Spigot
if (flag) {
nbttagcompound1.setByteArray("SkyLight", extendedblockstorage.getSkylightArray().getValueArray()); // Spigot
} else {
nbttagcompound1.setByteArray("SkyLight", new byte[extendedblockstorage.getBlocklightArray().getValueArray().length]); // Spigot
}
nbttaglist.appendTag(nbttagcompound1);
}
}
par3NBTTagCompound.setTag("Sections", nbttaglist);
par3NBTTagCompound.setByteArray("Biomes", par1Chunk.getBiomeArray());
par1Chunk.hasEntities = false;
NBTTagList nbttaglist1 = new NBTTagList();
Iterator iterator;
for (i = 0; i < par1Chunk.entityLists.length; ++i) {
iterator = par1Chunk.entityLists[i].iterator();
while (iterator.hasNext()) {
Entity entity = (Entity) iterator.next();
nbttagcompound1 = new NBTTagCompound();
try {
if (entity.addEntityID(nbttagcompound1)) {
par1Chunk.hasEntities = true;
nbttaglist1.appendTag(nbttagcompound1);
}
} catch (Throwable t) {
if (t instanceof RuntimeException && t.getMessage().contains("missing a mapping")) {
continue;
}
FMLLog.log(Level.SEVERE, t,
"An Entity type %s at %s,%f,%f,%f has thrown an exception trying to write state. It will not persist. Report this to the mod author",
entity.getClass().getName(),
Log.name(entity.worldObj),
entity.posX, entity.posY, entity.posZ); // MCPC+ - add location
}
}
}
par3NBTTagCompound.setTag("Entities", nbttaglist1);
NBTTagList nbttaglist2 = new NBTTagList();
iterator = par1Chunk.chunkTileEntityMap.values().iterator();
while (iterator.hasNext()) {
TileEntity tileentity = (TileEntity) iterator.next();
nbttagcompound1 = new NBTTagCompound();
try {
tileentity.writeToNBT(nbttagcompound1);
nbttaglist2.appendTag(nbttagcompound1);
} catch (Throwable t) {
if (t instanceof RuntimeException && t.getMessage().contains("missing a mapping")) {
continue; // TODO: Reset block to air? Recreate TE on next load?
}
FMLLog.log(Level.SEVERE, t,
"A TileEntity type %s at %s,%d,%d,%d has throw an exception trying to write state. It will not persist. Report this to the mod author",
tileentity.getClass().getName(),
Log.name(tileentity.worldObj),
tileentity.xCoord, tileentity.yCoord, tileentity.zCoord); // MCPC+ - add location
}
}
par3NBTTagCompound.setTag("TileEntities", nbttaglist2);
List list = par1Chunk.pendingBlockUpdates;
if (list != null) {
long k = par2World.getTotalWorldTime();
NBTTagList nbttaglist3 = new NBTTagList();
for (final Object aList : list) {
NextTickListEntry nextticklistentry = (NextTickListEntry) aList;
NBTTagCompound nbttagcompound2 = new NBTTagCompound();
nbttagcompound2.setInteger("i", nextticklistentry.blockID);
nbttagcompound2.setInteger("x", nextticklistentry.xCoord);
nbttagcompound2.setInteger("y", nextticklistentry.yCoord);
nbttagcompound2.setInteger("z", nextticklistentry.zCoord);
nbttagcompound2.setInteger("t", (int) (nextticklistentry.scheduledTime - k));
nbttagcompound2.setInteger("p", nextticklistentry.field_82754_f);
nbttaglist3.appendTag(nbttagcompound2);
}
par3NBTTagCompound.setTag("TileTicks", nbttaglist3);
}
}
@Override
protected Chunk readChunkFromNBT(World world, NBTTagCompound nbtTagCompound) {
int i = nbtTagCompound.getInteger("xPos");
int j = nbtTagCompound.getInteger("zPos");
Chunk chunk = new Chunk(world, i, j);
chunk.heightMap = nbtTagCompound.getIntArray("HeightMap");
chunk.isTerrainPopulated = nbtTagCompound.getBoolean("TerrainPopulated");
NBTTagList nbttaglist = nbtTagCompound.getTagList("Sections");
byte b0 = 16;
ExtendedBlockStorage[] aextendedblockstorage = new ExtendedBlockStorage[b0];
boolean flag = !world.provider.hasNoSky;
for (int k = 0; k < nbttaglist.tagCount(); ++k) {
NBTTagCompound nbttagcompound1 = (NBTTagCompound) nbttaglist.tagAt(k);
byte b1 = nbttagcompound1.getByte("Y");
ExtendedBlockStorage extendedblockstorage = new ExtendedBlockStorage(b1 << 4, flag);
extendedblockstorage.setBlockLSBArray(nbttagcompound1.getByteArray("Blocks"));
if (nbttagcompound1.hasKey("Add")) {
extendedblockstorage.setBlockMSBArray(new NibbleArray(nbttagcompound1.getByteArray("Add"), 4));
}
extendedblockstorage.setBlockMetadataArray(new NibbleArray(nbttagcompound1.getByteArray("Data"), 4));
extendedblockstorage.setBlocklightArray(new NibbleArray(nbttagcompound1.getByteArray("BlockLight"), 4));
if (flag) {
extendedblockstorage.setSkylightArray(new NibbleArray(nbttagcompound1.getByteArray("SkyLight"), 4));
}
extendedblockstorage.removeInvalidBlocks();
aextendedblockstorage[b1] = extendedblockstorage;
}
chunk.setStorageArrays(aextendedblockstorage);
if (nbtTagCompound.hasKey("Biomes")) {
chunk.setBiomeArray(nbtTagCompound.getByteArray("Biomes"));
}
NBTTagList nbttaglist1 = nbtTagCompound.getTagList("Entities");
if (nbttaglist1 != null) {
for (int l = 0; l < nbttaglist1.tagCount(); ++l) {
NBTTagCompound nbttagcompound2 = (NBTTagCompound) nbttaglist1.tagAt(l);
Entity entity = EntityList.createEntityFromNBT(nbttagcompound2, world);
chunk.hasEntities = true;
if (entity != null) {
chunk.addEntity(entity);
for (NBTTagCompound nbttagcompound3 = nbttagcompound2; nbttagcompound3.hasKey("Riding"); nbttagcompound3 = nbttagcompound3.getCompoundTag("Riding")) {
Entity entity2 = EntityList.createEntityFromNBT(nbttagcompound3.getCompoundTag("Riding"), world);
if (entity2 != null) {
chunk.addEntity(entity2);
entity.mountEntity(entity2);
}
}
}
}
}
NBTTagList nbttaglist2 = nbtTagCompound.getTagList("TileEntities");
if (nbttaglist2 != null) {
for (int i1 = 0; i1 < nbttaglist2.tagCount(); ++i1) {
NBTTagCompound nbttagcompound4 = (NBTTagCompound) nbttaglist2.tagAt(i1);
TileEntity tileentity = TileEntity.createAndLoadEntity(nbttagcompound4);
if (tileentity != null) {
chunk.addTileEntity(tileentity);
}
}
}
if (nbtTagCompound.hasKey("TileTicks")) {
NBTTagList nbttaglist3 = nbtTagCompound.getTagList("TileTicks");
if (nbttaglist3 != null) {
for (int j1 = 0; j1 < nbttaglist3.tagCount(); ++j1) {
NBTTagCompound nbttagcompound5 = (NBTTagCompound) nbttaglist3.tagAt(j1);
world.func_82740_a(nbttagcompound5.getInteger("x"), nbttagcompound5.getInteger("y"), nbttagcompound5.getInteger("z"), nbttagcompound5.getInteger("i"), nbttagcompound5.getInteger("t"), nbttagcompound5.getInteger("p"));
}
}
}
return chunk;
}
@Override
@Declare
public void close() {
regionFileCache.close();
}
private static long hash(int x, int z) {
return (((long) x) << 32) | (z & 0xffffffffL);
}
} |
package mjc.analysis;
import mjc.node.EOF;
import mjc.node.Node;
import mjc.node.Start;
import mjc.node.Token;
/**
* Simple visitor to print AST in GraphViz format on standard output.
*/
public class ASTGraphPrinter extends DepthFirstAdapter {
private StringBuilder builder;
public void print(Start tree) {
tree.apply(this);
}
@Override
public void inStart(final Start node) {
builder = new StringBuilder();
builder.append("digraph G {\n");
printNode(node, node.getClass().getSimpleName());
}
@Override
public void outStart(final Start node) {
builder.append("}\n");
System.out.print(builder.toString());
}
@Override
public void defaultIn(final Node node) {
printNode(node, node.getClass().getSimpleName());
}
@Override
public void defaultCase(Node node) {
if (!(node instanceof EOF))
printNode(node, ((Token) node).getText());
}
private void printNode(Node node, String label) {
builder.append(String.format("%s[label=\"%s\"];\n", uniqueName(node), label));
if (node.parent() != null)
printEdge(node.parent(), node);
}
private void printEdge(Node from, Node to) {
builder.append(uniqueName(from) + " -> " + uniqueName(to) + ";\n");
}
private String uniqueName(Node node) {
return node.getClass().getSimpleName() + node.hashCode();
}
} |
package models;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.SortedSet;
import java.util.TreeSet;
import org.json.JSONArray;
import org.json.JSONObject;
import play.Logger;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import controllers.algorithm.pre_and_core.ArcBox;
import controllers.algorithm.pre_and_core.Cal_Depth;
import controllers.algorithm.pre_and_core.CrossLinkedList;
import controllers.algorithm.pre_and_core.NodeInGraph;
import controllers.algorithm.req_and_course.ComplexReq;
import controllers.algorithm.req_and_course.ComplexReq_Node;
import controllers.algorithm.req_and_course.CourseNode;
import controllers.algorithm.req_and_course.Course_LinkList;
import controllers.algorithm.req_and_course.Linklist;
import controllers.algorithm.req_and_course.Node;
import controllers.algorithm.req_and_course.TestLinkList;
public class StudyPlan {
public int redNode = 0;
public TestLinkList degreeProgram;
CrossLinkedList allCross_relation;
Cal_Depth calSemester;
public ArrayList<Integer> courseBin; // Course Info after auto fill course
public Multimap<Integer, Integer> corerequsiteList = ArrayListMultimap.create();
public HashMap<Integer, ArrayList<Integer>> studyplanResult; // Study Plan
// Info
// after
// auto fill
// semester
public void GetCourseMaxDepthInGraph(Cal_Depth calSemester) {
calSemester.allCross_relation_example = allCross_relation;
calSemester.BFS_Max();
// calSemester.BFS_Min();
// calSemester.Display_All_Headnode_Max();
// calSemester.Display_All_Headnode_Min();
return;
}
@SuppressWarnings("unchecked")
public void GetAllCoureReq() {
HashMap<Integer, Integer> tempCoreList = new HashMap<Integer, Integer>();
HashMap<Integer, Integer> tempCoreList2 = new HashMap<Integer, Integer>();
HashMap<Integer, Integer> tempCoreList3 = new HashMap<Integer, Integer>();
HashMap<Integer, Integer> tempCoreList4 = new HashMap<Integer, Integer>();
Multimap<Integer, Integer> tempCoreList5 = ArrayListMultimap.create();
tempCoreList = allCross_relation.TraverCore();
// allCross_relation.DisplayCore(tempCoreList);
tempCoreList2 = (HashMap<Integer, Integer>) tempCoreList.clone();
tempCoreList3 = (HashMap<Integer, Integer>) tempCoreList.clone();
for (Integer key1 : tempCoreList2.keySet()) {
if (tempCoreList2.get(key1) < 0) {// get value. if the value is less
// than 0.
for (Integer key2 : tempCoreList3.keySet()) {
if (key2 == tempCoreList2.get(key1)) {
tempCoreList4.put(key1, tempCoreList3.get(key2));
}
}
} else if (key1 > 0 && tempCoreList2.get(key1) > 0) {
tempCoreList4.put(key1, tempCoreList2.get(key1));
}
}
// tempCoreList5 = (Multimap<Integer, Integer>) tempCoreList4.clone();
for (Integer kk : tempCoreList4.keySet()) {
tempCoreList5.put(kk, tempCoreList4.get(kk));
}
for (Integer kk : tempCoreList4.keySet()) {
tempCoreList5.put(tempCoreList4.get(kk), kk);
}
System.out.println("**************");
//allCross_relation.DisplayCore(tempCoreList5);
this.corerequsiteList = tempCoreList5;
return;
}
public void CreateDegreeProgram(Integer id) {
// boolean chooeseSuccess =false;//
Degree degree = Degree.findById(id);
degreeProgram = new TestLinkList(degree.getTitle()); // add new degree
List<String> complexIds = degree.getReq_ids(); // get Requirement ids
allCross_relation = new CrossLinkedList();
for (String complexId : complexIds) {
try {
Requirement req = Requirement.findById(Integer
.valueOf(complexId)); // get
// Requirement
JSONArray srReqs = new JSONArray(req.getSr_ids());
ComplexReq complexReq = null;
if (srReqs.length() < 2)
complexReq = new ComplexReq(Integer.valueOf(req.getId()),
req.getTitle(), "or");
else
complexReq = new ComplexReq(Integer.valueOf(req.getId()),
req.getTitle(),
(String) ((JSONObject) srReqs.get(1))
.get("relation"));
JSONObject srReqObject = null;
for (int i = 0; i < srReqs.length(); i++) {
srReqObject = (JSONObject) srReqs.get(i);
int srId = srReqObject.getInt("id"); // get Simple
// Requirment
Sr sr = Sr.findById(new Integer(srId));
int cgId = Integer.valueOf(sr.getCg_id());
int reqNum = Integer.valueOf(sr.getRequired_num());
Linklist simpleReq = find_or_create_simpleReq(srId,
sr.getTitle(), reqNum); // initiate
// simple
// requirement
Cg cg = Cg.findById(new Integer(cgId));
List<String> courseIds = cg.getCourse_ids();
for (String courseId : courseIds) {
addCourse(simpleReq, Integer.valueOf(courseId)); // add
// course
add2Course_List2(complexReq, simpleReq,
Integer.valueOf(courseId));
}
complexReq.insertSimple(simpleReq);
degreeProgram.course_list.add(simpleReq);
}
degreeProgram.addComplexReq(complexReq);
} catch (Exception e) {
e.printStackTrace();
}
}
createCrossLinkedList(degreeProgram.course);
GetAllCoureReq();
// degreeProgram.displayAllCourse();
// allCross_relation.Display_All_Headnode();
// degreeProgram.displayallComplexReq();
// degreeProgram.displayCourseList();
// degreeProgram.displayAllCourse();
// TestLinkList degreeProgram =new TestLinkList("degreeName1"); //need
// degreeName input
// ComplexReq complexReq1 = new ComplexReq(1,"complexReq1","or");
// Linklist simpleReq1 = new Linklist(1,"simpleReq1",15);
// //req1 -> course1->course2
// addCourse(degreeProgram, simpleReq1, 100);
// //req1 -> course1->course2
// addCourse(degreeProgram, simpleReq1, 200);
// addCourse(degreeProgram, simpleReq1, 300);
// addCourse(degreeProgram, simpleReq1, 400);
// addCourse(degreeProgram, simpleReq1, 500);
// addCourse(degreeProgram, simpleReq1, 600);
// complexReq1.insertSimple(simpleReq1);
// degreeProgram.addComplexReq(complexReq1);
// degreeProgram.course_list.add(simpleReq1);
// degreeProgram.displayallComplexReq();
// //course1 -> req1 ->re2
// add2Course_List2(degreeProgram, simpleReq1,100);
// add2Course_List2(degreeProgram, simpleReq1,200);
// add2Course_List2(degreeProgram, simpleReq1,300);
// add2Course_List2(degreeProgram, simpleReq1,400);
// add2Course_List2(degreeProgram, simpleReq1,500);
// add2Course_List2(degreeProgram, simpleReq1,600);
// degreeProgram.displayCourseList();
// mark student's chosen course
// boolean chooeseSuccess = degreeProgram.checkCourseIn_ReqList(10,108);
// if(chooeseSuccess){
// degreeProgram.displayallComplexReq();
// degreeProgram.displayCourseList();
// 74,84,85,86,87,88,89,90,92,93,94,95,96,97,98
// CheckInSelectedCourse(degreeProgram, 17, 7, 74);
// CheckInSelectedCourse(degreeProgram, 17, 7, 84);
// CheckInSelectedCourse(degreeProgram, 17, 7, 85);
// CheckInSelectedCourse(degreeProgram, 17, 7, 86);
// CheckInSelectedCourse(degreeProgram, 17, 7, 87);
// CheckInSelectedCourse(degreeProgram, 17, 7, 88);
// CheckInSelectedCourse(degreeProgram, 17, 7, 89);
// CheckInSelectedCourse(degreeProgram, 17, 7, 90);
// CheckInSelectedCourse(degreeProgram, 17, 7, 92);
// CheckInSelectedCourse(degreeProgram, 17, 7, 93);
// CheckInSelectedCourse(degreeProgram, 17, 7, 94);
// CheckInSelectedCourse(degreeProgram, 17, 7, 95);
// CheckInSelectedCourse(degreeProgram, 17, 7, 96);
// CheckInSelectedCourse(degreeProgram, 17, 7, 97);
// CheckInSelectedCourse(degreeProgram, 17, 7, 98);
// correct
// CheckInSelectedCourse(degreeProgram, 20, 10, 106);
// CheckInSelectedCourse(degreeProgram, 20, 10, 107);
// CheckInSelectedCourse(degreeProgram, 20, 10, 108);
// 1 of 2 in simple, 2 of 2 simple
// CheckInSelectedCourse(degreeProgram, 22, 17, 189);
// CheckInSelectedCourse(degreeProgram, 22, 17, 133);
// CheckInSelectedCourse(degreeProgram, 22, 18, 190);
// CheckInSelectedCourse(degreeProgram, 22, 17, 189);
// CheckInSelectedCourse(degreeProgram, 22, 17, 133);
// CheckInSelectedCourse(degreeProgram, 22, 16, 120);
// CheckInSelectedCourse(degreeProgram, 22, 16, 118);
// CheckInSelectedCourse(degreeProgram, 23, 19, 164);
// CheckInSelectedCourse(degreeProgram, 23, 19, 102);
// degreeProgram.CheckAllSimpleAndComplex();
// System.out.print("Before AutoFill:");
// degreeProgram.displayallComplexReq();
// degreeProgram.displayCourseList();
// System.out.print("\n");
// System.out.print("After AutoFill: \n");
// degreeProgram.displayallComplexReq();
// degreeProgram.displayCourseList();
// allCross_relation.Display_All_Headnode();
// allCross_relation.displayCrossLinkedList();
play.Logger.info("================================================");
}
public void addCourse(Linklist simpleReq1, int courseID) {
// System.out.println(ifCourseExist);
// System.out.println("OK");
Node newNode = new Node(courseID);
if (degreeProgram.course.containsKey(courseID)) {
degreeProgram.course.get(courseID).add(newNode);
} else {
ArrayList<Node> clist = new ArrayList<Node>();
clist.add(newNode);
degreeProgram.course.put(courseID, clist);
}
simpleReq1.insertNode(newNode);
return;
}
public void createCrossLinkedList(
HashMap<Integer, ArrayList<Node>> course_list) {
/**
* @author tongrui function: construct the crosslist
*/
allCross_relation.addAllCourseInGraph(course_list);
for (Entry<Integer, ArrayList<Node>> entry : course_list.entrySet()) {
int courseID = entry.getKey();
Course course = Course.findById(entry.getKey());
String prereq = course.getPrereq(2);
String coreq = course.getCoreq(2);
if (!prereq.trim().equals("-")) {
String[] prelist = prereq.split(" ");
if (prelist.length - 2 == 1) {
allCross_relation.setArcBox(Integer.valueOf(prelist[2]),
courseID, 1);
} else if (prelist.length - 2 == 3) {
if (prelist[3].equals(",")) {
allCross_relation.setArcBox(
Integer.valueOf(prelist[2]), courseID, 1);
allCross_relation.setArcBox(
Integer.valueOf(prelist[4]), courseID, 1);
} else if (prelist[3].equals("or")) {
allCross_relation.addCourse(--redNode);
allCross_relation.setArcBox(
Integer.valueOf(prelist[2]), redNode, 3);
allCross_relation.setArcBox(
Integer.valueOf(prelist[4]), redNode, 3);
allCross_relation.setArcBox(redNode, courseID, 1);
}
} else if (prelist.length - 2 == 5) {
if (prelist[3].equals(",")) {
allCross_relation.setArcBox(
Integer.valueOf(prelist[2]), courseID, 1);
allCross_relation.setArcBox(
Integer.valueOf(prelist[4]), courseID, 1);
if (prelist[5].equals("or")) {
// issue
} else if (prelist[5].equals(",")) {
allCross_relation.setArcBox(
Integer.valueOf(prelist[6]), courseID, 1);
}
} else if (prelist[3].equals("or")) {
allCross_relation.addCourse(--redNode);
allCross_relation.setArcBox(
Integer.valueOf(prelist[2]), redNode, 3);
allCross_relation.setArcBox(
Integer.valueOf(prelist[4]), redNode, 3);
allCross_relation.setArcBox(redNode, courseID, 1);
if (prelist[5].equals("or")) {
allCross_relation.setArcBox(
Integer.valueOf(prelist[6]), redNode, 3);
allCross_relation.setArcBox(redNode, courseID, 3);
} else if (prelist[5].equals(",")) {
allCross_relation.setArcBox(
Integer.valueOf(prelist[6]), courseID, 1);
}
}
}
}
if (!coreq.trim().equals("-")) {
String[] colist = coreq.split(" ");
if (colist.length - 2 == 1) {
allCross_relation.setArcBox(Integer.valueOf(colist[2]),
courseID, 2);
} else if (colist.length - 2 == 3) {
if (colist[3].equals(",")) {
allCross_relation.setArcBox(Integer.valueOf(colist[2]),
courseID, 2);
allCross_relation.setArcBox(Integer.valueOf(colist[4]),
courseID, 2);
} else if (colist[3].equals("or")) {
allCross_relation.addCourse(--redNode);
allCross_relation.setArcBox(Integer.valueOf(colist[2]),
redNode, 3);
allCross_relation.setArcBox(Integer.valueOf(colist[4]),
redNode, 3);
allCross_relation.setArcBox(redNode, courseID, 2);
}
} else if (colist.length - 2 == 5) {
if (colist[3].equals(",")) {
allCross_relation.setArcBox(Integer.valueOf(colist[2]),
courseID, 2);
allCross_relation.setArcBox(Integer.valueOf(colist[4]),
courseID, 2);
if (colist[5].equals("or")) {
// issue
} else if (colist[5].equals(",")) {
allCross_relation.setArcBox(
Integer.valueOf(colist[6]), courseID, 2);
}
} else if (colist[3].equals("or")) {
allCross_relation.addCourse(--redNode);
allCross_relation.setArcBox(Integer.valueOf(colist[2]),
redNode, 3);
allCross_relation.setArcBox(Integer.valueOf(colist[4]),
redNode, 3);
allCross_relation.setArcBox(redNode, courseID, 2);
if (colist[5].equals("or")) {
allCross_relation.setArcBox(
Integer.valueOf(colist[6]), redNode, 3);
allCross_relation.setArcBox(redNode, courseID, 3);
} else if (colist[5].equals(",")) {
allCross_relation.setArcBox(
Integer.valueOf(colist[6]), courseID, 2);
}
}
}
}
}
// allCross_relation.displayCrossLinkedList();
allCross_relation.removeAloneNode();
}
public void add2Course_List2(ComplexReq complexReq, Linklist simpleReq1,
int courseID) {
boolean ifCourseExist = degreeProgram
.prepareInsertCourseLinkList(courseID);
if (ifCourseExist) {
int simpleReqName = simpleReq1.first.cName;
int complexReqID = complexReq.first.ComplexReq_Id;
CourseNode ReqInfo = new CourseNode(simpleReqName, complexReqID);
for (int i = 0; i < degreeProgram.course_list2.size(); i++) {
if (courseID == degreeProgram.course_list2.get(i).first.rName) {
degreeProgram.course_list2.get(i).insertNode(ReqInfo);
}
}
} else {
Course_LinkList courseNode = new Course_LinkList(courseID);
int simpleReqName = simpleReq1.first.cName;
int complexReqID = complexReq.first.ComplexReq_Id;
CourseNode ReqInfo = new CourseNode(simpleReqName, complexReqID);
courseNode.insertNode(ReqInfo);
degreeProgram.addReq2List(courseNode);
}
}
public Linklist find_or_create_simpleReq(int srId, String srTitle,
int reqNum) {
boolean simpleReqExist = degreeProgram.prepareInsertSimple(srId);
if (simpleReqExist) {
int i = 0;
for (; i < degreeProgram.course_list.size(); i++) {
if (srId == degreeProgram.course_list.get(i).first.cName)
break;
}
return degreeProgram.course_list.get(i);
} else {
Linklist simpleReq = new Linklist(srId, srTitle, reqNum);
return simpleReq;
}
}
public void CheckInSelectedCourse(int complexID, int simpleID, int courseID) {
for (int i = 0; i < degreeProgram.allComplexReq.size(); i++) {
if (degreeProgram.allComplexReq.get(i).first.ComplexReq_Id == complexID) {
ComplexReq complexReq = degreeProgram.allComplexReq.get(i);
if (!complexReq.isNull()) { // if this complex has simples in it
for (int j = 0; j < degreeProgram.course_list.size(); j++) {
if (degreeProgram.course_list.get(j).first.cName == simpleID) {
degreeProgram.checkCourseIn_ReqList(simpleID,
courseID);
for (int k = 0; k < allCross_relation.headNodeList
.size(); k++) {
if (allCross_relation.headNodeList.get(k).courseID == courseID) {
allCross_relation.headNodeList.get(k).assign = true;
break;
}
}
}
}
}
}
}
}
public ArrayList<Integer> AutoFillCourseBin() { // change the arguments and
// recursively call this
// function
calSemester = new Cal_Depth();
calSemester.allCross_relation_example = allCross_relation;
ArrayList<Integer> courseBinResult = new ArrayList<Integer>();
GetCourseMaxDepthInGraph(calSemester); // mark the min and max in
// nodeInGraph
for (int i = 0; i < calSemester.allCross_relation_example.headNodeList
.size(); i++) {
// node
// graph
// find
// all
// value
NodeInGraph courseInGraph = calSemester.allCross_relation_example.headNodeList
.get(i);
for (Integer key : degreeProgram.course.keySet()) {
if (degreeProgram.course.get(key).get(0).cName == courseInGraph.courseID) {// update
// course
// both
// requirement
// and
// graph
ArrayList<Node> sameCourseList = degreeProgram.course
.get(key);
for (Node course : sameCourseList) {
course.maxDepth = courseInGraph.maxDepth;
// course.minDepth = courseInGraph.minDepth;
}
}
}
}
for (int i = 0; i < degreeProgram.allComplexReq.size(); i++) {
ComplexReq complexReq = degreeProgram.allComplexReq.get(i);
if (complexReq.first.satisfied == true) {
continue;// check next complex requirement
} else {
ComplexReq_Node simpleReq = complexReq.first.next;// find all
// unsatisfied
// complex
// requirement,
// fetch its
// simple
// requirement
while (simpleReq != null) {// as long as the simple is not null
if (simpleReq.SimpleReq.first.statisfied == true) {
// do nothing and check next simple requirement
} else {
// add a function to sort as semester as ascending
Node course = simpleReq.SimpleReq.first.next;// each
// course
// simple
// requirement
// HashMap<Integer, Node> courseHash = new
// HashMap<Integer, Node>();
HashMap<Integer, ArrayList<Node>> courseHash = new HashMap<Integer, ArrayList<Node>>();
SortedSet<Integer> courseOrderByMaxDepth = new TreeSet<Integer>();// each
// simple
// requirement
// has
// sortedset
// stores
// courses
// maxDepth
while (course != null) {
if (!courseHash.containsKey(course.maxDepth)) {
courseOrderByMaxDepth.add(course.maxDepth);
ArrayList<Node> alist = new ArrayList<Node>();
alist.add(course);
courseHash.put(course.maxDepth, alist);
} else {
ArrayList<Node> alist = courseHash
.get(course.maxDepth);
alist.add(course);
courseHash.put(course.maxDepth, alist);
}
course = course.next;
}
int maxMaxDepth = courseOrderByMaxDepth.last();
if (maxMaxDepth == 0) {
// all course in this simple requirement has no pre
// and core relation
FillNonePreCoreReq(complexReq, simpleReq.SimpleReq,
courseBinResult);
} else {
// the course in this simple requirement has pre and
// core relation
// test use:
// simpleReq.SimpleReq.first.statisfied=true;
// simpleReq.SimpleReq.first.needFinish--;
for (Entry<Integer, ArrayList<Node>> entry : courseHash
.entrySet()) {
int key = entry.getKey();
ArrayList<Node> courseNodeList = entry
.getValue();
// System.out.print("The maxDepth is " + key
// + " include these courses: \n");
for (Node courseNode : courseNodeList) {
if (complexReq.first.satisfied == false) {
// System.out.print("Output course: "
// + courseNode.cName + " ");
ArrayList<Integer> courseList = new ArrayList<Integer>(); // store
// its
// pre
// core
backtrackCourse(courseNode.cName,
courseList);
RemoveTheLastCourseItSelf(courseList);
RemoveTheRedInRelatedCourseList(courseList);
for (Integer needToBeSelectedCourse : courseList) {
// if(degreeProgram.course.containsKey(needToBeSelectedCourse)){
for (Linklist assignSimple : degreeProgram.course_list) {
if (degreeProgram
.checkCourseIn_ReqList(
assignSimple.first.cName,
courseNode.cName)) {
degreeProgram
.CheckAllSimpleAndComplex();
break;
}
}
boolean f = false;
for (int ii = 0; ii < courseBinResult
.size(); ii++) {
if (needToBeSelectedCourse
.compareTo(courseBinResult
.get(ii)) == 0) {
f = true;
}
}
if (!f)
courseBinResult
.add(needToBeSelectedCourse);
degreeProgram.CheckAllSimpleAndComplex();
}
degreeProgram
.checkCourseIn_ReqList(
simpleReq.SimpleReq.first.cName,
courseNode.cName);
degreeProgram
.CheckAllSimpleAndComplex();
boolean f = false;
for (int ii = 0; ii < courseBinResult
.size(); ii++) {
if (Integer.valueOf(
courseNode.cName)
.compareTo(
courseBinResult
.get(ii)) == 0) {
f = true;
}
}
if (!f)
courseBinResult.add(courseNode.cName);
}
}
}
}
}
// update/check complex requirement
degreeProgram.CheckAllSimpleAndComplex();
simpleReq = simpleReq.next;
}
}
}
// for (Integer id : courseBinResult) {
// Logger.info(id + " ");
// System.out.print(id + " ");
for (Integer id : degreeProgram.course.keySet()) {
ArrayList<Node> temp = degreeProgram.course.get(id);
Node tempNode = temp.get(0);
if (tempNode.chosen == true
&& !courseBinResult.contains(tempNode.cName)) {
courseBinResult.add(tempNode.cName);
}
}
// System.out.print("\n");
courseBin = courseBinResult;
return courseBinResult;
}
public void changeCourseStatus(){
for(Integer key : degreeProgram.course.keySet()){
ArrayList<Node> eachCourseInstance = degreeProgram.course.get(key);
for(Node oneInstance : eachCourseInstance){
if(oneInstance.chosen==true){
if(eachCourseInstance.get(0).chosen==false){
eachCourseInstance.get(0).chosen=true;
}
}
}
}
return;
}
public void setAssignSemester(String semesterData, HashMap<Integer, ArrayList<Node>> courseInHash, HashMap<Integer, ArrayList<Integer>> result) {
/**
* @author tongrui assign semester to back end
*/
if (semesterData.equals("[]"))
return;
try {
JSONArray semesterArray = new JSONArray(semesterData);
for (int i = 0; i < semesterArray.length(); i++) {
JSONObject semester = (JSONObject) semesterArray.get(i);
int semesterNum = semester.getInt("num");
JSONArray courses = (JSONArray) semester.get("courses");
result.put(semesterNum, new ArrayList<Integer>());
for (int j = 0; j < courses.length(); j++) {
int courseID = courses.getInt(j);
result.get(semesterNum).add(courseID);
ArrayList<Node> nodes = courseInHash.get(courseID);
for (Node node : nodes) {
node.semester = semesterNum;
}
}
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public HashMap<Integer, ArrayList<Integer>> AutoAssignSemester(int numOfSemester, String semesterData) {
HashMap<Integer, ArrayList<Node>> courseInHash = degreeProgram.course;
//degreeProgram.displayAllCourse();
// courses in each level
HashMap<Integer, ArrayList<Node>> semesterBin = new HashMap<Integer, ArrayList<Node>>();
// semester=>[courseID,courseID,courseID]
HashMap<Integer, ArrayList<Integer>> result = new HashMap<Integer, ArrayList<Integer>>();
// set student-specific semesters
//setAssignSemester(semesterData, courseInHash, result);
// initiate the courses, assign the courses with the semester which the
// student has choose.
JSONArray semesterJsonArray;
HashMap<Integer, Integer> courseCountInSemester = new HashMap<Integer, Integer>();
try {
semesterJsonArray = new JSONArray(semesterData);
for(int i=0;i<semesterJsonArray.length();i++){
JSONObject semester = (JSONObject) semesterJsonArray.get(i);
JSONArray courses = (JSONArray) semester.get("courses");
//Bowen: recored course count in per semester
courseCountInSemester.put(semester.getInt("num"), courses.length());
for(int j=0;j<courses.length();j++){
int id= courses.getInt(j);
courseInHash.get(id).get(0).semester=semester.getInt("num");
}
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int max = 0;
for (int i = 0; i < courseBin.size(); i++) {
for (Integer key : courseInHash.keySet()) {
if (courseBin.get(i).compareTo(key) == 0) {
Node temp = courseInHash.get(key).get(0);
if (max <= temp.maxDepth)
max = temp.maxDepth;
// semesterBin.put(temp.maxDepth,temp);
if (semesterBin.containsKey(temp.maxDepth)) { // if this
// semester
// exist
ArrayList<Node> alist = semesterBin.get(temp.maxDepth);
alist.add(temp);
semesterBin.put(temp.maxDepth, alist);
} else {
ArrayList<Node> alist = new ArrayList<Node>();
alist.add(temp);
semesterBin.put(temp.maxDepth, alist);
}
}
}
}
int courseInSemester = courseBin.size() / numOfSemester + 1;
// record the number of courses already in the semester
Map<Integer, Integer> numOfCourseInSemester = new HashMap<Integer, Integer>();
int level = max;
int curSemester = numOfSemester;
int hhhhh = -1;
while (level >= 0 && curSemester > 0) {
ArrayList<Node> courseInSameLvl = semesterBin.get(level);// get the
// courses
// this
// level
// depth
int num = courseInSemester;// record how many courses remain in one
// semester
num -= courseCountInSemester.get(curSemester);
int lvlRemainCourse = courseInSameLvl.size();// record how many
// courses remain in
// this level of
// depth
// mark the course with semester
for (int i = 0; i < courseInSameLvl.size() && num > 0; i++) {
// check the if the course has already been assigned with a
// semester.
if (courseInSameLvl.get(i).semester != -1) {
// -1 is the default number of semester,
// if course has been assigned with a semester, then do
// nothing continue the loop
lvlRemainCourse
continue;
}
// if the course has not been assigned
int tempt = courseInSameLvl.get(i).cName;
if (corerequsiteList.containsKey(Integer.valueOf(tempt))) {
courseInSameLvl.get(i).semester = curSemester; // assign the
// current
// semester
// to the
// course
num
num = BacktrackCore(courseInHash, courseInSameLvl.get(i).cName, curSemester, num);
// ArrayList<Integer> coreqs=(ArrayList<Integer>)
// corerequsiteList.get(courseInSameLvl.get(i).cName);
// for(Integer coreq:coreqs){
// for(int n = 0 ;n<courseBin.size();n++){
// if(courseInHash.get(coreq).get(0).cName==courseBin.get(n)){
// courseInHash.get(coreq).get(0).semester=curSemester;
// num--;
// //corequisite.
} else {
courseInSameLvl.get(i).semester = curSemester;
lvlRemainCourse
num
}
}
numOfCourseInSemester.put(curSemester, num);
// hhhhh = lvlRemainCourse;
if (lvlRemainCourse == 0) {
level
}
if (num < 6)
curSemester
}
for (int i = 1; i <= numOfCourseInSemester.size(); i++) {
int remainCourse = numOfCourseInSemester.get(i);
if (numOfCourseInSemester.get(i) > 0) {
ArrayList<Node> courseWithoutReq = semesterBin.get(0);
for (int j = 0; j < courseWithoutReq.size() && remainCourse > 0; j++) {
if (courseWithoutReq.get(j).semester == -1) {
courseWithoutReq.get(j).semester = i;
remainCourse
}
}
}
numOfCourseInSemester.put(i, remainCourse);
}
// for (Integer key : numOfCourseInSemester.keySet()) {
// + numOfCourseInSemester.get(key) + " size remain ");
// for (Integer key : semesterBin.keySet()) {
// System.out.print("The semester " + key + " is \n");
// ArrayList<Node> tempNodeList = semesterBin.get(key);
// for (Node course : tempNodeList) {
// System.out.print(course.cName + "\n");
for (Integer key : semesterBin.keySet()) {
ArrayList<Node> temp = semesterBin.get(key);
for (Node course : temp) {// get each course
if (result.containsKey(course.semester)) {
ArrayList<Integer> thisSemester = result
.get(course.semester);
thisSemester.add(Integer.valueOf(course.cName));
result.put(course.semester, thisSemester);
} else {
ArrayList<Integer> thisNewSemester = new ArrayList<Integer>();
thisNewSemester.add(Integer.valueOf(course.cName));
result.put(course.semester, thisNewSemester);
}
}
}
for (Integer key : result.keySet()) {
ArrayList<Integer> courseInSameSemester = result.get(key);
System.out.print("In semester " + key + ", there are ");
for (Integer courseId : courseInSameSemester) {
System.out.print(courseId + " ");
}
System.out.print("\n");
}
studyplanResult = result;
return result;
}
public int BacktrackCore(HashMap<Integer, ArrayList<Node>> courseInHash, Integer courseID, int currentSemester, int num) {
// course.semester = currentSemester;// assign the current semester to
// the course
// num--;
Integer[] coreqs = corerequsiteList.get(courseID).toArray(new Integer[0]);
for (Integer coreq : coreqs) {
if (courseInHash.containsKey(coreq)) {
if (courseInHash.get(coreq).get(0).semester != -1)
continue;
for (int n = 0; n < courseBin.size(); n++) {
if (coreq.equals(courseBin.get(n))) {
courseInHash.get(coreq).get(0).semester = currentSemester;
num
num = BacktrackCore(courseInHash, coreq, currentSemester, num);
// corequisite.
}
}
}
}
return num;
}
public void FillNonePreCoreReq(ComplexReq complexReq, Linklist simpleReq, ArrayList<Integer> courseBinResult) {
Node course = null;
Linklist tempSimple = null;
ComplexReq tempComplex = null;
for (Linklist simpleRequirement : degreeProgram.course_list) {
if (simpleRequirement.first.cName == simpleReq.first.cName) {
course = simpleRequirement.first.next;
tempSimple = simpleRequirement;
break;
}
}
for (ComplexReq complexRequirement : degreeProgram.allComplexReq) {
if (complexRequirement.first.ComplexReq_Id == complexReq.first.ComplexReq_Id) {
tempComplex = complexRequirement;
break;
}
}
while (course != null && course.chosen == false && tempSimple.first.statisfied == false && tempComplex.first.satisfied == false) {
degreeProgram.checkCourseIn_ReqList(tempSimple.first.cName, course.cName); // mark
// this
// course
// true
// the
// simple
degreeProgram.CheckAllSimpleAndComplex();
courseBinResult.add(course.cName);
course = course.next;
}
return;
}
// public void ShowRelatedCourse(ArrayList<Integer> pre_and_core) {
// for (int i = 0; i < pre_and_core.size(); i++) {
// System.out.print(pre_and_core.get(i) + "\n");
public ArrayList<Integer> RemoveTheLastCourseItSelf(
ArrayList<Integer> courseList) {
if (courseList.size() == 0) {
} else {
courseList.remove(courseList.size() - 1);
}
return courseList;
}
public ArrayList<Integer> RemoveTheRedInRelatedCourseList(
ArrayList<Integer> pre_and_core) {
for (int i = 0; i < pre_and_core.size(); i++) {
if (pre_and_core.get(i) < 0) {
pre_and_core.remove(i);
}
}
return pre_and_core;
}
public void backtrackCourse(int courseID, ArrayList<Integer> courseList) { // given
// course
// name
CrossLinkedList cr = allCross_relation;
int size = cr.headNodeList.size();
ArcBox tempArc = new ArcBox();
NodeInGraph tempNode = new NodeInGraph();
// int i = 0, j = 0; //
for (int i = 0; i < size; i++) {
tempNode = cr.headNodeList.get(i);
if (tempNode.courseID == courseID) {// headnode
tempArc = tempNode.firstIn;
for (; tempArc != null; tempArc = tempArc.hlink) {
int relation_type = tempArc.info;
int tempTailCourseID = tempArc.tailCourseID;
if (relation_type == 3) {
for (int j = 0; j < size; j++) { // for
// looptempNodeheadnodelist
NodeInGraph tempNode2 = cr.headNodeList.get(j);
if (tempNode2.courseID == tempTailCourseID) { // for
// loopif
if (tempNode2.finished) {// ,for
break;
} else if (tempNode2.finished == false
&& tempNode2.visited == true) { // mark
backtrackCourse(tempNode2.courseID,
courseList);
} else { // tempNode2.finished == false &&
// tempNode2.visited == true
tempNode2.visited = true; // mark
backtrackCourse(tempNode2.courseID,
courseList);
}
}
}
break;
} else {
for (int j = 0; j < size; j++) { // for
// looptempNodeheadnodelist
NodeInGraph tempNode2 = cr.headNodeList.get(j);
if (tempNode2.courseID == tempTailCourseID) { // for
// loopif
if (tempNode2.finished) {// ,for
break;
} else if (tempNode2.finished == false
&& tempNode2.visited == true) { // mark
backtrackCourse(tempNode2.courseID,
courseList);
} else { // tempNode2.finished == false &&
// tempNode2.visited == true
tempNode2.visited = true; // mark
backtrackCourse(tempNode2.courseID,
courseList);
}
}
}
}
}
tempNode.finished = true; // finished=true;
tempNode.visited = true;
courseList.add(tempNode.courseID);
// System.out.print(tempNode.courseID + " ");
// System.out.println();
return;
}
}
// System.out.print("Cannot find selected course in headnodelist!");
return;
}
} |
package com.hacktoolkit.android.utils;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.res.AssetFileDescriptor;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import com.hacktoolkit.android.adapters.HTKContactsAdapter;
import com.hacktoolkit.android.models.HTKContact;
public class ContactsUtils {
/**
* Wrapper for getContactsWithPhone to offload the work from the main UI activity thread and do it asynchronously
*
* @param currentActivity
* @param adapter the adapter to populate when contacts have been loaded
*/
public static void getContactsWithPhoneAsync(final Activity currentActivity, final HTKContactsAdapter adapter) {
AsyncTask<Void, Void, ArrayList<HTKContact>> getContactsAsyncTask = new AsyncTask<Void, Void, ArrayList<HTKContact>>() {
@Override
protected ArrayList<HTKContact> doInBackground(Void... v) {
ArrayList<HTKContact> resultContacts = ContactsUtils.getContactsWithPhone(currentActivity);
return resultContacts;
}
@Override
protected void onPostExecute(ArrayList<HTKContact> resultContacts) {
adapter.loadContacts(resultContacts);
}
};
getContactsAsyncTask.execute();
}
public static ArrayList<HTKContact> getContactsWithPhone(Activity currentActivity) {
ContentResolver contentResolver = currentActivity.getContentResolver();
Uri uri = ContactsContract.Contacts.CONTENT_URI;
String[] projection = {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.HAS_PHONE_NUMBER,
ContactsContract.Contacts.STARRED,
ContactsContract.Contacts.TIMES_CONTACTED,
ContactsContract.Contacts.LAST_TIME_CONTACTED,
};
String selection = String.format("%s > 0", ContactsContract.Contacts.HAS_PHONE_NUMBER);
String[] selectionArgs = null;
String sortOrder = String.format(
"%s DESC, %s DESC, %S DESC, UPPER(%s) ASC",
ContactsContract.Contacts.STARRED,
ContactsContract.Contacts.TIMES_CONTACTED,
ContactsContract.Contacts.LAST_TIME_CONTACTED,
ContactsContract.Contacts.DISPLAY_NAME
);
Cursor cursor = contentResolver.query(uri, projection, selection, selectionArgs, sortOrder);
ArrayList<HTKContact> contacts = new ArrayList<HTKContact>();
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
HTKContact contact = new HTKContact();
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String phone = "";
String phoneType = "";
if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
// System.out.println("name : " + name + ", ID : " + id);
String[] phoneData = getPhoneForContactId(contentResolver, contactId);
phone = phoneData[0];
phoneType = phoneData[1];
contact.setData("id", Integer.valueOf(contactId));
contact.setData("name", name);
contact.setData("phone", phone);
contact.setData("phoneType", phoneType);
contacts.add(contact);
}
}
cursor.close();
}
return contacts;
}
public static String[] getPhoneForContactId(ContentResolver contentResolver, String contactId) {
String[] phoneData = null;
Cursor phoneCursor = contentResolver.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[] { contactId },
null
);
String phone = "";
String phoneType = "";
while (phoneCursor.moveToNext()) {
// grab the first phone number
phone = phoneCursor.getString(
phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
phoneType = getPhoneType(phoneCursor);
break;
}
phoneCursor.close();
phoneData = new String[] { phone, phoneType };
return phoneData;
}
public static String getPhoneType(Cursor phoneCursor) {
String phoneType = "";
int type = Integer.parseInt(phoneCursor.getString(
phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE)));
if (type == ContactsContract.CommonDataKinds.Phone.TYPE_CUSTOM) {
phoneType = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.LABEL));
} else {
switch(type) {
case ContactsContract.CommonDataKinds.Phone.TYPE_HOME:
phoneType = "Home";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE:
phoneType = "Mobile";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_WORK:
phoneType = "Work";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_FAX_WORK:
phoneType = "Work Fax";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_FAX_HOME:
phoneType = "Home Fax";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_PAGER:
phoneType = "Pager";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_OTHER:
phoneType = "Other";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_CALLBACK:
phoneType = "Callback";
break;
// other types:
default:
break;
}
}
return phoneType;
}
public static InputStream openPhoto(Activity currentActivity, long contactId) {
if (HTKUtils.getCurrentAPIVersion() < android.os.Build.VERSION_CODES.HONEYCOMB) {
return null;
}
Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId);
Uri photoUri = Uri.withAppendedPath(contactUri, Contacts.Photo.CONTENT_DIRECTORY);
Cursor cursor = currentActivity.getContentResolver().query(photoUri,
new String[] { Contacts.Photo.PHOTO}, null, null, null);
if (cursor == null) {
return null;
}
try {
if (cursor.moveToFirst()) {
byte[] data = cursor.getBlob(0);
if (data != null) {
return new ByteArrayInputStream(data);
}
}
} finally {
cursor.close();
}
return null;
}
public static InputStream openDisplayPhoto(Activity currentActivity, long contactId) {
if (HTKUtils.getCurrentAPIVersion() < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
return null;
}
Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId);
Uri displayPhotoUri = Uri.withAppendedPath(contactUri, Contacts.Photo.DISPLAY_PHOTO);
try {
AssetFileDescriptor fd =
currentActivity.getContentResolver().openAssetFileDescriptor(displayPhotoUri, "r");
return fd.createInputStream();
} catch (IOException e) {
return null;
}
}
} |
package com.newput.utility;
import java.io.File;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import com.newput.domain.Employee;
/**
* {@link}
*
* @author Newput Description : Method use to send email to the registered mail
* id for the verification in this method mailSender variable
* is @Autowired with bean defined in the applicationContext.xml
*/
@Service
public class EMailSender {
@Autowired
private JavaMailSender mailSender;
@Autowired
private Employee emp;
@Autowired
private JsonResService jsonResService;
/**
* Description : Use to send the verification mail to the user for
* registration and password reset.
*
* @param module
* - password or registration
*/
public String sendMail(String module) {
try {
SimpleMailMessage email = new SimpleMailMessage();
email.setTo(emp.getEmail());
email.setSubject("Confirmation Mail");
if (module.equalsIgnoreCase("registration")) {
email.setText("Welcome, You are successfully register Please click here : " + System.getenv("WEBAPP_URL")
+ "/app/verifyuser?EM=" + emp.getEmail() + "&ET=" + emp.getvToken());
} else if (module.equalsIgnoreCase("password")) {
email.setText("Welcome, Please confirm your mail id. click here : " + System.getenv("WEBAPP_URL")
+ "/app/resetpassword?PT=" + emp.getpToken() + "&ID=" + emp.getId());
}
mailSender.send(email);
return null;
} catch (Exception ex) {
return "Email id is not valid to send email.";
}
}
/**
* Description : Use to send the time sheet on the registered mail id.
*
* @param email
* - abc.xyz@newput.com
* @param file
* - excelFile
*/
public String sendExcelSheet(String email, File file, String sheetName) {
if (email != null && !email.equalsIgnoreCase("")) {
try {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setTo(email);
helper.setSubject("Your Time Sheet");
helper.setText("This is your time sheet please check it.");
FileSystemResource fileNew = new FileSystemResource(file.getPath());
helper.addAttachment(sheetName, fileNew);
mailSender.send(message);
jsonResService.setDataValue("Your time sheet succefully send to your registered mail id.", "");
return null;
} catch (MessagingException e) {
return "Your mail is not send please retry";
}
} else {
jsonResService.errorResponse("Your mail id is not valid.");
return "Your mail id is not valid.";
}
}
/**
* Description : Use to send the reminder notification to user to fill the
* time sheet.
*
* @param emp
* - An Object
*/
public void notificationMail(Employee emp) {
SimpleMailMessage email = new SimpleMailMessage();
email.setTo(emp.getEmail());
email.setSubject("Notification Mail");
email.setText("Welcome, Please fill your daily status for today. Please ignore if already filled.");
mailSender.send(email);
}
} |
package org.sugr.gearshift;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.Loader;
import android.text.Html;
import android.text.Spanned;
import android.util.SparseBooleanArray;
import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView.MultiChoiceModeListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.Filter;
import android.widget.Filter.FilterListener;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SearchView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import org.sugr.gearshift.G.FilterBy;
import org.sugr.gearshift.G.SortBy;
import org.sugr.gearshift.G.SortOrder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Locale;
/**
* A list fragment representing a list of Torrents. This fragment
* also supports tablet devices by allowing list items to be given an
* 'activated' state upon selection. This helps indicate which item is
* currently being viewed in a {@link TorrentDetailFragment}.
* <p>
* Activities containing this fragment MUST implement the {@link Callbacks}
* interface.
*/
public class TorrentListFragment extends ListFragment {
/**
* The serialization (saved instance state) Bundle key representing the
* activated item position. Only used on tablets.
*/
private static final String STATE_ACTIVATED_POSITION = "activated_position";
private static final String STATE_FIND_SHOWN = "find_shown";
private static final String STATE_FIND_QUERY = "find_query";
private static final String STATE_CURRENT_PROFILE = "current_profile";
private static final String STATE_TORRENTS = "torrents";
/**
* The fragment's current callback object, which is notified of list item
* clicks.
*/
private Callbacks mCallbacks = sDummyCallbacks;
/**
* The current activated item position. Only used on tablets.
*/
private int mActivatedPosition = ListView.INVALID_POSITION;
private boolean mAltSpeed = false;
private boolean mRefreshing = true;
private ActionMode mActionMode;
private int mChoiceMode = ListView.CHOICE_MODE_NONE;
private TransmissionProfileListAdapter mProfileAdapter;
private TorrentListAdapter mTorrentListAdapter;
private TransmissionProfile mProfile;
private TransmissionSession mSession;
// private TransmissionSessionStats mSessionStats;
private boolean mScrollToTop = false;
private boolean mFindShown = false;
private String mFindQuery;
private boolean mPreventRefreshIndicator;
/**
* A callback interface that all activities containing this fragment must
* implement. This mechanism allows activities to be notified of item
* selections.
*/
public interface Callbacks {
/**
* Callback for when an item has been selected.
*/
public void onItemSelected(Torrent torrent);
}
/**
* A dummy implementation of the {@link Callbacks} interface that does
* nothing. Used only when this fragment is not attached to an activity.
*/
private static Callbacks sDummyCallbacks = new Callbacks() {
@Override
public void onItemSelected(Torrent torrent) {
}
};
private LoaderCallbacks<TransmissionProfile[]> mProfileLoaderCallbacks = new LoaderCallbacks<TransmissionProfile[]>() {
@Override
public android.support.v4.content.Loader<TransmissionProfile[]> onCreateLoader(
int id, Bundle args) {
return new TransmissionProfileSupportLoader(getActivity());
}
@Override
public void onLoadFinished(
android.support.v4.content.Loader<TransmissionProfile[]> loader,
TransmissionProfile[] profiles) {
TransmissionProfile oldProfile = mProfile;
mProfile = null;
mProfileAdapter.clear();
if (profiles.length > 0) {
mProfileAdapter.addAll(profiles);
} else {
mProfileAdapter.add(TransmissionProfileListAdapter.EMPTY_PROFILE);
setEmptyText(R.string.no_profiles_empty_list);
mRefreshing = false;
getActivity().invalidateOptionsMenu();
}
String currentId = TransmissionProfile.getCurrentProfileId(getActivity());
int index = 0;
for (TransmissionProfile prof : profiles) {
if (prof.getId().equals(currentId)) {
ActionBar actionBar = getActivity().getActionBar();
if (actionBar != null)
actionBar.setSelectedNavigationItem(index);
mProfile = prof;
break;
}
index++;
}
if (mProfile == null && profiles.length > 0) {
mProfile = profiles[0];
}
((TransmissionSessionInterface) getActivity()).setProfile(mProfile);
if (mProfile == null) {
getActivity().getSupportLoaderManager().destroyLoader(G.TORRENTS_LOADER_ID);
} else {
/* The torrents might be loaded before the navigation
* callback fires, which will cause the refresh indicator to
* appear until the next server request */
mPreventRefreshIndicator = true;
if (oldProfile != null && oldProfile.getId() == mProfile.getId()) {
getActivity().getSupportLoaderManager().initLoader(
G.TORRENTS_LOADER_ID,
null, mTorrentLoaderCallbacks);
} else {
getActivity().getSupportLoaderManager().restartLoader(
G.TORRENTS_LOADER_ID,
null, mTorrentLoaderCallbacks);
}
}
}
@Override
public void onLoaderReset(
android.support.v4.content.Loader<TransmissionProfile[]> loader) {
mProfileAdapter.clear();
}
};
private LoaderCallbacks<TransmissionData> mTorrentLoaderCallbacks = new LoaderCallbacks<TransmissionData>() {
@Override
public android.support.v4.content.Loader<TransmissionData> onCreateLoader(
int id, Bundle args) {
G.logD("Starting the torrents loader with profile " + mProfile);
if (mProfile == null) return null;
TransmissionDataLoader loader = new TransmissionDataLoader(getActivity(), mProfile);
return loader;
}
@Override
public void onLoadFinished(
android.support.v4.content.Loader<TransmissionData> loader,
TransmissionData data) {
boolean invalidateMenu = false;
G.logD("Data loaded: " + data.torrents.size() + " torrents, error: " + data.error + " , removed: " + data.hasRemoved + ", added: " + data.hasAdded + ", changed: " + data.hasStatusChanged + ", metadata: " + data.hasMetadataNeeded);
mSession = data.session;
((TransmissionSessionInterface) getActivity()).setSession(data.session);
/* if (data.stats != null)
mSessionStats = data.stats;*/
if (mSession != null && mAltSpeed != mSession.isAltSpeedLimitEnabled()) {
mAltSpeed = mSession.isAltSpeedLimitEnabled();
invalidateMenu = true;
}
boolean filtered = false;
View error = getView().findViewById(R.id.fatal_error_layer);
if (data.error == 0 && error.getVisibility() != View.GONE) {
error.setVisibility(View.GONE);
((TransmissionSessionInterface) getActivity()).setProfile(mProfile);
}
if (data.torrents.size() > 0 || data.error > 0
|| mTorrentListAdapter.getUnfilteredCount() > 0) {
/* The notifyDataSetChanged method sets this to true */
mTorrentListAdapter.setNotifyOnChange(false);
boolean notifyChange = true;
if (data.error == 0) {
if (data.hasRemoved || data.hasAdded
|| data.hasStatusChanged || data.hasMetadataNeeded
|| mTorrentListAdapter.getUnfilteredCount() == 0) {
notifyChange = false;
if (data.hasRemoved || data.hasAdded) {
((TransmissionSessionInterface) getActivity()).setTorrents(data.torrents);
}
mTorrentListAdapter.clear();
mTorrentListAdapter.addAll(data.torrents);
mTorrentListAdapter.repeatFilter();
filtered = true;
}
} else {
if (data.error == TransmissionData.Errors.DUPLICATE_TORRENT) {
Toast.makeText(getActivity(), R.string.duplicate_torrent, Toast.LENGTH_SHORT).show();
} else if (data.error == TransmissionData.Errors.INVALID_TORRENT) {
Toast.makeText(getActivity(), R.string.invalid_torrent, Toast.LENGTH_SHORT).show();
} else {
error.setVisibility(View.VISIBLE);
TextView text = (TextView) getView().findViewById(R.id.transmission_error);
((TransmissionSessionInterface) getActivity()).setProfile(null);
if (mActionMode != null) {
mActionMode.finish();
mActionMode = null;
}
if (data.error == TransmissionData.Errors.NO_CONNECTIVITY) {
text.setText(Html.fromHtml(getString(R.string.no_connectivity_empty_list)));
} else if (data.error == TransmissionData.Errors.ACCESS_DENIED) {
text.setText(Html.fromHtml(getString(R.string.access_denied_empty_list)));
} else if (data.error == TransmissionData.Errors.NO_JSON) {
text.setText(Html.fromHtml(getString(R.string.no_json_empty_list)));
} else if (data.error == TransmissionData.Errors.NO_CONNECTION) {
text.setText(Html.fromHtml(getString(R.string.no_connection_empty_list)));
} else if (data.error == TransmissionData.Errors.THREAD_ERROR) {
text.setText(Html.fromHtml(getString(R.string.thread_error_empty_list)));
} else if (data.error == TransmissionData.Errors.RESPONSE_ERROR) {
text.setText(Html.fromHtml(getString(R.string.response_error_empty_list)));
} else if (data.error == TransmissionData.Errors.TIMEOUT) {
text.setText(Html.fromHtml(getString(R.string.timeout_empty_list)));
}
}
}
if (data.torrents.size() > 0) {
if (notifyChange) {
mTorrentListAdapter.notifyDataSetChanged();
}
} else {
mTorrentListAdapter.notifyDataSetInvalidated();
}
if (data.error == 0) {
FragmentManager manager = getActivity().getSupportFragmentManager();
TorrentListMenuFragment menu = (TorrentListMenuFragment) manager.findFragmentById(R.id.torrent_list_menu);
if (menu != null) {
menu.notifyTorrentListUpdate(data.torrents, data.session);
}
if (!filtered) {
TorrentDetailFragment detail = (TorrentDetailFragment) manager.findFragmentByTag(
TorrentDetailFragment.TAG);
if (detail != null) {
detail.notifyTorrentListChanged(data.hasRemoved, data.hasAdded, data.hasStatusChanged);
if (data.hasStatusChanged) {
invalidateMenu = true;
}
}
}
}
}
if (mRefreshing) {
mRefreshing = false;
invalidateMenu = true;
}
if (invalidateMenu)
getActivity().invalidateOptionsMenu();
}
@Override
public void onLoaderReset(
android.support.v4.content.Loader<TransmissionData> loader) {
mTorrentListAdapter.clear();
}
};
private SharedPreferences.OnSharedPreferenceChangeListener mProfileChangeListener =
new SharedPreferences.OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
if (getActivity() == null || mProfile == null) return;
Loader<TransmissionData> loader = getActivity().getSupportLoaderManager()
.getLoader(G.TORRENTS_LOADER_ID);
mProfile.load(prefs);
TransmissionProfile.setCurrentProfile(mProfile, getActivity());
((TransmissionSessionInterface) getActivity()).setProfile(mProfile);
((TransmissionDataLoader) loader).setProfile(mProfile);
}
};
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public TorrentListFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
getActivity().setProgressBarIndeterminateVisibility(true);
ActionBar actionBar = getActivity().getActionBar();
if (actionBar != null) {
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
mProfileAdapter = new TransmissionProfileListAdapter(getActivity());
actionBar.setListNavigationCallbacks(mProfileAdapter, new ActionBar.OnNavigationListener() {
@Override
public boolean onNavigationItemSelected(int pos, long id) {
TransmissionProfile profile = mProfileAdapter.getItem(pos);
if (profile != TransmissionProfileListAdapter.EMPTY_PROFILE) {
final Loader<TransmissionData> loader = getActivity().getSupportLoaderManager()
.getLoader(G.TORRENTS_LOADER_ID);
if (mProfile != null) {
SharedPreferences prefs = mProfile.getPreferences(getActivity());
if (prefs != null)
prefs.unregisterOnSharedPreferenceChangeListener(mProfileChangeListener);
}
mProfile = profile;
TransmissionProfile.setCurrentProfile(profile, getActivity());
((TransmissionSessionInterface) getActivity()).setProfile(profile);
((TransmissionDataLoader) loader).setProfile(profile);
SharedPreferences prefs = mProfile.getPreferences(getActivity());
if (prefs != null)
prefs.registerOnSharedPreferenceChangeListener(mProfileChangeListener);
if (mPreventRefreshIndicator) {
mPreventRefreshIndicator = false;
} else {
mRefreshing = true;
getActivity().invalidateOptionsMenu();
}
}
return false;
}
});
actionBar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE);
}
if (savedInstanceState != null
&& savedInstanceState.containsKey(STATE_CURRENT_PROFILE)) {
mProfile = savedInstanceState.getParcelable(STATE_CURRENT_PROFILE);
}
getActivity().getSupportLoaderManager().initLoader(G.PROFILES_LOADER_ID, null, mProfileLoaderCallbacks);
}
@Override
public void onViewCreated(View view, final Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// Restore the previously serialized activated item position.
if (savedInstanceState != null) {
if (savedInstanceState.containsKey(STATE_FIND_SHOWN)) {
mFindShown = savedInstanceState.getBoolean(STATE_FIND_SHOWN);
if (savedInstanceState.containsKey(STATE_FIND_QUERY)) {
mFindQuery = savedInstanceState.getString(STATE_FIND_QUERY);
}
}
mRefreshing = false;
}
mTorrentListAdapter = new TorrentListAdapter(getActivity());
setListAdapter(mTorrentListAdapter);
if (savedInstanceState != null &&
(savedInstanceState.containsKey(STATE_TORRENTS) || savedInstanceState.containsKey(STATE_ACTIVATED_POSITION))) {
new Handler().post(new Runnable() {
@Override
public void run() {
if (savedInstanceState.containsKey(STATE_TORRENTS)) {
mTorrentListAdapter.setNotifyOnChange(false);
mTorrentListAdapter.clear();
ArrayList<Torrent> torrents = savedInstanceState.getParcelableArrayList(STATE_TORRENTS);
mTorrentListAdapter.addAll(torrents);
mTorrentListAdapter.repeatFilter();
}
if (savedInstanceState.containsKey(STATE_ACTIVATED_POSITION)) {
setActivatedPosition(savedInstanceState.getInt(STATE_ACTIVATED_POSITION));
}
}
});
}
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
final ListView list = getListView();
list.setChoiceMode(mChoiceMode);
list.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
if (!((TorrentListActivity) getActivity()).isDetailPanelShown()) {
list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
setActivatedPosition(position);
return true;
}
return false;
}});
list.setMultiChoiceModeListener(new MultiChoiceModeListener() {
private HashSet<Integer> mSelectedTorrentIds;
@Override
public boolean onActionItemClicked(final ActionMode mode, final MenuItem item) {
final Loader<TransmissionData> loader = getActivity().getSupportLoaderManager()
.getLoader(G.TORRENTS_LOADER_ID);
if (loader == null)
return false;
final int[] ids = new int[mSelectedTorrentIds.size()];
int index = 0;
for (Integer id : mSelectedTorrentIds)
ids[index++] = id;
AlertDialog.Builder builder;
switch (item.getItemId()) {
case R.id.select_all:
ListView v = getListView();
for (int i = 0; i < mTorrentListAdapter.getCount(); i++) {
if (!v.isItemChecked(i)) {
v.setItemChecked(i, true);
}
}
return true;
case R.id.remove:
case R.id.delete:
builder = new AlertDialog.Builder(getActivity())
.setCancelable(false)
.setNegativeButton(android.R.string.no, null);
builder.setPositiveButton(android.R.string.yes,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
((TransmissionDataLoader) loader).setTorrentsRemove(ids, item.getItemId() == R.id.delete);
mRefreshing = true;
getActivity().invalidateOptionsMenu();
mode.finish();
}
})
.setMessage(item.getItemId() == R.id.delete
? R.string.delete_selected_confirmation
: R.string.remove_selected_confirmation)
.show();
return true;
case R.id.resume:
((TransmissionDataLoader) loader).setTorrentsAction("torrent-start", ids);
break;
case R.id.pause:
((TransmissionDataLoader) loader).setTorrentsAction("torrent-stop", ids);
break;
case R.id.move:
return showMoveDialog(ids);
case R.id.verify:
((TransmissionDataLoader) loader).setTorrentsAction("torrent-verify", ids);
break;
case R.id.reannounce:
((TransmissionDataLoader) loader).setTorrentsAction("torrent-reannounce", ids);
break;
default:
return true;
}
mRefreshing = true;
getActivity().invalidateOptionsMenu();
mode.finish();
return true;
}
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.torrent_list_multiselect, menu);
mSelectedTorrentIds = new HashSet<Integer>();
mActionMode = mode;
return true;
}
@Override
public void onDestroyActionMode(ActionMode mode) {
G.logD("Destroying context menu");
mActionMode = null;
mSelectedTorrentIds = null;
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
@Override
public void onItemCheckedStateChanged(ActionMode mode,
int position, long id, boolean checked) {
if (checked)
mSelectedTorrentIds.add(mTorrentListAdapter.getItem(position).getId());
else
mSelectedTorrentIds.remove(mTorrentListAdapter.getItem(position).getId());
ArrayList<Torrent> torrents = ((TransmissionSessionInterface) getActivity()).getTorrents();
boolean hasPaused = false;
boolean hasRunning = false;
for (Torrent t : torrents) {
if (mSelectedTorrentIds.contains(t.getId())) {
if (t.getStatus() == Torrent.Status.STOPPED) {
hasPaused = true;
} else {
hasRunning = true;
}
}
}
Menu menu = mode.getMenu();
MenuItem item = menu.findItem(R.id.resume);
item.setVisible(hasPaused).setEnabled(hasPaused);
item = menu.findItem(R.id.pause);
item.setVisible(hasRunning).setEnabled(hasRunning);
}});
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// Activities containing this fragment must implement its callbacks.
if (!(activity instanceof Callbacks)) {
throw new IllegalStateException("Activity must implement fragment's callbacks.");
}
mCallbacks = (Callbacks) activity;
}
@Override
public void onDetach() {
super.onDetach();
// Reset the active callbacks interface to the dummy implementation.
mCallbacks = sDummyCallbacks;
}
@Override
public void onListItemClick(ListView listView, View view, int position, long id) {
super.onListItemClick(listView, view, position, id);
if (mActionMode == null)
listView.setChoiceMode(mChoiceMode);
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
mCallbacks.onItemSelected(mTorrentListAdapter.getItem(position));
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable(STATE_CURRENT_PROFILE, mProfile);
if (mActivatedPosition != ListView.INVALID_POSITION) {
// Serialize and persist the activated item position.
outState.putInt(STATE_ACTIVATED_POSITION, mActivatedPosition);
}
outState.putBoolean(STATE_FIND_SHOWN, mFindShown);
outState.putString(STATE_FIND_QUERY, mFindQuery);
outState.putParcelableArrayList(STATE_TORRENTS, mTorrentListAdapter.getUnfilteredItems());
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_torrent_list, container, false);
return rootView;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.torrent_list_options, menu);
MenuItem item = menu.findItem(R.id.menu_refresh);
if (mRefreshing)
item.setActionView(R.layout.action_progress_bar);
else
item.setActionView(null);
item = menu.findItem(R.id.menu_alt_speed);
if (mSession == null) {
item.setVisible(false);
} else {
item.setVisible(true);
if (mAltSpeed) {
item.setIcon(R.drawable.ic_menu_alt_speed_on);
item.setTitle(R.string.alt_speed_label_off);
} else {
item.setIcon(R.drawable.ic_menu_alt_speed_off);
item.setTitle(R.string.alt_speed_label_on);
}
}
item = menu.findItem(R.id.menu_find);
if (mFindShown) {
item.expandActionView();
item.setOnActionExpandListener(new MenuItem.OnActionExpandListener() {
@Override public boolean onMenuItemActionExpand(MenuItem item) {
return true;
}
@Override public boolean onMenuItemActionCollapse(MenuItem item) {
mFindShown = false;
mFindQuery = null;
setListFilter((String) null);
return true;
}
});
SearchView searchView = (SearchView) menu.findItem(R.id.menu_find).getActionView();
searchView.setQueryHint(getActivity().getString(R.string.filter));
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override public boolean onQueryTextSubmit(String query) {
return false;
}
@Override public boolean onQueryTextChange(String newText) {
G.logD("Search query " + newText);
mFindQuery = newText;
setListFilter(newText);
return false;
}
});
if (mFindQuery == null) {
searchView.setQuery("", false);
} else {
searchView.setQuery(mFindQuery, true);
}
} else {
item.collapseActionView();
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Loader<TransmissionData> loader;
switch (item.getItemId()) {
case R.id.menu_alt_speed:
loader = getActivity().getSupportLoaderManager()
.getLoader(G.TORRENTS_LOADER_ID);
if (loader != null) {
mAltSpeed = !mAltSpeed;
mSession.setAltSpeedLimitEnabled(mAltSpeed);
((TransmissionDataLoader) loader).setSession(mSession, "alt-speed-enabled");
getActivity().invalidateOptionsMenu();
}
return true;
case R.id.menu_refresh:
loader = getActivity().getSupportLoaderManager()
.getLoader(G.TORRENTS_LOADER_ID);
if (loader != null) {
loader.onContentChanged();
mRefreshing = !mRefreshing;
getActivity().invalidateOptionsMenu();
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void setEmptyText(int stringId) {
Spanned text = Html.fromHtml(getString(stringId));
((TextView) getListView().getEmptyView()).setText(text);
}
public void setEmptyText(String text) {
((TextView) getListView().getEmptyView()).setText(text);
}
/**
* Turns on activate-on-click mode. When this mode is on, list items will be
* given the 'activated' state when touched.
*/
public void setActivateOnItemClick(boolean activateOnItemClick) {
// When setting CHOICE_MODE_SINGLE, ListView will automatically
// give items the 'activated' state when touched.
mChoiceMode = activateOnItemClick
? ListView.CHOICE_MODE_SINGLE
: ListView.CHOICE_MODE_NONE;
getListView().setChoiceMode(mChoiceMode);
}
public void setListFilter(String query) {
mTorrentListAdapter.filter(query);
mScrollToTop = true;
}
public void setListFilter(FilterBy e) {
mTorrentListAdapter.filter(e);
mScrollToTop = true;
}
public void setListFilter(SortBy e) {
mTorrentListAdapter.filter(e);
mScrollToTop = true;
}
public void setListFilter(SortOrder e) {
mTorrentListAdapter.filter(e);
mScrollToTop = true;
}
public void setListDirectoryFilter(String e) {
mTorrentListAdapter.filterDirectory(e);
mScrollToTop = true;
}
public void setRefreshing(boolean refreshing) {
mRefreshing = refreshing;
getActivity().invalidateOptionsMenu();
}
public void showFind() {
mFindShown = true;
mFindQuery = null;
if (mActionMode != null) {
mActionMode.finish();
}
getActivity().invalidateOptionsMenu();
}
public boolean isFindShown() {
return mFindShown;
}
private void setActivatedPosition(int position) {
if (position == ListView.INVALID_POSITION) {
getListView().setItemChecked(mActivatedPosition, false);
} else {
getListView().setItemChecked(position, true);
}
mActivatedPosition = position;
}
private boolean showMoveDialog(final int[] ids) {
LayoutInflater inflater = getActivity().getLayoutInflater();
final Loader<TransmissionData> loader = getActivity().getSupportLoaderManager()
.getLoader(G.TORRENTS_LOADER_ID);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity())
.setTitle(R.string.set_location)
.setCancelable(false)
.setNegativeButton(android.R.string.no, null)
.setPositiveButton(android.R.string.yes,
new DialogInterface.OnClickListener() {
@Override public void onClick(DialogInterface dialog, int id) {
Spinner location = (Spinner) ((AlertDialog) dialog).findViewById(R.id.location_choice);
CheckBox move = (CheckBox) ((AlertDialog) dialog).findViewById(R.id.move);
String dir = (String) location.getSelectedItem();
((TransmissionDataLoader) loader).setTorrentsLocation(
ids, dir, move.isChecked());
mRefreshing = true;
getActivity().invalidateOptionsMenu();
if (mActionMode != null) {
mActionMode.finish();
}
}
}).setView(inflater.inflate(R.layout.torrent_location_dialog, null));
if (mSession == null) {
return true;
}
AlertDialog dialog = builder.create();
dialog.show();
TransmissionProfileDirectoryAdapter adapter =
new TransmissionProfileDirectoryAdapter(
getActivity(), android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
adapter.addAll(mSession.getDownloadDirectories());
adapter.sort();
Spinner location = (Spinner) dialog.findViewById(R.id.location_choice);
location.setAdapter(adapter);
if (mProfile.getLastDownloadDirectory() != null) {
int position = adapter.getPosition(mProfile.getLastDownloadDirectory());
if (position > -1) {
location.setSelection(position);
}
}
return true;
}
private static class TransmissionProfileListAdapter extends ArrayAdapter<TransmissionProfile> {
public static final TransmissionProfile EMPTY_PROFILE = new TransmissionProfile(null);
public TransmissionProfileListAdapter(Context context) {
super(context, 0);
add(EMPTY_PROFILE);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
TransmissionProfile profile = getItem(position);
if (rowView == null) {
LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = vi.inflate(R.layout.torrent_profile_selector, null);
}
TextView name = (TextView) rowView.findViewById(R.id.name);
TextView summary = (TextView) rowView.findViewById(R.id.summary);
if (profile == EMPTY_PROFILE) {
name.setText(R.string.no_profiles);
if (summary != null)
summary.setText(R.string.create_profile_in_settings);
} else {
name.setText(profile.getName());
if (summary != null)
summary.setText((profile.getUsername().length() > 0 ? profile.getUsername() + "@" : "")
+ profile.getHost() + ":" + profile.getPort());
}
return rowView;
}
@Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
if (rowView == null) {
LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = vi.inflate(R.layout.torrent_profile_selector_dropdown, null);
}
return getView(position, rowView, parent);
}
}
private class TorrentListAdapter extends ArrayAdapter<Torrent> {
private final Object mLock = new Object();
private ArrayList<Torrent> mObjects = new ArrayList<Torrent>();
private ArrayList<Torrent> mOriginalValues;
private TorrentFilter mFilter;
private CharSequence mCurrentConstraint;
private FilterListener mCurrentFilterListener;
private TorrentComparator mTorrentComparator = new TorrentComparator();
private FilterBy mFilterBy = FilterBy.ALL;
private SortBy mSortBy = mTorrentComparator.getSortBy();
private SortBy mBaseSort = mTorrentComparator.getBaseSort();
private SortOrder mSortOrder = mTorrentComparator.getSortOrder();
private String mDirectory;
private SparseBooleanArray mTorrentAdded = new SparseBooleanArray();
private SharedPreferences mSharedPrefs;
public TorrentListAdapter(Context context) {
super(context, R.layout.torrent_list_item, R.id.name);
mSharedPrefs = PreferenceManager.getDefaultSharedPreferences(getContext());
/*
if (mSharedPrefs.contains(G.PREF_LIST_SEARCH)) {
mCurrentConstraint = mSharedPrefs.getString(
G.PREF_LIST_SEARCH, null);
}
*/
if (mSharedPrefs.contains(G.PREF_LIST_FILTER)) {
try {
mFilterBy = FilterBy.valueOf(
mSharedPrefs.getString(G.PREF_LIST_FILTER, "")
);
} catch (Exception e) {
mFilterBy = FilterBy.ALL;
}
}
if (mSharedPrefs.contains(G.PREF_LIST_DIRECTORY)) {
mDirectory = mSharedPrefs.getString(G.PREF_LIST_DIRECTORY, null);
}
if (mSharedPrefs.contains(G.PREF_LIST_SORT_BY)) {
try {
mSortBy = SortBy.valueOf(
mSharedPrefs.getString(G.PREF_LIST_SORT_BY, "")
);
} catch (Exception e) {
mSortBy = mTorrentComparator.getSortBy();
}
}
if (mSharedPrefs.contains(G.PREF_BASE_SORT)) {
try {
mBaseSort = SortBy.valueOf(
mSharedPrefs.getString(G.PREF_BASE_SORT, "")
);
} catch (Exception e) {
mBaseSort = mTorrentComparator.getBaseSort();
}
}
if (mSharedPrefs.contains(G.PREF_LIST_SORT_ORDER)) {
try {
mSortOrder = SortOrder.valueOf(
mSharedPrefs.getString(G.PREF_LIST_SORT_ORDER, "")
);
} catch (Exception e) {
mSortOrder = mTorrentComparator.getSortOrder();
}
}
mTorrentComparator.setSortingMethod(mSortBy, mSortOrder);
mTorrentComparator.setBaseSort(mBaseSort);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
Torrent torrent = getItem(position);
if (rowView == null) {
LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = vi.inflate(R.layout.torrent_list_item, parent, false);
}
TextView name = (TextView) rowView.findViewById(R.id.name);
TextView traffic = (TextView) rowView.findViewById(R.id.traffic);
ProgressBar progress = (ProgressBar) rowView.findViewById(R.id.progress);
TextView status = (TextView) rowView.findViewById(R.id.status);
TextView errorText = (TextView) rowView.findViewById(R.id.error_text);
name.setText(torrent.getName());
if (torrent.getMetadataPercentComplete() < 1) {
progress.setSecondaryProgress((int) (torrent.getMetadataPercentComplete() * 100));
progress.setProgress(0);
} else if (torrent.getPercentDone() < 1) {
progress.setSecondaryProgress((int) (torrent.getPercentDone() * 100));
progress.setProgress(0);
} else {
progress.setSecondaryProgress(100);
float limit = torrent.getActiveSeedRatioLimit();
float current = torrent.getUploadRatio();
if (limit == -1) {
progress.setProgress(100);
} else {
if (current >= limit) {
progress.setProgress(100);
} else {
progress.setProgress((int) (current / limit * 100));
}
}
}
traffic.setText(torrent.getTrafficText());
status.setText(torrent.getStatusText());
boolean enabled = torrent.isActive();
name.setEnabled(enabled);
traffic.setEnabled(enabled);
status.setEnabled(enabled);
errorText.setEnabled(enabled);
if (torrent.getError() == Torrent.Error.OK) {
errorText.setVisibility(View.GONE);
} else {
errorText.setVisibility(View.VISIBLE);
errorText.setText(torrent.getErrorString());
}
if (!mTorrentAdded.get(torrent.getId(), false)) {
rowView.setTranslationY(100);
rowView.setAlpha((float) 0.3);
rowView.setRotationX(10);
rowView.animate().setDuration(300).translationY(0).alpha(1).rotationX(0).start();
mTorrentAdded.append(torrent.getId(), true);
}
return rowView;
}
@Override
public void addAll(Collection<? extends Torrent> collection) {
synchronized (mLock) {
if (mOriginalValues != null) {
mOriginalValues.addAll(collection);
} else {
mObjects.addAll(collection);
}
super.addAll(collection);
}
}
@Override
public void clear() {
synchronized (mLock) {
if (mOriginalValues != null) {
mOriginalValues = null;
}
if (mObjects != null) {
mObjects.clear();
}
super.clear();
}
}
@Override
public int getCount() {
synchronized(mLock) {
return mObjects == null ? 0 : mObjects.size();
}
}
public int getUnfilteredCount() {
synchronized(mLock) {
if (mOriginalValues != null) {
return mOriginalValues.size();
} else {
return mObjects.size();
}
}
}
public ArrayList<Torrent> getUnfilteredItems() {
synchronized(mLock) {
if (mOriginalValues != null) {
return mOriginalValues;
} else {
return mObjects;
}
}
}
@Override
public Torrent getItem(int position) {
return mObjects.get(position);
}
@Override
public int getPosition(Torrent item) {
return mObjects.indexOf(item);
}
@Override
public Filter getFilter() {
if (mFilter == null)
mFilter = new TorrentFilter();
return mFilter;
}
public void filter(String query) {
mCurrentConstraint = query;
applyFilter(query, G.PREF_LIST_SEARCH, false);
}
public void filter(FilterBy by) {
mFilterBy = by;
applyFilter(by.name(), G.PREF_LIST_FILTER);
}
public void filter(SortBy by) {
mSortBy = by;
applyFilter(by.name(), G.PREF_LIST_SORT_BY);
}
public void filter(SortOrder order) {
mSortOrder = order;
applyFilter(order.name(), G.PREF_LIST_SORT_ORDER);
}
public void filterDirectory(String directory) {
mDirectory = directory;
applyFilter(directory, G.PREF_LIST_DIRECTORY);
}
public void repeatFilter() {
if (mProfile != null) {
getFilter().filter(mCurrentConstraint, mCurrentFilterListener);
}
}
private void applyFilter(String value, String pref, boolean animate) {
if (mActionMode != null) {
mActionMode.finish();
}
if (pref != null) {
Editor e = mSharedPrefs.edit();
e.putString(pref, value);
e.apply();
}
mTorrentComparator.setSortingMethod(mSortBy, mSortOrder);
repeatFilter();
if (animate) {
mTorrentAdded = new SparseBooleanArray();
}
}
private void applyFilter(String value, String pref) {
applyFilter(value, pref, true);
}
private class TorrentFilter extends Filter {
@Override
protected FilterResults performFiltering(CharSequence prefix) {
FilterResults results = new FilterResults();
ArrayList<Torrent> resultList;
if (mOriginalValues == null) {
synchronized (mLock) {
mOriginalValues = new ArrayList<Torrent>(mObjects);
}
}
if (prefix == null) {
prefix = "";
}
if (prefix.length() == 0 && mFilterBy == FilterBy.ALL && mDirectory == null) {
ArrayList<Torrent> list;
synchronized (mLock) {
list = new ArrayList<Torrent>(mOriginalValues);
}
resultList = list;
} else {
ArrayList<Torrent> values;
synchronized (mLock) {
values = new ArrayList<Torrent>(mOriginalValues);
}
final int count = values.size();
final ArrayList<Torrent> newValues = new ArrayList<Torrent>();
String prefixString = prefix.toString().toLowerCase(Locale.getDefault());
for (int i = 0; i < count; i++) {
final Torrent torrent = values.get(i);
if (mFilterBy == FilterBy.DOWNLOADING) {
if (torrent.getStatus() != Torrent.Status.DOWNLOADING)
continue;
} else if (mFilterBy == FilterBy.SEEDING) {
if (torrent.getStatus() != Torrent.Status.SEEDING)
continue;
} else if (mFilterBy == FilterBy.PAUSED) {
if (torrent.getStatus() != Torrent.Status.STOPPED)
continue;
} else if (mFilterBy == FilterBy.COMPLETE) {
if (torrent.getPercentDone() != 1)
continue;
} else if (mFilterBy == FilterBy.INCOMPLETE) {
if (torrent.getPercentDone() >= 1)
continue;
} else if (mFilterBy == FilterBy.ACTIVE) {
if (torrent.isStalled() || torrent.isFinished() || (
torrent.getStatus() != Torrent.Status.DOWNLOADING
&& torrent.getStatus() != Torrent.Status.SEEDING
))
continue;
} else if (mFilterBy == FilterBy.CHECKING) {
if (torrent.getStatus() != Torrent.Status.CHECKING)
continue;
}
if (mDirectory != null) {
if (torrent.getDownloadDir() == null
|| !torrent.getDownloadDir().equals(mDirectory))
continue;
}
if (prefix.length() == 0) {
newValues.add(torrent);
} else if (prefix.length() > 0) {
final String valueText = torrent.getName().toLowerCase(Locale.getDefault());
int lastIndex = -1;
boolean match = false;
for (int j = 0; j < prefixString.length(); ++j) {
char c = prefixString.charAt(j);
if (Character.isWhitespace(c)) {
continue;
}
int newIndex = valueText.indexOf(c, lastIndex);
if (newIndex > -1 && (lastIndex == -1 || newIndex - lastIndex < 3)) {
lastIndex = newIndex + 1;
if (j == prefixString.length() - 1) {
match = true;
}
} else {
break;
}
}
if (match) {
newValues.add(torrent);
}
}
}
resultList = newValues;
}
Collections.sort(resultList, mTorrentComparator);
results.values = resultList;
results.count = resultList.size();
return results;
}
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
mObjects = (ArrayList<Torrent>) results.values;
TransmissionSessionInterface context = (TransmissionSessionInterface) getActivity();
if (context == null) {
return;
}
if (results.count > 0) {
context.setTorrents((ArrayList<Torrent>) results.values);
FragmentManager manager = getActivity().getSupportFragmentManager();
TorrentDetailFragment detail = (TorrentDetailFragment) manager.findFragmentByTag(
TorrentDetailFragment.TAG);
if (detail != null) {
detail.notifyTorrentListChanged(true, true, false);
}
notifyDataSetChanged();
} else {
if (mTorrentListAdapter.getUnfilteredCount() == 0) {
setEmptyText(R.string.no_torrents_empty_list);
} else if (mTorrentListAdapter.getCount() == 0) {
((TransmissionSessionInterface) getActivity())
.setTorrents(null);
setEmptyText(R.string.no_filtered_torrents_empty_list);
}
notifyDataSetInvalidated();
}
if (mScrollToTop) {
mScrollToTop = false;
getListView().setSelectionAfterHeaderView();
}
}
}
}
} |
package dyvilx.tools.compiler.ast.classes;
import dyvil.annotation.internal.NonNull;
import dyvil.collection.Iterators;
import dyvil.lang.Formattable;
import dyvil.lang.Name;
import dyvil.reflect.Modifiers;
import dyvilx.tools.compiler.ast.expression.IValue;
import dyvilx.tools.compiler.ast.field.IField;
import dyvilx.tools.compiler.ast.method.IMethod;
import dyvilx.tools.compiler.ast.method.MatchList;
import dyvilx.tools.compiler.ast.parameter.ArgumentList;
import dyvilx.tools.compiler.ast.type.IType;
import dyvilx.tools.compiler.phase.ResolvableList;
import java.util.ArrayList;
public class ClassList extends ArrayList<IClass> implements Formattable, ResolvableList<IClass>
{
public ClassList()
{
}
public ClassList(int capacity)
{
super(capacity);
}
public IClass get(Name name)
{
for (final IClass iclass : this)
{
if (iclass.getName() == name)
{
return iclass;
}
}
return null;
}
public Iterable<IClass> objectClasses()
{
return () -> Iterators.filtered(this.iterator(), IClass::isObject);
}
public Iterable<IField> objectClassInstanceFields()
{
return () -> Iterators
.mapped(this.objectClasses().iterator(), iclass -> iclass.getMetadata().getInstanceField());
}
public IField resolveImplicitObjectInstanceField(IType type)
{
return ClassBody.resolveImplicitField(type, this.objectClassInstanceFields());
}
public void getExtensionMethodMatches(MatchList<IMethod> list, IValue receiver, Name name, ArgumentList arguments)
{
for (final IClass iclass : this)
{
if (iclass.hasModifier(Modifiers.EXTENSION) && iclass.getBody() != null)
{
// only uses the body to avoid infinite recursion with PrimitiveType
// (and because extension classes can only define extension methods in the body anyway)
iclass.getBody().getMethodMatches(list, receiver, name, arguments);
}
}
}
public void getExtensionImplicitMatches(MatchList<IMethod> list, IValue value, IType targetType)
{
for (final IClass iclass : this)
{
if (iclass.hasModifier(Modifiers.EXTENSION) && iclass.getBody() != null)
{
// s.a. for body rationale
iclass.getBody().getImplicitMatches(list, value, targetType);
}
}
}
@Override
public String toString()
{
return Formattable.toString(this);
}
@Override
public void toString(@NonNull StringBuilder buffer)
{
this.toString("", buffer);
}
public void toString(@NonNull String indent, @NonNull StringBuilder buffer)
{
for (final IClass iclass : this)
{
iclass.toString(indent, buffer);
buffer.append("\n\n").append(indent);
}
}
} |
// Package
package com.hp.hpl.jena.ontology;
// Imports
import java.io.*;
import java.util.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.xerces.util.XMLChar;
import com.hp.hpl.jena.rdf.model.*;
import com.hp.hpl.jena.util.*;
import com.hp.hpl.jena.vocabulary.OntDocManagerVocab;
import com.hp.hpl.jena.vocabulary.RDF;
import com.hp.hpl.jena.shared.*;
import com.hp.hpl.jena.shared.impl.PrefixMappingImpl;
public class OntDocumentManager
{
// Constants
/** The default path for searching for the metadata on locally cached ontologies */
public static final String DEFAULT_METADATA_PATH = "file:ont-policy.rdf;file:etc/ont-policy.rdf";
/** Namespace for ontology metadata resources and properties */
public static final String NS = "http://jena.hpl.hp.com/schemas/2003/03/ont-manager
/** The anchor char is added to the end of namespace prefix expansions */
public static final String ANCHOR = "
/** rdf:type for ontology specification nodes in meta-data file */
public static final Resource ONTOLOGY_SPEC = OntDocManagerVocab.OntologySpec;
/** Represents the public URI of an ontology; also used to derive the namespace */
public static final Property PUBLIC_URI = OntDocManagerVocab.publicURI;
/** Represents the alternative local copy of the public ontology; assumed to be resolvable, hence URL not URI */
public static final Property ALT_URL = OntDocManagerVocab.altURL;
/** Represents the standard prefix for this namespace */
public static final Property PREFIX = OntDocManagerVocab.prefix;
/** Represents the ontology language used to encode the ontology */
public static final Property LANGUAGE = OntDocManagerVocab.language;
/** rdf:type for document manager policy nodes */
public static final Resource DOC_MGR_POLICY = OntDocManagerVocab.DocumentManagerPolicy;
/** Defines boolean policy choice of caching loaded models */
public static final Property CACHE_MODELS = OntDocManagerVocab.cacheModels;
/** Defines boolean policy choice of loading the imports closure */
public static final Property PROCESS_IMPORTS = OntDocManagerVocab.processImports;
/** Specifies the URI of an ontology that we do not want to import, even if processImports is true. */
public static final Property IGNORE_IMPORT = OntDocManagerVocab.ignoreImport;
/** The policy property for including the pre-declared namespace prefixes in a model. */
public static final Property USE_DECLARED_NS_PREFIXES = OntDocManagerVocab.useDeclaredNsPrefixes;
// Static variables
/** Default document manager instance */
private static OntDocumentManager s_instance = null;
/** Log for this class */
private static Log log = LogFactory.getLog( OntDocumentManager.class );
// Instance variables
/** The search path for metadata */
protected String m_searchPath = DEFAULT_METADATA_PATH;
/** FileManager instance that provides location resolution service - defaults to global instance */
protected FileManager m_fileMgr = null;
/** Flag to indicate we're using a copy of the global file manager */
protected boolean m_usingGlobalFileMgr = false;
/** Mapping of public public URI's to language resources */
protected Map m_languageMap = new HashMap();
/** Flag: process the imports closure */
protected boolean m_processImports = true;
/** List of URI's that will be ignored when doing imports processing */
protected Set m_ignoreImports = new HashSet();
/** Default prefix mapping to use to seed all models */
protected PrefixMapping m_prefixMap = new PrefixMappingImpl();
/** Flag to control whether we include the standard prefixes in generated models - default true. */
protected boolean m_useDeclaredPrefixes = true;
/** The URL of the policy file that was loaded, or null if no external policy file has yet been loaded */
protected String m_policyURL = null;
// Constructors
/**
* <p>
* Initialise a document manager by searching the default path for ontology
* metadata about known ontologies cached locally.
* </p>
*/
public OntDocumentManager() {
this( DEFAULT_METADATA_PATH );
}
/**
* <p>
* Initialise a document manager by searching the given path for ontology
* metadata about known ontologies cached locally.
* </p>
*
* @param path The search path to search for initial metadata, which will
* also replace the current search path for this document manager. Use
* null to prevent loading of any initial ontology metadata. The path is a series
* of URL's, separated by a semi-colon (;).
*/
public OntDocumentManager( String path ) {
this( null, path );
}
/**
* <p>
* Initialise a document manager by with the given FileManager, and
* then searching the given path for ontology
* metadata about known ontologies cached locally.
* </p>
*
* @param path The search path to search for initial metadata
* @see #OntDocumentManager(String)
*/
public OntDocumentManager( FileManager fileMgr, String path ) {
setFileManager( fileMgr );
setDefaults();
m_searchPath = (path == null) ? "" : path;
initialiseMetadata( m_searchPath );
}
/**
* <p>Initialise a document manager with the given configuration model. This model
* is used in place of any model that might be
* found by searching the meta-data search path. Uses the default file manager,
* i.e. a copy of the global file manager.</p>
* @param config An RDF model containing configuration information for this document manager.
*/
public OntDocumentManager( Model config ) {
this( null, config );
}
/**
* <p>Initialise a document manager with the given configuration model. This model
* is used in place of any model that might be
* found by searching the meta-data search path.</p>
* @param fileMgr A file manager to use when locating source files for ontologies
* @param config An RDF model containing configuration information for this document manager.
*/
public OntDocumentManager( FileManager fileMgr, Model config ) {
// we don't need to reset first since this is a new doc mgr
setFileManager( fileMgr );
setDefaults();
configure( config, false );
}
// External signature methods
/**
* <p>
* OntDocumentManager is not a singleton, but a global default instance is available
* for applications where a single shared document manager is sufficient.
* </p>
*
* @return The default, global instance of a document manager
*/
public static OntDocumentManager getInstance() {
if (s_instance == null) {
s_instance = new OntDocumentManager();
}
return s_instance;
}
/**
* <p>Answer the file manager instance being used by this document manager.</p>
* @return This object's file manager
*/
public FileManager getFileManager() {
return m_fileMgr;
}
/**
* <p>Set the file manager used by this ODM instance to <strong>a
* copy</strong> of the global file manager (and, by extension, the
* global location mapper).</p>
*/
public void setFileManager() {
setFileManager( new FileManager( FileManager.get() ) );
m_usingGlobalFileMgr = true;
}
/**
* <p>Set the file manager used by this ODM instance to <strong>a
* copy</strong> of the global file manager (and, by extension, the
* global location mapper).</p>
* @param fileMgr The new file manager
*/
public void setFileManager( FileManager fileMgr ) {
if (fileMgr == null) {
// use default fm
setFileManager();
}
else {
m_fileMgr = fileMgr;
m_usingGlobalFileMgr = false;
}
}
/**
* <p>
* Answer the path used to search for the ontology metadata to load. The format is
* a ';' separated list of URI's. The first URI on the path that is readable is
* taken to be the location of the local ontology metadata.
* </p>
*
* @return The ontology metadata search path, as a string.
*/
public String getMetadataSearchPath() {
return m_searchPath;
}
/**
* <p>
* Change the search path for loading ontology metadata to the given path. If
* <code>replace</code> is true, any existing mappings are removed before the
* new path is searched. Otherwise, existing data will only be replaced if
* it is clobbered by keys loaded from the metadata loaded from the new path.
* </p>
*
* @param path The new metadata search path (see {@link #getMetadataSearchPath} for format)
* @param replace If true, clear existing mappings first
*/
public void setMetadataSearchPath( String path, boolean replace ) {
if (replace) {
reset();
}
m_searchPath = path;
m_policyURL = null;
initialiseMetadata( path );
}
/**
* <p>Configure this document manager using the given configuration information, after
* first resetting the model back to all default values.</p>
* @param config Document manager configuration as an RDF model
* @see #configure( Model, boolean )
*/
public void configure( Model config ) {
configure( config, true );
}
/**
* <p>Configure this document manager according to the configuration options
* supplied by the given configuration model. If <code>reset</code> is true, the
* document manager is first reset back to all default values.</p>
* @param config Document manager configuration as an RDF model
* @param reset If true, reset the document manager to default values, before
* attempting to configure the document manager using the given model.
* @see #reset
*/
public void configure( Model config, boolean reset ) {
if (reset) {
reset( false );
}
processMetadata( config );
}
/**
* <p>Reset all state in this document manager back to the default
* values it would have had when the object was created. Optionally
* reload the profile metadata from the search path. <strong>Note</strong>
* that the metadata search path is not changed by this reset.</p>
* @param reload If true, reload the configuration file from the
* search path.
*/
public void reset( boolean reload ) {
// first check if we are using the global file manager, or a local one
if (m_usingGlobalFileMgr) {
// we can do a general reset by throwing away the old FM and creating a new one
setFileManager();
}
else {
// not using the global default FM, so we reset to best effort
getFileManager().resetCache();
}
setDefaults();
m_languageMap.clear();
m_ignoreImports.clear();
// copy the standard prefixes
m_prefixMap = new PrefixMappingImpl();
m_prefixMap.setNsPrefixes( PrefixMapping.Standard );
if (reload) {
initialiseMetadata( m_searchPath );
}
}
/**
* <p>Reset all state in this document manager back to the default
* values it would have had when the object was created. This does
* <strong>not</strong> reload the configuration information from
* the search path. Note also that the metadata search path is one
* of the values that is reset back to its default value.</p>
* @see #reset( boolean )
*/
public void reset() {
reset( false );
}
/**
* <p>
* Answer an iterator over the ontology document URI's that this document manager
* knows to re-direct to other URL's. <strong>Note</strong> that being in this
* iteration does <em>not</em> mean that a document with the given name is in
* the set of cached models held by this document manager.
* </p>
*
* @return An Iterator ranging over the public URI strings for the known
* document URI's.
*/
public Iterator listDocuments() {
return getFileManager().getLocationMapper().listAltEntries();
}
/**
* <p>
* Answer the URL of the alternative copy of the ontology document with the given URI, if known,
* or the URI unchanged if no alternative is known.
* </p>
*
* @param uri The ontology document to lookup
* @return The resolvable location of the alternative copy, if known, or <code>uri</code> otherwise
*/
public String doAltURLMapping( String uri ) {
return getFileManager().mapURI( uri );
}
/**
* <p>
* Answer the representation of the ontology document with the given URI, if known.
* </p>
*
* @param uri The ontology document to lookup
* @return The URI of the representation language, or null.
* @deprecated Language determination via the ODM will be removed from Jena 2.4 onwards
*/
public String getLanguage( String uri ) {
return (String) m_languageMap.get( uri );
}
/**
* <p>
* Answer the prefix for the qnames in the given document, if known.
* </p>
*
* @param uri The ontology document to lookup
* @return The string to use as a prefix when serialising qnames in the
* given document's namespace, or null if not known
* @deprecated Prefix management via the ODM is very likely to be removed from Jena 2.4 onwards
*/
public String getPrefixForURI( String uri ) {
return m_prefixMap.getNsURIPrefix( uri );
}
/**
* <p>
* Answer the base URI for qnames with the given prefix, if known.
* </p>
*
* @param prefix A prefix string
* @return The basename that the prefix expands to, or null
* @deprecated Prefix management via the ODM is very likely to be removed from Jena 2.4 onwards
*/
public String getURIForPrefix( String prefix ) {
return m_prefixMap.getNsPrefixURI( prefix );
}
/**
* <p>
* Answer the cached model corresponding to the given document, if known.
* </p>
*
* @param uri The ontology document to lookup
* @return The model for the document, or null if the model is not known.
* @see #getOntology
*/
public Model getModel( String uri ) {
return getFileManager().getFromCache( uri );
}
/**
* <p>Answer true if, according to the policy expressed by this document manager, newly
* generated ontology models should include the pre-declared namespace prefixes.
* </p>
*
* @return True if pre-declared prefixes should be added to the models
* @deprecated Prefix management via the ODM is very likely to be removed from Jena 2.4 onwards
*/
public boolean useDeclaredPrefixes() {
return m_useDeclaredPrefixes;
}
/**
* <p>Set the flag that determines whether pre-declared namespace prefixes will be added to newly
* generated ontology models.</p>
*
* @param useDeclaredPrefixes If true, new models will include the pre-declared prefixes set held
* by this document manager.
* @deprecated Prefix management via the ODM is very likely to be removed from Jena 2.4 onwards
*/
public void setUseDeclaredPrefixes( boolean useDeclaredPrefixes ) {
m_useDeclaredPrefixes = useDeclaredPrefixes;
}
/**
* <p>Answer the namespace prefix map that contains the shared prefixes managed by this
* document manager.</p>
*
* @return The namespace prefix mapping
* @deprecated Prefix management via the ODM is very likely to be removed from Jena 2.4 onwards
*/
public PrefixMapping getDeclaredPrefixMapping() {
return m_prefixMap;
}
/**
* <p>
* Add a prefix mapping between the given public base URI and the
* given prefix.
* </p>
*
* @param uri The base URI that <code>prefix</code> expands to
* @param prefix A qname prefix
* @deprecated Prefix management via the ODM is very likely to be removed from Jena 2.4 onwards
*/
public void addPrefixMapping( String uri, String prefix ) {
m_prefixMap.setNsPrefix( prefix, uri );
}
/**
* <p>
* Add an entry for an alternative copy of the document with the given document
* URI.
* </p>
*
* @param docURI The public URI of the ontology document
* @param locationURL A locally resolvable URL where an alternative copy of the
* ontology document can be found
*/
public void addAltEntry( String docURI, String locationURL ) {
getFileManager().getLocationMapper().addAltEntry( docURI, locationURL );
}
/**
* <p>
* Add an entry that <code>model</code> is the appropriate model to use
* for the given ontology document. Will not replace any existing
* model that is cached for this URI (see
* {@link #addModel(String, Model, boolean)} for an alternative
* that can replace existing models).
* </p>
*
* @param docURI The public URI of the ontology document
* @param model A model containing the triples from the document
*/
public void addModel( String docURI, Model model ) {
addModel( docURI, model, false );
}
/**
* <p>
* Add an entry that <code>model</code> is the appropriate model to use
* for the given ontology document
* </p>
*
* @param docURI The public URI of the ontology document
* @param model A model containing the triples from the document
* @param replace If true, replace any existing entry with this one.
*/
public void addModel( String docURI, Model model, boolean replace ) {
if (getFileManager().getCachingModels() &&
(replace || !getFileManager().hasCachedModel( docURI )))
{
getFileManager().addCacheModel( docURI, model );
}
}
/**
* <p>
* Add an entry that <code>language</code> is the URI defining the
* representation language for the given document
* </p>
*
* @param docURI The public URI of the ontology document
* @param language A string defining the URI of the language
* @deprecated Language determination via the ODM will be removed from Jena 2.4 onwards
*/
public void addLanguageEntry( String docURI, String language ) {
m_languageMap.put( docURI, language );
}
/**
* <p>
* Remove all managed entries for the given document. Note does not side-effect
* the prefixes table: this will have to be done separately.
* </p>
*
* @param docURI The public URI for an ontology document
*/
public void forget( String docURI ) {
getFileManager().getLocationMapper().removeAltEntry( docURI );
getFileManager().removeCacheModel( docURI );
m_languageMap.remove( docURI );
}
/**
* <p>
* Answer the ontology model that results from loading the document with the
* given URI. This may be a cached model, if this document manager's policy
* is to cache loaded models. If not, or if no model is cached, the document
* will be read into a suitable model. The model will contain the imports closure
* of the ontology, if that is the current policy of this document manager.
* </p>
*
* @param uri Identifies the model to load.
* @param spec Specifies the structure of the ontology model to create
* @return An ontology model containing the statements from the ontology document.
* @see #getModel
*/
public OntModel getOntology( String uri, OntModelSpec spec ) {
// ensure consistency of document managers (to allow access to cached documents)
OntModelSpec _spec = spec;
if (_spec.getDocumentManager() != this) {
_spec = new OntModelSpec( spec );
_spec.setDocumentManager( this );
}
// cached already?
if (getFileManager().hasCachedModel( uri )) {
Model cached = getFileManager().getFromCache( uri );
if (cached instanceof OntModel) {
return (OntModel) cached;
}
else {
return ModelFactory.createOntologyModel( _spec, cached );
}
}
else {
OntModel m = ModelFactory.createOntologyModel( _spec, null );
read( m, uri, true );
// cache this model for future re-use
getFileManager().addCacheModel( uri, m );
return m;
}
}
/**
* <p>
* Answer the policy flag indicating whether the imports statements of
* loaded ontologies will be processed to build a union of s.
* </p>
*
* @return True if imported models will be included in a loaded model
*/
public boolean getProcessImports() {
return m_processImports;
}
/**
* <p>
* Answer true if the models loaded by this document manager from a given
* URI will be cached, so that they can be re-used in other compound
* ontology models.
* </p>
*
* @return If true, a cache is maintained of loaded models from their URI's.
*/
public boolean getCacheModels() {
return getFileManager().getCachingModels();
}
/**
* <p>
* Set the policy flag for processing imports of loaded ontologies.
* </p>
*
* @param processImports If true, load imported ontologies during load
* @see #getProcessImports
*/
public void setProcessImports( boolean processImports ) {
m_processImports = processImports;
}
/**
* <p>
* Set the policy flag that indicates whether loaded models are cached by URI
* </p>
*
* @param cacheModels If true, models will be cached by URI
* @see #getCacheModels()
*/
public void setCacheModels( boolean cacheModels ) {
getFileManager().setModelCaching( cacheModels );
}
/**
* <p>Add the given URI to the set of URI's we ignore in imports statements</p>
* @param uri A URI to ignore when importing
*/
public void addIgnoreImport( String uri ) {
m_ignoreImports.add( uri );
}
/**
* <p>Remove the given URI from the set of URI's we ignore in imports statements</p>
* @param uri A URI to ignore no longer when importing
*/
public void removeIgnoreImport( String uri ) {
m_ignoreImports.remove( uri );
}
/**
* <p>Answer an iterator over the set of URI's we're ignoring</p>
* @return An iterator over ignored imports
*/
public Iterator listIgnoredImports() {
return m_ignoreImports.iterator();
}
/**
* <p>Answer true if the given URI is one that will be ignored during imports </p>
* @param uri A URI to test
* @return True if uri will be ignored as an import
*/
public boolean ignoringImport( String uri ) {
return m_ignoreImports.contains( uri );
}
/**
* <p>
* Remove all entries from the model cache
* </p>
*/
public void clearCache() {
getFileManager().resetCache();
}
/**
* <p>
* Inspect the statements in the graph expressed by the given model, and load
* into the model any imported documents. Imports statements are recognised according
* to the model's language profile. An occurs check allows cycles of importing
* safely. This method will do nothing if the {@linkplain #getProcessImports policy}
* for this manager is not to process imports. If the {@linkplain #getCacheModels cache policy}
* for this doc manager allows, models will be cached by URI and re-used where possible.
* </p>
*
* @param model An ontology model whose imports are to be loaded.
*/
public void loadImports( OntModel model ) {
if (m_processImports) {
List readQueue = new ArrayList();
// add the imported statements from the given model to the processing queue
queueImports( model, readQueue, model.getProfile() );
loadImports( model, readQueue );
}
}
/**
* <p>Add the given model from the given URI as an import to the given model. Any models imported by the given
* URI will also be imported.</p>
*
* @param model A model to import into
* @param uri The URI of a document to import
*/
public void loadImport( OntModel model, String uri ) {
if (m_processImports) {
List readQueue = new ArrayList();
readQueue.add( uri );
loadImports( model, readQueue );
}
}
/**
* <p>Remove from the given model the import denoted by the given URI.</p>
*
* @param model A model
* @param uri The URI of a document to no longer import
*/
public void unloadImport( OntModel model, String uri ) {
if (m_processImports) {
List unloadQueue = new ArrayList();
unloadQueue.add( uri );
unloadImports( model, unloadQueue );
}
}
/**
* <p>Answer the URL of the most recently loaded policy URL, or null
* if no document manager policy has yet been loaded since the metadata
* search path was last set.</p>
* @return The most recently loaded policy URL or null.
*/
public String getLoadedPolicyURL() {
return m_policyURL;
}
// Internal implementation methods
/**
* <p>Load all of the imports in the queue</p>
* @param model The model to load the imports into
* @param readQueue The queue of imports to load
*/
protected void loadImports( OntModel model, List readQueue ) {
while (!readQueue.isEmpty()) {
// we process the import statements as a FIFO queue
String importURI = (String) readQueue.remove( 0 );
if (!model.hasLoadedImport( importURI ) && !ignoringImport( importURI )) {
// this file has not been processed yet
loadImport( model, importURI, readQueue );
}
}
}
/**
* <p>Unload all of the imports in the queue</p>
* @param model The model to unload the imports from
* @param unloadQueue The queue of imports to unload
*/
protected void unloadImports( OntModel model, List unloadQueue ) {
while (!unloadQueue.isEmpty()) {
// we process the import statements as a FIFO queue
String importURI = (String) unloadQueue.remove( 0 );
if (model.hasLoadedImport( importURI )) {
// this import has not been unloaded yet
// look up the cached model - if we can't find it, we can't unload the import
Model importModel = getModel( importURI );
if (importModel != null) {
List imports = new ArrayList();
// collect a list of the imports from the model that is scheduled for removal
for (StmtIterator i = importModel.listStatements( null, model.getProfile().IMPORTS(), (RDFNode) null ); i.hasNext(); ) {
imports.add( i.nextStatement().getResource().getURI() );
}
// now remove the sub-model
model.removeSubModel( importModel, false );
model.removeLoadedImport( importURI );
// check the list of imports of the model we have removed - if they are not
// imported by other imports that remain, we should remove them as well
for (StmtIterator i = model.listStatements( null, model.getProfile().IMPORTS(), (RDFNode) null ); i.hasNext(); ) {
imports.remove( i.nextStatement().getResource().getURI() );
}
// any imports that remain are scheduled for removal
unloadQueue.addAll( imports );
}
}
}
model.rebind();
}
/**
* <p>Add the ontologies imported by the given model to the end of the queue.</p>
*/
protected void queueImports( Model model, List readQueue, Profile profile ) {
if (model instanceof OntModel) {
// add the imported ontologies to the queue
readQueue.addAll( ((OntModel) model).listImportedOntologyURIs() );
}
else {
// we have to do the query manually
StmtIterator i = model.listStatements( null, profile.IMPORTS(), (RDFNode) null );
while (i.hasNext()) {
// read the next import statement and add to the queue
readQueue.add( i.nextStatement().getResource().getURI() );
}
}
}
/**
* <p>
* Initialise the mappings for uri's and prefixes by loading metadata
* from an RDF model.
* </p>
*
* @param path The URI path to search for a loadable model
*/
protected void initialiseMetadata( String path ) {
// search the path for metadata about locally cached models
Model metadata = findMetadata( path );
if (metadata != null) {
processMetadata( metadata );
}
}
/**
* <p>
* Search the given path for a resolvable URI, from which we load a model
* (assuming RDF/XML).
* </p>
*
* @param configPath The path to search
* @return A model loaded by resolving an entry on the path, or null if
* no path entries succeed.
*/
protected Model findMetadata( String configPath ) {
if (configPath == null) {
return null;
}
// Make a temporary file manager to look for the metadata file
FileManager fm = new FileManager();
fm.addLocatorFile();
fm.addLocatorURL();
fm.addLocatorClassLoader( fm.getClass().getClassLoader() );
try {
String uri = null ;
InputStream in = null ;
StringTokenizer pathElems = new StringTokenizer( configPath, FileManager.PATH_DELIMITER );
while (in == null && pathElems.hasMoreTokens()) {
uri = pathElems.nextToken();
in = fm.openNoMap( uri );
}
if (in != null) {
String syntax = FileUtils.guessLang(uri);
Model model = ModelFactory.createDefaultModel() ;
model.read( in, uri, syntax );
m_policyURL = uri;
return model;
}
}
catch (JenaException e) {
log.warn( "Exception while reading configuration: " + e.getMessage(), e);
}
return null;
}
/**
* <p>
* Load the ontology specification metadata from the model into the local
* mapping tables.
* </p>
*
* @param metadata A model containing metadata about ontologies.
*/
protected void processMetadata( Model metadata ) {
// there may be configuration for the location mapper in the ODM metadata file
getFileManager().getLocationMapper().processConfig( metadata );
// first we process the general policy statements for this document manager
for (ResIterator i = metadata.listSubjectsWithProperty( RDF.type, DOC_MGR_POLICY ); i.hasNext(); ) {
Resource policy = i.nextResource();
// iterate over each policy statement
for (StmtIterator j = policy.listProperties(); j.hasNext(); ) {
Statement s = j.nextStatement();
Property pred = s.getPredicate();
if (pred.equals( CACHE_MODELS )) {
setCacheModels( s.getBoolean() );
}
else if (pred.equals( PROCESS_IMPORTS )) {
setProcessImports( s.getBoolean() );
}
else if (pred.equals( IGNORE_IMPORT )) {
addIgnoreImport( s.getResource().getURI() );
}
else if (pred.equals( USE_DECLARED_NS_PREFIXES )) {
setUseDeclaredPrefixes( s.getBoolean() );
}
}
}
// then we look up individual meta-data for particular ontologies
for (ResIterator i = metadata.listSubjectsWithProperty( RDF.type, ONTOLOGY_SPEC ); i.hasNext(); ) {
Resource root = i.nextResource();
Statement s = root.getProperty( PUBLIC_URI );
if (s != null) {
// this will be the key in the mappings
String publicURI = s.getResource().getURI();
// there may be a cached copy for this ontology
s = root.getProperty( ALT_URL );
if (s != null) addAltEntry( publicURI, s.getResource().getURI() );
// there may be a standard prefix for this ontology
s = root.getProperty( PREFIX );
if (s != null) {
// if the namespace doesn't end with a suitable split point character, add a
boolean endWithNCNameCh = XMLChar.isNCName( publicURI.charAt( publicURI.length() - 1 ) );
String prefixExpansion = endWithNCNameCh ? (publicURI + ANCHOR) : publicURI;
addPrefixMapping( prefixExpansion, s.getString() );
}
// there may be a language specified for this ontology
s = root.getProperty( LANGUAGE );
if (s != null) addLanguageEntry( publicURI, s.getResource().getURI() );
}
else {
log.warn( "Ontology specification node lists no public URI - node ignored");
}
}
}
/**
* <p>
* Load the document referenced by the given URI into the model. The cache will be
* used if permitted by the policy, and the imports of loaded model will be added to
* the end of the queue.
* </p>
*
* @param model The composite model to load into
* @param importURI The URI of the document to load
* @param readQueue Cumulative read queue for this operation
*/
protected void loadImport( OntModel model, String importURI, List readQueue ) {
if (m_processImports) {
log.debug( "OntDocumentManager loading " + importURI );
// add this model to occurs check list
model.addLoadedImport( importURI );
// if we have a cached version get that, otherwise load from the URI but don't do the imports closure
Model in = getModel( importURI );
// if not cached, we must load it from source
if (in == null) {
// create a sub ontology model and load it from the source
// note that we do this to ensure we recursively load imports
ModelMaker maker = model.getSpecification().getImportModelMaker();
boolean loaded = maker.hasModel( importURI );
in = maker.openModel( importURI );
// if the graph was already in existence, we don't need to read the contents (we assume)!
if (!loaded) {
read( in, importURI, true );
}
}
// we trap the case of importing ourself (which may happen via an indirect imports chain)
if (in != model) {
// queue the imports from the input model on the end of the read queue
queueImports( in, readQueue, model.getProfile() );
// add to the imports union graph, but don't do the rebind yet
model.addSubModel( in, false );
// we also cache the model if we haven't seen it before (and caching is on)
addModel( importURI, in );
}
}
}
/**
* <p>
* Load into the given model from the given URI, or from a local cache URI if defined.
* </p>
*
* @param model A model to read statements into
* @param uri A URI string
* @param warn If true, warn on RDF exception
* @return True if the uri was read successfully
*/
protected boolean read( Model model, String uri, boolean warn ) {
boolean success = false;
try {
getFileManager().readModel( model, uri );
success = true;
}
catch (Exception e) {
log.warn( "An error occurred while attempting to read from " + uri + ". Msg was '" + e.getMessage() + "'.", e );
}
return success;
}
/**
* <p>Set the default option settings.</p>
*/
protected void setDefaults() {
setCacheModels( true );
setUseDeclaredPrefixes( true );
setProcessImports( true );
}
// Inner class definitions
} |
package com.ninty.runtime;
import com.ninty.runtime.heap.NiObject;
import java.util.Arrays;
public class OperandStack {
int size;
Slot[] slots;
OperandStack(int size) {
slots = new Slot[size];
for (int i = 0; i < size; i++) {
slots[i] = new Slot();
}
}
public void pushInt(int val) {
slots[size].num = val;
size++;
}
public int popInt() {
size
return slots[size].num;
}
public void pushLong(long val) {
int low = (int) val;
int high = (int) (val >>> 32);
pushInt(low);
pushInt(high);
}
public long popLong() {
long high = (popInt() & 0x00000000ffffffffL) << 32;
long low = popInt() & 0x00000000ffffffffL;
return high | low;
}
public void pushFloat(float val) {
int num = Float.floatToIntBits(val);
pushInt(num);
}
public float popFloat() {
int num = popInt();
return Float.intBitsToFloat(num);
}
public void pushDouble(double val) {
long num = Double.doubleToLongBits(val);
pushLong(num);
}
public double popDouble() {
long num = popLong();
return Double.longBitsToDouble(num);
}
public void pushRef(NiObject ref) {
slots[size].ref = ref;
size++;
}
public NiObject popRef() {
size
NiObject ref = slots[size].ref;
// slots[size].ref = null;
return ref;
}
public void pushSlot(Slot slot) {
slots[size] = slot;
size++;
}
public Slot popSlot() {
size
return slots[size];
}
public NiObject getRefFromTop(int n) {
return slots[size - n].ref;
}
@Override
public String toString() {
return "OperandStack{" +
"slots=" + Arrays.toString(slots) +
", size=" + size +
'}';
}
} |
// This file was generated by RobotBuilder. It contains sections of
// code that are automatically generated and assigned by robotbuilder.
// These sections will be updated in the future when you export to
// Java from RobotBuilder. Do not put any code or make any change in
// the blocks indicating autogenerated code or it will be lost on an
// update. Deleting the comments indicating the section will prevent
// it from being updated in th future.
package org.usfirst.frc330.Beachbot2013Java;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.buttons.JoystickButton;
import org.usfirst.frc330.Beachbot2013Java.commands.*;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
/*
* $Log: OI.java,v $
* Revision 1.20 2013-03-17 17:17:32 jross
* use command group for shooting and pickup on
*
* Revision 1.19 2013-03-17 01:57:22 jdavid
* Added pickup sensor
*
* Revision 1.18 2013-03-15 03:08:37 echan
* Added the command to shoot low at full speed
*
* Revision 1.17 2013-03-15 02:50:16 echan
* added cvs log comments
*
*/
/**
* This class is the glue that binds the controls on the physical operator
* interface to the commands and command groups that allow control of the robot.
*/
public class OI {
//// CREATING BUTTONS
// One type of button is a joystick button which is any button on a joystick.
// You create one by telling it which joystick it's on and which button
// number it is.
// Joystick stick = new Joystick(port);
// Button button = new JoystickButton(stick, buttonNumber);
// Another type of button you can create is a DigitalIOButton, which is
// a button or switch hooked up to the cypress module. These are useful if
// you want to build a customized operator interface.
// Button button = new DigitalIOButton(1);
// There are a few additional built in buttons you can use. Additionally,
// by subclassing Button you can create custom triggers and bind those to
// commands the same as any other Button.
//// TRIGGERING COMMANDS WITH BUTTONS
// Once you have a button, it's trivial to bind it to a button in one of
// three ways:
// Start the command when the button is pressed and let it run the command
// until it is finished as determined by it's isFinished method.
// button.whenPressed(new ExampleCommand());
// Run the command while the button is being held down and interrupt it once
// the button is released.
// button.whileHeld(new ExampleCommand());
// Start the command when the button is released and let it run the command
// until it is finished as determined by it's isFinished method.
// button.whenReleased(new ExampleCommand());
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS
public JoystickButton shiftHighButton;
public Joystick leftJoystick;
public JoystickButton shiftLowButton;
public Joystick rightJoystick;
public JoystickButton pickupDownButton;
public JoystickButton pickupUpButton;
public JoystickButton shootButton;
public JoystickButton shootHighButton;
public JoystickButton shootLowButton;
public JoystickButton armClimbingButton;
public JoystickButton frisbeePickupOffButton;
public JoystickButton frisbeePickupOnButton;
public JoystickButton slowFrisbeePickupButton;
public JoystickButton reversePickupButton;
public Joystick operatorJoystick;
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS
public OI() {
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS
operatorJoystick = new Joystick(3);
reversePickupButton = new JoystickButton(operatorJoystick, 10);
reversePickupButton.whenPressed(new ReversePickup());
slowFrisbeePickupButton = new JoystickButton(operatorJoystick, 3);
slowFrisbeePickupButton.whenPressed(new SlowPickupFrisbees());
frisbeePickupOnButton = new JoystickButton(operatorJoystick, 7);
frisbeePickupOnButton.whenPressed(new PickupOnCommandGroup());
frisbeePickupOffButton = new JoystickButton(operatorJoystick, 6);
frisbeePickupOffButton.whenPressed(new PickupFrisbeesOff());
armClimbingButton = new JoystickButton(operatorJoystick, 5);
armClimbingButton.whenPressed(new ArmClimbing());
shootLowButton = new JoystickButton(operatorJoystick, 2);
shootLowButton.whenPressed(new ShootLowCommandGroup());
shootHighButton = new JoystickButton(operatorJoystick, 4);
shootHighButton.whenPressed(new ArmHighShooting());
shootButton = new JoystickButton(operatorJoystick, 1);
shootButton.whenPressed(new LaunchFrisbee());
pickupUpButton = new JoystickButton(operatorJoystick, 8);
pickupUpButton.whenPressed(new PickupUp());
pickupDownButton = new JoystickButton(operatorJoystick, 9);
pickupDownButton.whenPressed(new PickupDown());
rightJoystick = new Joystick(2);
shiftLowButton = new JoystickButton(rightJoystick, 1);
shiftLowButton.whenPressed(new ShiftLow());
leftJoystick = new Joystick(1);
shiftHighButton = new JoystickButton(leftJoystick, 1);
shiftHighButton.whenPressed(new ShiftHigh());
// SmartDashboard Buttons
SmartDashboard.putData("AutonomousCommand", new AutonomousCommand());
SmartDashboard.putData("ShiftHigh", new ShiftHigh());
SmartDashboard.putData("ShiftLow", new ShiftLow());
SmartDashboard.putData("MarsRock", new MarsRock());
SmartDashboard.putData("PickupDown", new PickupDown());
SmartDashboard.putData("PickupUp", new PickupUp());
SmartDashboard.putData("LaunchFrisbee", new LaunchFrisbee());
SmartDashboard.putData("ShootHigh", new ShootHigh());
SmartDashboard.putData("ShootLow", new ShootLow());
SmartDashboard.putData("PickupFrisbees", new PickupFrisbees());
SmartDashboard.putData("PickupFrisbeesOn", new PickupFrisbeesOn());
SmartDashboard.putData("PickupFrisbeesOff", new PickupFrisbeesOff());
SmartDashboard.putData("ReversePickup", new ReversePickup());
SmartDashboard.putData("SlowPickupFrisbees", new SlowPickupFrisbees());
SmartDashboard.putData("ArmLowShooting", new ArmLowShooting());
SmartDashboard.putData("ArmHighShooting", new ArmHighShooting());
SmartDashboard.putData("ArmClimbing", new ArmClimbing());
SmartDashboard.putData("StopShootHigh", new StopShootHigh());
SmartDashboard.putData("StopShootLow", new StopShootLow());
SmartDashboard.putData("ControlLEDs", new ControlLEDs());
SmartDashboard.putData("TurnCamera", new TurnCamera());
SmartDashboard.putData("TurnCameraIterative", new TurnCameraIterative());
SmartDashboard.putData("ArmLowPickup", new ArmLowPickup());
SmartDashboard.putData("SetArmZero", new SetArmZero());
SmartDashboard.putData("PickupOnCommandGroup", new PickupOnCommandGroup());
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS
}
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=FUNCTIONS
public Joystick getLeftJoystick() {
return leftJoystick;
}
public Joystick getRightJoystick() {
return rightJoystick;
}
public Joystick getOperatorJoystick() {
return operatorJoystick;
}
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=FUNCTIONS
} |
package com.northernwall.hadrian;
import com.squareup.okhttp.MediaType;
public class Const {
public static final String NO_STATUS = "-";
public static final String HTTP = "http:
public static final String HTTP_GET = "GET";
public static final String HTTP_POST = "POST";
public static final String HTTP_PUT = "PUT";
public static final String HTTP_DELETE = "DELETE";
public static final String COOKIE_SESSION = "session";
public static final String COOKIE_PORTAL_NAME = "portalname";
public static final int COOKIE_EXPRIY = 24*60*60*1000;
public static final String HOST = "{host}";
public static final String OPERATION_CREATE = "create";
public static final String OPERATION_UPDATE = "update";
public static final String OPERATION_DELETE = "delete";
public static final String TYPE_SERVICE = "service";
public static final String TYPE_HOST = "host";
public static final String TYPE_VIP = "vip";
public static final String TYPE_HOST_VIP = "hostvip";
public static final String ATTR_SESSION = "session";
public static final String ATTR_USER = "user";
public static final String TEXT = "text/plain; charset=utf-8";
public static final String HTML = "text/html; charset=utf-8";
public static final String JSON = "application/json; charset=utf-8";
public static final MediaType JSON_MEDIA_TYPE = MediaType.parse(JSON);
public static final String MAVEN_SNAPSHOT = "SNAPSHOT";
//Properties file constants
public static final String PROPERTIES_FILENAME = "hadrian.properties";
public static final String LOGBACK_FILENAME = "logback.filename";
public static final String LOGBACK_FILENAME_DEFAULT = "logback.xml";
public static final String JETTY_PORT = "jetty.port";
public static final String JETTY_PORT_DEFAULT = "9090";
public static final String JETTY_IDLE_TIMEOUT = "jetty.idleTimeout";
public static final String JETTY_IDLE_TIMEOUT_DEFAULT = "1000";
public static final String JETTY_ACCEPT_QUEUE_SIZE = "jetty.idleTimeout";
public static final String JETTY_ACCEPT_QUEUE_SIZE_DEFAULT = "100";
public static final String HOST_DETAILS_URL = "host.detailsUrl";
public static final String HOST_DETAILS_ATTRIBUTES = "host.detailsAttrs";
public static final String WEB_HOOK_SENDER_FACTORY_CLASS_NAME = "webHookSender.factoryClassName";
public static final String WEB_HOOK_SENDER_FACTORY_CLASS_NAME_DEFAULT = "com.northernwall.hadrian.webhook.simple.SimpleWebHookSenderFactory";
public static final String WEB_HOOK_CALLBACK_HOST = "webhook.callbackHost";
public static final String WEB_HOOK_CALLBACK_HOST_DEFAULT = "http://127.0.0.1";
public static final String SIMPLE_WEB_HOOK_URL = "simpleWebhook.url";
public static final String SIMPLE_WEB_HOOK_URL_DEFAULT = "http://127.0.0.1:9090/webhook";
public static final String SIMPLE_WEB_HOOK_DELAY = "simpleWebhook.delay";
public static final String SIMPLE_WEB_HOOK_DELAY_DEFAULT = "15";
public static final String MAVEN_HELPER_FACTORY_CLASS_NAME = "maven.factoryClassName";
//public static final String MAVEN_HELPER_FACTORY_CLASS_NAME_DEFAULT = "com.northernwall.hadrian.maven.ssh.SshMavenHelperFactory";
public static final String MAVEN_HELPER_FACTORY_CLASS_NAME_DEFAULT = "com.northernwall.hadrian.maven.http.HttpMavenHelperFactory";
public static final String MAVEN_MAX_VERSIONS = "maven.maxVersions";
public static final String MAVEN_MAX_VERSIONS_DEFAULT = "15";
public static final String MAVEN_URL = "maven.http.url";
public static final String MAVEN_URL_DEFAULT = "http://127.0.0.1/mvnrepo/internal/";
public static final String MAVEN_USERNAME = "maven.http.username";
public static final String MAVEN_USERNAME_DEFAULT = "-";
public static final String MAVEN_PASSWORD = "maven.http.password";
public static final String MAVEN_PASSWORD_DEFAULT = "-";
public static final String DATA_ACCESS_FACTORY_CLASS_NAME = "dataAccess.factoryClassName";
public static final String DATA_ACCESS_FACTORY_CLASS_NAME_DEFAULT = "com.northernwall.hadrian.db.InMemoryDataAccessFactory";
//public static final String DATA_ACCESS_FACTORY_CLASS_NAME_DEFAULT = "com.northernwall.hadrian.db.CassandraDataAccessFactory";
public static final String CASS_NODE = "dataAccess.cassandra.node";
public static final String CASS_NODE_DEFAULT = "127.0.0.1";
public static final String CASS_KEY_SPACE = "dataAccess.cassandra.keyspace";
public static final String CASS_KEY_SPACE_DEFAULT = "devops";
public static final String CASS_REPLICATION_FACTOR = "dataAccess.cassandra.replicationFactor";
public static final String CASS_REPLICATION_FACTOR_DEFAULT = "1";
public static final String IN_MEMORY_DATA_FILE_NAME = "dataAccess.inMemory.dataFileName";
public static final String IN_MEMORY_DATA_FILE_NAME_DEFAULT = "data.json";
public static final String ACCESS_FACTORY_CLASS_NAME = "access.factoryClassName";
public static final String ACCESS_FACTORY_CLASS_NAME_DEFAULT = "com.northernwall.hadrian.access.SimpleAccessFactory";
public static final String CONFIG_DATA_CENTERS = "config.dataCenters";
public static final String CONFIG_DATA_CENTERS_DEFAULT = "dc";
public static final String CONFIG_NETWORKS = "config.networks";
public static final String CONFIG_NETWORKS_DEFAULT = "prd, tst";
public static final String CONFIG_ENVSS = "config.envs";
public static final String CONFIG_ENVS_DEFAULT = "Java7, Java8, NodeJS";
public static final String CONFIG_SIZES = "config.sizes";
public static final String CONFIG_SIZES_DEFAULT = "S, M, L, XL";
public static final String CONFIG_PROTOCOLS = "config.protocols";
public static final String CONFIG_PROTOCOLS_DEFAULT = "HTTP, HTTPS, TCP";
public static final String CONFIG_DOMAINS = "config.domains";
public static final String CONFIG_DOMAINS_DEFAULT = "northernwall.com";
public static final String CONFIG_ARTIFACT_TYPES = "config.artifactTypes";
public static final String CONFIG_ARTIFACT_TYPES_DEFAULT = ".jar, .war, .targz";
private Const() {
}
} |
package no.s11.owlapi;
import java.io.File;
import java.net.URI;
import java.util.Arrays;
import java.util.List;
import org.semanticweb.owlapi.apibinding.OWLManager;
import org.semanticweb.owlapi.model.IRI;
import org.semanticweb.owlapi.model.OWLOntology;
import org.semanticweb.owlapi.model.OWLOntologyCreationException;
import org.semanticweb.owlapi.model.OWLOntologyManager;
import org.semanticweb.owlapi.profiles.OWL2DLProfile;
import org.semanticweb.owlapi.profiles.OWL2ELProfile;
import org.semanticweb.owlapi.profiles.OWL2Profile;
import org.semanticweb.owlapi.profiles.OWL2QLProfile;
import org.semanticweb.owlapi.profiles.OWL2RLProfile;
import org.semanticweb.owlapi.profiles.OWLProfile;
import org.semanticweb.owlapi.profiles.OWLProfileReport;
import org.semanticweb.owlapi.profiles.OWLProfileViolation;
public class ProfileChecker {
OWLProfile DEFAULT_PROFILE = new OWL2Profile();
List<OWLProfile> PROFILES = Arrays.asList(new OWL2DLProfile(),
new OWL2ELProfile(), new OWL2Profile(), new OWL2QLProfile(),
new OWL2RLProfile());
OWLOntologyManager m = OWLManager.createOWLOntologyManager();
public static void main(String[] args) throws OWLOntologyCreationException {
System.exit(new ProfileChecker().check(args));
}
public int check(String[] args) throws OWLOntologyCreationException {
if (args.length == 0 || args[0].equals("-h")) {
System.out
.println("Usage: profilechecker.jar <ontology.owl> [profile]");
System.out.println();
System.out.println("Available profiles:");
for (OWLProfile p : PROFILES) {
System.out.print(p.getClass().getSimpleName());
System.out.print(" (" + p.getName() + ")");
if (p.getClass().equals(DEFAULT_PROFILE.getClass())) {
System.out.print(" -default-");
}
// Can't use p.getName() as it contains spaces
System.out.println();
}
System.out.println("--all");
return 0;
}
IRI documentIRI = IRI.create(args[0]);
if (!documentIRI.isAbsolute()) {
// Assume it's a file
documentIRI = IRI.create(new File(args[0]));
}
OWLOntology o = m.loadOntologyFromOntologyDocument(documentIRI);
OWLProfile profile = null;
if (args.length > 1) {
String profileName = args[1];
for (OWLProfile p : PROFILES) {
if (p.getClass().getSimpleName().equals(profileName)) {
profile = p;
}
}
if (profile == null && !profileName.equals("--all")) {
throw new IllegalArgumentException("Unknown profile: "
+ profileName);
}
} else {
profile = DEFAULT_PROFILE;
}
if (profile == null) {
boolean anyFailed = false;
for (OWLProfile p : PROFILES) {
System.out.print(p.getClass().getSimpleName() + ": ");
OWLProfileReport report = p.checkOntology(o);
if (report.isInProfile()) {
System.out.println("OK");
} else {
System.out.println(report.getViolations().size()
+ " violations");
anyFailed = true;
}
}
return anyFailed ? 1 : 0;
} else {
OWLProfileReport report = profile.checkOntology(o);
for (OWLProfileViolation v : report.getViolations()) {
System.err.println(v.toString());
}
if (!report.isInProfile()) {
return 1;
}
return 0;
}
}
} |
package com.ociweb.iot.grove;
import com.ociweb.iot.hardware.I2CConnection;
import com.ociweb.iot.hardware.IODevice;
import com.ociweb.iot.maker.Hardware;
/**
* Holds information for all standard Analog and Digital I/O twigs in the Grove starter kit.
*
* Methods are necessary for interpreting new connections declared in
* IoTSetup declareConnections in the maker app.
*
* @see com.ociweb.iot.hardware.IODevice
*/
public enum GroveTwig implements IODevice {
UVSensor() {
@Override
public boolean isInput() {
return true;
}
@Override
public int response() {
return 30;
}
},
LightSensor() {
@Override
public boolean isInput() {
return true;
}
@Override
public int response() {
return 100;
}
},
SoundSensor() {
@Override
public boolean isInput() {
return true;
}
@Override
public int response() {
return 2;
}
},
AngleSensor() {
@Override
public boolean isInput() {
return true;
}
@Override
public int response() {
return 40;
}
},
MoistureSensor() {
@Override
public boolean isInput() {
return true;
}
},
Button() {
@Override
public boolean isInput() {
return true;
}
public int response() {
return 40;
}
@Override
public int range() {
return 1;
}
},
MotionSensor() {
@Override
public boolean isInput() {
return true;
}
@Override
public int range() {
return 1;
}
},
RotaryEncoder() {
@Override
public boolean isInput() {
return true;
}
@Override
public int pinsUsed() {
return 2;
}
},
Buzzer() {
@Override
public boolean isOutput() {
return true;
}
},
LED() {
@Override
public boolean isOutput() {
return true;
}
@Override
public boolean isPWM() {
return true;
}
},
Relay() {
@Override
public boolean isOutput() {
return true;
}
},
Servo() {
@Override
public boolean isOutput() {
return true;
}
},
I2C() {
@Override
public boolean isInput() {
return true;
}
@Override
public boolean isOutput() {
return true;
}
},
UltrasonicRanger() {
@Override
public boolean isInput() {
return true;
}
@Override
public int range() {
return 1024;
}
@Override
public int response() {
return 200;
}
@Override
public int scanDelay() {
return 1_420_000;
}
},
WaterSensor(){
@Override
public boolean isInput(){
return true;
}
@Override
public int range(){
return 512;
}
};
/**
* @return True if this twig is an input device, and false otherwise.
*/
public boolean isInput() {
return false;
}
/**
* @return True if this twig is an output device, and false otherwise.
*/
public boolean isOutput() {
return false;
}
/**
* @return Response time, in milliseconds, for this twig.
*/
public int response() {
return 20;
}
/**
* @return Delay, in milliseconds, for scan. TODO: What's scan?
*/
public int scanDelay() {
return 0;
}
/**
* @return True if this twig is Pulse Width Modulated (PWM) device, and
* false otherwise.
*/
public boolean isPWM() {
return false;
}
/**
* @return True if this twig is an I2C device, and false otherwise.
*/
public boolean isI2C() {
return false;
}
/**
* @return The {@link I2CConnection} for this twig if it is an I2C
* device, as indicated by {@link #isI2C()}.
*/
public I2CConnection getI2CConnection() {
return null;
}
/**
* @return The possible value range for reads from this device (from zero).
*/
public int range() {
return 256;
}
/**
* @return the setup bytes needed to initialized the connected I2C device
*/
public byte[] I2COutSetup() {
return null;
}
/**
* Validates if the I2C data from from the device is a valid response for this twig
*
* @param backing
* @param position
* @param length
* @param mask
*
* @return fals if the bytes returned from the device were not some valid response
*/
public boolean isValid(byte[] backing, int position, int length, int mask) {
return true;
}
/**
* @return The number of hardware pins that this twig uses.
*/
public int pinsUsed() {
return 1;
}
} |
package com.jme.scene.state.lwjgl;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.ArrayList;
import java.util.Stack;
import java.util.logging.Logger;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.ARBFragmentShader;
import org.lwjgl.opengl.ARBMultitexture;
import org.lwjgl.opengl.ARBTextureBorderClamp;
import org.lwjgl.opengl.ARBTextureCompression;
import org.lwjgl.opengl.ARBTextureEnvCombine;
import org.lwjgl.opengl.ARBTextureEnvDot3;
import org.lwjgl.opengl.ARBVertexShader;
import org.lwjgl.opengl.EXTTextureCompressionS3TC;
import org.lwjgl.opengl.EXTTextureFilterAnisotropic;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.GLContext;
import org.lwjgl.opengl.Util;
import org.lwjgl.opengl.glu.GLU;
import org.lwjgl.opengl.glu.MipMap;
import com.jme.image.Image;
import com.jme.image.Texture;
import com.jme.math.FastMath;
import com.jme.math.Vector3f;
import com.jme.renderer.ColorRGBA;
import com.jme.renderer.RenderContext;
import com.jme.scene.SceneElement;
import com.jme.scene.state.RenderState;
import com.jme.scene.state.TextureState;
import com.jme.scene.state.lwjgl.records.StateRecord;
import com.jme.scene.state.lwjgl.records.TextureRecord;
import com.jme.scene.state.lwjgl.records.TextureStateRecord;
import com.jme.scene.state.lwjgl.records.TextureUnitRecord;
import com.jme.system.DisplaySystem;
import com.jme.util.TextureManager;
/**
* <code>LWJGLTextureState</code> subclasses the TextureState object using the
* LWJGL API to access OpenGL for texture processing.
*
* @author Mark Powell
* @author Joshua Slack - updates, optimizations, etc. also StateRecords
* @version $Id: LWJGLTextureState.java,v 1.94 2007-08-20 16:53:53 nca Exp $
*/
public class LWJGLTextureState extends TextureState {
private static final Logger logger = Logger.getLogger(LWJGLTextureState.class.getName());
private static final long serialVersionUID = 1L;
private static int[] imageComponents = { GL11.GL_RGBA4, GL11.GL_RGB8,
GL11.GL_RGB5_A1, GL11.GL_RGBA8, GL11.GL_LUMINANCE8_ALPHA8,
EXTTextureCompressionS3TC.GL_COMPRESSED_RGB_S3TC_DXT1_EXT,
EXTTextureCompressionS3TC.GL_COMPRESSED_RGBA_S3TC_DXT1_EXT,
EXTTextureCompressionS3TC.GL_COMPRESSED_RGBA_S3TC_DXT3_EXT,
EXTTextureCompressionS3TC.GL_COMPRESSED_RGBA_S3TC_DXT5_EXT,
EXTTextureCompressionS3TC.GL_COMPRESSED_RGB_S3TC_DXT1_EXT,
EXTTextureCompressionS3TC.GL_COMPRESSED_RGBA_S3TC_DXT1_EXT,
EXTTextureCompressionS3TC.GL_COMPRESSED_RGBA_S3TC_DXT3_EXT,
EXTTextureCompressionS3TC.GL_COMPRESSED_RGBA_S3TC_DXT5_EXT };
private static int[] imageFormats = { GL11.GL_RGBA, GL11.GL_RGB,
GL11.GL_RGBA, GL11.GL_RGBA, GL11.GL_LUMINANCE_ALPHA, GL11.GL_RGB,
GL11.GL_RGBA, GL11.GL_RGBA, GL11.GL_RGBA };
private static boolean inited = false;
/**
* Constructor instantiates a new <code>LWJGLTextureState</code> object.
* The number of textures that can be combined is determined during
* construction. This equates the number of texture units supported by the
* graphics card.
*/
public LWJGLTextureState() {
super();
// get our array of texture objects ready.
texture = new ArrayList<Texture>();
// See if we haven't already setup a texturestate before.
if (!inited) {
// Check for support of multitextures.
supportsMultiTexture = supportsMultiTextureDetected = GLContext.getCapabilities().GL_ARB_multitexture;
// Check for support of fixed function dot3 environment settings
supportsEnvDot3 = supportsEnvDot3Detected = GLContext.getCapabilities().GL_ARB_texture_env_dot3;
// Check for support of fixed function dot3 environment settings
supportsEnvCombine = supportsEnvCombineDetected = GLContext.getCapabilities().GL_ARB_texture_env_combine;
// If we do support multitexturing, find out how many textures we
// can handle.
if (supportsMultiTexture) {
IntBuffer buf = BufferUtils.createIntBuffer(16);
GL11.glGetInteger(ARBMultitexture.GL_MAX_TEXTURE_UNITS_ARB, buf);
numFixedTexUnits = buf.get(0);
} else {
numFixedTexUnits = 1;
}
// Go on to check number of texture units supported for vertex and
// fragment shaders
if (GLContext.getCapabilities().GL_ARB_shader_objects
&& GLContext.getCapabilities().GL_ARB_vertex_shader
&& GLContext.getCapabilities().GL_ARB_fragment_shader) {
IntBuffer buf = BufferUtils.createIntBuffer(16);
GL11.glGetInteger(
ARBVertexShader.GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS_ARB,
buf);
numVertexTexUnits = buf.get(0);
GL11.glGetInteger(
ARBFragmentShader.GL_MAX_TEXTURE_IMAGE_UNITS_ARB, buf);
numFragmentTexUnits = buf.get(0);
GL11.glGetInteger(
ARBFragmentShader.GL_MAX_TEXTURE_COORDS_ARB, buf);
numFragmentTexCoordUnits = buf.get(0);
} else {
// based on nvidia dev doc:
// http://developer.nvidia.com/object/General_FAQ.html
// "For GPUs that do not support GL_ARB_fragment_program and
// GL_NV_fragment_program, those two limits are set equal to
// GL_MAX_TEXTURE_UNITS."
numFragmentTexCoordUnits = numFixedTexUnits;
numFragmentTexUnits = numFixedTexUnits;
// We'll set this to 0 for now since we do not know:
numVertexTexUnits = 0;
}
// Now determine the maximum number of supported texture units
numTotalTexUnits = Math.max(numFragmentTexCoordUnits,
Math.max(numFixedTexUnits,
Math.max(numFragmentTexUnits,
numVertexTexUnits)));
// Check for S3 texture compression capability.
supportsS3TCCompression = supportsS3TCCompressionDetected = GLContext.getCapabilities().GL_EXT_texture_compression_s3tc;
// See if we support anisotropic filtering
supportsAniso = supportsAnisoDetected = GLContext.getCapabilities().GL_EXT_texture_filter_anisotropic;
if (supportsAniso) {
// Due to LWJGL buffer check, you can't use smaller sized
// buffers (min_size = 16 for glGetFloat()).
FloatBuffer max_a = BufferUtils.createFloatBuffer(16);
max_a.rewind();
// Grab the maximum anisotropic filter.
GL11.glGetFloat(
EXTTextureFilterAnisotropic.GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT,
max_a);
// set max.
maxAnisotropic = max_a.get(0);
}
// See if we support textures that are not power of 2 in size.
supportsNonPowerTwo = supportsNonPowerTwoDetected = GLContext.getCapabilities().GL_ARB_texture_non_power_of_two;
// See if we support textures that do not have width == height.
supportsRectangular = supportsRectangularDetected = GLContext.getCapabilities().GL_ARB_texture_rectangle;
// Setup our default texture by adding it to our array and loading
// it, then clearing our array.
setTexture(defaultTexture);
load(0);
this.texture.clear();
// We're done initing! Wee! :)
inited = true;
}
}
/**
* override MipMap to access helper methods
*/
protected static class LWJGLMipMap extends MipMap {
/**
* @see MipMap#glGetIntegerv(int)
*/
protected static int glGetIntegerv(int what) {
return org.lwjgl.opengl.glu.Util.glGetIntegerv(what);
}
/**
* @see MipMap#nearestPower(int)
*/
protected static int nearestPower(int value) {
return org.lwjgl.opengl.glu.Util.nearestPower(value);
}
/**
* @see MipMap#bytesPerPixel(int, int)
*/
protected static int bytesPerPixel(int format, int type) {
return org.lwjgl.opengl.glu.Util.bytesPerPixel(format, type);
}
}
@Override
public void load(int unit) {
Texture texture = getTexture(unit);
if (texture == null) {
return;
}
RenderContext context = DisplaySystem.getDisplaySystem()
.getCurrentContext();
TextureStateRecord record = null;
if (context != null)
record = (TextureStateRecord) context.getStateRecord(RS_TEXTURE);
// Check we are in the right unit
if (record != null)
checkAndSetUnit(unit, record);
// Create the texture
if (texture.getTextureKey() != null) {
Texture cached = TextureManager.findCachedTexture(texture
.getTextureKey());
if (cached == null) {
TextureManager.addToCache(texture);
} else if (cached.getTextureId() != 0) {
texture.setTextureId(cached.getTextureId());
GL11.glBindTexture(GL11.GL_TEXTURE_2D, cached.getTextureId());
if (record != null)
record.units[unit].boundTexture = texture.getTextureId();
return;
}
}
IntBuffer id = BufferUtils.createIntBuffer(1);
id.clear();
GL11.glGenTextures(id);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, id.get(0));
if (record != null)
record.units[unit].boundTexture = id.get(0);
texture.setTextureId(id.get(0));
TextureManager.registerForCleanup(texture.getTextureKey(), texture
.getTextureId());
// pass image data to OpenGL
Image image = texture.getImage();
if (image == null) {
logger.warning("Image data for texture is null.");
}
// set alignment to support images with width % 4 != 0, as images are
// not aligned
GL11.glPixelStorei(GL11.GL_UNPACK_ALIGNMENT, 1);
// Get texture image data. Not all textures have image data.
// For example, AM_COMBINE modes can use primary colors,
// texture output, and constants to modify fragments via the
// texture units.
if (image != null) {
if (!supportsNonPowerTwo
&& (!FastMath.isPowerOfTwo(image.getWidth()) || !FastMath
.isPowerOfTwo(image.getHeight()))) {
logger.warning("Attempted to apply texture with size that is not power "
+ "of 2: "
+ image.getWidth()
+ " x "
+ image.getHeight());
final int maxSize = LWJGLMipMap
.glGetIntegerv(GL11.GL_MAX_TEXTURE_SIZE);
int actualWidth = image.getWidth();
int w = LWJGLMipMap.nearestPower(actualWidth);
if (w > maxSize) {
w = maxSize;
}
int actualHeight = image.getHeight();
int h = LWJGLMipMap.nearestPower(actualHeight);
if (h > maxSize) {
h = maxSize;
}
logger.warning("Rescaling image to " + w + " x " + h + " !!!");
// must rescale image to get "top" mipmap texture image
int format = imageFormats[image.getType()];
int type = GL11.GL_UNSIGNED_BYTE;
int bpp = LWJGLMipMap.bytesPerPixel(format, type);
ByteBuffer scaledImage = BufferUtils.createByteBuffer((w + 4)
* h * bpp);
int error = MipMap.gluScaleImage(format, actualWidth,
actualHeight, type, image.getData(), w, h, type,
scaledImage);
if (error != 0) {
Util.checkGLError();
}
image.setWidth(w);
image.setHeight(h);
image.setData(scaledImage);
}
// For textures which need mipmaps auto-generating and which
// aren't using compressed images, generate the mipmaps.
// A new mipmap builder may be needed to build mipmaps for
// compressed textures.
if (texture.getMipmap() >= Texture.MM_NEAREST_NEAREST
&& !image.hasMipmaps() && !image.isCompressedType()) {
// insure the buffer is ready for reading
image.getData().rewind();
GLU.gluBuild2DMipmaps(GL11.GL_TEXTURE_2D, imageComponents[image
.getType()], image.getWidth(), image.getHeight(),
imageFormats[image.getType()], GL11.GL_UNSIGNED_BYTE,
image.getData());
} else {
// Get mipmap data sizes and amount of mipmaps to send to
// opengl. Then loop through all mipmaps and send them.
int[] mipSizes = image.getMipMapSizes();
ByteBuffer data = image.getData();
int max = 1;
int pos = 0;
if (mipSizes == null) {
mipSizes = new int[] { data.capacity() };
} else if (texture.getMipmap() != Texture.MM_NONE) {
max = mipSizes.length;
}
for (int m = 0; m < max; m++) {
int width = Math.max(1, image.getWidth() >> m);
int height = Math.max(1, image.getHeight() >> m);
data.position(pos);
if (image.isCompressedType()) {
data.limit(pos+mipSizes[m]);
ARBTextureCompression.glCompressedTexImage2DARB(
GL11.GL_TEXTURE_2D, m, imageComponents[image
.getType()], width, height, 0, data);
} else {
data.limit(data.position() + mipSizes[m]);
GL11.glTexImage2D(GL11.GL_TEXTURE_2D, m,
imageComponents[image.getType()], width,
height, 0, imageFormats[image.getType()],
GL11.GL_UNSIGNED_BYTE, data);
}
pos += mipSizes[m];
}
data.clear();
}
}
}
/**
* <code>apply</code> manages the textures being described by the state.
* If the texture has not been loaded yet, it is generated and loaded using
* OpenGL11. This means the initial pass to set will be longer than
* subsequent calls. The multitexture extension is used to define the
* multiple texture states, with the number of units being determined at
* construction time.
*
* @see com.jme.scene.state.RenderState#apply()
*/
public void apply() {
// ask for the current state record
RenderContext context = DisplaySystem.getDisplaySystem()
.getCurrentContext();
TextureStateRecord record = (TextureStateRecord) context
.getStateRecord(RS_TEXTURE);
context.currentStates[RS_TEXTURE] = this;
if (isEnabled()) {
Texture texture;
TextureUnitRecord unitRecord;
TextureRecord texRecord;
int glHint = getPerspHint(getCorrection());
if (!record.isValid() || record.hint != glHint) {
// set up correction mode
GL11.glHint(GL11.GL_PERSPECTIVE_CORRECTION_HINT,
glHint);
record.hint = glHint;
}
// loop through all available texture units...
for (int i = 0; i < numTotalTexUnits; i++) {
unitRecord = record.units[i];
// grab a texture for this unit, if available
texture = getTexture(i);
// check for invalid textures - ones that have no opengl id and
// no image data
if (texture != null && texture.getTextureId() == 0
&& texture.getImage() == null)
texture = null;
// null textures above fixed limit do not need to be disabled
// since they are not really part of the pipeline.
if (texture == null) {
if (i >= numFixedTexUnits)
continue;
else {
// a null texture indicates no texturing at this unit
// Disable 2D texturing on this unit if enabled.
if (!unitRecord.isValid() || unitRecord.enabled) {
// Check we are in the right unit
checkAndSetUnit(i, record);
GL11.glDisable(GL11.GL_TEXTURE_2D);
unitRecord.enabled = false;
}
if (i < idCache.length)
idCache[i] = 0;
// next texture!
continue;
}
}
// Time to bind the texture, so see if we need to load in image
// data for this texture.
if (texture.getTextureId() == 0) {
// texture not yet loaded.
// this will load and bind and set the records...
load(i);
if (texture.getTextureId() == 0) continue;
} else {
// texture already exists in OpenGL, just bind it if needed
if (!unitRecord.isValid() || unitRecord.boundTexture != texture.getTextureId()) {
// Check we are in the right unit
checkAndSetUnit(i, record);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, texture.getTextureId());
unitRecord.boundTexture = texture.getTextureId();
}
}
// Grab our record for this texture
texRecord = record.getTextureRecord(texture.getTextureId());
// Set the idCache value for this unit of this texture state
// This is done so during state comparison we don't have to
// spend a lot of time pulling out classes and finding field
// data.
idCache[i] = texture.getTextureId();
// Some texture things only apply to fixed function pipeline
if (i < numFixedTexUnits) {
// Enable 2D texturing on this unit if not enabled.
if (!unitRecord.isValid() || !unitRecord.enabled) {
checkAndSetUnit(i, record);
GL11.glEnable(GL11.GL_TEXTURE_2D);
unitRecord.enabled = true;
}
// Set our blend color, if needed.
applyBlendColor(texture, unitRecord, i, record);
// Set the texture environment mode if this unit isn't
// already set properly
int glEnvMode = getGLEnvMode(texture.getApply());
applyEnvMode(glEnvMode, unitRecord, i, record);
// If our mode is combine, and we support multitexturing
// apply combine settings.
if (glEnvMode == ARBTextureEnvCombine.GL_COMBINE_ARB && supportsMultiTexture && supportsEnvCombine) {
applyCombineFactors(texture, unitRecord, i, record);
}
}
// Other items only apply to textures below the frag unit limit
if (i < numFragmentTexUnits) {
// texture specific params
applyFilter(texture, texRecord, i, record);
applyWrap(texture, texRecord, i, record);
}
// Other items only apply to textures below the frag tex coord unit limit
if (i < numFragmentTexCoordUnits) {
// Now time to play with texture matrices
// Determine which transforms to do.
applyTextureTransforms(texture, i, record);
// Now let's look at automatic texture coordinate generation.
applyTexCoordGeneration(texture, unitRecord, i, record);
}
}
} else {
// turn off texturing
TextureUnitRecord unitRecord;
if (supportsMultiTexture) {
for (int i = 0; i < numFixedTexUnits; i++) {
unitRecord = record.units[i];
if (!unitRecord.isValid() || unitRecord.enabled) {
checkAndSetUnit(i, record);
GL11.glDisable(GL11.GL_TEXTURE_2D);
unitRecord.enabled = false;
}
}
} else {
unitRecord = record.units[0];
if (!unitRecord.isValid() || unitRecord.enabled) {
GL11.glDisable(GL11.GL_TEXTURE_2D);
unitRecord.enabled = false;
}
}
}
if (!record.isValid())
record.validate();
}
private void applyCombineFactors(Texture texture, TextureUnitRecord unitRecord, int unit, TextureStateRecord record) {
// check that this is a valid fixed function unit. glTexEnv is only supported for unit < GL_MAX_TEXTURE_UNITS
if (unit >= numFixedTexUnits) {
return;
}
// first thing's first... if we are doing dot3 and don't
// support it, disable this texture.
boolean checked = false;
if (!supportsEnvDot3 && (texture.getCombineFuncAlpha() == Texture.ACF_DOT3_RGB
|| texture.getCombineFuncAlpha() == Texture.ACF_DOT3_RGBA
|| texture.getCombineFuncRGB() == Texture.ACF_DOT3_RGB
|| texture.getCombineFuncRGB() == Texture.ACF_DOT3_RGBA)) {
checkAndSetUnit(unit, record);
checked = true;
GL11.glDisable(GL11.GL_TEXTURE_2D);
unitRecord.enabled = false;
// No need to continue
return;
}
// Okay, now let's set our scales if we need to:
// First RGB Combine scale
if (!unitRecord.isValid() || unitRecord.envRGBScale != texture.getCombineScaleRGB()) {
if (!checked) {
checkAndSetUnit(unit, record);
checked = true;
}
GL11.glTexEnvf(GL11.GL_TEXTURE_ENV, ARBTextureEnvCombine.GL_RGB_SCALE_ARB, texture
.getCombineScaleRGB());
unitRecord.envRGBScale = texture.getCombineScaleRGB();
}
// Then Alpha Combine scale
if (!unitRecord.isValid() || unitRecord.envAlphaScale != texture.getCombineScaleAlpha()) {
if (!checked) {
checkAndSetUnit(unit, record);
checked = true;
}
GL11.glTexEnvf(GL11.GL_TEXTURE_ENV, GL11.GL_ALPHA_SCALE, texture
.getCombineScaleRGB());
unitRecord.envAlphaScale = texture.getCombineScaleAlpha();
}
// Time to set the RGB combines
int rgbCombineFunc = texture.getCombineFuncRGB();
if (!unitRecord.isValid() || unitRecord.rgbCombineFunc != rgbCombineFunc) {
if (!checked) {
checkAndSetUnit(unit, record);
checked = true;
}
GL11.glTexEnvi(GL11.GL_TEXTURE_ENV, ARBTextureEnvCombine.GL_COMBINE_RGB_ARB,
getGLCombineFunc(rgbCombineFunc));
unitRecord.rgbCombineFunc = rgbCombineFunc;
}
int combSrcRGB = texture.getCombineSrc0RGB();
if (!unitRecord.isValid() || unitRecord.combSrcRGB0 != combSrcRGB) {
if (!checked) {
checkAndSetUnit(unit, record);
checked = true;
}
GL11.glTexEnvi(GL11.GL_TEXTURE_ENV, ARBTextureEnvCombine.GL_SOURCE0_RGB_ARB, getGLCombineSrc(combSrcRGB));
unitRecord.combSrcRGB0 = combSrcRGB;
}
int combOpRGB = texture.getCombineOp0RGB();
if (!unitRecord.isValid() || unitRecord.combOpRGB0 != combOpRGB) {
if (!checked) {
checkAndSetUnit(unit, record);
checked = true;
}
GL11.glTexEnvi(GL11.GL_TEXTURE_ENV, ARBTextureEnvCombine.GL_OPERAND0_RGB_ARB, getGLCombineOpRGB(combOpRGB));
unitRecord.combOpRGB0 = combOpRGB;
}
if (rgbCombineFunc != Texture.ACF_REPLACE) {
combSrcRGB = texture.getCombineSrc1RGB();
if (!unitRecord.isValid() || unitRecord.combSrcRGB1 != combSrcRGB) {
if (!checked) {
checkAndSetUnit(unit, record);
checked = true;
}
GL11.glTexEnvi(GL11.GL_TEXTURE_ENV, ARBTextureEnvCombine.GL_SOURCE1_RGB_ARB, getGLCombineSrc(combSrcRGB));
unitRecord.combSrcRGB1 = combSrcRGB;
}
combOpRGB = texture.getCombineOp1RGB();
if (!unitRecord.isValid() || unitRecord.combOpRGB1 != combOpRGB) {
if (!checked) {
checkAndSetUnit(unit, record);
checked = true;
}
GL11.glTexEnvi(GL11.GL_TEXTURE_ENV, ARBTextureEnvCombine.GL_OPERAND1_RGB_ARB, getGLCombineOpRGB(combOpRGB));
unitRecord.combOpRGB1 = combOpRGB;
}
if (rgbCombineFunc == Texture.ACF_INTERPOLATE) {
combSrcRGB = texture.getCombineSrc2RGB();
if (!unitRecord.isValid() || unitRecord.combSrcRGB2 != combSrcRGB) {
if (!checked) {
checkAndSetUnit(unit, record);
checked = true;
}
GL11.glTexEnvi(GL11.GL_TEXTURE_ENV, ARBTextureEnvCombine.GL_SOURCE2_RGB_ARB, getGLCombineSrc(combSrcRGB));
unitRecord.combSrcRGB2 = combSrcRGB;
}
combOpRGB = texture.getCombineOp2RGB();
if (!unitRecord.isValid() || unitRecord.combOpRGB2 != combOpRGB) {
if (!checked) {
checkAndSetUnit(unit, record);
checked = true;
}
GL11.glTexEnvi(GL11.GL_TEXTURE_ENV, ARBTextureEnvCombine.GL_OPERAND2_RGB_ARB, getGLCombineOpRGB(combOpRGB));
unitRecord.combOpRGB2 = combOpRGB;
}
}
}
// Now Alpha combines
int alphaCombineFunc = texture.getCombineFuncAlpha();
if (!unitRecord.isValid() || unitRecord.alphaCombineFunc != alphaCombineFunc) {
if (!checked) {
checkAndSetUnit(unit, record);
checked = true;
}
GL11.glTexEnvi(GL11.GL_TEXTURE_ENV, ARBTextureEnvCombine.GL_COMBINE_ALPHA_ARB,
getGLCombineFunc(alphaCombineFunc));
unitRecord.alphaCombineFunc = alphaCombineFunc;
}
int combSrcAlpha = texture.getCombineSrc0Alpha();
if (!unitRecord.isValid() || unitRecord.combSrcAlpha0 != combSrcAlpha) {
if (!checked) {
checkAndSetUnit(unit, record);
checked = true;
}
GL11.glTexEnvi(GL11.GL_TEXTURE_ENV, ARBTextureEnvCombine.GL_SOURCE0_ALPHA_ARB, getGLCombineSrc(combSrcAlpha));
unitRecord.combSrcAlpha0 = combSrcAlpha;
}
int combOpAlpha = texture.getCombineOp0Alpha();
if (!unitRecord.isValid() || unitRecord.combOpAlpha0 != combOpAlpha) {
if (!checked) {
checkAndSetUnit(unit, record);
checked = true;
}
GL11.glTexEnvi(GL11.GL_TEXTURE_ENV, ARBTextureEnvCombine.GL_OPERAND0_ALPHA_ARB, getGLCombineOpAlpha(combOpAlpha));
unitRecord.combOpAlpha0 = combOpAlpha;
}
if (alphaCombineFunc != Texture.ACF_REPLACE) {
combSrcAlpha = texture.getCombineSrc1Alpha();
if (!unitRecord.isValid() || unitRecord.combSrcAlpha1 != combSrcAlpha) {
if (!checked) {
checkAndSetUnit(unit, record);
checked = true;
}
GL11.glTexEnvi(GL11.GL_TEXTURE_ENV, ARBTextureEnvCombine.GL_SOURCE1_ALPHA_ARB, getGLCombineSrc(combSrcAlpha));
unitRecord.combSrcAlpha1 = combSrcAlpha;
}
combOpAlpha = texture.getCombineOp1Alpha();
if (!unitRecord.isValid() || unitRecord.combOpAlpha1 != combOpAlpha) {
if (!checked) {
checkAndSetUnit(unit, record);
checked = true;
}
GL11.glTexEnvi(GL11.GL_TEXTURE_ENV, ARBTextureEnvCombine.GL_OPERAND1_ALPHA_ARB, getGLCombineOpAlpha(combOpAlpha));
unitRecord.combOpAlpha1 = combOpAlpha;
}
if (alphaCombineFunc == Texture.ACF_INTERPOLATE) {
combSrcAlpha = texture.getCombineSrc2Alpha();
if (!unitRecord.isValid() || unitRecord.combSrcAlpha2 != combSrcAlpha) {
if (!checked) {
checkAndSetUnit(unit, record);
checked = true;
}
GL11.glTexEnvi(GL11.GL_TEXTURE_ENV, ARBTextureEnvCombine.GL_SOURCE2_ALPHA_ARB, getGLCombineSrc(combSrcAlpha));
unitRecord.combSrcAlpha2 = combSrcAlpha;
}
combOpAlpha = texture.getCombineOp2Alpha();
if (!unitRecord.isValid() || unitRecord.combOpAlpha2 != combOpAlpha) {
if (!checked) {
checkAndSetUnit(unit, record);
checked = true;
}
GL11.glTexEnvi(GL11.GL_TEXTURE_ENV, ARBTextureEnvCombine.GL_OPERAND2_ALPHA_ARB, getGLCombineOpAlpha(combOpAlpha));
unitRecord.combOpAlpha2 = combOpAlpha;
}
}
}
}
private static int getGLCombineOpRGB(int combineOpRGB) {
switch (combineOpRGB) {
case Texture.ACO_SRC_COLOR:
return GL11.GL_SRC_COLOR;
case Texture.ACO_ONE_MINUS_SRC_COLOR:
return GL11.GL_ONE_MINUS_SRC_COLOR;
case Texture.ACO_SRC_ALPHA:
return GL11.GL_SRC_ALPHA;
case Texture.ACO_ONE_MINUS_SRC_ALPHA:
return GL11.GL_ONE_MINUS_SRC_ALPHA;
default:
return GL11.GL_SRC_COLOR;
}
}
private static int getGLCombineOpAlpha(int combineOpAlpha) {
switch (combineOpAlpha) {
case Texture.ACO_SRC_ALPHA:
return GL11.GL_SRC_ALPHA;
case Texture.ACO_ONE_MINUS_SRC_ALPHA:
return GL11.GL_ONE_MINUS_SRC_ALPHA;
case Texture.ACO_SRC_COLOR: // these 2 we just put here to help prevent errors.
return GL11.GL_SRC_ALPHA;
case Texture.ACO_ONE_MINUS_SRC_COLOR:
return GL11.GL_ONE_MINUS_SRC_ALPHA;
default:
return GL11.GL_SRC_ALPHA;
}
}
private static int getGLCombineSrc(int combineSrc) {
switch (combineSrc) {
case Texture.ACS_TEXTURE:
return GL11.GL_TEXTURE;
case Texture.ACS_PRIMARY_COLOR:
return ARBTextureEnvCombine.GL_PRIMARY_COLOR_ARB;
case Texture.ACS_CONSTANT:
return ARBTextureEnvCombine.GL_CONSTANT_ARB;
case Texture.ACS_PREVIOUS:
return ARBTextureEnvCombine.GL_PREVIOUS_ARB;
case Texture.ACS_TEXTURE0:
return ARBMultitexture.GL_TEXTURE0_ARB;
case Texture.ACS_TEXTURE1:
return ARBMultitexture.GL_TEXTURE1_ARB;
case Texture.ACS_TEXTURE2:
return ARBMultitexture.GL_TEXTURE2_ARB;
case Texture.ACS_TEXTURE3:
return ARBMultitexture.GL_TEXTURE3_ARB;
case Texture.ACS_TEXTURE4:
return ARBMultitexture.GL_TEXTURE4_ARB;
case Texture.ACS_TEXTURE5:
return ARBMultitexture.GL_TEXTURE5_ARB;
case Texture.ACS_TEXTURE6:
return ARBMultitexture.GL_TEXTURE6_ARB;
case Texture.ACS_TEXTURE7:
return ARBMultitexture.GL_TEXTURE7_ARB;
case Texture.ACS_TEXTURE8:
return ARBMultitexture.GL_TEXTURE8_ARB;
case Texture.ACS_TEXTURE9:
return ARBMultitexture.GL_TEXTURE9_ARB;
case Texture.ACS_TEXTURE10:
return ARBMultitexture.GL_TEXTURE10_ARB;
case Texture.ACS_TEXTURE11:
return ARBMultitexture.GL_TEXTURE11_ARB;
case Texture.ACS_TEXTURE12:
return ARBMultitexture.GL_TEXTURE12_ARB;
case Texture.ACS_TEXTURE13:
return ARBMultitexture.GL_TEXTURE13_ARB;
case Texture.ACS_TEXTURE14:
return ARBMultitexture.GL_TEXTURE14_ARB;
case Texture.ACS_TEXTURE15:
return ARBMultitexture.GL_TEXTURE15_ARB;
case Texture.ACS_TEXTURE16:
return ARBMultitexture.GL_TEXTURE16_ARB;
case Texture.ACS_TEXTURE17:
return ARBMultitexture.GL_TEXTURE17_ARB;
case Texture.ACS_TEXTURE18:
return ARBMultitexture.GL_TEXTURE18_ARB;
case Texture.ACS_TEXTURE19:
return ARBMultitexture.GL_TEXTURE19_ARB;
case Texture.ACS_TEXTURE20:
return ARBMultitexture.GL_TEXTURE20_ARB;
case Texture.ACS_TEXTURE21:
return ARBMultitexture.GL_TEXTURE21_ARB;
case Texture.ACS_TEXTURE22:
return ARBMultitexture.GL_TEXTURE22_ARB;
case Texture.ACS_TEXTURE23:
return ARBMultitexture.GL_TEXTURE23_ARB;
case Texture.ACS_TEXTURE24:
return ARBMultitexture.GL_TEXTURE24_ARB;
case Texture.ACS_TEXTURE25:
return ARBMultitexture.GL_TEXTURE25_ARB;
case Texture.ACS_TEXTURE26:
return ARBMultitexture.GL_TEXTURE26_ARB;
case Texture.ACS_TEXTURE27:
return ARBMultitexture.GL_TEXTURE27_ARB;
case Texture.ACS_TEXTURE28:
return ARBMultitexture.GL_TEXTURE28_ARB;
case Texture.ACS_TEXTURE29:
return ARBMultitexture.GL_TEXTURE29_ARB;
case Texture.ACS_TEXTURE30:
return ARBMultitexture.GL_TEXTURE30_ARB;
case Texture.ACS_TEXTURE31:
return ARBMultitexture.GL_TEXTURE31_ARB;
default:
return ARBTextureEnvCombine.GL_PRIMARY_COLOR_ARB;
}
}
private static int getGLCombineFunc(int combineFunc) {
switch (combineFunc) {
case Texture.ACF_REPLACE:
return GL11.GL_REPLACE;
case Texture.ACF_ADD:
return GL11.GL_ADD;
case Texture.ACF_ADD_SIGNED:
return ARBTextureEnvCombine.GL_ADD_SIGNED_ARB;
case Texture.ACF_SUBTRACT:
if (GLContext.getCapabilities().OpenGL13) {
return GL13.GL_SUBTRACT;
} else {
// XXX: lwjgl's ARBTextureEnvCombine is missing subtract?
// for now... a backup.
return GL11.GL_MODULATE;
}
case Texture.ACF_INTERPOLATE:
return ARBTextureEnvCombine.GL_INTERPOLATE_ARB;
case Texture.ACF_DOT3_RGB:
return ARBTextureEnvDot3.GL_DOT3_RGB_ARB;
case Texture.ACF_DOT3_RGBA:
return ARBTextureEnvDot3.GL_DOT3_RGBA_ARB;
case Texture.ACF_MODULATE:
default:
return GL11.GL_MODULATE;
}
}
private void applyEnvMode(int glEnvMode, TextureUnitRecord unitRecord, int unit, TextureStateRecord record) {
if (!unitRecord.isValid() || unitRecord.envMode != glEnvMode) {
checkAndSetUnit(unit, record);
GL11.glTexEnvi(GL11.GL_TEXTURE_ENV,
GL11.GL_TEXTURE_ENV_MODE, glEnvMode);
unitRecord.envMode = glEnvMode;
}
}
private void applyBlendColor(Texture texture, TextureUnitRecord unitRecord, int unit, TextureStateRecord record) {
ColorRGBA texBlend = texture.getBlendColor();
if (texBlend == null) texBlend = TextureRecord.defaultColor;
if (!unitRecord.isValid() || unitRecord.blendColor.r != texBlend.r ||
unitRecord.blendColor.g != texBlend.g ||
unitRecord.blendColor.b != texBlend.b ||
unitRecord.blendColor.a != texBlend.a) {
checkAndSetUnit(unit, record);
unitRecord.colorBuffer.clear();
unitRecord.colorBuffer.put(texBlend.r).put(texBlend.g).put(texBlend.b).put(texBlend.a);
unitRecord.colorBuffer.rewind();
GL11.glTexEnv(GL11.GL_TEXTURE_ENV,
GL11.GL_TEXTURE_ENV_COLOR, unitRecord.colorBuffer);
unitRecord.blendColor.set(texBlend);
}
}
private void applyTextureTransforms(Texture texture, int unit,
TextureStateRecord record) {
boolean needsReset = !record.units[unit].identityMatrix;
// Should we load a base matrix?
boolean doMatrix = (texture.getMatrix() != null && !texture.getMatrix()
.isIdentity());
// Should we apply transforms?
boolean doTrans = texture.getTranslation() != null
&& (texture.getTranslation().x != 0
|| texture.getTranslation().y != 0
|| texture.getTranslation().z != 0);
boolean doRot = texture.getRotation() != null
&& !texture.getRotation().isIdentity();
boolean doScale = texture.getScale() != null
&& (texture.getScale().x != 1
|| texture.getScale().y != 1
|| texture.getScale().z != 1);
// Now do them.
if (doMatrix || doTrans || doRot || doScale) {
checkAndSetUnit(unit, record);
GL11.glMatrixMode(GL11.GL_TEXTURE);
if (doMatrix) {
texture.getMatrix().fillFloatBuffer(record.tmp_matrixBuffer, true);
GL11.glLoadMatrix(record.tmp_matrixBuffer);
} else {
GL11.glLoadIdentity();
}
if (doTrans) {
GL11.glTranslatef(texture.getTranslation().x, texture
.getTranslation().y, texture.getTranslation().z);
}
if (doRot) {
Vector3f vRot = record.tmp_rotation1;
float rot = texture.getRotation().toAngleAxis(vRot)
* FastMath.RAD_TO_DEG;
GL11.glRotatef(rot, vRot.x, vRot.y, vRot.z);
}
if (doScale)
GL11.glScalef(texture.getScale().x, texture.getScale().y,
texture.getScale().z);
// Switch back to the modelview matrix for further operations
GL11.glMatrixMode(GL11.GL_MODELVIEW);
record.units[unit].identityMatrix = false;
} else if (needsReset) {
checkAndSetUnit(unit, record);
GL11.glMatrixMode(GL11.GL_TEXTURE);
GL11.glLoadIdentity();
GL11.glMatrixMode(GL11.GL_MODELVIEW);
record.units[unit].identityMatrix = true;
}
}
private void applyTexCoordGeneration(Texture texture,
TextureUnitRecord unitRecord, int unit, TextureStateRecord record) {
checkAndSetUnit(unit, record);
if (texture.getEnvironmentalMapMode() == Texture.EM_NONE) {
// No coordinate generation
if (!unitRecord.isValid() || unitRecord.textureGenQ) {
GL11.glDisable(GL11.GL_TEXTURE_GEN_Q);
unitRecord.textureGenQ = false;
}
if (!unitRecord.isValid() || unitRecord.textureGenR) {
GL11.glDisable(GL11.GL_TEXTURE_GEN_R);
unitRecord.textureGenR = false;
}
if (!unitRecord.isValid() || unitRecord.textureGenS) {
GL11.glDisable(GL11.GL_TEXTURE_GEN_S);
unitRecord.textureGenS = false;
}
if (!unitRecord.isValid() || unitRecord.textureGenT) {
GL11.glDisable(GL11.GL_TEXTURE_GEN_T);
unitRecord.textureGenT = false;
}
} else if (texture.getEnvironmentalMapMode() == Texture.EM_SPHERE) {
// generate spherical texture coordinates
if (!unitRecord.isValid() || unitRecord.textureGenSMode != GL11.GL_SPHERE_MAP) {
GL11.glTexGeni(GL11.GL_S, GL11.GL_TEXTURE_GEN_MODE,
GL11.GL_SPHERE_MAP);
unitRecord.textureGenSMode = GL11.GL_SPHERE_MAP;
}
if (!unitRecord.isValid() || unitRecord.textureGenTMode != GL11.GL_SPHERE_MAP) {
GL11.glTexGeni(GL11.GL_T, GL11.GL_TEXTURE_GEN_MODE,
GL11.GL_SPHERE_MAP);
unitRecord.textureGenTMode = GL11.GL_SPHERE_MAP;
}
if (!unitRecord.isValid() || unitRecord.textureGenQ) {
GL11.glDisable(GL11.GL_TEXTURE_GEN_Q);
unitRecord.textureGenQ = false;
}
if (!unitRecord.isValid() || unitRecord.textureGenR) {
GL11.glDisable(GL11.GL_TEXTURE_GEN_R);
unitRecord.textureGenR = false;
}
if (!unitRecord.isValid() || !unitRecord.textureGenS) {
GL11.glEnable(GL11.GL_TEXTURE_GEN_S);
unitRecord.textureGenS = true;
}
if (!unitRecord.isValid() || !unitRecord.textureGenT) {
GL11.glEnable(GL11.GL_TEXTURE_GEN_T);
unitRecord.textureGenT = true;
}
} else if (texture.getEnvironmentalMapMode() == Texture.EM_EYE_LINEAR) {
// generate eye linear texture coordinates
if (!unitRecord.isValid() || unitRecord.textureGenQMode != GL11.GL_EYE_LINEAR) {
GL11.glTexGeni(GL11.GL_Q, GL11.GL_TEXTURE_GEN_MODE,
GL11.GL_EYE_LINEAR);
unitRecord.textureGenSMode = GL11.GL_EYE_LINEAR;
}
if (!unitRecord.isValid() || unitRecord.textureGenRMode != GL11.GL_EYE_LINEAR) {
GL11.glTexGeni(GL11.GL_R, GL11.GL_TEXTURE_GEN_MODE,
GL11.GL_EYE_LINEAR);
unitRecord.textureGenTMode = GL11.GL_EYE_LINEAR;
}
if (!unitRecord.isValid() || unitRecord.textureGenSMode != GL11.GL_EYE_LINEAR) {
GL11.glTexGeni(GL11.GL_S, GL11.GL_TEXTURE_GEN_MODE,
GL11.GL_EYE_LINEAR);
unitRecord.textureGenSMode = GL11.GL_EYE_LINEAR;
}
if (!unitRecord.isValid() || unitRecord.textureGenTMode != GL11.GL_EYE_LINEAR) {
GL11.glTexGeni(GL11.GL_T, GL11.GL_TEXTURE_GEN_MODE,
GL11.GL_EYE_LINEAR);
unitRecord.textureGenTMode = GL11.GL_EYE_LINEAR;
}
record.eyePlaneS.rewind();
GL11.glTexGen(GL11.GL_S, GL11.GL_EYE_PLANE, record.eyePlaneS);
record.eyePlaneT.rewind();
GL11.glTexGen(GL11.GL_T, GL11.GL_EYE_PLANE, record.eyePlaneT);
record.eyePlaneR.rewind();
GL11.glTexGen(GL11.GL_R, GL11.GL_EYE_PLANE, record.eyePlaneR);
record.eyePlaneQ.rewind();
GL11.glTexGen(GL11.GL_Q, GL11.GL_EYE_PLANE, record.eyePlaneQ);
if (!unitRecord.isValid() || !unitRecord.textureGenQ) {
GL11.glEnable(GL11.GL_TEXTURE_GEN_Q);
unitRecord.textureGenQ = true;
}
if (!unitRecord.isValid() || !unitRecord.textureGenR) {
GL11.glEnable(GL11.GL_TEXTURE_GEN_R);
unitRecord.textureGenR = true;
}
if (!unitRecord.isValid() || !unitRecord.textureGenS) {
GL11.glEnable(GL11.GL_TEXTURE_GEN_S);
unitRecord.textureGenS = true;
}
if (!unitRecord.isValid() || !unitRecord.textureGenT) {
GL11.glEnable(GL11.GL_TEXTURE_GEN_T);
unitRecord.textureGenT = true;
}
} else if (texture.getEnvironmentalMapMode() == Texture.EM_OBJECT_LINEAR) {
// generate eye linear texture coordinates
if (!unitRecord.isValid() || unitRecord.textureGenQMode != GL11.GL_OBJECT_LINEAR) {
GL11.glTexGeni(GL11.GL_Q, GL11.GL_TEXTURE_GEN_MODE,
GL11.GL_OBJECT_LINEAR);
unitRecord.textureGenSMode = GL11.GL_OBJECT_LINEAR;
}
if (!unitRecord.isValid() || unitRecord.textureGenRMode != GL11.GL_OBJECT_LINEAR) {
GL11.glTexGeni(GL11.GL_R, GL11.GL_TEXTURE_GEN_MODE,
GL11.GL_OBJECT_LINEAR);
unitRecord.textureGenTMode = GL11.GL_OBJECT_LINEAR;
}
if (!unitRecord.isValid() || unitRecord.textureGenSMode != GL11.GL_OBJECT_LINEAR) {
GL11.glTexGeni(GL11.GL_S, GL11.GL_TEXTURE_GEN_MODE,
GL11.GL_OBJECT_LINEAR);
unitRecord.textureGenSMode = GL11.GL_OBJECT_LINEAR;
}
if (!unitRecord.isValid() || unitRecord.textureGenTMode != GL11.GL_OBJECT_LINEAR) {
GL11.glTexGeni(GL11.GL_T, GL11.GL_TEXTURE_GEN_MODE,
GL11.GL_OBJECT_LINEAR);
unitRecord.textureGenTMode = GL11.GL_OBJECT_LINEAR;
}
record.eyePlaneS.rewind();
GL11.glTexGen(GL11.GL_S, GL11.GL_OBJECT_PLANE, record.eyePlaneS);
record.eyePlaneT.rewind();
GL11.glTexGen(GL11.GL_T, GL11.GL_OBJECT_PLANE, record.eyePlaneT);
record.eyePlaneR.rewind();
GL11.glTexGen(GL11.GL_R, GL11.GL_OBJECT_PLANE, record.eyePlaneR);
record.eyePlaneQ.rewind();
GL11.glTexGen(GL11.GL_Q, GL11.GL_OBJECT_PLANE, record.eyePlaneQ);
if (!unitRecord.isValid() || !unitRecord.textureGenQ) {
GL11.glEnable(GL11.GL_TEXTURE_GEN_Q);
unitRecord.textureGenQ = true;
}
if (!unitRecord.isValid() || !unitRecord.textureGenR) {
GL11.glEnable(GL11.GL_TEXTURE_GEN_R);
unitRecord.textureGenR = true;
}
if (!unitRecord.isValid() || !unitRecord.textureGenS) {
GL11.glEnable(GL11.GL_TEXTURE_GEN_S);
unitRecord.textureGenS = true;
}
if (!unitRecord.isValid() || !unitRecord.textureGenT) {
GL11.glEnable(GL11.GL_TEXTURE_GEN_T);
unitRecord.textureGenT = true;
}
}
}
private static int getGLEnvMode(int apply) {
switch (apply) {
case Texture.AM_REPLACE:
return GL11.GL_REPLACE;
case Texture.AM_BLEND:
return GL11.GL_BLEND;
case Texture.AM_COMBINE:
return ARBTextureEnvCombine.GL_COMBINE_ARB;
case Texture.AM_DECAL:
return GL11.GL_DECAL;
case Texture.AM_ADD:
return GL11.GL_ADD;
case Texture.AM_MODULATE:
default:
return GL11.GL_MODULATE;
}
}
private static int getPerspHint(int correction) {
switch (correction) {
case TextureState.CM_AFFINE:
return GL11.GL_FASTEST;
case TextureState.CM_PERSPECTIVE:
default:
return GL11.GL_NICEST;
}
}
// If we support multtexturing, specify the unit we are affecting.
private static void checkAndSetUnit(int unit, TextureStateRecord record) {
if (unit >= numTotalTexUnits || !supportsMultiTexture || unit < 0) {
// ignore this request as it is not valid for the user's hardware.
return;
}
// No need to worry about valid record, since invalidate sets record's
// currentUnit to -1.
if (record.currentUnit != unit) {
ARBMultitexture.glActiveTextureARB(ARBMultitexture.GL_TEXTURE0_ARB + unit);
record.currentUnit = unit;
}
}
/**
* Check if the filter settings of this particular texture have been changed and
* apply as needed.
*
* @param texture
* our texture object
* @param texRecord
* our record of the last state of the texture in gl
* @param record
*/
private void applyFilter(Texture texture, TextureRecord texRecord, int unit, TextureStateRecord record) {
int magFilter = getGLMagFilter(texture.getFilter());
// set up magnification filter
if (!texRecord.isValid() || texRecord.magFilter != magFilter) {
checkAndSetUnit(unit, record);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D,
GL11.GL_TEXTURE_MAG_FILTER, magFilter);
texRecord.magFilter = magFilter;
}
int minFilter = getGLMinFilter(texture.getMipmap());
// set up mipmap filter
if (!texRecord.isValid() || texRecord.minFilter != minFilter) {
checkAndSetUnit(unit, record);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D,
GL11.GL_TEXTURE_MIN_FILTER, minFilter);
texRecord.minFilter = minFilter;
}
// set up aniso filter
if (supportsAniso) {
float aniso = texture.getAnisoLevel() * (maxAnisotropic - 1.0f);
aniso += 1.0f;
if (!texRecord.isValid() || texRecord.anisoLevel != aniso) {
checkAndSetUnit(unit, record);
GL11.glTexParameterf(GL11.GL_TEXTURE_2D,
EXTTextureFilterAnisotropic.GL_TEXTURE_MAX_ANISOTROPY_EXT,
aniso);
texRecord.anisoLevel = aniso;
}
}
}
private static int getGLMagFilter(int magFilter) {
switch (magFilter) {
case Texture.FM_LINEAR:
return GL11.GL_LINEAR;
case Texture.FM_NEAREST:
default:
return GL11.GL_NEAREST;
}
}
private static int getGLMinFilter(int minFilter) {
switch (minFilter) {
case Texture.MM_LINEAR:
return GL11.GL_LINEAR;
case Texture.MM_LINEAR_LINEAR:
return GL11.GL_LINEAR_MIPMAP_LINEAR;
case Texture.MM_LINEAR_NEAREST:
return GL11.GL_LINEAR_MIPMAP_NEAREST;
case Texture.MM_NEAREST:
return GL11.GL_NEAREST;
case Texture.MM_NEAREST_NEAREST:
return GL11.GL_NEAREST_MIPMAP_NEAREST;
case Texture.MM_NONE:
return GL11.GL_NEAREST;
case Texture.MM_NEAREST_LINEAR:
default:
return GL11.GL_NEAREST_MIPMAP_LINEAR;
}
}
/**
* Check if the wrap mode of this particular texture has been changed and
* apply as needed.
*
* @param texture
* our texture object
* @param texRecord
* our record of the last state of the unit in gl
* @param record
*/
private void applyWrap(Texture texture, TextureRecord texRecord, int unit, TextureStateRecord record) {
int wrapS = -1;
int wrapT = -1;
switch (texture.getWrap()) {
case Texture.WM_ECLAMP_S_ECLAMP_T:
wrapS = GL12.GL_CLAMP_TO_EDGE;
wrapT = GL12.GL_CLAMP_TO_EDGE;
break;
case Texture.WM_BCLAMP_S_BCLAMP_T:
wrapS = ARBTextureBorderClamp.GL_CLAMP_TO_BORDER_ARB;
wrapT = ARBTextureBorderClamp.GL_CLAMP_TO_BORDER_ARB;
break;
case Texture.WM_CLAMP_S_CLAMP_T:
wrapS = GL11.GL_CLAMP;
wrapT = GL11.GL_CLAMP;
break;
case Texture.WM_CLAMP_S_WRAP_T:
wrapS = GL11.GL_CLAMP;
wrapT = GL11.GL_REPEAT;
break;
case Texture.WM_WRAP_S_CLAMP_T:
wrapS = GL11.GL_REPEAT;
wrapT = GL11.GL_CLAMP;
break;
case Texture.WM_WRAP_S_WRAP_T:
default:
wrapS = GL11.GL_REPEAT;
wrapT = GL11.GL_REPEAT;
}
if (!texRecord.isValid() || texRecord.wrapS != wrapS) {
checkAndSetUnit(unit, record);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D,
GL11.GL_TEXTURE_WRAP_S, wrapS);
texRecord.wrapS = wrapS;
}
if (!texRecord.isValid() || texRecord.wrapT != wrapT) {
checkAndSetUnit(unit, record);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D,
GL11.GL_TEXTURE_WRAP_T, wrapT);
texRecord.wrapT = wrapT;
}
}
public RenderState extract(Stack stack, SceneElement spat) {
int mode = spat.getTextureCombineMode();
if (mode == REPLACE || (mode != OFF && stack.size() == 1)) // todo: use
// dummy
// state if
// off?
return (LWJGLTextureState) stack.peek();
// accumulate the textures in the stack into a single LightState object
LWJGLTextureState newTState = new LWJGLTextureState();
boolean foundEnabled = false;
Object states[] = stack.toArray();
switch (mode) {
case COMBINE_CLOSEST:
case COMBINE_RECENT_ENABLED:
for (int iIndex = states.length - 1; iIndex >= 0; iIndex
TextureState pkTState = (TextureState) states[iIndex];
if (!pkTState.isEnabled()) {
if (mode == COMBINE_RECENT_ENABLED)
break;
continue;
}
foundEnabled = true;
for (int i = 0, max = pkTState.getNumberOfSetTextures(); i < max; i++) {
Texture pkText = pkTState.getTexture(i);
if (newTState.getTexture(i) == null) {
newTState.setTexture(pkText, i);
}
}
}
break;
case COMBINE_FIRST:
for (int iIndex = 0, max = states.length; iIndex < max; iIndex++) {
TextureState pkTState = (TextureState) states[iIndex];
if (!pkTState.isEnabled())
continue;
foundEnabled = true;
for (int i = 0; i < numTotalTexUnits; i++) {
Texture pkText = pkTState.getTexture(i);
if (newTState.getTexture(i) == null) {
newTState.setTexture(pkText, i);
}
}
}
break;
case OFF:
break;
}
newTState.setEnabled(foundEnabled);
return newTState;
}
/*
* (non-Javadoc)
*
* @see com.jme.scene.state.TextureState#delete(int)
*/
public void delete(int unit) {
if (unit < 0 || unit >= texture.size() || texture.get(unit) == null)
return;
// ask for the current state record
RenderContext context = DisplaySystem.getDisplaySystem()
.getCurrentContext();
TextureStateRecord record = (TextureStateRecord) context
.getStateRecord(RS_TEXTURE);
Texture tex = texture.get(unit);
int texId = tex.getTextureId();
IntBuffer id = BufferUtils.createIntBuffer(1);
id.clear();
id.put(texId);
id.rewind();
tex.setTextureId(0);
GL11.glDeleteTextures(id);
// if the texture was currently bound glDeleteTextures reverts the binding to 0
// however we still have to clear it from currentTexture.
record.removeTextureRecord(texId);
idCache[unit] = 0;
}
/*
* (non-Javadoc)
*
* @see com.jme.scene.state.TextureState#deleteAll()
*/
public void deleteAll() {
deleteAll(false);
}
/*
* (non-Javadoc)
*
* @see com.jme.scene.state.TextureState#deleteAll()
*/
public void deleteAll(boolean removeFromCache) {
// ask for the current state record
RenderContext context = DisplaySystem.getDisplaySystem()
.getCurrentContext();
TextureStateRecord record = (TextureStateRecord) context
.getStateRecord(RS_TEXTURE);
IntBuffer id = BufferUtils.createIntBuffer(texture.size());
for (int i = 0; i < texture.size(); i++) {
Texture tex = texture.get(i);
if (removeFromCache) TextureManager.releaseTexture(tex);
int texId = tex.getTextureId();
if (tex == null)
continue;
id.put(texId);
tex.setTextureId(0);
// if the texture was currently bound glDeleteTextures reverts the binding to 0
// however we still have to clear it from currentTexture.
record.removeTextureRecord(texId);
idCache[i] = 0;
}
// Now delete them all from GL in one fell swoop.
id.rewind();
GL11.glDeleteTextures(id);
}
public void deleteTextureId(int textureId) {
// ask for the current state record
RenderContext context = DisplaySystem.getDisplaySystem()
.getCurrentContext();
TextureStateRecord record = (TextureStateRecord) context
.getStateRecord(RS_TEXTURE);
IntBuffer id = BufferUtils.createIntBuffer(1);
id.clear();
id.put(textureId);
id.rewind();
GL11.glDeleteTextures(id);
record.removeTextureRecord(textureId);
}
@Override
public StateRecord createStateRecord() {
return new TextureStateRecord(numTotalTexUnits);
}
/**
* Useful for external lwjgl based classes that need to safely set the
* current texture.
*/
public static void doTextureBind(int textureId, int unit) {
// ask for the current state record
RenderContext context = DisplaySystem.getDisplaySystem()
.getCurrentContext();
TextureStateRecord record = (TextureStateRecord) context
.getStateRecord(RenderState.RS_TEXTURE);
context.currentStates[RenderState.RS_TEXTURE] = null;
checkAndSetUnit(unit, record);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, textureId);
}
} |
package com.tinkerrocks.storage;
import com.tinkerrocks.structure.*;
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.util.ElementHelper;
import org.rocksdb.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class EdgeDB {
public void close() {
this.rocksDB.close();
}
public <V> void setProperty(String id, String key, V value) {
try {
this.rocksDB.put(getColumn(EDGE_COLUMNS.PROPERTIES), (id + key).getBytes(), String.valueOf(value).getBytes());
} catch (RocksDBException e) {
e.printStackTrace();
}
}
public void addEdge(byte[] edge_id, String label, RocksElement inVertex, RocksElement outVertex, Object[] keyValues) throws RocksDBException {
//todo add check back when finished testing
// if (this.rocksDB.get(edge_id) != null) {
// throw Graph.Exceptions.edgeWithIdAlreadyExists(edge_id);
if (label == null) {
throw Edge.Exceptions.labelCanNotBeNull();
}
if (label.isEmpty()) {
throw Edge.Exceptions.labelCanNotBeEmpty();
}
this.rocksDB.put(edge_id, label.getBytes());
this.rocksDB.put(getColumn(EDGE_COLUMNS.IN_VERTICES), ByteUtil.merge(edge_id,
VertexDB.PROPERTY_SEPERATOR.getBytes(), (byte[]) inVertex.id()), (byte[]) inVertex.id());
this.rocksDB.put(getColumn(EDGE_COLUMNS.OUT_VERTICES), ByteUtil.merge(edge_id,
VertexDB.PROPERTY_SEPERATOR.getBytes(), (byte[]) outVertex.id()), (byte[]) outVertex.id());
Map<String, Object> properties = ElementHelper.asMap(keyValues);
for (Map.Entry<String, Object> entry : properties.entrySet()) {
this.rocksDB.put(getColumn(EDGE_COLUMNS.PROPERTIES),
ByteUtil.merge(edge_id, VertexDB.PROPERTY_SEPERATOR.getBytes(), entry.getKey().getBytes()),
String.valueOf(entry.getValue()).getBytes());
}
}
public List<byte[]> getVertexIDs(byte[] edgeId, Direction direction) {
List<byte[]> vertexIDs = new ArrayList<>(16);
RocksIterator rocksIterator;
byte[] seek_key = ByteUtil.merge(edgeId, VertexDB.PROPERTY_SEPERATOR.getBytes());
if (direction == Direction.BOTH || direction == Direction.IN) {
rocksIterator = this.rocksDB.newIterator(getColumn(EDGE_COLUMNS.IN_VERTICES));
for (rocksIterator.seek(seek_key); rocksIterator.isValid()
&& ByteUtil.startsWith(rocksIterator.key(), 0, seek_key); rocksIterator.next()) {
vertexIDs.add(ByteUtil.slice(rocksIterator.value(), seek_key.length));
}
}
if (direction == Direction.BOTH || direction == Direction.OUT) {
rocksIterator = this.rocksDB.newIterator(getColumn(EDGE_COLUMNS.OUT_VERTICES));
for (rocksIterator.seek(seek_key); rocksIterator.isValid()
&& ByteUtil.startsWith(rocksIterator.key(), 0, seek_key); rocksIterator.next()) {
vertexIDs.add(ByteUtil.slice(rocksIterator.value(), seek_key.length));
}
}
return vertexIDs;
}
public Map<String, byte[]> getProperties(RocksElement element, String[] propertyKeys) throws RocksDBException {
Map<String, byte[]> results = new HashMap<>();
if (propertyKeys == null || propertyKeys.length == 0) {
RocksIterator rocksIterator = this.rocksDB.newIterator(getColumn(EDGE_COLUMNS.PROPERTIES));
byte[] seek_key = (element.id() + VertexDB.PROPERTY_SEPERATOR).getBytes();
for (rocksIterator.seek(seek_key); rocksIterator.isValid() && ByteUtil.startsWith(rocksIterator.key(), 0, seek_key);
rocksIterator.next()) {
results.put(new String(ByteUtil.slice(rocksIterator.key(), seek_key.length, rocksIterator.key().length)),
rocksIterator.value());
}
return results;
}
for (String property : propertyKeys) {
byte[] val = rocksDB.get((element.id() + VertexDB.PROPERTY_SEPERATOR + property).getBytes());
if (val != null)
results.put(property, val);
}
return results;
}
public List<Edge> edges(List<byte[]> ids, RocksGraph rocksGraph) throws RocksDBException {
List<Edge> edges = new ArrayList<>();
if (ids.size() == 0) {
RocksIterator iterator = this.rocksDB.newIterator();
iterator.seekToFirst();
while (iterator.isValid()) {
edges.add(getEdge(iterator.key(), rocksGraph));
iterator.next();
}
}
for (byte[] id : ids) {
edges.add(getEdge(id, rocksGraph));
}
return edges;
}
RocksEdge getEdge(byte[] id, RocksGraph rocksGraph) throws RocksDBException {
byte[] in_vertex_id = getVertex(id, Direction.IN);
byte[] out_vertex_id = getVertex(id, Direction.OUT);
RocksVertex inVertex = rocksGraph.getStorageHandler().getVertexDB().vertex(in_vertex_id, rocksGraph);
RocksVertex outVertex = rocksGraph.getStorageHandler().getVertexDB().vertex(out_vertex_id, rocksGraph);
return new RocksEdge(id, getLabel(id), rocksGraph, inVertex, outVertex);
}
private byte[] getVertex(byte[] id, Direction direction) {
RocksIterator iterator;
if (direction == Direction.BOTH || direction == Direction.OUT)
iterator = this.rocksDB.newIterator(getColumn(EDGE_COLUMNS.OUT_VERTICES));
else {
iterator = this.rocksDB.newIterator(getColumn(EDGE_COLUMNS.IN_VERTICES));
}
byte[] seek_key = ByteUtil.merge(id, VertexDB.PROPERTY_SEPERATOR.getBytes());
iterator.seek(seek_key);
if (iterator.isValid() && ByteUtil.startsWith(iterator.key(), 0, seek_key)) {
return ByteUtil.slice(iterator.key(), seek_key.length);
}
return null;
}
public static enum EDGE_COLUMNS {
PROPERTIES("PROPERTIES"),
IN_VERTICES("IN_VERTICES"),
OUT_VERTICES("OUT_VERTICES");
String value;
EDGE_COLUMNS(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
RocksDB rocksDB;
List<ColumnFamilyHandle> columnFamilyHandleList;
List<ColumnFamilyDescriptor> columnFamilyDescriptors;
public EdgeDB() throws RocksDBException {
columnFamilyDescriptors = new ArrayList<>(EDGE_COLUMNS.values().length);
columnFamilyHandleList = new ArrayList<>(EDGE_COLUMNS.values().length);
columnFamilyDescriptors.add(new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY));
for (EDGE_COLUMNS vertex_columns : EDGE_COLUMNS.values()) {
columnFamilyDescriptors.add(new ColumnFamilyDescriptor(vertex_columns.getValue().getBytes(),
new ColumnFamilyOptions()));
}
this.rocksDB = RocksDB.open(new DBOptions().setCreateIfMissing(true).setCreateMissingColumnFamilies(true), "/tmp/edges", columnFamilyDescriptors, columnFamilyHandleList);
}
public ColumnFamilyHandle getColumn(EDGE_COLUMNS edge_column) {
return columnFamilyHandleList.get(edge_column.ordinal() + 1);
}
public String getLabel(byte[] id) throws RocksDBException {
return new String(this.rocksDB.get(id));
}
} |
package com.jme.scene.state.lwjgl;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;
import java.util.Stack;
import java.util.logging.Level;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.GLContext;
import org.lwjgl.opengl.glu.GLU;
import com.jme.image.Image;
import com.jme.image.Texture;
import com.jme.scene.Spatial;
import com.jme.scene.state.RenderState;
import com.jme.scene.state.TextureState;
import com.jme.util.LoggingSystem;
/**
* <code>LWJGLTextureState</code> subclasses the TextureState object using the
* LWJGL API to access OpenGL for texture processing.
*
* @author Mark Powell
* @version $Id: LWJGLTextureState.java,v 1.12 2004-05-15 02:17:27 renanse Exp $
*/
public class LWJGLTextureState extends TextureState {
//OpenGL texture attributes.
private int[] textureCorrection = { GL11.GL_FASTEST, GL11.GL_NICEST};
private int[] textureApply = { GL11.GL_REPLACE, GL11.GL_DECAL,
GL11.GL_MODULATE, GL11.GL_BLEND, GL13.GL_COMBINE};
private int[] textureFilter = { GL11.GL_NEAREST, GL11.GL_LINEAR};
private int[] textureMipmap = { GL11.GL_NEAREST, // MM_NONE (no mipmap)
GL11.GL_NEAREST, GL11.GL_LINEAR, GL11.GL_NEAREST_MIPMAP_NEAREST,
GL11.GL_NEAREST_MIPMAP_LINEAR, GL11.GL_LINEAR_MIPMAP_NEAREST,
GL11.GL_LINEAR_MIPMAP_LINEAR};
private int[] textureCombineFunc = { GL11.GL_REPLACE, GL11.GL_MODULATE,
GL11.GL_ADD, GL13.GL_ADD_SIGNED, GL13.GL_SUBTRACT,
GL13.GL_INTERPOLATE};
private int[] textureCombineSrc = { GL11.GL_TEXTURE, GL13.GL_PRIMARY_COLOR,
GL13.GL_CONSTANT, GL13.GL_PREVIOUS};
private int[] textureCombineOpRgb = { GL11.GL_SRC_COLOR,
GL11.GL_ONE_MINUS_SRC_COLOR};
private int[] textureCombineOpAlpha = { GL11.GL_SRC_ALPHA,
GL11.GL_ONE_MINUS_SRC_ALPHA};
private float[] textureCombineScale = { 1.0f, 2.0f, 4.0f};
private int[] imageComponents = { GL11.GL_RGBA4, GL11.GL_RGB8,
GL11.GL_RGB5_A1, GL11.GL_RGBA8, GL11.GL_LUMINANCE8_ALPHA8};
private int[] imageFormats = { GL11.GL_RGBA, GL11.GL_RGB, GL11.GL_RGBA,
GL11.GL_RGBA, GL11.GL_LUMINANCE_ALPHA};
private static int numTexUnits = 0;
/**
* Constructor instantiates a new <code>LWJGLTextureState</code> object.
* The number of textures that can be combined is determined during
* construction. This equates the number of texture units supported by the
* graphics card.
*
*/
public LWJGLTextureState() {
super();
if (numTexUnits == 0) {
if(GLContext.GL_ARB_multitexture) {
IntBuffer buf = ByteBuffer.allocateDirect(64).order(
ByteOrder.nativeOrder()).asIntBuffer();
GL11.glGetInteger(GL13.GL_MAX_TEXTURE_UNITS, buf);
numTexUnits = buf.get(0);
} else {
numTexUnits = 1;
}
}
texture = new Texture[numTexUnits];
}
/**
* <code>set</code> manages the textures being described by the state. If
* the texture has not been loaded yet, it is generated and loaded using
* OpenGL11. This means the initial pass to set will be longer than
* subsequent calls. The multitexture extension is used to define the
* multiple texture states, with the number of units being determined at
* construction time.
*
* @see com.jme.scene.state.RenderState#unset()
*/
public void apply() {
for (int i = 0; i < getNumberOfUnits(); i++) {
if (!isEnabled() || getTexture(i) == null) {
if(GLContext.GL_ARB_multitexture && GLContext.OpenGL13) {
GL13.glActiveTexture(GL13.GL_TEXTURE0 + i);
}
GL11.glDisable(GL11.GL_TEXTURE_2D);
}
}
if (isEnabled()) {
int index;
Texture texture;
for (int i = 0; i < getNumberOfUnits(); i++) {
index = GL13.GL_TEXTURE0 + i;
texture = getTexture(i);
if (texture == null) {
continue;
}
if(GLContext.GL_ARB_multitexture && GLContext.OpenGL13) {
GL13.glActiveTexture(index);
}
GL11.glEnable(GL11.GL_TEXTURE_2D);
//texture not yet loaded.
if (texture.getTextureId() == 0) {
// Create A IntBuffer For Image Address In Memory
IntBuffer buf = ByteBuffer.allocateDirect(4).order(
ByteOrder.nativeOrder()).asIntBuffer();
//Create the texture
GL11.glGenTextures(buf);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, buf.get(0));
texture.setTextureId(buf.get(0));
// pass image data to OpenGL
Image image = texture.getImage();
if (image == null) {
LoggingSystem.getLogger().log(Level.WARNING,
"Image data for texture is null.");
texture.setTextureId(-1);
return;
}
if (texture.getMipmap() == Texture.MM_NONE) {
GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0,
imageComponents[image.getType()], image
.getWidth(), image.getHeight(), 0,
imageFormats[image.getType()],
GL11.GL_UNSIGNED_BYTE, image.getData());
} else {
GLU.gluBuild2DMipmaps(GL11.GL_TEXTURE_2D,
imageComponents[image.getType()], image
.getWidth(), image.getHeight(),
imageFormats[image.getType()],
GL11.GL_UNSIGNED_BYTE, image.getData());
}
} else {
// texture already exists in OpenGL, just bind it
GL11.glBindTexture(GL11.GL_TEXTURE_2D, texture
.getTextureId());
}
// set up correction mode
GL11.glHint(GL11.GL_PERSPECTIVE_CORRECTION_HINT,
textureCorrection[texture.getCorrection()]);
if (texture.getApply() == Texture.AM_COMBINE && GLContext.GL_ARB_multitexture) {
GL11.glTexEnvi(GL11.GL_TEXTURE_ENV,
GL11.GL_TEXTURE_ENV_MODE, textureApply[texture
.getApply()]);
GL11.glTexEnvi(GL11.GL_TEXTURE_ENV, GL13.GL_COMBINE_RGB,
textureCombineFunc[texture.getCombineFuncRGB()]);
GL11.glTexEnvi(GL11.GL_TEXTURE_ENV, GL13.GL_COMBINE_ALPHA,
textureCombineFunc[texture.getCombineFuncAlpha()]);
GL11.glTexEnvi(GL11.GL_TEXTURE_ENV, GL13.GL_SOURCE0_RGB,
textureCombineSrc[texture.getCombineSrc0RGB()]);
GL11.glTexEnvi(GL11.GL_TEXTURE_ENV, GL13.GL_SOURCE1_RGB,
textureCombineSrc[texture.getCombineSrc1RGB()]);
GL11.glTexEnvi(GL11.GL_TEXTURE_ENV, GL13.GL_SOURCE2_RGB,
textureCombineSrc[texture.getCombineSrc2RGB()]);
GL11.glTexEnvi(GL11.GL_TEXTURE_ENV, GL13.GL_SOURCE0_ALPHA,
textureCombineSrc[texture.getCombineSrc0Alpha()]);
GL11.glTexEnvi(GL11.GL_TEXTURE_ENV, GL13.GL_SOURCE1_ALPHA,
textureCombineSrc[texture.getCombineSrc1Alpha()]);
GL11.glTexEnvi(GL11.GL_TEXTURE_ENV, GL13.GL_SOURCE2_ALPHA,
textureCombineSrc[texture.getCombineSrc2Alpha()]);
GL11.glTexEnvi(GL11.GL_TEXTURE_ENV, GL13.GL_OPERAND0_RGB,
textureCombineOpRgb[texture.getCombineOp0RGB()]);
GL11.glTexEnvi(GL11.GL_TEXTURE_ENV, GL13.GL_OPERAND1_RGB,
textureCombineOpRgb[texture.getCombineOp1RGB()]);
GL11.glTexEnvi(GL11.GL_TEXTURE_ENV, GL13.GL_OPERAND2_RGB,
textureCombineOpRgb[texture.getCombineOp2RGB()]);
GL11
.glTexEnvi(GL11.GL_TEXTURE_ENV,
GL13.GL_OPERAND0_ALPHA,
textureCombineOpAlpha[texture
.getCombineOp0Alpha()]);
GL11
.glTexEnvi(GL11.GL_TEXTURE_ENV,
GL13.GL_OPERAND1_ALPHA,
textureCombineOpAlpha[texture
.getCombineOp1Alpha()]);
GL11
.glTexEnvi(GL11.GL_TEXTURE_ENV,
GL13.GL_OPERAND2_ALPHA,
textureCombineOpAlpha[texture
.getCombineOp2Alpha()]);
GL11.glTexEnvf(GL11.GL_TEXTURE_ENV, GL13.GL_RGB_SCALE,
textureCombineScale[texture.getCombineScaleRGB()]);
GL11.glTexEnvf(GL11.GL_TEXTURE_ENV, GL11.GL_ALPHA_SCALE,
textureCombineScale[texture.getCombineScaleRGB()]);
} else if (texture.getEnvironmentalMapMode() == Texture.EM_NONE) {
// turn off anything that other maps might have turned on
GL11.glDisable(GL11.GL_TEXTURE_GEN_Q);
GL11.glDisable(GL11.GL_TEXTURE_GEN_R);
GL11.glDisable(GL11.GL_TEXTURE_GEN_S);
GL11.glDisable(GL11.GL_TEXTURE_GEN_T);
} else if (texture.getEnvironmentalMapMode() == Texture.EM_SPHERE) {
// generate texture coordinates
GL11.glTexGeni(GL11.GL_S, GL11.GL_TEXTURE_GEN_MODE,
GL11.GL_SPHERE_MAP);
GL11.glTexGeni(GL11.GL_T, GL11.GL_TEXTURE_GEN_MODE,
GL11.GL_SPHERE_MAP);
GL11.glEnable(GL11.GL_TEXTURE_GEN_S);
GL11.glEnable(GL11.GL_TEXTURE_GEN_T);
} else if (texture.getEnvironmentalMapMode() == Texture.EM_IGNORE) {
// Do not alter the texure generation status. This allows
// complex texturing outside of texture state to exist
// peacefully.
} else {
// set up apply mode
GL11.glTexEnvi(GL11.GL_TEXTURE_ENV,
GL11.GL_TEXTURE_ENV_MODE, textureApply[texture
.getApply()]);
}
GL11.glTexEnv(GL11.GL_TEXTURE_ENV, GL11.GL_TEXTURE_ENV_COLOR,
texture.getBlendColor());
// set up wrap mode
switch (texture.getWrap()) {
case Texture.WM_ECLAMP_S_ECLAMP_T:
GL11.glTexParameteri(GL11.GL_TEXTURE_2D,
GL11.GL_TEXTURE_WRAP_S, GL12.GL_CLAMP_TO_EDGE);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D,
GL11.GL_TEXTURE_WRAP_T, GL12.GL_CLAMP_TO_EDGE);
break;
case Texture.WM_BCLAMP_S_BCLAMP_T:
GL11.glTexParameteri(GL11.GL_TEXTURE_2D,
GL11.GL_TEXTURE_WRAP_S, GL13.GL_CLAMP_TO_BORDER);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D,
GL11.GL_TEXTURE_WRAP_T, GL13.GL_CLAMP_TO_BORDER);
break;
case Texture.WM_CLAMP_S_CLAMP_T:
GL11.glTexParameteri(GL11.GL_TEXTURE_2D,
GL11.GL_TEXTURE_WRAP_S, GL11.GL_CLAMP);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D,
GL11.GL_TEXTURE_WRAP_T, GL11.GL_CLAMP);
break;
case Texture.WM_CLAMP_S_WRAP_T:
GL11.glTexParameteri(GL11.GL_TEXTURE_2D,
GL11.GL_TEXTURE_WRAP_S, GL11.GL_CLAMP);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D,
GL11.GL_TEXTURE_WRAP_T, GL11.GL_REPEAT);
break;
case Texture.WM_WRAP_S_CLAMP_T:
GL11.glTexParameteri(GL11.GL_TEXTURE_2D,
GL11.GL_TEXTURE_WRAP_S, GL11.GL_REPEAT);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D,
GL11.GL_TEXTURE_WRAP_T, GL11.GL_CLAMP);
break;
case Texture.WM_WRAP_S_WRAP_T:
GL11.glTexParameteri(GL11.GL_TEXTURE_2D,
GL11.GL_TEXTURE_WRAP_S, GL11.GL_REPEAT);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D,
GL11.GL_TEXTURE_WRAP_T, GL11.GL_REPEAT);
break;
}
// set up filter mode
GL11.glTexParameteri(GL11.GL_TEXTURE_2D,
GL11.GL_TEXTURE_MAG_FILTER, textureFilter[texture
.getFilter()]);
// set up mipmap mode
GL11.glTexParameteri(GL11.GL_TEXTURE_2D,
GL11.GL_TEXTURE_MIN_FILTER, textureMipmap[texture
.getMipmap()]);
}
}
}
public RenderState extract(Stack stack, Spatial spat) {
int mode = spat.getTextureCombineMode();
if (mode == REPLACE) return (LWJGLTextureState) stack.peek();
// accumulate the lights in the stack into a single LightState object
LWJGLTextureState newTState = new LWJGLTextureState();
boolean foundEnabled = false;
Object states[] = stack.toArray();
switch (mode) {
case COMBINE_CLOSEST:
case COMBINE_RECENT_ENABLED:
for (int iIndex = states.length - 1; iIndex >= 0; iIndex
TextureState pkTState = (TextureState) states[iIndex];
if (!pkTState.isEnabled()) {
if (mode == COMBINE_RECENT_ENABLED)
break;
else
continue;
} else
foundEnabled = true;
for (int i = 0, maxT = pkTState.getNumberOfUnits(); i < maxT; i++) {
Texture pkText = pkTState.getTexture(i);
if (newTState.getTexture(i) == null) {
newTState.setTexture(pkText, i);
}
}
}
break;
case COMBINE_FIRST:
for (int iIndex = 0, max = states.length; iIndex < max; iIndex++) {
TextureState pkTState = (TextureState) states[iIndex];
if (!pkTState.isEnabled())
continue;
else
foundEnabled = true;
for (int i = 0, maxT = pkTState.getNumberOfUnits(); i < maxT; i++) {
Texture pkText = pkTState.getTexture(i);
if (newTState.getTexture(i) == null) {
newTState.setTexture(pkText, i);
}
}
}
break;
}
newTState.setEnabled(foundEnabled);
return newTState;
}
} |
package org.joda.modulenames;
import java.nio.file.Path;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
/** Single scan run summary. */
class Summary {
/** Collection of suspicious modules. */
class Suspicious {
final Set<Item> impostors = new TreeSet<>();
final Set<Item> naming = new TreeSet<>();
final Set<Item> syntax = new TreeSet<>();
}
/** Date and time. */
final String timestamp = new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss").format(new Date());
/** Number of scanned lines. */
long scanLineCounter = 0L;
/** Number of scanned objects, i.e. csv files. */
long scanObjectCounter = 0L;
/** Number of scanned modules. */
long scanModuleCounter = 0L;
/** {@code modulescanner-report-2018_11_15_05_33_36.csv} or blank. */
String lastProcessed = "";
/** {@code modulescanner-report-2018_11_15_05_33_36.csv} or blank. */
String firstProcessed = "";
/** {@code modulescanner-report-2018_11_15_05_33_36.csv} or blank. */
String startedAfter = "";
/** Number of modules that were already well-known. */
int startedWith = 0;
/** New modules. */
final Map<String, Item> uniques = new TreeMap<>();
/** Updated modules. */
final Map<String, Item> updates = new TreeMap<>();
/** Suspicious or even plain invalid modules. */
final Suspicious suspicious = new Suspicious();
/** Defaults to volatile {@code target/workspace}. */
final Path workspace;
Summary(Path workspace) {
this.workspace = workspace;
}
List<String> toStrings() {
return List.of(
"Summary of " + timestamp,
"",
scanObjectCounter + " objects (`.csv` files) processed",
scanLineCounter + " lines scanned",
scanModuleCounter + " modules detected",
"Started with " + startedWith + " well-known modules",
"Started after file: " + (startedAfter.isBlank() ? "-" : startedAfter),
"First processed file: " + firstProcessed,
"Last processed file: " + lastProcessed,
"",
uniques.size() + " new modules found",
updates.size() + " modules updated",
"",
suspicious.syntax.size() + " module names were syntactically invalid",
suspicious.naming.size() + " module names didn't start with the Maven Group or an alias",
suspicious.impostors.size() + " impostors detected");
}
List<String> toMarkdown() {
var md = new ArrayList<String>();
md.add("# Scan `" + timestamp + "`");
md.add("");
md.add("## Summary");
md.add("");
md.add("```");
md.addAll(toStrings());
md.add("```");
md.add("");
md.add("### " + uniques.size() + " new modules");
uniques.values().forEach(it -> md.add("- `" + it.moduleName + "` -> " + it.line));
md.add("");
md.add("### " + updates.size() + " updated modules");
updates.values().forEach(it -> md.add("- `" + it.moduleName + "` -> " + it.line));
md.add("");
md.add("## Suspicious Modules");
md.add("");
md.add("Modules listed below didn't make it into the `modules.properties` database.");
md.add("");
md.add("### Syntax Error (" + suspicious.syntax.size() + ")");
md.add("");
suspicious.syntax.forEach(it -> md.add("- `" + it.moduleName + "` -> " + it.line));
md.add("");
md.add("### Impostor (" + suspicious.impostors.size() + ")");
md.add("");
suspicious.impostors.forEach(it -> md.add("- `" + it.moduleName + "` -> " + it.line));
md.add("");
md.add("### Unexpected Naming (" + suspicious.naming.size() + ")");
md.add("");
suspicious.naming.forEach(it -> md.add("- `" + it.moduleName + "` -> " + it.line));
md.add("");
return md;
}
} |
package com.zimmerbell.repaper;
import java.awt.Desktop;
import java.awt.Graphics2D;
import java.awt.HeadlessException;
import java.awt.Menu;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;
import java.awt.image.RescaleOp;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.util.HashMap;
import java.util.Properties;
import javax.imageio.ImageIO;
import javax.swing.JOptionPane;
import org.apache.logging.log4j.util.Strings;
import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.ObjectAlreadyExistsException;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.sun.jna.Native;
import com.sun.jna.platform.win32.WinDef.UINT_PTR;
import com.sun.jna.win32.StdCallLibrary;
import com.sun.jna.win32.W32APIFunctionMapper;
import com.sun.jna.win32.W32APITypeMapper;
import com.zimmerbell.repaper.sources.MomentumSource;
import com.zimmerbell.repaper.sources.MuzeiSource;
public class Repaper {
private final static Logger LOG = LoggerFactory.getLogger(Repaper.class);
public final static String HOME = System.getProperty("user.home") + File.separator + ".repaper";
public final static int GAUSS_RADIUS = 15;
public final static float BRIGTHNESS = 0.5f;
private final static File CURRENT_FILE = new File(HOME, "current.jpg");
private final static File CURRENT_FILE_ORIGINAL = new File(HOME, "current-original.jpg");
private final static File CONFIG_FILE = new File(HOME, "repaper.conf");
private final static String CONFIG_SOURCE = "source";
private final static String CONFIG_BLUR = "blur";
private final static String CONFIG_DARKEN = "darken";
private static enum SourceType {
Muzei, Momentum
}
private static Repaper repaperInstance;
private TrayIcon trayIcon;
private Properties config;
private Source source;
private Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
private JobDetail updateJob = JobBuilder.newJob(UpdateJob.class).build();
public static void main(String[] args) throws Exception {
repaperInstance = new Repaper();
}
public static Repaper getInstance() {
return repaperInstance;
}
public Repaper() throws Exception {
initTray();
initScheduler();
initConfig();
}
private void initConfig() throws IOException {
config = new Properties();
try {
config.load(new FileInputStream(CONFIG_FILE));
} catch (FileNotFoundException e) {
}
switch (SourceType.valueOf(config.getProperty(CONFIG_SOURCE, SourceType.Muzei.name()))) {
case Muzei:
source = new MuzeiSource();
break;
case Momentum:
source = new MomentumSource();
break;
}
update();
}
private void initScheduler() {
Trigger trigger = TriggerBuilder.newTrigger()
.startNow()
.withSchedule(
CronScheduleBuilder.dailyAtHourAndMinute(5, 0).withMisfireHandlingInstructionFireAndProceed())
.build();
try {
scheduler.start();
scheduler.scheduleJob(updateJob, trigger);
} catch (SchedulerException e) {
logError(e);
}
}
private void initTray() throws Exception {
PopupMenu popup = new PopupMenu();
MenuItem mi;
Menu preferences = new Menu("Preferences");
popup.add(preferences);
Menu sourceMenu = new Menu("Source");
preferences.add(sourceMenu);
for (SourceType sourceType : SourceType.values()) {
sourceMenu.add(new ConfigMenuItem(sourceType.name(), CONFIG_SOURCE, sourceType));
}
popup.add(mi = new MenuItem("Update"));
mi.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
try {
scheduler.triggerJob(updateJob.getKey());
} catch (SchedulerException e) {
logError(e);
}
}
});
popup.add(mi = new MenuItem("Show original"));
mi.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
showOriginal();
}
});
if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
popup.add(mi = new MenuItem("Details"));
mi.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
try {
Desktop.getDesktop().browse(new URI(source.getDetailsUri()));
} catch (Exception e) {
logError(e);
}
}
});
}
popup.addSeparator();
popup.add(mi = new MenuItem("Exit"));
mi.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
exit();
}
});
trayIcon = new TrayIcon(ImageIO.read(Repaper.class.getResourceAsStream("/icon_16.png")), null, popup);
trayIcon.setImageAutoSize(true);
trayIcon.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
showOriginal();
}
});
SystemTray.getSystemTray().add(trayIcon);
}
private void setConfig(String key, String value) {
config.setProperty(key, value);
CONFIG_FILE.getParentFile().mkdirs();
try {
config.store(new FileOutputStream(CONFIG_FILE), "");
initConfig();
} catch (Exception e) {
logError(e);
}
}
public void update() {
try {
LOG.info("update");
source.update();
BufferedImage image = ImageIO.read(new URL(source.getImageUri()).openStream());
try {
CURRENT_FILE_ORIGINAL.getParentFile().mkdir();
ImageIO.write(image, "jpg", CURRENT_FILE_ORIGINAL);
if (!config.getProperty(CONFIG_BLUR, "true").equals("false")) {
image = blur(image);
}
if (!config.getProperty(CONFIG_DARKEN, "true").equals("false")) {
image = darken(image);
}
CURRENT_FILE.getParentFile().mkdirs();
ImageIO.write(image, "jpg", CURRENT_FILE);
trayIcon.setToolTip("\"" + source.getTitle() + "\"\n by " + source.getBy());
setBackgroundImage(false);
} catch (Exception e) {
trayIcon.setToolTip(null);
logError(e);
}
} catch (Exception e) {
logError(e);
}
}
private void showOriginal() {
try {
JobKey jobKey = JobKey.jobKey("showJob");
// scheduler.interrupt(jobKey);
scheduler.scheduleJob(JobBuilder.newJob(ShowJob.class).withIdentity(jobKey).build(),
TriggerBuilder.newTrigger().build());
} catch (ObjectAlreadyExistsException e) {
// do nothing
} catch (SchedulerException e) {
logError(e);
}
}
public void setBackgroundImage(boolean original) throws IOException {
LOG.info("show " + (original ? " original" : "") + " image");
File file = original ? CURRENT_FILE_ORIGINAL : CURRENT_FILE;
SPI.INSTANCE.SystemParametersInfo(new UINT_PTR(SPI.SPI_SETDESKWALLPAPER), new UINT_PTR(0),
file.getCanonicalPath(), new UINT_PTR(SPI.SPIF_UPDATEINIFILE | SPI.SPIF_SENDWININICHANGE));
}
private void exit() {
try {
scheduler.shutdown();
} catch (SchedulerException e) {
logError(e);
}
System.exit(0);
}
public static void logError(Throwable e) {
LOG.error(e.getMessage(), e);
JOptionPane.showMessageDialog(null, e.getMessage());
}
private BufferedImage blur(BufferedImage image) {
// image = gauss(GAUSS_RADIUS).filter(image, null);
image = getGaussianBlurFilter(Repaper.GAUSS_RADIUS, true).filter(image, null);
image = getGaussianBlurFilter(Repaper.GAUSS_RADIUS, false).filter(image, null);
// cropping black borders
BufferedImage croppedImage = new BufferedImage(image.getWidth() - (2 * Repaper.GAUSS_RADIUS),
image.getHeight() - (2 * Repaper.GAUSS_RADIUS), BufferedImage.TYPE_INT_RGB);
Graphics2D g = croppedImage.createGraphics();
g.drawImage(image,
0, 0, croppedImage.getWidth(), croppedImage.getHeight(),
Repaper.GAUSS_RADIUS, Repaper.GAUSS_RADIUS, croppedImage.getWidth() + Repaper.GAUSS_RADIUS,
croppedImage.getHeight() + Repaper.GAUSS_RADIUS,
null);
image = croppedImage;
return image;
}
@SuppressWarnings("unused")
private static ConvolveOp gauss(final int radius) {
double sigma = ((2 * radius) + 1) / 6.0;
float[][] matrix = new float[(2 * radius) + 1][(2 * radius) + 1];
for (int x = 0; x <= radius; x++) {
for (int y = 0; y <= radius; y++) {
float d = (float) (1 / (2 * Math.PI * sigma * sigma)
* Math.exp(-((x * x) + (y * y)) / (2 * sigma * sigma)));
matrix[radius + x][radius + y] = d;
matrix[radius + x][radius - y] = d;
matrix[radius - x][radius + y] = d;
matrix[radius - x][radius - y] = d;
}
}
for (int x = 0; x < matrix.length; x++) {
for (int y = 0; y < matrix[x].length; y++) {
System.out.print((x - radius) + "," + (y - radius) + "=" + matrix[x][y]);
System.out.print("\t");
}
System.out.println();
}
float[] data = new float[((2 * radius) + 1) * ((2 * radius) + 1)];
int d = 0;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
data[d++] = matrix[i][j];
}
}
return new ConvolveOp(new Kernel((2 * radius) + 1, (2 * radius) + 1, data));
}
private BufferedImage darken(BufferedImage image) {
return new RescaleOp(Repaper.BRIGTHNESS, 0, null).filter(image, null);
}
private static ConvolveOp getGaussianBlurFilter(int radius, boolean horizontal) {
if (radius < 1) {
throw new IllegalArgumentException("Radius must be >= 1");
}
int size = radius * 2 + 1;
float[] data = new float[size];
float sigma = radius / 3.0f;
float twoSigmaSquare = 2.0f * sigma * sigma;
float sigmaRoot = (float) Math.sqrt(twoSigmaSquare * Math.PI);
float total = 0.0f;
for (int i = -radius; i <= radius; i++) {
float distance = i * i;
int index = i + radius;
data[index] = (float) Math.exp(-distance / twoSigmaSquare) / sigmaRoot;
total += data[index];
}
for (int i = 0; i < data.length; i++) {
data[i] /= total;
}
Kernel kernel = null;
if (horizontal) {
kernel = new Kernel(size, 1, data);
} else {
kernel = new Kernel(1, size, data);
}
// return new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
return new ConvolveOp(kernel);
}
private class ConfigMenuItem extends MenuItem {
private static final long serialVersionUID = 1L;
public ConfigMenuItem(String label, final String key, final Object value) {
super(label);
LOG.info(key + "=" + value);
addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
setConfig(key, value.toString());
}
});
}
}
public interface SPI extends StdCallLibrary {
long SPI_SETDESKWALLPAPER = 20;
long SPIF_UPDATEINIFILE = 0x01;
long SPIF_SENDWININICHANGE = 0x02;
SPI INSTANCE = (SPI) Native.loadLibrary("user32", SPI.class, new HashMap<Object, Object>() {
private static final long serialVersionUID = 1L;
{
put(OPTION_TYPE_MAPPER, W32APITypeMapper.UNICODE);
put(OPTION_FUNCTION_MAPPER, W32APIFunctionMapper.UNICODE);
}
});
boolean SystemParametersInfo(UINT_PTR uiAction, UINT_PTR uiParam, String pvParam, UINT_PTR fWinIni);
}
} |
package org.jpmml.converter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.function.Function;
import javax.xml.bind.JAXBElement;
import javax.xml.namespace.QName;
import org.dmg.pmml.Application;
import org.dmg.pmml.Apply;
import org.dmg.pmml.Array;
import org.dmg.pmml.ComplexArray;
import org.dmg.pmml.Constant;
import org.dmg.pmml.DataType;
import org.dmg.pmml.Expression;
import org.dmg.pmml.Field;
import org.dmg.pmml.FieldColumnPair;
import org.dmg.pmml.FieldName;
import org.dmg.pmml.HasDiscreteDomain;
import org.dmg.pmml.Header;
import org.dmg.pmml.InlineTable;
import org.dmg.pmml.MapValues;
import org.dmg.pmml.PMMLFunctions;
import org.dmg.pmml.RealSparseArray;
import org.dmg.pmml.Row;
import org.dmg.pmml.Timestamp;
import org.dmg.pmml.Value;
import org.dmg.pmml.Version;
import org.jpmml.model.inlinetable.InputCell;
import org.jpmml.model.inlinetable.OutputCell;
public class PMMLUtil {
private PMMLUtil(){
}
static
public Header createHeader(Class<?> clazz){
Package _package = clazz.getPackage();
return createHeader(_package.getImplementationTitle(), _package.getImplementationVersion());
}
static
public Header createHeader(String name, String version){
Application application = new Application()
.setName(name)
.setVersion(version);
return createHeader(application);
}
static
public Header createHeader(Application application){
Date now = new Date();
// XML Schema "dateTime" data format (corresponds roughly to ISO 8601)
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
dateFormat.setTimeZone(PMMLUtil.UTC);
Timestamp timestamp = new Timestamp()
.addContent(dateFormat.format(now));
Header header = new Header()
.setApplication(application)
.setTimestamp(timestamp);
return header;
}
static
public <F extends Field<F> & HasDiscreteDomain<F>> List<?> getValues(F field){
return getValues(field, null);
}
static
public <F extends Field<F> & HasDiscreteDomain<F>> List<?> getValues(F field, Value.Property property){
List<Object> result = new ArrayList<>();
if(property == null){
property = Value.Property.VALID;
}
List<Value> pmmlValues = field.getValues();
for(Value pmmlValue : pmmlValues){
if((property).equals(pmmlValue.getProperty())){
result.add(pmmlValue.getValue());
}
}
return result;
}
static
public <F extends Field<F> & HasDiscreteDomain<F>> void addValues(F field, List<?> values){
addValues(field, values, null);
}
static
public <F extends Field<F> & HasDiscreteDomain<F>> void addValues(F field, List<?> values, Value.Property property){
if((Value.Property.VALID).equals(property)){
property = null;
}
List<Value> pmmlValues = field.getValues();
for(Object value : values){
Value pmmlValue = new Value(value)
.setProperty(property);
pmmlValues.add(pmmlValue);
}
}
static
public Apply createApply(String function, Expression... expressions){
Apply apply = new Apply(function)
.addExpressions(expressions);
return apply;
}
static
public Constant createConstant(Number value){
if(value == null){
return createConstant(value, null);
}
return createConstant(value, TypeUtil.getDataType(value));
}
static
public Constant createConstant(Object value, DataType dataType){
Constant constant = new Constant(value)
.setDataType(dataType)
.setMissing(value == null);
return constant;
}
static
public MapValues createMapValues(FieldName name, Map<?, ?> mapping){
List<Object> inputValues = new ArrayList<>();
List<Object> outputValues = new ArrayList<>();
Collection<? extends Map.Entry<?, ?>> entries = mapping.entrySet();
for(Map.Entry<?, ?> entry : entries){
inputValues.add(entry.getKey());
outputValues.add(entry.getValue());
}
return createMapValues(name, inputValues, outputValues);
}
static
public MapValues createMapValues(FieldName name, List<?> inputValues, List<?> outputValues){
String inputColumn = "data:input";
String outputColumn = "data:output";
Map<String, List<?>> data = new LinkedHashMap<>();
data.put(inputColumn, inputValues);
data.put(outputColumn, outputValues);
MapValues mapValues = new MapValues(outputColumn, null, PMMLUtil.createInlineTable(data))
.addFieldColumnPairs(new FieldColumnPair(name, inputColumn));
return mapValues;
}
static
public Expression toNegative(Expression expression){
if(expression instanceof Constant){
Constant constant = (Constant)expression;
Object value = constant.getValue();
if(value instanceof Long){
value = -((Long)value).longValue();
} else
if(value instanceof Integer){
value = -((Integer)value).intValue();
} else
if(value instanceof Float){
value = -((Float)value).floatValue();
} else
if(value instanceof Double){
value = -((Double)value).doubleValue();
} else
{
String string = ValueUtil.asString(value);
if(string.startsWith("-")){
string = string.substring(1);
} else
{
string = ("-" + string);
}
value = string;
}
constant.setValue(value);
return constant;
}
return createApply(PMMLFunctions.MULTIPLY, createConstant(-1), expression);
}
static
public Array createStringArray(List<?> values){
Array array = new ComplexArray()
.setType(Array.Type.STRING)
.setValue(values);
return array;
}
static
public Array createIntArray(List<Integer> values){
Array array = new ComplexArray()
.setType(Array.Type.INT)
.setValue(values);
return array;
}
static
public Array createRealArray(List<? extends Number> values){
Array array = new ComplexArray()
.setType(Array.Type.REAL)
.setValue(values);
return array;
}
static
public RealSparseArray createRealSparseArray(List<? extends Number> values, Double defaultValue){
RealSparseArray sparseArray = new RealSparseArray()
.setN(values.size())
.setDefaultValue(defaultValue);
List<Integer> indices = sparseArray.getIndices();
List<Double> entries = sparseArray.getEntries();
int index = 1;
for(Number value : values){
if(!ValueUtil.equals(value, defaultValue)){
indices.add(index);
entries.add(ValueUtil.asDouble(value));
}
index++;
}
return sparseArray;
}
static
public InlineTable createInlineTable(Map<String, ? extends List<?>> data){
return createInlineTable(Function.identity(), data);
}
static
public <K> InlineTable createInlineTable(Function<K, String> function, Map<K, ? extends List<?>> data){
int rows = 0;
Map<K, QName> columns = new LinkedHashMap<>();
{
Collection<? extends Map.Entry<K, ? extends List<?>>> entries = data.entrySet();
for(Map.Entry<K, ? extends List<?>> entry : entries){
K column = entry.getKey();
List<?> columnData = entry.getValue();
if(rows == 0){
rows = columnData.size();
} else
{
if(rows != columnData.size()){
throw new IllegalArgumentException();
}
}
QName columnName;
String tagName = function.apply(column);
if(tagName.startsWith("data:")){
columnName = new QName("http://jpmml.org/jpmml-model/InlineTable", tagName.substring("data:".length()), "data");
} else
{
if(tagName.indexOf(':') > -1){
throw new IllegalArgumentException(tagName);
}
columnName = new QName(Version.PMML_4_4.getNamespaceURI(), tagName);
}
columns.put(column, columnName);
}
}
QName inputColumnName = InputCell.QNAME;
QName outputColumnName = OutputCell.QNAME;
InlineTable inlineTable = new InlineTable();
for(int i = 0; i < rows; i++){
Row row = new Row();
Collection<Map.Entry<K, QName>> entries = columns.entrySet();
for(Map.Entry<K, QName> entry : entries){
List<?> columnData = data.get(entry.getKey());
Object value = columnData.get(i);
if(value == null){
continue;
}
QName columName = entry.getValue();
Object cell;
if((inputColumnName).equals(columName)){
cell = new InputCell(value);
} else
if((outputColumnName).equals(columName)){
cell = new OutputCell(value);
} else
{
cell = new JAXBElement<>(columName, String.class, ValueUtil.asString(value));
}
row.addContent(cell);
}
inlineTable.addRows(row);
}
return inlineTable;
}
private static final TimeZone UTC = TimeZone.getTimeZone("UTC");
} |
package com.utoken.concurrent.atomic;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
public class AtomicBaseTest {
public static void main(String[] args) {
testAtomicBoolean();
}
/**
* AtomicInteger
*/
public static void testAtomicInteger(){
ExecutorService es = Executors.newFixedThreadPool(10);
AtomicIntegerThread ait = new AtomicIntegerThread();
for(int i = 0; i < 100; ++i){
es.submit(ait);
}
es.shutdown();
}
/**
* AtomicLong
*/
public static void testAtomicLong(){
ExecutorService es = Executors.newFixedThreadPool(10);
AtomicLongThread alt = new AtomicLongThread();
for(int i = 0; i < 100; ++i){
es.submit(alt);
}
es.shutdown();
}
/**
* AtomicBoolean
*/
public static void testAtomicBoolean(){
ExecutorService es = Executors.newFixedThreadPool(10);
AtomicBooleanThread alt = new AtomicBooleanThread();
for(int i = 0; i < 100; ++i){
es.submit(alt);
}
es.shutdown();
}
static class AtomicIntegerThread implements Runnable{
private AtomicInteger atomicInteger = new AtomicInteger(1);
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " value = " + atomicInteger.getAndIncrement());
}
}
static class AtomicLongThread implements Runnable{
private AtomicLong atomicLong = new AtomicLong(1);
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " value = " + atomicLong.getAndIncrement());
}
}
static class AtomicBooleanThread implements Runnable{
private AtomicBoolean atomicBoolean = new AtomicBoolean(false);
@Override
public void run() {
boolean flg = atomicBoolean.get();
atomicBoolean.set(!flg);
System.out.println(Thread.currentThread().getName() + " value = " + flg);
}
}
} |
package cronapi.rest;
import java.io.File;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import cronapi.util.Operations;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(value = "/js/blockly.js")
public class ImportBlocklyREST {
private static List<String> imports;
private static boolean isDebug = Operations.IS_DEBUG;
private final static List<String> API_PATHS = new ArrayList<String>(){{add("cronapi-js");add("cronapp-framework-js");add("cronapp-framework-mobile-js");}};
private static JsonObject localesJson = new JsonObject();
private static List<String> localesKeys = new ArrayList<String>();
private static JsonObject localesRef = new JsonObject();
private void fill(String base, File folder, List<String> imports) {
for(File file : folder.listFiles( (d,s) ->{
boolean valid = true;
for(String api : API_PATHS){
if(d.getName().contains(api)){
valid = false;
break;
}
}
return valid;
} )) {
if(file.isDirectory()) {
fill(base, file, imports);
}
else {
if(file.getName().endsWith(".blockly.js")) {
String js = file.getAbsolutePath().replace(base, "");
js = js.replace("\\", "/");
if(js.startsWith("/")) {
js = js.substring(1);
}
imports.add(js + "?" + file.lastModified());
}
}
}
}
@RequestMapping(method = RequestMethod.GET)
public void listBlockly(HttpServletRequest request, HttpServletResponse response) throws Exception {
response.setContentType("application/javascript");
PrintWriter out = response.getWriter();
if(imports == null) {
synchronized(ImportBlocklyREST.class) {
if(imports == null) {
List<String> fillImports = new ArrayList<>();
File folder = new File(request.getServletContext().getRealPath("/"));
fill(request.getServletContext().getRealPath("/"), folder, fillImports);
if(!isDebug) {
imports = fillImports;
}
else {
fillLanguages(folder);
write(out, fillImports);
}
}
}
}
if(imports != null) {
write(out, imports);
}
}
private void fillLanguages(File folder){
localesJson = new JsonObject();
localesKeys = new ArrayList<String>();
localesRef = new JsonObject();
File folderI18n = new File(folder, "i18n");
if (folderI18n.exists()) {
for(File filee : folderI18n.listFiles( (d,s) ->{
boolean valid = false;
if(s.startsWith("locale") && s.endsWith(".json")){
valid = true;
return valid;
}
return valid;
} )) {
String localeName = filee.getName().substring(7, filee.getName().length() - 5);
fillLanguageSet(localeName);
}
}
}
private void write(PrintWriter out, List<String> imports) {
String localesJsonString = localesJson.toString() + ";";
String localesKeysString = arrayToString(localesKeys) + ";";
String localesRefString = localesRef.toString() + ";";
out.println("window.blockly = window.blockly || {};");
out.println("window.blockly.js = window.blockly.js || {};");
out.println("window.blockly.js.blockly = window.blockly.js.blockly || {};");
out.println("window.translations = window.translations || {};");
out.println("window.translations.locales = " + localesJsonString);
out.println("window.translations.localesKeys = " + localesKeysString);
out.println("window.translations.localesRef = " + localesRefString);
for(String js : imports) {
out.println("document.write(\"<script src='" + js + "'></script>\")");
}
}
private void fillLanguageSet(String localeName){
if(localesJson.get(localeName) == null){
localesJson.addProperty(localeName, localeName);
}
if(localesKeys.indexOf(localeName) == -1){
localesKeys.add(localeName);
}
localesRef.addProperty(localeName.substring(0,2) + "*", localeName);
if(localesRef.get("*") == null){
localesRef.addProperty("*", localeName);
}
if(localeName.equals("pt_br")){
localesRef.addProperty("*", localeName);
}
}
private String arrayToString(List<String> stringList){
StringBuilder b = new StringBuilder();
b.append("[");
for(String key : stringList){
if(stringList.indexOf(key) != 0) {
b.append(",");
}
b.append("'" + key + "'");
}
b.append("]");
return b.toString();
}
} |
package com.valkryst.VTerminal.builder;
import com.valkryst.VRadio.Radio;
import com.valkryst.VTerminal.Panel;
import com.valkryst.VTerminal.builder.component.ScreenBuilder;
import com.valkryst.VTerminal.component.Screen;
import com.valkryst.VTerminal.font.Font;
import com.valkryst.VTerminal.misc.ImageCache;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
import java.awt.Color;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
@EqualsAndHashCode
@ToString
public class PanelBuilder {
/** The width of the panel, in characters. */
@Getter @Setter private int widthInCharacters;
/** The height of the panel, in characters. */
@Getter @Setter private int heightInCharacters;
/** The font to draw with. */
@Getter @Setter private Font font;
/** The radio being listened to. */
@Getter private Radio<String> radio = new Radio<>();
/** The screen being displayed on the panel. */
@Getter @Setter private Screen screen;
/** The frame in which the panel is to be placed. */
@Getter @Setter private JFrame frame;
/** The image cache to retrieve character images from. */
@Getter @Setter private ImageCache imageCache;
/** Whether or not to allow the Panel to redraw itself based on received radio transmissions. */
@Getter @Setter private boolean dynamicallyRedrawn;
/** Constructs a new PanelBuilder. */
public PanelBuilder() {
reset();
}
/**
* Uses the builder to construct a new VTerminal.
*
* If no frame is set, a default frame will be used.
*
* @return
* The new VTerminal.
*/
public Panel build() {
checkState();
final Color backgroundColor = new Color(255, 0, 255, 255);
final Panel panel = new Panel(this);
frame.add(panel);
frame.setResizable(false);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setBackground(backgroundColor);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.addComponentListener(new ComponentListener() {
@Override
public void componentResized(final ComponentEvent e) {
panel.getScreen().setAllCharactersToBeRedrawn();
panel.draw();
}
@Override
public void componentMoved(final ComponentEvent e) {
panel.getScreen().setAllCharactersToBeRedrawn();
panel.draw();
}
@Override
public void componentShown(final ComponentEvent e) {
panel.getScreen().setAllCharactersToBeRedrawn();
panel.draw();
}
@Override
public void componentHidden(final ComponentEvent e) {}
});
panel.setIgnoreRepaint(true);
panel.createBufferStrategy(2);
panel.setFocusable(true);
panel.setFocusTraversalKeysEnabled(false);
panel.setBackground(backgroundColor);
return panel;
}
private void checkState() throws NullPointerException {
if (widthInCharacters < 1) {
throw new IllegalArgumentException("The width, in characters, cannot be less than one.");
}
if (heightInCharacters < 1) {
throw new IllegalArgumentException("The height, in characters, cannot be less than one.");
}
if (font == null) {
throw new NullPointerException("The panel must have an AsciiFont to draw with.");
}
if (screen == null) {
final ScreenBuilder screenBuilder = new ScreenBuilder();
screenBuilder.setRadio(radio);
screenBuilder.setColumnIndex(0);
screenBuilder.setRowIndex(0);
screenBuilder.setWidth(widthInCharacters);
screenBuilder.setHeight(heightInCharacters);
screen = screenBuilder.build();
}
if (frame == null) {
frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
if (imageCache == null) {
imageCache = new ImageCache(font);
}
}
/** Resets the builder to it's default state. */
public void reset() {
widthInCharacters = 80;
heightInCharacters = 24;
font = null;
screen = null;
frame = null;
dynamicallyRedrawn = true;
}
} |
package org.lightmare.utils;
import org.apache.log4j.Logger;
/**
* Utility class for logging
*
* @author levan
* @since 0.0.81-SNAPSHOT
*/
public class LogUtils {
/**
* Generates logging messages
*
* @param message
* @param formats
* @return {@link String}
*/
public static String logMessage(String message, Object... formats) {
String logMessage;
if (CollectionUtils.valid(formats)) {
logMessage = String.format(message, formats);
} else {
logMessage = message;
}
return logMessage;
}
/**
* Generated fatal log
*
* @param log
* @param ex
* @param message
* @param formats
*/
public static void fatal(Logger log, Throwable ex, String message,
Object... formats) {
String logMessage = logMessage(message, formats);
if (ex == null) {
log.fatal(logMessage);
} else {
log.fatal(logMessage, ex);
}
}
/**
* Generates fatal logs
*
* @param log
* @param message
* @param formats
*/
public static void fatal(Logger log, String message, Object... formats) {
fatal(log, null, message, formats);
}
/**
* Generates error log
*
* @param log
* @param ex
* @param message
* @param formats
*/
public static void error(Logger log, Throwable ex, String message,
Object... formats) {
String logMessage = logMessage(message, formats);
if (ex == null) {
log.error(logMessage);
} else {
log.error(logMessage, ex);
}
}
/**
* Generates error logs
*
* @param log
* @param message
* @param formats
*/
public static void error(Logger log, String message, Object... formats) {
error(log, null, message, formats);
}
/**
* Generates debug logs
*
* @param log
* @param ex
* @param message
* @param formats
*/
public static void debug(Logger log, Throwable ex, String message,
Object... formats) {
String logMessage = logMessage(message, formats);
if (ex == null) {
log.debug(logMessage);
} else {
log.debug(logMessage, ex);
}
}
/**
* Generates debug logs
*
* @param log
* @param message
* @param formats
*/
public static void debug(Logger log, String message, Object... formats) {
debug(log, null, message, formats);
}
/**
* Generates info logs
*
* @param log
* @param ex
* @param message
* @param formats
*/
public static void info(Logger log, Throwable ex, String message,
Object... formats) {
String logMessage = logMessage(message, formats);
if (ex == null) {
log.info(logMessage);
} else {
log.info(logMessage, ex);
}
}
/**
* Generates info logs
*
* @param log
* @param message
* @param formats
*/
public static void info(Logger log, String message, Object... formats) {
info(log, null, message, formats);
}
} |
package eu.modernmt.model;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Tag extends Token implements Comparable<Tag> {
private static final String TAG_NAME = "(\\p{Alpha}|_|:)(\\p{Alpha}|\\p{Digit}|\\.|-|_|:|)*";
private static final Pattern TagNameRegex = Pattern.compile(TAG_NAME);
public static final Pattern TagRegex = Pattern.compile(
"(<(" + TAG_NAME + ")[^>]*/?>)|" +
"(<!(" + TAG_NAME + ")[^>]*[^/]>)|" +
"(</(" + TAG_NAME + ")[^>]*>)|" +
"()");
public void setType(Type type) {
this.type = type;
}
public enum Type {
OPENING_TAG,
CLOSING_TAG,
EMPTY_TAG,
}
public static Tag fromText(String text) {
return fromText(text, false, null, -1);
}
public static Tag fromText(String text, boolean leftSpace, String rightSpace, int position) {
if ("<!--".equals(text)) {
return new Tag("--", text, leftSpace, rightSpace, position, Type.OPENING_TAG, false);
} else if ("-->".equals(text)) {
return new Tag("--", text, leftSpace, rightSpace, position, Type.CLOSING_TAG, false);
}
int length = text.length();
if (length < 3)
throw new IllegalArgumentException("Invalid tag: " + text);
String name;
Type type;
boolean dtd = false;
int nameStartPosition = 1;
if (text.charAt(1) == '!') {
dtd = true;
type = Type.OPENING_TAG;
nameStartPosition = 2;
} else if (text.charAt(1) == '/') {
type = Type.CLOSING_TAG;
nameStartPosition = 2;
} else if (text.charAt(length - 2) == '/') {
type = Type.EMPTY_TAG;
} else {
type = Type.OPENING_TAG;
}
Matcher matcher = TagNameRegex.matcher(text);
if (!matcher.find(nameStartPosition))
throw new IllegalArgumentException("Invalid tag: " + text);
name = matcher.group();
return new Tag(name, text, leftSpace, rightSpace, position, type, dtd);
}
public static Tag fromTag(Tag other) {
return new Tag(other.name, other.text, other.leftSpace, other.rightSpace, other.position, other.type, other.dtd);
}
protected Type type; /* tag type */
protected final String name; /* tag name */
protected boolean leftSpace; /* true if there is at least one space on the left of the tag*/
/* position of the word after which the tag is placed; indexes of words start from 0
e.g. a tag at the beginning of the sentence has position=0
e.g. a tag at the end of the sentence (of Length words) has position=Length
*/
protected int position;
protected boolean dtd;
public Tag(String name, String text, boolean leftSpace, String rightSpace, int position, Type type, boolean dtd) {
super(text, text, rightSpace);
this.leftSpace = leftSpace;
this.position = position;
this.type = type;
this.name = name;
this.dtd = dtd;
}
public boolean hasLeftSpace() {
return leftSpace;
}
public int getPosition() {
return position;
}
public void setPosition(int position) {
this.position = position;
}
public Type getType() {
return type;
}
public String getName() {
return name;
}
public void setLeftSpace(boolean leftSpace) {
this.leftSpace = leftSpace;
}
public boolean isEmptyTag() {
return this.type == Type.EMPTY_TAG;
}
public boolean isOpeningTag() {
return this.type == Type.OPENING_TAG;
}
public boolean isClosingTag() {
return this.type == Type.CLOSING_TAG;
}
public boolean isDTD() {
return dtd;
}
public boolean isComment() {
return "--".equals(name);
}
public boolean closes(Tag other) {
return !this.dtd && this.type == Type.CLOSING_TAG && other.type == Type.OPENING_TAG && nameEquals(this.name, other.name);
}
public boolean opens(Tag other) {
return !this.dtd && this.type == Type.OPENING_TAG && other.type == Type.CLOSING_TAG && nameEquals(this.name, other.name);
}
private static boolean nameEquals(String n1, String n2) {
if (n1 == null)
return n2 == null;
else
return n1.equals(n2);
}
@Override
public int compareTo(Tag other) {
return Integer.compare(this.position, other.getPosition());
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
Tag tag = (Tag) o;
if (leftSpace != tag.leftSpace) return false;
if (position != tag.position) return false;
if (dtd != tag.dtd) return false;
if (type != tag.type) return false;
return name.equals(tag.name);
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + type.hashCode();
result = 31 * result + name.hashCode();
result = 31 * result + (leftSpace ? 1 : 0);
result = 31 * result + position;
result = 31 * result + (dtd ? 1 : 0);
return result;
}
} |
package dk.itu.kelvin.thread;
// General utilities
import java.util.Map;
import java.util.Queue;
// Concurrency utilities
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentHashMap;
// JavaFX concurrency utilities
import javafx.concurrent.Task;
/**
* Task queue class.
*
* @version 1.0.0
*/
public final class TaskQueue {
static {
// Initialize the map containing the task groups. We use a concurrent hash
// map since it will potentially be modified from multiple threads at the
// same time.
// If the task queue is never used, this statement will never run thus
// ensuring that we don't allocate memory to a map which is never used.
TaskQueue.groups = new ConcurrentHashMap<>();
}
/**
* The map containing the different groups mapped to their task queues.
*/
private static Map<String, Queue<FunctionalTask>> groups;
/**
* Don't allow instantiation of the class.
*
* Since the class only contains static fields and methods, we never want to
* instantiate the class. We therefore define a private constructor so that
* noone can create instances of the class other than the class itself.
*
* NB: This does not make the class a singleton. In fact, there never exists
* an instance of the class since not even the class instantiates itself.
*/
private TaskQueue() {
super();
}
/**
* Register a new task belonging to the specified group.
*
* @param group The group that the task belongs to.
* @param tasks The tasks to perform.
*/
public static void register(
final String group,
final FunctionalTask... tasks
) {
if (group == null || tasks == null || tasks.length == 0) {
return;
}
// Initialize the group if it hasn't been initialized yet.
if (!TaskQueue.groups.containsKey(group)) {
// A concurrent linked queue is used as the task queue will potentially be
// modified from several threads at the same time. This will for example
// be the case if a new task is added before `start()` has finished
// running all the tasks in the queue.
TaskQueue.groups.put(group, new ConcurrentLinkedQueue<FunctionalTask>());
}
Queue<FunctionalTask> queue = TaskQueue.groups.get(group);
for (FunctionalTask task: tasks) {
queue.add(task);
}
}
/**
* Run the specified task on a separate thread.
*
* @param task The task to perform.
*/
public static void run(final FunctionalTask task) {
// Encapsulate the FunctionalTask in a JavaFX Task.
Task<Void> runner = new Task<Void>() {
@Override
public Void call() {
// Run the task.
task.run();
// We're done here.
return null;
}
};
// Start the task on a separate thread.
new Thread(runner).start();
}
/**
* Start all tasks belonging to the specified group.
*
* @param group The group whose tasks to run.
*/
public static void start(final String group) {
if (group == null || !TaskQueue.groups.containsKey(group)) {
return;
}
// Boot a new thread whose only purpose is to dequeue and run tasks from the
// task queue. If there are a lot of tasks to run, this ensures that the
// main thread isn't blocked.
TaskQueue.run(() -> {
// Get the task queue for the specified group.
Queue<FunctionalTask> queue = TaskQueue.groups.get(group);
// While there are tasks left in the queue, get the next one and run it.
while (!queue.isEmpty()) {
TaskQueue.run(queue.poll());
}
// Remove the group from the map of groups. No loitering!
TaskQueue.groups.remove(group);
});
}
/**
* A functional interface for defining asynchronous tasks.
*/
@FunctionalInterface
public interface FunctionalTask {
/**
* Run the task.
*/
void run();
}
} |
package edu.cmu.lti.oaqa.util;
import static java.util.stream.Collectors.toCollection;
import static java.util.stream.Collectors.toList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.IntStream;
import org.apache.uima.fit.util.FSCollectionFactory;
import org.apache.uima.fit.util.JCasUtil;
import org.apache.uima.jcas.JCas;
import org.apache.uima.jcas.tcas.Annotation;
import com.google.common.collect.Range;
import edu.cmu.lti.oaqa.type.answer.Answer;
import edu.cmu.lti.oaqa.type.answer.Summary;
import edu.cmu.lti.oaqa.type.input.Question;
import edu.cmu.lti.oaqa.type.kb.Concept;
import edu.cmu.lti.oaqa.type.kb.ConceptMention;
import edu.cmu.lti.oaqa.type.kb.ConceptType;
import edu.cmu.lti.oaqa.type.nlp.LexicalAnswerType;
import edu.cmu.lti.oaqa.type.nlp.Token;
import edu.cmu.lti.oaqa.type.retrieval.AbstractQuery;
import edu.cmu.lti.oaqa.type.retrieval.ConceptSearchResult;
import edu.cmu.lti.oaqa.type.retrieval.Document;
import edu.cmu.lti.oaqa.type.retrieval.Passage;
import edu.cmu.lti.oaqa.type.retrieval.QueryConcept;
import edu.cmu.lti.oaqa.type.retrieval.SearchResult;
import edu.cmu.lti.oaqa.type.retrieval.TripleSearchResult;
public class TypeUtil {
public static Question getQuestion(JCas jcas) {
return JCasUtil.selectSingle(jcas, Question.class);
}
public static List<Token> getOrderedTokens(JCas jcas) {
return JCasUtil.select(jcas, Token.class).stream().sorted(Comparator.comparing(Token::getBegin))
.collect(toList());
}
public static Token getHeadTokenOfAnnotation(JCas jcas, Annotation annotation) {
return getHeadTokenInRange(jcas, annotation.getBegin(), annotation.getEnd());
}
public static Token getHeadTokenInRange(JCas jcas, int begin, int end) {
List<Token> tokens = JCasUtil.selectCovered(jcas, Token.class, begin, end);
if (tokens.isEmpty()) {
return null;
}
// get path to root for the first token
List<Token> pathToRoot = new ArrayList<>();
Token hop = tokens.get(0);
do {
pathToRoot.add(hop);
} while ((hop = hop.getHead()) != null);
// prune the path to contain only the common sub path to the root of each remaining token
for (Token token : tokens) {
hop = token;
do {
int index;
if ((index = pathToRoot.indexOf(hop)) >= 0) {
pathToRoot = pathToRoot.subList(index, pathToRoot.size());
break;
}
} while ((hop = hop.getHead()) != null);
assert false;
}
// get the head of the resulting path to root
assert!pathToRoot.isEmpty();
return pathToRoot.get(0);
}
public static Collection<Concept> getConcepts(JCas jcas) {
return JCasUtil.select(jcas, Concept.class);
}
public static Collection<ConceptType> getConceptTypes(Concept concept) {
return FSCollectionFactory.create(concept.getTypes(), ConceptType.class);
}
public static String getFirstConceptId(Concept concept) {
return FSCollectionFactory.create(concept.getIds()).stream().findFirst().get();
}
public static Collection<ConceptMention> getConceptMentions(Concept concept) {
return FSCollectionFactory.create(concept.getMentions(), ConceptMention.class);
}
public static List<ConceptMention> getOrderedConceptMentions(JCas jcas) {
return JCasUtil.select(jcas, ConceptMention.class).stream()
.sorted(Comparator.comparing(ConceptMention::getBegin)).collect(toList());
}
public static Collection<AbstractQuery> getAbstractQueries(JCas jcas) {
return JCasUtil.select(jcas, AbstractQuery.class);
}
@Deprecated
public static AbstractQuery getAbstractQueriesCombined(JCas jcas) {
List<QueryConcept> conceptsCombined = getAbstractQueries(jcas).stream()
.flatMap(a -> FSCollectionFactory.create(a.getConcepts(), QueryConcept.class).stream())
.collect(toList());
return TypeFactory.createAbstractQuery(jcas, conceptsCombined);
}
public static final Comparator<SearchResult> SEARCH_RESULT_SCORE_COMPARATOR = Comparator
.comparing(SearchResult::getScore).reversed();
public static <T extends SearchResult> List<T> rankedSearchResultsByScore(Collection<T> results,
int hitSize) {
List<T> sorted = results.stream().sorted(SEARCH_RESULT_SCORE_COMPARATOR).limit(hitSize)
.collect(toList());
IntStream.range(0, sorted.size()).forEach(rank -> sorted.get(rank).setRank(rank));
return sorted;
}
public static final Comparator<SearchResult> SEARCH_RESULT_RANK_COMPARATOR = Comparator
.comparing(SearchResult::getRank);
private static <T extends SearchResult> Collection<T> rankedSearchResultsByRank(
Collection<T> results) {
return results.stream().sorted(SEARCH_RESULT_RANK_COMPARATOR)
.collect(toCollection(ArrayList::new));
}
public static Collection<ConceptSearchResult> getRankedConceptSearchResults(JCas jcas) {
return rankedSearchResultsByRank(JCasUtil.select(jcas, ConceptSearchResult.class));
}
public static Collection<TripleSearchResult> getRankedTripleSearchResults(JCas jcas) {
return rankedSearchResultsByRank(JCasUtil.select(jcas, TripleSearchResult.class));
}
public static Collection<Document> getRankedDocuments(JCas jcas) {
return rankedSearchResultsByRank(JCasUtil.select(jcas, Document.class));
}
public static Collection<Passage> getRankedPassages(JCas jcas) {
return rankedSearchResultsByRank(JCasUtil.select(jcas, Passage.class));
}
public static LexicalAnswerType getLexicalAnswerType(JCas jcas) {
return JCasUtil.selectSingle(jcas, LexicalAnswerType.class);
}
public static Collection<Answer> getAnswers(JCas jcas) {
return JCasUtil.select(jcas, Answer.class);
}
public static Collection<Summary> getSummary(JCas jcas) {
return JCasUtil.select(jcas, Summary.class);
}
public static List<String> getAnswerVariants(Answer answer) {
List<String> variants = Arrays.asList(answer.getText());
variants.addAll(FSCollectionFactory.create(answer.getVariants()));
return variants;
}
public static Range<Integer> spanRange(Annotation annotation) {
return Range.closedOpen(annotation.getBegin(), annotation.getEnd());
}
public static Range<Integer> spanRangeInSection(Passage passage) {
return Range.closedOpen(passage.getOffsetInBeginSection(), passage.getOffsetInEndSection());
}
public static int hash(Passage passage) {
return Objects.hash(passage.getUri(), passage.getDocId(), passage.getOffsetInBeginSection(),
passage.getOffsetInEndSection(), passage.getBeginSection(), passage.getEndSection());
}
} |
package org.mapyrus.gui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.ScrollPane;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.PrintStream;
import java.io.StringReader;
import java.net.URL;
import java.util.concurrent.LinkedBlockingQueue;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JEditorPane;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.filechooser.FileFilter;
import org.mapyrus.Constants;
import org.mapyrus.ContextStack;
import org.mapyrus.FileOrURL;
import org.mapyrus.ImageSelection;
import org.mapyrus.Interpreter;
import org.mapyrus.MapyrusException;
import org.mapyrus.MapyrusMessages;
import org.mapyrus.Mutex;
/**
* Mapyrus GUI, allowing user to edit and run commands and see the output on the screen.
*/
public class MapyrusFrame implements MapyrusEventListener
{
/*
* Font for command input and output.
*/
private static Font m_fixedFont = new Font("Monospaced", Font.PLAIN, 12);
private Mutex m_mutex;
private JFrame m_frame;
private MapyrusEditorPanel m_editorPanel;
private JTextArea m_outputTextArea;
private Thread m_outputThread;
private JPanel m_displayPanel;
private LinkedBlockingQueue<MapyrusEventListener.Action> m_actionQueue = null;
private Thread m_actionThread;
private BufferedImage m_displayImage;
private CrosshairMouseListener m_displayPanelListener;
private File m_lastOpenedDirectory;
public MapyrusFrame(String []filenames)
{
setLookAndFeel();
createActionQueue();
/*
* Create frame maximised to fill nearly the whole screen.
*/
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
screenSize = new Dimension((int)screenSize.getWidth(), (int)screenSize.getHeight() - 48);
m_frame = new JFrame(Constants.PROGRAM_NAME + " " + Constants.getVersion());
m_frame.setPreferredSize(screenSize);
m_mutex = new Mutex();
m_mutex.lock();
m_frame.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
/*
* If any changes saved successfully then we can exit.
*/
if (saveAndExit())
m_mutex.unlock();
}
});
Container contentPane = m_frame.getContentPane();
contentPane.setLayout(new BorderLayout());
/*
* Add menubar and menu options.
*/
MapyrusMenuBar menuBar = new MapyrusMenuBar();
menuBar.addListener(this);
contentPane.add(menuBar, BorderLayout.NORTH);
/*
* Add display panel, toolbar, text editor panel, output panel.
*/
JSplitPane splitPane1 = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
JSplitPane splitPane2 = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
m_displayPanel = new JPanel(){
static final long serialVersionUID = 0x3302;
public void paintComponent(Graphics g)
{
/*
* Double-buffering. Redisplay image that Mapyrus has drawn.
*/
super.paintComponent(g);
if (m_displayPanel != null && m_displayImage != null)
{
g.drawImage(m_displayImage, 0, 0, null);
}
}
};
m_displayPanelListener = new CrosshairMouseListener();
m_displayPanel.addMouseMotionListener(m_displayPanelListener);
m_displayPanel.addMouseListener(m_displayPanelListener);
m_displayPanel.setPreferredSize(screenSize);
splitPane1.add(m_displayPanel);
JPanel toolBarAndEditorPanel = new JPanel();
toolBarAndEditorPanel.setLayout(new BorderLayout());
MapyrusToolBar toolBar = new MapyrusToolBar();
toolBar.addListener(this);
toolBarAndEditorPanel.add(toolBar, BorderLayout.NORTH);
m_editorPanel = new MapyrusEditorPanel();
m_editorPanel.setFont(m_fixedFont);
toolBarAndEditorPanel.add(m_editorPanel, BorderLayout.CENTER);
splitPane2.add(toolBarAndEditorPanel);
m_outputTextArea = new JTextArea(2, 80);
m_outputTextArea.setBackground(Color.WHITE);
m_outputTextArea.setFont(m_fixedFont);
m_outputTextArea.setEditable(false);
JScrollPane outputPane = new JScrollPane(m_outputTextArea);
splitPane2.add(outputPane);
splitPane1.add(splitPane2);
contentPane.add(splitPane1, BorderLayout.CENTER);
m_frame.pack();
/*
* Show mostly the display panel and only a few lines of the editor
* and output.
*/
splitPane1.setDividerLocation(0.60);
m_frame.setVisible(true);
/*
* Add each file as a tab.
*/
if (filenames != null)
{
for (int i = 0; i < filenames.length; i++)
{
m_editorPanel.createTab(filenames[i], null, null);
}
}
else
{
/*
* Create some tabs with example commands for the user to
* experiment with.
*/
String []tabNames = new String[]{"Mapyrus Logo", "USA", "Eurozone"};
String []urls = new String[]{"commands1.txt", "commands2.txt", "commands3.txt"};
for (int i = 0; i < tabNames.length; i++)
{
m_editorPanel.createTab(null, tabNames[i], null);
InputStreamReader r = null;
try
{
URL commandsUrl = this.getClass().getResource(urls[i]);
r = new InputStreamReader(commandsUrl.openConnection().getInputStream());
StringBuilder commands = new StringBuilder();
int c;
while ((c = r.read()) != -1)
commands.append((char)c);
m_editorPanel.appendToSelectedTextArea(commands.toString());
/*
* Run last set of sample commands too.
*/
if (i == tabNames.length - 1)
actionPerformed(MapyrusEventListener.Action.RUN);
}
catch (IOException e)
{
/*
* Oh well, just start with an empty tab then.
*/
}
finally
{
try
{
if (r != null)
r.close();
}
catch (IOException e)
{
}
}
}
}
m_editorPanel.addChangeListener(new ChangeListener(){
public void stateChanged(ChangeEvent e)
{
/*
* Re-interpret commands in current tab and display output.
*/
}
});
waitForClose();
}
/**
* Create new window displaying image.
* @param title tile for window.
* @param image image to display in window.
*/
public MapyrusFrame(String title, BufferedImage image)
{
setLookAndFeel();
createActionQueue();
m_displayImage = image;
m_frame = new JFrame(title);
Container contentPane = m_frame.getContentPane();
contentPane.setLayout(new BorderLayout());
/*
* Add menubar and menu options.
*/
MapyrusMenuBar menuBar = new MapyrusMenuBar();
menuBar.addListener(this);
contentPane.add(menuBar, BorderLayout.NORTH);
ImageIcon icon = new ImageIcon(image);
final JLabel label = new JLabel(icon);
/*
* Put image on an icon, putting it in a scrollable area if it is bigger
* than the screen.
*/
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
if (image.getWidth() > screenSize.getWidth() ||
image.getHeight() > screenSize.getHeight() - 50)
{
ScrollPane pane = new ScrollPane();
pane.add(label);
contentPane.add(pane, BorderLayout.CENTER);
}
else
{
contentPane.add(label, BorderLayout.CENTER);
}
m_mutex = new Mutex();
m_mutex.lock();
m_frame.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
/*
* If any changes saved successfully then we can exit.
*/
if (saveAndExit())
m_mutex.unlock();
}
});
m_frame.pack();
m_frame.setVisible(true);
waitForClose();
}
private void setLookAndFeel()
{
try
{
/*
* Set operating system specific LookAndFeel.
*/
String className = UIManager.getSystemLookAndFeelClassName();
UIManager.setLookAndFeel(className);
}
catch (UnsupportedLookAndFeelException e)
{
}
catch (ClassNotFoundException e)
{
}
catch (IllegalAccessException e)
{
}
catch (InstantiationException e)
{
}
}
private void createActionQueue()
{
/*
* Create or recreate queue of actions from GUI.
*/
if (m_actionQueue != null)
m_actionQueue.clear();
else
m_actionQueue = new LinkedBlockingQueue<MapyrusEventListener.Action>();
/*
* Create another thread to read this queue and process
* actions so that the GUI is not blocked.
*/
m_actionThread = new Thread(){
public void run()
{
try
{
processActions();
}
catch (InterruptedException e)
{
}
}
};
m_actionThread.start();
}
public void actionPerformed(MapyrusEventListener.Action action)
{
if (action == MapyrusEventListener.Action.STOP ||
action == MapyrusEventListener.Action.EXIT)
{
/*
* Interrupt any action that is already running,
* clear queue and restart thread that handles events.
*
* This ensures that event is handled immediately.
*/
m_actionThread.interrupt();
if (m_outputThread != null)
{
m_outputThread.interrupt();
m_outputThread = null;
}
createActionQueue();
}
/*
* Add action to queue.
*/
try
{
m_actionQueue.put(action);
}
catch (InterruptedException e)
{
}
}
public void processActions() throws InterruptedException
{
while (true)
{
MapyrusEventListener.Action action = m_actionQueue.take();
if (action == MapyrusEventListener.Action.NEW_TAB_ACTION)
{
/*
* Create new tab in editor panel.
*/
if (m_editorPanel != null)
m_editorPanel.createTab(null, null, null);
}
else if (action == MapyrusEventListener.Action.OPEN_FILE)
{
/*
* Show file chooser dialog for user to select a file
* from, show it in a new tab and the output in the
* display window.
*/
openFile();
}
else if (action == MapyrusEventListener.Action.COPY)
{
/*
* Copy display panel output to clipboard.
*/
ImageSelection imageSelection = new ImageSelection(m_displayImage);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(imageSelection, null);
}
else if (action == MapyrusEventListener.Action.EXPORT_PNG)
{
try
{
exportToPNG();
}
catch (SecurityException e)
{
JOptionPane.showMessageDialog(m_frame,
e.getClass().getName() + ": " + e.getMessage(),
Constants.PROGRAM_NAME, JOptionPane.ERROR_MESSAGE);
}
}
else if (action == MapyrusEventListener.Action.EXPORT_PDF)
{
try
{
exportToPDF();
}
catch (SecurityException e)
{
JOptionPane.showMessageDialog(m_frame,
e.getClass().getName() + ": " + e.getMessage(),
Constants.PROGRAM_NAME, JOptionPane.ERROR_MESSAGE);
}
}
else if (action == MapyrusEventListener.Action.RUN)
{
runCommands();
}
else if (action == MapyrusEventListener.Action.CLOSE_TAB)
{
/*
* Close currently open tab.
*/
if (m_editorPanel != null && m_editorPanel.getTabCount() > 0)
{
boolean status = true;
if (m_editorPanel.isSelectedTabEdited())
status = saveTab(true);
if (status)
m_editorPanel.closeSelectedTab();
}
}
else if (action == MapyrusEventListener.Action.SAVE_TAB)
{
/*
* Save currently open tab.
*/
if (m_editorPanel != null && m_editorPanel.getTabCount() > 0)
{
saveTab(false);
}
}
else if (action == MapyrusEventListener.Action.EXIT)
{
/*
* If any changes saved successfully then we can exit.
*/
if (saveAndExit())
m_mutex.unlock();
}
else if (action == MapyrusEventListener.Action.ONLINE_HELP)
{
/*
* Show HTML GUI help page.
*/
final JFrame helpFrame = new JFrame(MapyrusMessages.get(MapyrusMessages.ONLINE_HELP));
try
{
JEditorPane helpPane = new JEditorPane();
helpPane.setEditable(false);
URL helpUrl = this.getClass().getResource("onlinehelp.html");
helpPane.setPage(helpUrl);
JButton closeButton = new JButton(MapyrusMessages.get(MapyrusMessages.CLOSE));
closeButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
/*
* Close window when user clicks 'Close' button.
*/
helpFrame.setVisible(false);
helpFrame.dispose();
}
});
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
mainPanel.add(helpPane, BorderLayout.CENTER);
JPanel southPanel = new JPanel();
southPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
southPanel.add(closeButton);
mainPanel.add(southPanel, BorderLayout.SOUTH);
helpFrame.getContentPane().add(mainPanel);
helpFrame.setPreferredSize(new Dimension(600, 600));
helpFrame.pack();
helpFrame.setVisible(true);
}
catch (IOException e)
{
JOptionPane.showMessageDialog(m_frame, e.getMessage(),
Constants.PROGRAM_NAME, JOptionPane.ERROR_MESSAGE);
helpFrame.dispose();
}
}
else if (action == MapyrusEventListener.Action.ABOUT)
{
StringBuilder sb = new StringBuilder();
sb.append(Constants.PROGRAM_NAME).append(" ").append(Constants.getVersion());
sb.append(", ").append(Constants.getReleaseDate());
sb.append(" ").append(Constants.WEB_SITE);
sb.append(Constants.LINE_SEPARATOR);
sb.append(Constants.LINE_SEPARATOR);
String []license = Constants.getLicense();
for (int i = 0; i < license.length; i++)
sb.append(license[i]).append(Constants.LINE_SEPARATOR);
JOptionPane.showMessageDialog(m_frame, sb.toString(),
Constants.PROGRAM_NAME, JOptionPane.INFORMATION_MESSAGE);
}
}
}
/*
* File filter limiting file selection to PNG images.
*/
private class PNGImageFilter extends FileFilter
{
public boolean accept(File f)
{
boolean retval = f.isDirectory();
if (!retval)
{
String name = f.getName();
retval = name.endsWith(".png") || name.endsWith(".PNG");
}
return(retval);
}
public String getDescription()
{
return(MapyrusMessages.get(MapyrusMessages.PNG_IMAGE_FILES));
}
}
/*
* File filter limiting file selection to PDF images.
*/
private class PDFImageFilter extends FileFilter
{
public boolean accept(File f)
{
boolean retval = f.isDirectory();
if (!retval)
{
String name = f.getName();
retval = name.endsWith(".pdf") || name.endsWith(".PDF");
}
return(retval);
}
public String getDescription()
{
return(MapyrusMessages.get(MapyrusMessages.PDF_FILES));
}
}
/**
* Open file with Mapyrus commands in new tab.
*/
private void openFile()
{
if (m_editorPanel != null)
{
JFileChooser chooser = new JFileChooser();
chooser.setDialogType(JFileChooser.OPEN_DIALOG);
chooser.setCurrentDirectory(m_lastOpenedDirectory);
int status = chooser.showOpenDialog(m_frame);
if (status == JFileChooser.APPROVE_OPTION)
{
File selectedFile = chooser.getSelectedFile();
m_lastOpenedDirectory = selectedFile.getParentFile();
String filename = selectedFile.getPath();
m_editorPanel.createTab(filename, null, null);
}
}
}
/**
* Export image to a PNG file.
*/
private void exportToPNG()
{
JFileChooser fileChooser = new JFileChooser();
fileChooser.setMultiSelectionEnabled(false);
fileChooser.setFileFilter(new PNGImageFilter());
fileChooser.setSelectedFile(m_lastOpenedDirectory);
int retval = fileChooser.showSaveDialog(m_frame);
if (retval == JFileChooser.APPROVE_OPTION)
{
File selectedFile = fileChooser.getSelectedFile();
m_lastOpenedDirectory = selectedFile;
try
{
FileOutputStream outStream = new FileOutputStream(selectedFile);
ImageIO.write(m_displayImage, "png", outStream);
}
catch (IOException e)
{
JOptionPane.showMessageDialog(m_frame, e.getMessage(), Constants.PROGRAM_NAME, JOptionPane.ERROR_MESSAGE);
selectedFile.delete();
}
}
}
/**
* Re-run commands to generate a PDF file.
*/
private void exportToPDF()
{
JFileChooser fileChooser = new JFileChooser();
fileChooser.setMultiSelectionEnabled(false);
fileChooser.setFileFilter(new PDFImageFilter());
fileChooser.setSelectedFile(m_lastOpenedDirectory);
int retval = fileChooser.showSaveDialog(m_frame);
if (retval == JFileChooser.APPROVE_OPTION)
{
File selectedFile = fileChooser.getSelectedFile();
m_lastOpenedDirectory = selectedFile;
try
{
createPDF(selectedFile);
}
catch (InterruptedException e)
{
JOptionPane.showMessageDialog(m_frame, e.getMessage(), Constants.PROGRAM_NAME, JOptionPane.ERROR_MESSAGE);
selectedFile.delete();
}
}
}
/**
* Run commands in currently selected tab, showing output in display window.
*/
private void runCommands() throws InterruptedException
{
String contents = m_editorPanel.getSelectedTabContents();
if (contents.length() > 0)
{
try
{
String title = m_editorPanel.getSelectedTabTitle();
FileOrURL f = new FileOrURL(new StringReader(contents), title);
Dimension displayDim = m_displayPanel.getSize();
m_displayPanel.getGraphics().clearRect(0, 0, displayDim.width, displayDim.height);
m_displayImage = new BufferedImage(displayDim.width, displayDim.height,
BufferedImage.TYPE_4BYTE_ABGR);
m_displayImage.getGraphics().setColor(Color.WHITE);
m_displayImage.getGraphics().fillRect(0, 0, displayDim.width, displayDim.height);
Interpreter interpreter = new Interpreter();
ContextStack context = new ContextStack();
context.setOutputFormat(m_displayImage, "lineantialiasing=true");
m_displayPanelListener.setImage(m_displayImage);
m_displayPanelListener.setWorlds(context.getWorlds());
ByteArrayInputStream stdin = new ByteArrayInputStream(new byte[]{});
PipedOutputStream outStream = new PipedOutputStream();
final PipedInputStream inStream = new PipedInputStream(outStream);
m_outputTextArea.setText("");
/*
* Create thread to read Mapyrus output and append it
* to the output panel.
*/
m_outputThread = new Thread(){
public void run()
{
try
{
byte []buf = new byte[256];
int nBytes;
while ((nBytes = inStream.read(buf)) > 0)
{
String s = new String(buf, 0, nBytes);
int caretPosition = m_outputTextArea.getCaretPosition();
m_outputTextArea.append(s);
/*
* Ensure last lines of output are displayed.
*/
m_outputTextArea.setCaretPosition(caretPosition + s.length());
m_outputTextArea.repaint();
}
}
catch (IOException e)
{
/*
* Reading pipes so should be no IOExceptions.
*/
m_outputTextArea.append(e.getMessage());
}
}
};
m_outputThread.start();
try (PrintStream p = new PrintStream(outStream))
{
interpreter.interpret(context, f, stdin, p);
m_displayPanelListener.setWorlds(context.getWorlds());
}
if (m_outputThread != null)
{
m_outputThread.join();
m_outputThread = null;
inStream.close();
}
m_outputTextArea.repaint();
m_displayPanel.repaint();
}
catch (IOException e)
{
JOptionPane.showMessageDialog(m_frame, e.getMessage(), Constants.PROGRAM_NAME,
JOptionPane.ERROR_MESSAGE);
}
catch (MapyrusException e)
{
JOptionPane.showMessageDialog(m_frame, e.getMessage(), Constants.PROGRAM_NAME,
JOptionPane.ERROR_MESSAGE);
}
}
}
/**
* Run commands in currently selected tab, writing output to a PDF file.
*/
private void createPDF(File selectedFile) throws InterruptedException
{
String contents = m_editorPanel.getSelectedTabContents();
if (contents.length() > 0)
{
try
{
String path = selectedFile.getPath();
path = path.replace("\\", "\\\\");
path = path.replace("'", "\\'");
contents = "newpage 'pdf', '" + path + "', 'A4'\n" +
contents + "\n" +
"endpage";
String title = m_editorPanel.getSelectedTabTitle();
FileOrURL f = new FileOrURL(new StringReader(contents), title);
Interpreter interpreter = new Interpreter();
ContextStack context = new ContextStack();
ByteArrayInputStream stdin = new ByteArrayInputStream(new byte[]{});
PipedOutputStream outStream = new PipedOutputStream();
final PipedInputStream inStream = new PipedInputStream(outStream);
m_outputTextArea.setText("");
/*
* Create thread to read Mapyrus output and append it
* to the output panel.
*/
m_outputThread = new Thread(){
public void run()
{
try
{
byte []buf = new byte[256];
int nBytes;
while ((nBytes = inStream.read(buf)) > 0)
{
String s = new String(buf, 0, nBytes);
int caretPosition = m_outputTextArea.getCaretPosition();
m_outputTextArea.append(s);
/*
* Ensure last lines of output are displayed.
*/
m_outputTextArea.setCaretPosition(caretPosition + s.length());
m_outputTextArea.repaint();
}
}
catch (IOException e)
{
/*
* Reading pipes so should be no IOExceptions.
*/
m_outputTextArea.append(e.getMessage());
}
}
};
m_outputThread.start();
try (PrintStream p = new PrintStream(outStream))
{
interpreter.interpret(context, f, stdin, p);
}
if (m_outputThread != null)
{
m_outputThread.join();
m_outputThread = null;
inStream.close();
}
m_outputTextArea.repaint();
String message = MapyrusMessages.get(MapyrusMessages.EXPORTED_TO) + ": " + selectedFile.getPath();
JOptionPane.showMessageDialog(m_frame, message, Constants.PROGRAM_NAME,
JOptionPane.INFORMATION_MESSAGE);
}
catch (IOException e)
{
JOptionPane.showMessageDialog(m_frame, e.getMessage(), Constants.PROGRAM_NAME,
JOptionPane.ERROR_MESSAGE);
}
catch (MapyrusException e)
{
JOptionPane.showMessageDialog(m_frame, e.getMessage(), Constants.PROGRAM_NAME,
JOptionPane.ERROR_MESSAGE);
}
}
}
/**
* Block until window is closed.
*/
private void waitForClose()
{
m_mutex.lock();
}
/**
* Save selected tab to a file.
* @param promptSave first show dialog asking user if they want to save.
* @return false if user changes their mind and decides not to save tab.
*/
private boolean saveTab(boolean promptSave)
{
int status = JOptionPane.OK_OPTION;
String filename = m_editorPanel.getSelectedTabFilename();
if (promptSave)
{
String message = MapyrusMessages.get(MapyrusMessages.SAVE_CHANGES_IN_TAB) +
" " + m_editorPanel.getSelectedTabTitle();
if (!filename.startsWith(MapyrusMessages.get(MapyrusMessages.UNTITLED)))
{
message = message + "\n" +
MapyrusMessages.get(MapyrusMessages.TO_FILE) + " " +
filename;
}
status = JOptionPane.showConfirmDialog(m_frame,
message + "?", Constants.PROGRAM_NAME, JOptionPane.YES_NO_CANCEL_OPTION);
}
if (status == JOptionPane.CANCEL_OPTION)
{
return(false);
}
else if (status == JOptionPane.OK_OPTION)
{
/*
* Find filename for this tab.
*/
if (filename.startsWith(MapyrusMessages.get(MapyrusMessages.UNTITLED)))
{
/*
* Give user a chance to specify a different filename.
*/
do
{
try
{
JFileChooser chooser = new JFileChooser();
chooser.setDialogType(JFileChooser.SAVE_DIALOG);
chooser.setSelectedFile(new File(m_lastOpenedDirectory, filename));
status = chooser.showSaveDialog(m_frame);
if (status != JFileChooser.APPROVE_OPTION)
return(false);
File selectedFile = chooser.getSelectedFile();
status = JOptionPane.YES_OPTION;
m_lastOpenedDirectory = selectedFile.getParentFile();
filename = selectedFile.getPath();
if (selectedFile.exists())
{
/*
* Check that the user wants to overwrite this file.
*/
status = JOptionPane.showConfirmDialog(m_frame,
MapyrusMessages.get(MapyrusMessages.OVERWRITE) + " " + filename +"?",
Constants.PROGRAM_NAME,
JOptionPane.YES_NO_OPTION);
}
}
catch (SecurityException e)
{
JOptionPane.showMessageDialog(m_frame, e.getMessage(),
Constants.PROGRAM_NAME, JOptionPane.ERROR_MESSAGE);
return(false);
}
}
while (status != JOptionPane.YES_OPTION);
}
try (FileWriter f = new FileWriter(filename))
{
/*
* Write the tab contents to file.
*/
String contents = m_editorPanel.getSelectedTabContents();
f.write(contents);
f.flush();
m_editorPanel.setSelectedTabEdited(false);
}
catch (IOException e)
{
JOptionPane.showMessageDialog(m_frame, e.getMessage(),
Constants.PROGRAM_NAME, JOptionPane.ERROR_MESSAGE);
return(false);
}
catch (SecurityException e)
{
JOptionPane.showMessageDialog(m_frame, e.getMessage(),
Constants.PROGRAM_NAME, JOptionPane.ERROR_MESSAGE);
return(false);
}
}
return(true);
}
/**
* Ask user if they want to save any edited tabs before exiting.
* @return true if all tabs saved and/or closed.
*/
private boolean saveAndExit()
{
boolean retval = true;
while (retval && m_editorPanel != null && m_editorPanel.getTabCount() > 0)
{
if (m_editorPanel.isSelectedTabEdited())
retval = saveTab(true);
if (retval)
m_editorPanel.closeSelectedTab();
}
return(retval);
}
} |
package ev3dev.sensors.ev3;
import ev3dev.sensors.BaseSensor;
import ev3dev.sensors.EV3DevSensorMode;
import ev3dev.utils.Sysfs;
import lejos.hardware.port.Port;
import lejos.hardware.sensor.SensorMode;
import java.io.File;
public class EV3IRSensor extends BaseSensor {
private static final String LEGO_EV3_IR = "lego-ev3-ir";
public static float MIN_RANGE = 5f;
public static float MAX_RANGE = 100f;
public EV3IRSensor(final Port portName) {
super(portName, LEGO_UART_SENSOR, LEGO_EV3_IR);
init();
}
private void init() {
setModes(new SensorMode[] {
new DistanceMode(this.PATH_DEVICE),
new SeekMode(this.PATH_DEVICE),
new RemoteMode(this.PATH_DEVICE)
});
}
public SensorMode getDistanceMode() {
return getMode(0);
}
private class DistanceMode extends EV3DevSensorMode {
private static final String MODE = "IR-PROX";
final private File pathDevice;
public DistanceMode(File pathDevice) {
this.pathDevice = pathDevice;
}
@Override
public int sampleSize() {
return 1;
}
@Override
public void fetchSample(float[] sample, int offset) {
switchMode(MODE, SWITCH_DELAY);
float rawValue = Sysfs.readFloat(this.pathDevice + "/" + VALUE0);
if (rawValue < MIN_RANGE) {
sample[offset] = 0;
} else if (rawValue > MAX_RANGE) {
sample[offset] = Float.POSITIVE_INFINITY;
} else {
sample[offset] = rawValue;
}
}
@Override
public String getName() {
return "Distance";
}
}
public SensorMode getSeekMode() {
return getMode(1);
}
private class SeekMode extends EV3DevSensorMode {
private static final String MODE = "IR-SEEK";
final private File pathDevice;
public SeekMode(File pathDevice) {
this.pathDevice = pathDevice;
}
@Override
public int sampleSize() {
return 8;
}
@Override
public void fetchSample(float[] sample, int offset) {
switchMode(MODE, SWITCH_DELAY);
sample[0] = Sysfs.readFloat(this.pathDevice + "/" + VALUE0);
sample[1] = Sysfs.readFloat(this.pathDevice + "/" + VALUE1);
sample[2] = Sysfs.readFloat(this.pathDevice + "/" + VALUE2);
sample[3] = Sysfs.readFloat(this.pathDevice + "/" + VALUE3);
sample[4] = Sysfs.readFloat(this.pathDevice + "/" + VALUE4);
sample[5] = Sysfs.readFloat(this.pathDevice + "/" + VALUE5);
sample[6] = Sysfs.readFloat(this.pathDevice + "/" + VALUE6);
sample[7] = Sysfs.readFloat(this.pathDevice + "/" + VALUE7);
}
@Override
public String getName() {
return "Seek";
}
}
public SensorMode getRemoteMode() {
return getMode(2);
}
private class RemoteMode extends EV3DevSensorMode {
private static final String MODE = "IR-REMOTE";
final private File pathDevice;
public RemoteMode(File pathDevice) {
this.pathDevice = pathDevice;
}
@Override
public int sampleSize() {
return 4;
}
@Override
public void fetchSample(float[] sample, int offset) {
switchMode(MODE, SWITCH_DELAY);
sample[0] = Sysfs.readFloat(this.pathDevice + "/" + VALUE0);
sample[1] = Sysfs.readFloat(this.pathDevice + "/" + VALUE1);
sample[2] = Sysfs.readFloat(this.pathDevice + "/" + VALUE2);
sample[3] = Sysfs.readFloat(this.pathDevice + "/" + VALUE3);
}
@Override
public String getName() {
return "Remote";
}
}
} |
package fi.csc.microarray.util;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.io.Reader;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
/**
*
* @author Aleksi Kallio
*
*/
public class IOUtils {
private static final int BUFFER_SIZE = 16*1024;
private static final long CALLBACK_INTERVAL = 500;
/**
* Closes Reader if it is not null. Ignores all exceptions. Useful for those finally-blocks.
*/
public static void closeIfPossible(Reader reader) {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
// ignore
}
}
}
/**
* Closes Writer if it is not null. Ignores all exceptions. Useful for those finally-blocks.
*/
public static void closeIfPossible(Writer writer) {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
// ignore
}
}
}
/**
* Closes InputStream if it is not null. Ignores all exceptions. Useful for those finally-blocks.
*/
public static void closeIfPossible(InputStream stream) {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
// ignore
}
}
}
/**
* Closes OutputStream if it is not null. Ignores all exceptions. Useful for those finally-blocks.
*/
public static void closeIfPossible(OutputStream stream) {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
// ignore
}
}
}
public static void disconnectIfPossible(HttpURLConnection connection) {
if (connection != null) {
connection.disconnect();
}
}
public static void disconnectIfPossible(URLConnection connection) {
if (connection instanceof HttpURLConnection) {
disconnectIfPossible((HttpURLConnection)connection);
}
}
public static interface CopyProgressListener {
public void progress(long bytes);
}
/**
*
* Copies stream contents of source to target and reports progress.
*
* @param source input stream
* @param target output stream
* @param progressListener can be null
*
* @throws IOException all exceptions from underlying IO are passed through
*/
public static void copy(InputStream source, OutputStream target, CopyProgressListener progressListener) throws IOException {
BufferedInputStream bSource = new BufferedInputStream(source);
BufferedOutputStream bTarget = new BufferedOutputStream(target);
// initialise
byte buffer[] = new byte[BUFFER_SIZE];
int len = BUFFER_SIZE;
long sum = 0;
long lastCallback = Long.MAX_VALUE;
// tell that we are in the beginning
if (progressListener != null) {
progressListener.progress(0);
lastCallback = System.currentTimeMillis();
}
// copy while there is content
while (true) {
len = bSource.read(buffer, 0, BUFFER_SIZE);
if (len < 0) {
break;
}
bTarget.write(buffer, 0, len);
sum += len;
// report progress every CALLBACK_INTERVAL milliseconds
if (progressListener != null && (lastCallback+CALLBACK_INTERVAL) < System.currentTimeMillis()) {
progressListener.progress(sum);
lastCallback = System.currentTimeMillis();
}
}
bTarget.flush();
}
public static void copy(InputStream source, OutputStream target) throws IOException {
copy(source, target, null);
}
public static void copy(InputStream source, File target) throws IOException {
FileOutputStream out = new FileOutputStream(target);
try {
copy(source, out, null);
} finally {
closeIfPossible(out);
}
}
/**
* Copies a file.
*
* @param from source file
* @param to destination file
*
* @throws IOException if copying if file contents fails
*/
public static void copy(File from, File to) throws IOException {
FileInputStream in = new FileInputStream(from);
FileOutputStream out = new FileOutputStream(to);
try {
copy(in, out, null);
} finally {
closeIfPossible(in);
closeIfPossible(out);
}
}
public static void closeIfPossible(RandomAccessFile raf) {
if (raf != null) {
try {
raf.close();
} catch (IOException e) {
// ignore
}
}
}
public static URL createURL(URL url, String postfix) throws MalformedURLException {
return new URL(url, url.getFile() + "/" + postfix);
}
public static boolean isLocalFileURL(URL url) {
return "file".equals(url.getProtocol());
}
public static String getFilenameWithoutPath(URL url) {
return url.getPath().substring(url.getPath().lastIndexOf('/') + 1);
}
/**
* Compare the contents of two Streams to determine if they are equal or not.
*
* This method buffers the input internally using <code>BufferedInputStream</code> if they are
* not already buffered.
*
* @param input1
* the first stream
* @param input2
* the second stream
* @return true if the content of the streams are equal or they both don't exist, false
* otherwise
* @throws NullPointerException
* if either input is null
* @throws IOException
* if an I/O error occurs
*/
public static boolean contentEquals(InputStream input1, InputStream input2) throws IOException {
if (!(input1 instanceof BufferedInputStream)) {
input1 = new BufferedInputStream(input1);
}
if (!(input2 instanceof BufferedInputStream)) {
input2 = new BufferedInputStream(input2);
}
int ch = input1.read();
while (-1 != ch) {
int ch2 = input2.read();
if (ch != ch2) {
return false;
}
ch = input1.read();
}
int ch2 = input2.read();
return (ch2 == -1);
}
} |
package org.nudge.elasticstack;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Utility class for the connector.
*/
public class Utils {
private static final String ES_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
private static final String INDEX_SUFFIX_FMT = "yyyy-MM-dd";
private static final ThreadLocal<DateFormat> indexf = new ThreadLocal<>();
private static final ThreadLocal<DateFormat> timef = new ThreadLocal<>();
private Utils() {
}
public static String formatTimeToString(long timestamp) {
DateFormat sdf = timef.get();
if (sdf == null) {
sdf = new SimpleDateFormat(ES_DATE_FORMAT);
timef.set(sdf);
}
return sdf.format(timestamp);
}
public static String getIndexSuffix() {
DateFormat sdf = indexf.get();
if (sdf == null) {
sdf = new SimpleDateFormat(INDEX_SUFFIX_FMT);
indexf.set(sdf);
}
return sdf.format(new Date());
}
} |
package fr.aumgn.diamondrush.game;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import fr.aumgn.bukkitutils.util.Vector;
import fr.aumgn.diamondrush.DiamondRush;
import fr.aumgn.diamondrush.Util;
import fr.aumgn.diamondrush.exception.NoSuchTeam;
import fr.aumgn.diamondrush.exception.NotEnoughTeams;
import fr.aumgn.diamondrush.exception.PlayerNotInGame;
import fr.aumgn.diamondrush.region.GameSpawn;
import fr.aumgn.diamondrush.stage.PauseStage;
import fr.aumgn.diamondrush.stage.Stage;
public class Game {
private Stage stage;
private World world;
private GameSpawn spawn;
private Map<String, Team> teams;
private Map<Player, Team> players;
private Spectators spectators;
private int turnCount;
public Game(Map<String, TeamColor> teamsMap, World world, Vector spawnPoint) {
this.stage = null;
this.teams = new LinkedHashMap<String, Team>();
int lives = DiamondRush.getConfig().getLives();
lives = Math.max(4, lives);
lives = Math.min(8, lives);
for (Map.Entry<String, TeamColor> teamEntry : teamsMap.entrySet()) {
Team team = new Team(teamEntry.getKey(),
teamEntry.getValue(), lives);
teams.put(teamEntry.getKey(), team);
}
if (teams.keySet().size() < 2) {
throw new NotEnoughTeams();
}
this.world = world;
spawn = new GameSpawn(spawnPoint);
players = new HashMap<Player, Team>();
spectators = new Spectators(this);
turnCount = -1;
}
public Stage getStage() {
return stage;
}
private void unregisterStageListeners() {
for (Listener listener : stage.getListeners()) {
HandlerList.unregisterAll(listener);
}
}
private void registerStageListeners() {
for (Listener listener : stage.getListeners()) {
Bukkit.getPluginManager().registerEvents(listener, DiamondRush.getPlugin());
}
}
public void nextStage(Stage newStage) {
if (newStage == null) {
throw new IllegalArgumentException("New stage cannot be null");
}
if (stage != null) {
unregisterStageListeners();
Bukkit.getScheduler().cancelTasks(DiamondRush.getPlugin());
stage.stop();
}
stage = newStage;
registerStageListeners();
stage.start();
}
public boolean isPaused() {
return (stage instanceof PauseStage);
}
public void pause() {
if (stage == null) {
throw new UnsupportedOperationException();
}
unregisterStageListeners();
stage.pause();
stage = new PauseStage(this, stage);
stage.start();
registerStageListeners();
}
public void resume() {
unregisterStageListeners();
stage.stop();
stage = ((PauseStage) stage).getOldStage();
registerStageListeners();
stage.resume();
}
public World getWorld() {
return world;
}
public GameSpawn getSpawn() {
return spawn;
}
public Team getTeam(String name) {
if (!teams.containsKey(name)) {
throw new NoSuchTeam(name);
}
return teams.get(name);
}
public Team getTeam(Player player) {
if (!players.containsKey(player)) {
throw new PlayerNotInGame();
}
return players.get(player);
}
public Spectators getSpectators() {
return spectators;
}
public int getTurnCount() {
return turnCount;
}
public void incrementTurnCount() {
++turnCount;
}
public void sendMessage(String message) {
for (Team team : getTeams()) {
team.sendMessage(message);
}
for (Player spectator : spectators) {
spectator.sendMessage(message);
}
}
public boolean contains(Player player) {
return players.containsKey(player);
}
public List<Team> getTeams() {
return new ArrayList<Team>(teams.values());
}
private Team getTeamWithMinimumPlayers() {
int minimum = Integer.MAX_VALUE;
List<Team> roulette = null;
for (Team team : getTeams()) {
int size = team.size();
if (size < minimum) {
minimum = size;
roulette = new ArrayList<Team>();
roulette.add(team);
} else if (size == minimum) {
roulette.add(team);
}
}
return Util.pickRandom(roulette);
}
public void addPlayer(Player player, Team team) {
if (team == null) {
team = getTeamWithMinimumPlayers();
}
team.addPlayer(player, world);
players.put(player, team);
}
public void removePlayer(Player player) {
Team team = getTeam(player);
team.removePlayer(player);
players.remove(player);
}
public void decreaseLives(Team team) {
team.decreaseLives();
if (team.getLives() == 0) {
teams.remove(team.getName());
if (teams.size() > 1) {
String msg = ChatColor.RED +"L'équipe " + team.getDisplayName()
+ ChatColor.RED + " a perdu la partie.";
sendMessage(msg);
team.sendMessage(msg);
for (Player player : team.getPlayers()) {
players.remove(player);
spectators.add(player);
player.sendMessage(ChatColor.GREEN +
"Vous êtes maintenant spectateur.");
}
} else {
Team winningTeam = teams.values().iterator().next();
String msg = ChatColor.GREEN +
"L'équipe " + winningTeam.getDisplayName() +
ChatColor.GREEN + " a gagné la partie.";
sendMessage(msg);
team.sendMessage(msg);
DiamondRush.forceStop();
}
} else {
sendMessage(ChatColor.YELLOW + "L'équipe " + team.getDisplayName() +
ChatColor.YELLOW + " a perdu une vie. " + team.getLives() + " restantes.");
}
}
} |
package org.pfaa.chemica.model;
import org.pfaa.chemica.processing.MaterialStoich;
public enum State {
SOLID, LIQUID, GAS, AQUEOUS;
public boolean isFluid() {
return this == LIQUID || this == GAS || this == AQUEOUS;
}
public float getVolumeFactor() {
if (this == State.GAS) {
return 100;
} else if (this == State.AQUEOUS) {
return (1 - Constants.STANDARD_SOLUTE_WEIGHT) / Constants.STANDARD_SOLUTE_WEIGHT;
}
return 1;
}
public State ofMatter() {
return this == State.AQUEOUS ? State.LIQUID : this;
}
public <T extends IndustrialMaterial> MaterialState<T> of(T material) {
return MaterialState.of(this, material);
}
public <T extends IndustrialMaterial> MaterialStoich<T> of(float stoich, T material) {
return MaterialStoich.of(stoich, this, material);
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.