answer stringlengths 17 10.2M |
|---|
package com.faforever.client.main;
import com.faforever.client.chat.ChatController;
import com.faforever.client.chat.ChatService;
import com.faforever.client.fx.SceneFactory;
import com.faforever.client.fx.WindowDecorator;
import com.faforever.client.game.GamesController;
import com.faforever.client.i18n.I18n;
import com.faforever.client.leaderboard.LadderController;
import com.faforever.client.legacy.OnLobbyConnectedListener;
import com.faforever.client.legacy.OnLobbyConnectingListener;
import com.faforever.client.legacy.OnLobbyDisconnectedListener;
import com.faforever.client.lobby.LobbyService;
import com.faforever.client.network.PortCheckService;
import com.faforever.client.news.NewsController;
import com.faforever.client.patch.PatchService;
import com.faforever.client.preferences.PreferencesService;
import com.faforever.client.preferences.WindowPrefs;
import com.faforever.client.task.PrioritizedTask;
import com.faforever.client.task.TaskGroup;
import com.faforever.client.task.TaskService;
import com.faforever.client.user.UserService;
import com.faforever.client.util.Callback;
import com.faforever.client.util.JavaFxUtil;
import com.faforever.client.vault.VaultController;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonBase;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Label;
import javafx.scene.control.Labeled;
import javafx.scene.control.MenuButton;
import javafx.scene.control.ProgressBar;
import javafx.scene.control.ToggleButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Pane;
import javafx.scene.layout.Region;
import javafx.stage.Stage;
import org.springframework.beans.factory.annotation.Autowired;
import javax.annotation.PostConstruct;
import java.util.List;
import static com.faforever.client.fx.WindowDecorator.WindowButtonType.CLOSE;
import static com.faforever.client.fx.WindowDecorator.WindowButtonType.MAXIMIZE_RESTORE;
import static com.faforever.client.fx.WindowDecorator.WindowButtonType.MINIMIZE;
public class MainController implements OnLobbyConnectedListener, OnLobbyConnectingListener, OnLobbyDisconnectedListener {
@FXML
Pane contentPane;
@FXML
ToggleGroup mainNavigationToggleGroup;
@FXML
ButtonBase newsButton;
@FXML
ButtonBase chatButton;
@FXML
ButtonBase gamesButton;
@FXML
ButtonBase vaultButton;
@FXML
ButtonBase ladderButton;
@FXML
ProgressBar taskProgressBar;
@FXML
Region mainRoot;
@FXML
MenuButton usernameButton;
@FXML
Pane taskPane;
@FXML
Labeled portCheckStatusButton;
@FXML
MenuButton fafConnectionButton;
@FXML
MenuButton ircConnectionButton;
@FXML
Label taskProgressLabel;
@Autowired
NewsController newsController;
@Autowired
ChatController chatController;
@Autowired
GamesController gamesController;
@Autowired
VaultController vaultController;
@Autowired
LadderController ladderController;
@Autowired
PreferencesService preferencesService;
@Autowired
SceneFactory sceneFactory;
@Autowired
LobbyService lobbyService;
@Autowired
PortCheckService portCheckService;
@Autowired
PatchService patchService;
@Autowired
ChatService chatService;
@Autowired
I18n i18n;
@Autowired
UserService userService;
@Autowired
TaskService taskService;
private Stage stage;
@FXML
void initialize() {
taskPane.managedProperty().bind(taskPane.visibleProperty());
taskProgressBar.managedProperty().bind(taskProgressBar.visibleProperty());
taskProgressLabel.managedProperty().bind(taskProgressLabel.visibleProperty());
setCurrentTaskInStatusBar(null);
}
@PostConstruct
void postConstruct() {
taskService.addChangeListener(TaskGroup.NET_HEAVY, change -> {
while (change.next()) {
if (change.wasAdded()) {
addTasks(change.getAddedSubList());
}
if (change.wasRemoved()) {
removeTasks(change.getRemoved());
}
}
});
portCheckStatusButton.getTooltip().setText(
i18n.get("statusBar.portCheckTooltip", preferencesService.getPreferences().getForgedAlliance().getPort())
);
}
private void removeTasks(List<? extends PrioritizedTask<?>> removed) {
setCurrentTaskInStatusBar(null);
}
/**
* @param tasks a list of prioritized tasks, sorted by priority (lowest first)
*/
private void addTasks(List<? extends PrioritizedTask<?>> tasks) {
// List<Node> taskPanes = new ArrayList<>();
// for (PrioritizedTask<?> taskPane : tasks) {
// taskPanes.add(new Pane());
// taskPane.getChildren().setAll(taskPanes);
setCurrentTaskInStatusBar(tasks.get(tasks.size() - 1));
}
/**
* @param task the task to set, {@code null} to unset
*/
private void setCurrentTaskInStatusBar(PrioritizedTask<?> task) {
if (task == null) {
taskProgressBar.setVisible(false);
taskProgressLabel.setVisible(false);
return;
}
taskProgressBar.setVisible(true);
taskProgressBar.progressProperty().bind(task.progressProperty());
taskProgressLabel.setVisible(true);
taskProgressLabel.setText(task.getTitle());
}
public void display(Stage stage) {
this.stage = stage;
lobbyService.setOnFafConnectedListener(this);
lobbyService.setOnLobbyConnectingListener(this);
lobbyService.setOnLobbyDisconnectedListener(this);
chatService.connect();
final WindowPrefs mainWindowPrefs = preferencesService.getPreferences().getMainWindow();
sceneFactory.createScene(stage, mainRoot, true, MINIMIZE, MAXIMIZE_RESTORE, CLOSE);
stage.setTitle("FA Forever");
restoreState(mainWindowPrefs, stage);
stage.show();
JavaFxUtil.centerOnScreen(stage);
registerWindowPreferenceListeners(stage, mainWindowPrefs);
usernameButton.setText(userService.getUsername());
checkGamePort();
checkForFafUpdate();
}
private void checkForFafUpdate() {
patchService.needsPatching(new Callback<Boolean>() {
@Override
public void success(Boolean needsPatching) {
if (!needsPatching) {
return;
}
ButtonType updateNowButtonType = new ButtonType(i18n.get("patch.updateAvailable.updateNow"));
ButtonType updateLaterButtonType = new ButtonType(i18n.get("patch.updateAvailable.updateLater"));
Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
alert.setTitle(i18n.get("patch.updateAvailable.title"));
alert.setHeaderText(i18n.get("patch.updateAvailable.header"));
alert.setContentText(i18n.get("patch.updateAvailable.content"));
alert.getButtonTypes().setAll(updateNowButtonType, updateLaterButtonType);
alert.resultProperty().addListener((observable, oldValue, newValue) -> {
if (newValue == updateNowButtonType) {
patchService.patchInBackground(new Callback<Void>() {
@Override
public void success(Void result) {
// FIXME implement
}
@Override
public void error(Throwable e) {
// FIXME implement
}
});
}
});
alert.show();
}
@Override
public void error(Throwable e) {
}
});
}
private void checkGamePort() {
portCheckStatusButton.setText(i18n.get("statusBar.checkingPort"));
portCheckService.checkUdpPortInBackground(preferencesService.getPreferences().getForgedAlliance().getPort(), new Callback<Boolean>() {
@Override
public void success(Boolean result) {
if (result) {
portCheckStatusButton.setText(i18n.get("statusBar.portReachable"));
} else {
portCheckStatusButton.setText(i18n.get("statusBar.portUnreachable"));
}
}
@Override
public void error(Throwable e) {
portCheckStatusButton.setText("NAT: Error");
}
});
}
private void restoreState(WindowPrefs mainWindowPrefs, Stage stage) {
if (mainWindowPrefs.isMaximized()) {
WindowDecorator.maximize(stage);
} else {
stage.setWidth(mainWindowPrefs.getWidth());
stage.setHeight(mainWindowPrefs.getHeight());
}
String lastView = mainWindowPrefs.getLastView();
if (lastView != null) {
mainNavigationToggleGroup.getToggles().stream()
.filter(button -> button instanceof ToggleButton)
.filter(navigationItem -> lastView.equals(((Node) navigationItem).getId()))
.forEach(navigationItem -> {
((ToggleButton) navigationItem).fire();
});
} else {
newsButton.fire();
}
}
@FXML
void onNavigationButton(ActionEvent event) {
ToggleButton button = (ToggleButton) event.getSource();
preferencesService.getPreferences().getMainWindow().setLastView(button.getId());
preferencesService.storeInBackground();
if (!button.isSelected()) {
button.setSelected(true);
}
// TODO let the component initialize themselves instead of calling a setUp method
if (button == newsButton) {
newsController.setUpIfNecessary();
setContent(newsController.getRoot());
} else if (button == chatButton) {
setContent(chatController.getRoot());
} else if (button == gamesButton) {
gamesController.setUpIfNecessary(stage);
setContent(gamesController.getRoot());
} else if (button == vaultButton) {
vaultController.setUpIfNecessary();
setContent(vaultController.getRoot());
} else if (button == ladderButton) {
ladderController.setUpIfNecessary();
setContent(ladderController.getRoot());
}
}
private void registerWindowPreferenceListeners(final Stage stage, final WindowPrefs mainWindowPrefs) {
stage.maximizedProperty().addListener((observable, oldValue, newValue) -> {
mainWindowPrefs.setMaximized(newValue);
});
stage.heightProperty().addListener((observable, oldValue, newValue) -> {
mainWindowPrefs.setHeight(newValue.intValue());
preferencesService.storeInBackground();
});
stage.widthProperty().addListener((observable, oldValue, newValue) -> {
mainWindowPrefs.setWidth(newValue.intValue());
preferencesService.storeInBackground();
});
}
@Override
public void onFaConnected() {
fafConnectionButton.setText(i18n.get("statusBar.fafConnected"));
}
@Override
public void onFaConnecting() {
fafConnectionButton.setText(i18n.get("statusBar.fafConnecting"));
}
@Override
public void onFafDisconnected() {
fafConnectionButton.setText(i18n.get("statusBar.fafDisconnected"));
}
private void setContent(Node node) {
ObservableList<Node> children = contentPane.getChildren();
if (!children.contains(node)) {
children.add(node);
AnchorPane.setTopAnchor(node, 0d);
AnchorPane.setRightAnchor(node, 0d);
AnchorPane.setBottomAnchor(node, 0d);
AnchorPane.setLeftAnchor(node, 0d);
}
for (Node child : children) {
child.setVisible(child == node);
}
}
public void onPortCheckHelpClicked(ActionEvent event) {
// FIXME implement
}
public void onChangePortClicked(ActionEvent event) {
// FIXME implement
}
public void onEnableUpnpClicked(ActionEvent event) {
// FIXME implement
}
public void onPortCheckRetryClicked(ActionEvent event) {
checkGamePort();
}
public void onFafReconnectClicked(ActionEvent event) {
// FIXME implement
}
public void onIrcReconnectClicked(ActionEvent event) {
// FIXME implement
}
} |
package com.faforever.client.remote;
import com.faforever.client.fx.JavaFxUtil;
import com.faforever.client.preferences.PreferencesService;
import javafx.scene.image.Image;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.validator.routines.UrlValidator;
import org.jetbrains.annotations.Nullable;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.web.util.UriUtils;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.util.function.Supplier;
import static com.github.nocatch.NoCatch.noCatch;
@Lazy
@Service
@Slf4j
public class AssetService {
private final PreferencesService preferencesService;
private final UrlValidator urlValidator;
public AssetService(PreferencesService preferencesService) {
this.preferencesService = preferencesService;
urlValidator = new UrlValidator();
}
@Nullable
public Image loadAndCacheImage(URL url, Path cacheSubFolder, @Nullable Supplier<Image> defaultSupplier) {
return loadAndCacheImage(url, cacheSubFolder, defaultSupplier, 0, 0);
}
@Nullable
public Image loadAndCacheImage(URL url, Path cacheSubFolder, @Nullable Supplier<Image> defaultSupplier, int width, int height) {
if (url == null) {
if (defaultSupplier == null) {
return null;
}
return defaultSupplier.get();
}
try {
String urlString = url.toString();
urlString = urlValidator.isValid(urlString) ? urlString : UriUtils.encodePath(urlString, StandardCharsets.UTF_8);
String filename = urlString.substring(urlString.lastIndexOf('/') + 1);
Path cachePath = preferencesService.getCacheDirectory().resolve(cacheSubFolder).resolve(filename);
if (Files.exists(cachePath)) {
log.debug("Using cached image: {}", cachePath);
return new Image(noCatch(() -> cachePath.toUri().toURL().toExternalForm()), width, height, true, true);
}
log.debug("Fetching image {}", url);
Image image = new Image(urlString, width, height, true, true, true);
JavaFxUtil.persistImage(image, cachePath, filename.substring(filename.lastIndexOf('.') + 1));
return image;
} catch (InvalidPathException e) {
log.warn("Unable to load image due to invalid fileName {}", url, e);
if (defaultSupplier == null) {
return null;
}
return defaultSupplier.get();
}
}
} |
package com.forgeessentials.core;
import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraftforge.common.ForgeChunkManager;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.event.CommandEvent;
import net.minecraftforge.permission.PermissionLevel;
import net.minecraftforge.permission.PermissionManager;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.core.Logger;
import com.forgeessentials.api.APIRegistry;
import com.forgeessentials.api.UserIdent;
import com.forgeessentials.commons.BuildInfo;
import com.forgeessentials.commons.network.NetworkUtils;
import com.forgeessentials.commons.network.NetworkUtils.NullMessageHandler;
import com.forgeessentials.commons.network.Packet0Handshake;
import com.forgeessentials.commons.network.Packet1SelectionUpdate;
import com.forgeessentials.commons.network.Packet2Reach;
import com.forgeessentials.commons.network.Packet3PlayerPermissions;
import com.forgeessentials.commons.network.Packet5Noclip;
import com.forgeessentials.commons.network.Packet7Remote;
import com.forgeessentials.compat.CompatReiMinimap;
import com.forgeessentials.compat.HelpFixer;
import com.forgeessentials.core.commands.CommandFEInfo;
import com.forgeessentials.core.commands.CommandFEWorldInfo;
import com.forgeessentials.core.commands.CommandFeSettings;
import com.forgeessentials.core.commands.CommandUuid;
import com.forgeessentials.core.environment.Environment;
import com.forgeessentials.core.mcstats.ConstantPlotter;
import com.forgeessentials.core.mcstats.Metrics;
import com.forgeessentials.core.mcstats.Metrics.Graph;
import com.forgeessentials.core.misc.BlockModListFile;
import com.forgeessentials.core.misc.FECommandManager;
import com.forgeessentials.core.misc.TaskRegistry;
import com.forgeessentials.core.misc.TeleportHelper;
import com.forgeessentials.core.misc.Translator;
import com.forgeessentials.core.moduleLauncher.ModuleLauncher;
import com.forgeessentials.core.moduleLauncher.config.ConfigLoaderBase;
import com.forgeessentials.core.moduleLauncher.config.ConfigManager;
import com.forgeessentials.core.preloader.FELaunchHandler;
import com.forgeessentials.data.v2.DataManager;
import com.forgeessentials.util.FEChunkLoader;
import com.forgeessentials.util.PlayerInfo;
import com.forgeessentials.util.ServerUtil;
import com.forgeessentials.util.events.FEModuleEvent;
import com.forgeessentials.util.events.FEModuleEvent.FEModuleServerPreInitEvent;
import com.forgeessentials.util.events.FEModuleEvent.FEModuleServerStoppedEvent;
import com.forgeessentials.util.events.ForgeEssentialsEventFactory;
import com.forgeessentials.util.output.ChatOutputHandler;
import com.forgeessentials.util.output.LoggingHandler;
import com.forgeessentials.util.questioner.Questioner;
import com.forgeessentials.util.selections.CommandDeselect;
import com.forgeessentials.util.selections.CommandExpand;
import com.forgeessentials.util.selections.CommandExpandY;
import com.forgeessentials.util.selections.CommandPos;
import com.forgeessentials.util.selections.CommandWand;
import com.forgeessentials.util.selections.SelectionEventHandler;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.EventHandler;
import cpw.mods.fml.common.Mod.Instance;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.event.FMLServerAboutToStartEvent;
import cpw.mods.fml.common.event.FMLServerStartedEvent;
import cpw.mods.fml.common.event.FMLServerStartingEvent;
import cpw.mods.fml.common.event.FMLServerStoppedEvent;
import cpw.mods.fml.common.event.FMLServerStoppingEvent;
import cpw.mods.fml.common.eventhandler.EventPriority;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.PlayerEvent.PlayerLoggedInEvent;
import cpw.mods.fml.common.gameevent.PlayerEvent.PlayerLoggedOutEvent;
import cpw.mods.fml.common.gameevent.PlayerEvent.PlayerRespawnEvent;
import cpw.mods.fml.common.gameevent.TickEvent.ServerTickEvent;
import cpw.mods.fml.common.network.simpleimpl.IMessage;
import cpw.mods.fml.common.network.simpleimpl.IMessageHandler;
import cpw.mods.fml.common.network.simpleimpl.MessageContext;
import cpw.mods.fml.relauncher.Side;
/**
* Main mod class
*/
@Mod(modid = ForgeEssentials.MODID, name = "Forge Essentials", version = BuildInfo.BASE_VERSION, acceptableRemoteVersions = "*", dependencies = "required-after:Forge@[10.13.4.1448,);after:WorldEdit")
public class ForgeEssentials extends ConfigLoaderBase
{
public static final String MODID = "ForgeEssentials";
@Instance(value = MODID)
public static ForgeEssentials instance;
public static final String PERM = "fe";
public static final String PERM_CORE = PERM + ".core";
public static final String PERM_INFO = PERM_CORE + ".info";
public static final String PERM_VERSIONINFO = PERM_CORE + ".versioninfo";
/* ForgeEssentials core submodules */
protected static ConfigManager configManager;
protected static ModuleLauncher moduleLauncher;
protected static TaskRegistry tasks = new TaskRegistry();
protected static SelectionEventHandler wandHandler;
protected static ForgeEssentialsEventFactory factory;
protected static TeleportHelper teleportHelper;
protected static Questioner questioner;
protected static FECommandManager commandManager;
protected static Metrics mcStats;
protected static Graph mcStatsGeneralGraph;
protected static File configDirectory;
protected static boolean debugMode = false;
protected static boolean safeMode = false;
protected static boolean logCommandsToConsole;
public ForgeEssentials()
{
initConfiguration();
LoggingHandler.init();
BuildInfo.getBuildInfo(FELaunchHandler.getJarLocation());
Environment.check();
FMLCommonHandler.instance().bus().register(this);
MinecraftForge.EVENT_BUS.register(this);
}
@Mod.EventHandler
public void preInit(FMLPreInitializationEvent event)
{
LoggingHandler.felog.info(String.format("Running ForgeEssentials %s (%s)", BuildInfo.getFullVersion(), BuildInfo.getBuildHash()));
if (safeMode)
{
LoggingHandler.felog.warn("You are running FE in safe mode. Please only do so if requested to by the ForgeEssentials team.");
}
registerNetworkMessages();
// Init McStats
mcStats = new Metrics(MODID + "New", BuildInfo.BASE_VERSION);
mcStatsGeneralGraph = mcStats.createGraph("general");
// Set up logger level
if (debugMode)
((Logger) LoggingHandler.felog).setLevel(Level.DEBUG);
else
((Logger) LoggingHandler.felog).setLevel(Level.INFO);
// Register core submodules
factory = new ForgeEssentialsEventFactory();
wandHandler = new SelectionEventHandler();
teleportHelper = new TeleportHelper();
questioner = new Questioner();
APIRegistry.getFEEventBus().register(new CompatReiMinimap());
// Load submodules
moduleLauncher = new ModuleLauncher();
moduleLauncher.preLoad(event);
}
@EventHandler
public void load(FMLInitializationEvent e)
{
registerCommands();
// Init McStats
mcStats.createGraph("build_type").addPlotter(new ConstantPlotter(BuildInfo.getBuildType(), 1));
mcStats.createGraph("server_type").addPlotter(new ConstantPlotter(e.getSide() == Side.SERVER ? "server" : "client", 1));
Graph gModules = mcStats.createGraph("modules");
for (String module : ModuleLauncher.getModuleList())
gModules.addPlotter(new ConstantPlotter(module, 1));
LoggingHandler.felog
.info(String.format("Running ForgeEssentials %s-%s (%s)", BuildInfo.getFullVersion(), BuildInfo.getBuildType(), BuildInfo.getBuildHash()));
if (BuildInfo.isOutdated())
{
LoggingHandler.felog.warn("
LoggingHandler.felog.warn(String.format("WARNING! Using ForgeEssentials build #%d, latest build is #%d", //
BuildInfo.getBuildNumber(), BuildInfo.getBuildNumberLatest()));
LoggingHandler.felog.warn("We highly recommend updating asap to get the latest security and bug fixes");
LoggingHandler.felog.warn("
}
APIRegistry.getFEEventBus().post(new FEModuleEvent.FEModuleInitEvent(e));
}
@EventHandler
public void postLoad(FMLPostInitializationEvent e)
{
APIRegistry.getFEEventBus().post(new FEModuleEvent.FEModulePostInitEvent(e));
commandManager = new FECommandManager();
}
private void initConfiguration()
{
configDirectory = new File(ServerUtil.getBaseDir(), "/ForgeEssentials");
configManager = new ConfigManager(configDirectory, "main");
configManager.registerLoader(configManager.getMainConfigName(), this);
configManager.registerLoader(configManager.getMainConfigName(), new FEConfig());
configManager.registerLoader(configManager.getMainConfigName(), new ChatOutputHandler());
}
private void registerNetworkMessages()
{
// Load network packages
NetworkUtils.registerMessage(new IMessageHandler<Packet0Handshake, IMessage>() {
@Override
public IMessage onMessage(Packet0Handshake message, MessageContext ctx)
{
PlayerInfo.get(ctx.getServerHandler().playerEntity).setHasFEClient(true);
return null;
}
}, Packet0Handshake.class, 0, Side.SERVER);
NetworkUtils.registerMessageProxy(Packet1SelectionUpdate.class, 1, Side.CLIENT, new NullMessageHandler<Packet1SelectionUpdate>() {
/* dummy */
});
NetworkUtils.registerMessageProxy(Packet2Reach.class, 2, Side.CLIENT, new NullMessageHandler<Packet2Reach>() {
/* dummy */
});
NetworkUtils.registerMessageProxy(Packet3PlayerPermissions.class, 3, Side.CLIENT, new NullMessageHandler<Packet3PlayerPermissions>() {
/* dummy */
});
NetworkUtils.registerMessageProxy(Packet5Noclip.class, 5, Side.CLIENT, new NullMessageHandler<Packet5Noclip>() {
/* dummy */
});
NetworkUtils.registerMessageProxy(Packet7Remote.class, 7, Side.CLIENT, new NullMessageHandler<Packet7Remote>() {
/* dummy */
});
}
private void registerCommands()
{
FECommandManager.registerCommand(new CommandFEInfo());
FECommandManager.registerCommand(new CommandFeSettings());
FECommandManager.registerCommand(new CommandWand());
FECommandManager.registerCommand(new CommandUuid());
FECommandManager.registerCommand(new CommandFEWorldInfo());
if (!ModuleLauncher.getModuleList().contains("WEIntegrationTools"))
{
FECommandManager.registerCommand(new CommandPos(1));
FECommandManager.registerCommand(new CommandPos(2));
FECommandManager.registerCommand(new CommandDeselect());
FECommandManager.registerCommand(new CommandExpand());
FECommandManager.registerCommand(new CommandExpandY());
}
}
@EventHandler
public void serverPreInit(FMLServerAboutToStartEvent e)
{
// Initialize data manager once server begins to start
DataManager.setInstance(new DataManager(new File(ServerUtil.getWorldPath(), "FEData/json")));
APIRegistry.getFEEventBus().post(new FEModuleServerPreInitEvent(e));
}
@EventHandler
public void serverStarting(FMLServerStartingEvent e)
{
mcStats.start();
BlockModListFile.makeModList();
BlockModListFile.dumpFMLRegistries();
ForgeChunkManager.setForcedChunkLoadingCallback(this, new FEChunkLoader());
ServerUtil.replaceCommand("help", new HelpFixer()); // Will be overwritten again by commands module
registerPermissions();
APIRegistry.getFEEventBus().post(new FEModuleEvent.FEModuleServerInitEvent(e));
}
@EventHandler
public void serverStarted(FMLServerStartedEvent e)
{
APIRegistry.getFEEventBus().post(new FEModuleEvent.FEModuleServerPostInitEvent(e));
// TODO: what the fuck? I don't think we should just go and delete all commands colliding with ours!
// CommandSetChecker.remove();
FECommandManager.registerCommands();
FMLCommonHandler.instance().bus().register(new CommandPermissionRegistrationHandler());
}
public static final class CommandPermissionRegistrationHandler
{
@SubscribeEvent
public void serverTickEvent(ServerTickEvent event)
{
PermissionManager.registerCommandPermissions();
FMLCommonHandler.instance().bus().unregister(this);
}
}
@EventHandler
public void serverStopping(FMLServerStoppingEvent e)
{
APIRegistry.getFEEventBus().post(new FEModuleEvent.FEModuleServerStopEvent(e));
PlayerInfo.discardAll();
}
@EventHandler
public void serverStopped(FMLServerStoppedEvent e)
{
mcStats.stop();
APIRegistry.getFEEventBus().post(new FEModuleServerStoppedEvent(e));
FECommandManager.clearRegisteredCommands();
Translator.save();
}
protected void registerPermissions()
{
APIRegistry.perms.registerPermission(PERM_VERSIONINFO, PermissionLevel.OP, "Shows notification to the player if FE version is outdated");
APIRegistry.perms.registerPermission("mc.help", PermissionLevel.TRUE, "Help command");
// Teleport
APIRegistry.perms.registerPermissionProperty(TeleportHelper.TELEPORT_COOLDOWN, "5", "Allow bypassing teleport cooldown");
APIRegistry.perms.registerPermissionProperty(TeleportHelper.TELEPORT_WARMUP, "3", "Allow bypassing teleport warmup");
APIRegistry.perms.registerPermissionPropertyOp(TeleportHelper.TELEPORT_COOLDOWN, "0");
APIRegistry.perms.registerPermissionPropertyOp(TeleportHelper.TELEPORT_WARMUP, "0");
APIRegistry.perms.registerPermission(TeleportHelper.TELEPORT_FROM, PermissionLevel.TRUE, "Allow being teleported from a certain location / dimension");
APIRegistry.perms.registerPermission(TeleportHelper.TELEPORT_TO, PermissionLevel.TRUE, "Allow being teleported to a certain location / dimension");
CommandFeSettings.addAlias("Teleport", "warmup", TeleportHelper.TELEPORT_WARMUP);
CommandFeSettings.addAlias("Teleport", "cooldown", TeleportHelper.TELEPORT_COOLDOWN);
}
@SubscribeEvent(priority = EventPriority.HIGHEST)
public void playerLoggedInEvent(PlayerLoggedInEvent event)
{
if (event.player instanceof EntityPlayerMP)
{
EntityPlayerMP player = (EntityPlayerMP) event.player;
UserIdent.login(player);
PlayerInfo.login(player.getPersistentID());
if (FEConfig.checkSpacesInNames)
{
Pattern pattern = Pattern.compile("\\s");
Matcher matcher = pattern.matcher(player.getGameProfile().getName());
if (matcher.find())
{
String msg = Translator.format("Invalid name \"%s\" containing spaces. Please change your name!", player.getCommandSenderName());
player.playerNetServerHandler.kickPlayerFromServer(msg);
}
}
// Show version notification
if (BuildInfo.isOutdated() && UserIdent.get(player).checkPermission(PERM_VERSIONINFO))
ChatOutputHandler.chatWarning(player,
String.format("ForgeEssentials build #%d outdated. Current build is #%d. Consider updating to get latest security and bug fixes.", //
BuildInfo.getBuildNumber(), BuildInfo.getBuildNumberLatest()));
}
}
@SubscribeEvent(priority = EventPriority.LOWEST)
public void playerLoggedOutEvent(PlayerLoggedOutEvent event)
{
if (event.player instanceof EntityPlayerMP)
{
PlayerInfo.logout(event.player.getPersistentID());
UserIdent.logout((EntityPlayerMP) event.player);
}
}
@SubscribeEvent
public void playerRespawnEvent(PlayerRespawnEvent event)
{
if (event.player instanceof EntityPlayerMP)
{
UserIdent.get((EntityPlayerMP) event.player);
}
}
@SubscribeEvent(priority = EventPriority.LOWEST)
public void commandEvent(CommandEvent event)
{
if (logCommandsToConsole)
{
LoggingHandler.felog.info(String.format("Player \"%s\" used command \"/%s %s\"", event.sender.getCommandSenderName(),
event.command.getCommandName(), StringUtils.join(event.parameters, " ")));
}
}
@Override
public void load(Configuration config, boolean isReload)
{
if (isReload)
Translator.translations.clear();
Translator.load();
if (!config.get(FEConfig.CONFIG_CAT, "versionCheck", true, "Check for newer versions of ForgeEssentials on load?").getBoolean())
BuildInfo.cancelVersionCheck();
configManager.setUseCanonicalConfig(
config.get(FEConfig.CONFIG_CAT, "canonicalConfigs", false, "For modules that support it, place their configs in this file.").getBoolean());
debugMode = config.get(FEConfig.CONFIG_CAT, "debug", false, "Activates developer debug mode. Spams your FML logs.").getBoolean();
safeMode = config.get(FEConfig.CONFIG_CAT, "safeMode", false, "Activates safe mode with will ignore some errors which would normally crash the game. "
+ "Please only enable this after being instructed to do so by FE team in response to an issue on GitHub!").getBoolean();
HelpFixer.hideWorldEditCommands = config
.get(FEConfig.CONFIG_CAT, "hide_worldedit_help", true, "Hide WorldEdit commands from /help and only show them in //help command").getBoolean();
logCommandsToConsole = config.get(FEConfig.CONFIG_CAT, "logCommands", false, "Log commands to console").getBoolean();
}
public static ConfigManager getConfigManager()
{
return configManager;
}
public static Metrics getMcStats()
{
return mcStats;
}
public static Graph getMcStatsGeneralGraph()
{
return mcStatsGeneralGraph;
}
public static File getFEDirectory()
{
return configDirectory;
}
public static boolean isDebug()
{
return debugMode;
}
public static boolean isSafeMode()
{
return safeMode;
}
} |
/**
* A client to the Google Cloud Datastore.
* Typical usage would be:
* <pre> {@code
* DatastoreServiceOptions options = DatastoreServiceOptions.builder().dataset(DATASET).build();
* DatastoreService datastore = DatastoreServiceFactory.getDefault(options);
* KeyBuilder keyBuilder = datastore.newKeyBuilder(kind);
* Key key = keyBuilder.build(keyName);
* Entity entity = datastore.get(key);
* if (entity == null) {
* entity = Entity.builder(key)
* .setStringProperty("name", "John Do")
* .setProperty("age", LongValue.builder(100).indexed(false).build())
* .setBooleanProperty("updated", false)
* .build();
* datastore.put(entity);
* } else {
* boolean updated = entity.booleanProperty("updated");
* if (!updated) {
* String[] name = entity.stringProperty("name").split(" ");
* entity = Entity.builder(entity)
* .setStringProperty("name", name[0])
* .setProperty("last_name", StringValue.builder(name[1]).indexed(false).build())
* .setBooleanProperty("updated", true)
* .removeProperty("old_property")
* .setDoubleProperty("new_property", 1.1)
* .build();
* datastore.update(entity);
* }
* }
* } </pre>
*/
package com.google.gcloud.datastore; |
package com.jaamsim.BasicObjects;
import com.jaamsim.Graphics.DisplayEntity;
import com.jaamsim.Samples.SampleConstant;
import com.jaamsim.Samples.SampleExpInput;
import com.jaamsim.basicsim.Entity;
import com.jaamsim.input.EntityInput;
import com.jaamsim.input.Input;
import com.jaamsim.input.IntegerInput;
import com.jaamsim.input.Keyword;
import com.jaamsim.input.Output;
import com.jaamsim.units.DimensionlessUnit;
import com.jaamsim.units.TimeUnit;
/**
* EntityGenerator creates sequence of DisplayEntities at random intervals, which are placed in a target Queue.
*/
public class EntityGenerator extends LinkedService {
@Keyword(description = "The arrival time for the first generated entity.\n" +
"A constant value, a distribution to be sampled, or a time series can be entered.",
exampleList = { "3.0 h", "ExponentialDistribution1", "'1[s] + 0.5*[TimeSeries1].PresentValue'" })
private final SampleExpInput firstArrivalTime;
@Keyword(description = "The inter-arrival time between generated entities.\n" +
"A constant value, a distribution to be sampled, or a time series can be entered.",
exampleList = { "3.0 h", "ExponentialDistribution1", "'1[s] + 0.5*[TimeSeries1].PresentValue'" })
private final SampleExpInput interArrivalTime;
@Keyword(description = "The number of entities to be generated for each arrival.\n" +
"A constant value, a distribution to be sampled, or a time series can be entered.",
exampleList = {"3", "TimeSeries1", "'1 + 2*[DiscreteDistribution1].Value'"})
private final SampleExpInput entitiesPerArrival;
@Keyword(description = "The prototype for entities to be generated.\n" +
"The generated entities will be copies of this entity.",
exampleList = {"Proto"})
private final EntityInput<DisplayEntity> prototypeEntity;
@Keyword(description = "The maximum number of entities to be generated.",
exampleList = {"3"})
private final IntegerInput maxNumber;
private int numberGenerated = 0; // Number of entities generated so far
{
testEntity.setHidden(true);
stateAssignment.setHidden(true);
waitQueue.setHidden(true);
match.setHidden(true);
processPosition.setHidden(true);
firstArrivalTime = new SampleExpInput("FirstArrivalTime", "Key Inputs", new SampleConstant(TimeUnit.class, 0.0));
firstArrivalTime.setUnitType(TimeUnit.class);
firstArrivalTime.setEntity(this);
firstArrivalTime.setValidRange(0, Double.POSITIVE_INFINITY);
this.addInput(firstArrivalTime);
interArrivalTime = new SampleExpInput("InterArrivalTime", "Key Inputs", new SampleConstant(TimeUnit.class, 1.0));
interArrivalTime.setUnitType(TimeUnit.class);
interArrivalTime.setEntity(this);
interArrivalTime.setValidRange(0, Double.POSITIVE_INFINITY);
this.addInput(interArrivalTime);
entitiesPerArrival = new SampleExpInput("EntitiesPerArrival", "Key Inputs", new SampleConstant(DimensionlessUnit.class, 1.0));
entitiesPerArrival.setUnitType(DimensionlessUnit.class);
entitiesPerArrival.setEntity(this);
entitiesPerArrival.setValidRange(1, Double.POSITIVE_INFINITY);
this.addInput(entitiesPerArrival);
prototypeEntity = new EntityInput<>(DisplayEntity.class, "PrototypeEntity", "Key Inputs", null);
prototypeEntity.setRequired(true);
this.addInput(prototypeEntity);
maxNumber = new IntegerInput("MaxNumber", "Key Inputs", null);
maxNumber.setValidRange(1, Integer.MAX_VALUE);
maxNumber.setDefaultText(Input.POSITIVE_INFINITY);
this.addInput(maxNumber);
}
public EntityGenerator() {}
@Override
public void earlyInit() {
super.earlyInit();
numberGenerated = 0;
}
@Override
public void addEntity( DisplayEntity ent ) {
error("An entity cannot be sent to an EntityGenerator.");
}
@Override
public void startUp() {
super.startUp();
// Start generating entities
this.setBusy(true);
this.setPresentState();
this.startAction();
}
@Override
public void startAction() {
// Stop if the gate is closed or the last entity been generated
if (!this.isOpen() || (maxNumber.getValue() != null && numberGenerated >= maxNumber.getValue())) {
this.setBusy(false);
this.setPresentState();
return;
}
// Schedule the next entity to be generated
double dt;
if (numberGenerated == 0)
dt = firstArrivalTime.getValue().getNextSample(getSimTime());
else
dt = interArrivalTime.getValue().getNextSample(getSimTime());
this.scheduleProcess(dt, 5, endActionTarget);
}
@Override
public void endAction() {
// Do any of the thresholds stop the generator?
if (!this.isOpen()) {
this.setBusy(false);
this.setPresentState();
return;
}
// Create the new entities
int num = (int) entitiesPerArrival.getValue().getNextSample(getSimTime());
for (int i=0; i<num; i++) {
numberGenerated++;
DisplayEntity proto = prototypeEntity.getValue();
StringBuilder sb = new StringBuilder();
sb.append(this.getName()).append("_").append(numberGenerated);
DisplayEntity ent = Entity.fastCopy(proto, sb.toString());
ent.earlyInit();
// Send the entity to the next element in the chain
this.sendToNextComponent(ent);
}
// Try to generate another entity
this.startAction();
}
@Output(name = "NumberGenerated",
description = "The number of entities generated by this generator.",
unitType = DimensionlessUnit.class)
public int getNumberGenerated(double simTime) {
return numberGenerated;
}
} |
package com.jaeksoft.searchlib.index;
import com.jaeksoft.searchlib.Logging;
import com.jaeksoft.searchlib.SearchLibException;
import com.jaeksoft.searchlib.SearchLibException.UniqueKeyMissing;
import com.jaeksoft.searchlib.analysis.AbstractAnalyzer;
import com.jaeksoft.searchlib.analysis.Analyzer;
import com.jaeksoft.searchlib.analysis.CompiledAnalyzer;
import com.jaeksoft.searchlib.analysis.IndexDocumentAnalyzer;
import com.jaeksoft.searchlib.analysis.LanguageEnum;
import com.jaeksoft.searchlib.analysis.PerFieldAnalyzer;
import com.jaeksoft.searchlib.request.AbstractRequest;
import com.jaeksoft.searchlib.schema.FieldValueItem;
import com.jaeksoft.searchlib.schema.Schema;
import com.jaeksoft.searchlib.schema.SchemaField;
import com.jaeksoft.searchlib.schema.SchemaFieldList;
import com.jaeksoft.searchlib.util.IOUtils;
import com.jaeksoft.searchlib.webservice.query.document.IndexDocumentResult;
import com.jaeksoft.searchlib.webservice.query.document.IndexDocumentResult.IndexField;
import com.jaeksoft.searchlib.webservice.query.document.IndexDocumentResult.IndexTerm;
import org.apache.commons.collections.CollectionUtils;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.index.SerialMergeScheduler;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.Similarity;
import org.apache.lucene.util.Version;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.ReentrantLock;
public class WriterLocal extends WriterAbstract {
private IndexDirectory indexDirectory;
private final ReentrantLock indexWriterLock;
protected WriterLocal(IndexConfig indexConfig, IndexDirectory indexDirectory) throws IOException {
super(indexConfig);
this.indexDirectory = indexDirectory;
indexWriterLock = new ReentrantLock();
}
private void close(IndexWriter indexWriter) {
if (indexWriter == null)
return;
try {
indexWriter.close();
} catch (Exception e) {
Logging.warn(e);
} finally {
indexWriterLock.unlock();
indexDirectory.unlock();
}
}
public final void create() throws IOException, SearchLibException {
IndexWriter indexWriter = null;
try {
indexWriter = open(true);
} finally {
close(indexWriter);
}
}
private IndexWriter open(boolean create) throws IOException, SearchLibException {
indexWriterLock.lock();
IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_36, null);
config.setOpenMode(create ? OpenMode.CREATE_OR_APPEND : OpenMode.APPEND);
config.setMergeScheduler(new SerialMergeScheduler());
config.setWriteLockTimeout(indexConfig.getWriteLockTimeout());
config.setRAMBufferSizeMB(128);
Similarity similarity = indexConfig.getNewSimilarityInstance();
if (similarity != null)
config.setSimilarity(similarity);
Logging.debug("WriteLocal open " + indexDirectory.getDirectory());
return new IndexWriter(indexDirectory.getDirectory(), config);
}
private IndexWriter open() throws IOException, SearchLibException {
return open(false);
}
@Deprecated
public void addDocument(Document document) throws IOException, SearchLibException {
IndexWriter indexWriter = null;
try {
indexWriter = open();
indexWriter.addDocument(document);
} finally {
close(indexWriter);
}
}
private boolean updateDocNoLock(SchemaField uniqueField, IndexWriter indexWriter, Schema schema,
IndexDocument document) throws IOException, NoSuchAlgorithmException, SearchLibException {
if (!acceptDocument(document))
return false;
Document doc = getLuceneDocument(schema, document);
PerFieldAnalyzer pfa = schema.getIndexPerFieldAnalyzer(document.getLang());
updateDocNoLock(uniqueField, indexWriter, pfa, doc);
return true;
}
private void updateDocNoLock(SchemaField uniqueField, IndexWriter indexWriter, AbstractAnalyzer analyzer,
Document doc) throws UniqueKeyMissing, CorruptIndexException, IOException {
if (uniqueField != null) {
String uniqueFieldName = uniqueField.getName();
String uniqueFieldValue = doc.get(uniqueFieldName);
if (uniqueFieldValue == null)
throw new UniqueKeyMissing(uniqueFieldName);
indexWriter.updateDocument(new Term(uniqueFieldName, uniqueFieldValue), doc, analyzer);
} else
indexWriter.addDocument(doc, analyzer);
}
@Override
public boolean updateDocument(Schema schema, IndexDocument document) throws SearchLibException {
IndexWriter indexWriter = null;
try {
indexWriter = open();
SchemaField uniqueField = schema.getFieldList().getUniqueField();
boolean updated = updateDocNoLock(uniqueField, indexWriter, schema, document);
close(indexWriter);
indexWriter = null;
return updated;
} catch (IOException | NoSuchAlgorithmException e) {
throw new SearchLibException(e);
} finally {
close(indexWriter);
}
}
@Override
public int updateDocuments(Schema schema, Collection<IndexDocument> documents) throws SearchLibException {
IndexWriter indexWriter = null;
try {
final AtomicInteger count = new AtomicInteger();
final IndexWriter iw = indexWriter = open();
final SchemaField uniqueField = schema.getFieldList().getUniqueField();
final AtomicReference<Exception> exceptionReference = new AtomicReference<>();
final ExecutorService executorService = Executors.newFixedThreadPool(
Runtime.getRuntime().availableProcessors() * 2);
try {
for (IndexDocument document : documents) {
executorService.submit(() -> {
try {
if (updateDocNoLock(uniqueField, iw, schema, document))
count.incrementAndGet();
} catch (IOException | NoSuchAlgorithmException | SearchLibException e) {
exceptionReference.weakCompareAndSet(null, e);
}
});
}
} finally {
executorService.shutdown();
}
executorService.awaitTermination(1, TimeUnit.HOURS);
if (exceptionReference.get() != null)
throw SearchLibException.newInstance(exceptionReference.get());
close(indexWriter);
indexWriter = null;
return count.get();
} catch (IOException | InterruptedException e) {
throw new SearchLibException(e);
} finally {
close(indexWriter);
}
}
@Override
public int updateIndexDocuments(Schema schema, Collection<IndexDocumentResult> documents)
throws SearchLibException {
IndexWriter indexWriter = null;
try {
final AtomicInteger count = new AtomicInteger();
final IndexWriter iw = indexWriter = open();
final SchemaField uniqueField = schema.getFieldList().getUniqueField();
final AtomicReference<Exception> exceptionReference = new AtomicReference<>();
final ExecutorService executorService = Executors.newFixedThreadPool(
Runtime.getRuntime().availableProcessors() * 2);
try {
for (IndexDocumentResult document : documents) {
executorService.submit(() -> {
final Document doc = getLuceneDocument(schema, document);
final IndexDocumentAnalyzer analyzer = new IndexDocumentAnalyzer(document);
try {
updateDocNoLock(uniqueField, iw, analyzer, doc);
count.incrementAndGet();
} catch (IOException | SearchLibException e) {
exceptionReference.weakCompareAndSet(null, e);
}
});
}
} finally {
executorService.shutdown();
}
executorService.awaitTermination(1, TimeUnit.HOURS);
if (exceptionReference.get() != null)
throw SearchLibException.newInstance(exceptionReference.get());
close(indexWriter);
indexWriter = null;
return count.get();
} catch (IOException | InterruptedException e) {
throw new SearchLibException(e);
} finally {
close(indexWriter);
}
}
private static Document getLuceneDocument(Schema schema, IndexDocument document)
throws IOException, SearchLibException {
schema.getIndexPerFieldAnalyzer(document.getLang());
Document doc = new Document();
LanguageEnum lang = document.getLang();
SchemaFieldList schemaFieldList = schema.getFieldList();
for (FieldContent fieldContent : document) {
if (fieldContent == null)
continue;
String fieldName = fieldContent.getField();
SchemaField field = schemaFieldList.get(fieldName);
if (field == null)
continue;
Analyzer analyzer = schema.getAnalyzer(field, lang);
@SuppressWarnings("resource") CompiledAnalyzer compiledAnalyzer =
(analyzer == null) ? null : analyzer.getIndexAnalyzer();
List<FieldValueItem> valueItems = fieldContent.getValues();
if (valueItems == null)
continue;
for (FieldValueItem valueItem : valueItems) {
if (valueItem == null)
continue;
String value = valueItem.getValue();
if (value == null)
continue;
if (compiledAnalyzer != null)
if (!compiledAnalyzer.isAnyToken(fieldName, value))
continue;
doc.add(field.getLuceneField(value, valueItem.getBoost()));
}
}
return doc;
}
private static Document getLuceneDocument(Schema schema, IndexDocumentResult document) {
if (CollectionUtils.isEmpty(document.fields))
return null;
SchemaFieldList schemaFieldList = schema.getFieldList();
Document doc = new Document();
for (IndexField indexField : document.fields) {
SchemaField field = schemaFieldList.get(indexField.field);
if (field == null)
continue;
if (indexField.stored != null) {
for (String value : indexField.stored)
doc.add(field.getLuceneField(value, null));
} else {
if (indexField.terms != null)
for (IndexTerm term : indexField.terms)
doc.add(field.getLuceneField(term.t, null));
}
}
return doc;
}
public int deleteDocuments(int[] ids) throws IOException, SearchLibException {
if (ids == null || ids.length == 0)
return 0;
IndexReader indexReader = null;
try {
int l = 0;
indexReader = IndexReader.open(indexDirectory.getDirectory(), false);
for (int id : ids)
if (!indexReader.isDeleted(id)) {
indexReader.deleteDocument(id);
l++;
}
indexReader.close();
indexReader = null;
return l;
} finally {
IOUtils.close(indexReader);
}
}
@Override
public void deleteAll() throws SearchLibException {
IndexWriter indexWriter = null;
try {
indexWriter = open();
indexWriter.deleteAll();
close(indexWriter);
indexWriter = null;
} catch (IOException e) {
throw new SearchLibException(e);
} finally {
close(indexWriter);
}
}
@Override
public int deleteDocuments(AbstractRequest request) throws SearchLibException {
throw new SearchLibException("WriterLocal.deleteDocument(request) is not implemented");
}
private void mergeNoLock(IndexDirectory directory) throws SearchLibException {
IndexWriter indexWriter = null;
try {
indexWriter = open();
indexWriter.addIndexes(directory.getDirectory());
close(indexWriter);
indexWriter = null;
} catch (IOException e) {
throw new SearchLibException(e);
} finally {
close(indexWriter);
}
}
@Override
public void mergeData(WriterInterface source) throws SearchLibException {
WriterLocal sourceWriter;
if (!(source instanceof WriterLocal))
throw new SearchLibException("Unsupported operation");
sourceWriter = (WriterLocal) source;
try {
sourceWriter.setMergingSource(true);
setMergingTarget(true);
mergeNoLock(sourceWriter.indexDirectory);
} finally {
if (sourceWriter != null)
sourceWriter.setMergingSource(false);
setMergingTarget(false);
}
}
} |
package com.kolich.blog.components;
import com.google.common.collect.Sets;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.kolich.blog.ApplicationConfig;
import com.kolich.curacao.annotations.Component;
import com.kolich.curacao.annotations.Injectable;
import com.kolich.curacao.handlers.components.CuracaoComponent;
import org.apache.commons.io.FileUtils;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.storage.file.FileRepositoryBuilder;
import org.slf4j.Logger;
import javax.annotation.Nonnull;
import javax.servlet.ServletContext;
import java.io.File;
import java.util.Set;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
import static org.slf4j.LoggerFactory.getLogger;
@Component
public final class GitRepository implements CuracaoComponent {
private static final Logger logger__ = getLogger(GitRepository.class);
private static final Boolean isDevMode__ =
ApplicationConfig.isDevMode();
private static final String blogRepoCloneUrl__ =
ApplicationConfig.getBlogRepoCloneUrl();
private static final String clonePath__ =
ApplicationConfig.getClonePath();
private static final Boolean shouldCloneOnStartup__ =
ApplicationConfig.shouldCloneOnStartup();
private static final String contentRootDir__ =
ApplicationConfig.getContentRootDir();
private static final Long gitUpdateInterval__ =
ApplicationConfig.getGitPullUpdateInterval();
private static final String userDir__ = System.getProperty("user.dir");
private final Repository repo_;
private final Git git_;
private final ScheduledExecutorService executor_;
/**
* A set of {@link PullListener}'s which are notified in order when this
* Git repository is updated on disk (e.g., when a "pull" request
* finishes).
*/
private final Set<PullListener> listeners_;
@Injectable
public GitRepository(final ServletContext context) throws Exception {
executor_ = newSingleThreadScheduledExecutor(
new ThreadFactoryBuilder()
.setDaemon(true)
.setNameFormat("git-puller")
.build());
listeners_ = Sets.newLinkedHashSet();
final File repoDir = getRepoDir(context);
logger__.info("Activated repository path: " +
repoDir.getCanonicalFile());
// If were not in dev mode, and the clone path doesn't exist or we need
// to force clone from scratch, do that now.
final boolean clone = (!repoDir.exists() || shouldCloneOnStartup__);
if(!isDevMode__ && clone) {
logger__.info("Clone path does not exist, or we were asked " +
"to re-clone. Cloning from: " + blogRepoCloneUrl__);
// Recursively delete the existing clone of the repo, if it exists,
// and clone the repository.
FileUtils.deleteDirectory(repoDir);
Git.cloneRepository()
.setURI(blogRepoCloneUrl__)
.setDirectory(repoDir)
.setBranch("master")
.call();
}
// Construct a new pointer to the repository on disk.
repo_ = new FileRepositoryBuilder()
.setWorkTree(repoDir)
.readEnvironment()
.build();
git_ = new Git(repo_);
logger__.info("Successfully initialized repository at: " + repo_);
}
@Override
public final void initialize() throws Exception {
// Schedule a new updater at a "fixed" interval that has no
// initial delay to fetch/pull in new content immediately.
executor_.scheduleAtFixedRate(
new GitPuller(), // new puller
0L, // initial delay, start ~now~
gitUpdateInterval__, // repeat every
TimeUnit.MILLISECONDS); // units
}
@Override
public final void destroy() throws Exception {
// Close our handle to the repository on shutdown.
repo_.close();
// Ask the single thread updater pool to "shutdown".
if(executor_ != null) {
executor_.shutdown();
}
}
private static final File getRepoDir(final ServletContext context) {
final File repoDir;
if(isDevMode__) {
// If in "development mode", the clone path is the local copy of
// the repo on disk.
repoDir = new File(userDir__);
} else {
// Otherwise, it could be somewhere else either in an absolute
// location (/...) or somewhere under the Servlet container when
// relative.
repoDir = (clonePath__.startsWith(File.separator)) ?
// If the specified clone path in the application configuration
// is "absolute", then use that path raw.
new File(clonePath__) :
// Otherwise, the clone path is relative to the container Servlet
// context of this application.
new File(context.getRealPath(File.separator + clonePath__));
}
return repoDir;
}
@Nonnull
public final Git getGit() {
return git_;
}
@Nonnull
public final Repository getRepo() {
return repo_;
}
@Nonnull
public final File getContentRoot() {
return new File(repo_.getWorkTree(), contentRootDir__);
}
@Nonnull
public final File getFileRelativeToContentRoot(final String child) {
return new File(getContentRoot(), child);
}
public final boolean registerListener(final PullListener listener) {
return listeners_.add(listener);
}
public final boolean unRegisterListener(final PullListener listener) {
return listeners_.remove(listener);
}
public interface PullListener {
public void onPull() throws Exception;
}
private class GitPuller implements Runnable {
/**
* The number of times a Git pull has to fail before it shows up
* in the logs. Often there are intermittent failures with GitHub
* where the network is down or the GitHub infrastructure is having
* problems; in those cases, we don't want to bother logging the
* failure on every pull because it will very likely succeed if we
* try again a few moments later.
*/
private static final int COMPLAINT_THRESHOLD = 12; // 12 = 60 mins / 5
private int failures_ = 0;
@Override
public final void run() {
try {
// Only attempt a "pull" if we're not in development mode.
// We should not pull when in dev mode, because of pending
// changes that are likely waiting to be committed may
// unexpectedly interfere with the pull (merge conflicts, etc.)
if(!isDevMode__) {
git_.pull().call();
}
// Notify each pull listener that the pull is done and they can
// update their caches as needed.
for(final PullListener listener : listeners_) {
try {
listener.onPull();
} catch (Exception e) {
logger__.warn("Failure notifying pull listener.", e);
}
}
failures_ = 0; // Reset counter, pull completed successfully.
} catch (Exception e) {
// Only log the failure if we've failed enough times to
// warrant some log spew.
if(++failures_ >= COMPLAINT_THRESHOLD) {
logger__.warn("Failed to Git 'pull', raw Git operation " +
"did not complete successfully.", e);
}
}
}
}
} |
package com.lothrazar.samscontent;
import java.util.ArrayList;
import java.util.List;
import org.apache.logging.log4j.Logger;
import com.lothrazar.util.Reference;
import com.lothrazar.util.Util;
import net.minecraft.block.Block;
import net.minecraft.block.material.MapColor;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.ICrafting;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.CraftingManager;
import net.minecraft.item.crafting.IRecipe;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.common.config.Property;
import net.minecraftforge.fml.client.event.ConfigChangedEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.Mod.EventHandler;
import net.minecraftforge.fml.common.Mod.Instance;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.event.FMLServerStartingEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.oredict.OreDictionary;
public class RecipeRegistry
{
static int EXP = 0;
public static void registerRecipes()
{
RecipeRegistry.netherwartPurple();
RecipeRegistry.quartsFromPrismarine();
RecipeRegistry.mushroomBlocks();
RecipeRegistry.bonemealWool();
RecipeRegistry.simpleDispenser();
RecipeRegistry.records();
RecipeRegistry.uncrafting();
RecipeRegistry.smoothstoneRequired();
RecipeRegistry.furnaceNeedsCoal();
RecipeRegistry.tieredArmor();
RecipeRegistry.woolDyeSavings();
RecipeRegistry.repeaterSimple();
RecipeRegistry.minecartsSimple();
RecipeRegistry.beetroot();
RecipeRegistry.experience_bottle();
if(ModMain.cfg.smelt_gravel)
{
GameRegistry.addSmelting(Blocks.gravel, new ItemStack(Items.flint),0);
}
}
private static void quartsFromPrismarine()
{
if(!ModMain.cfg.quartz_from_prismarine) {return;}
GameRegistry.addShapelessRecipe(new ItemStack(Items.quartz,4)
, new ItemStack(Items.prismarine_shard)
, new ItemStack(Items.iron_ingot)
, new ItemStack(Items.dye,1,Reference.dye_bonemeal)
, new ItemStack(Items.potato)
);
}
private static void experience_bottle()
{
if(!ModMain.cfg.experience_bottle) {return;}
experience_stripe(Items.rotten_flesh);
experience_stripe(Items.bone);
experience_stripe(Items.spider_eye);
experience_stripe(Items.blaze_powder);
experience_stripe(Items.gunpowder);
experience_stripe(Items.feather);
experience_stripe(Items.fish);
experience_stripe(Items.magma_cream);
experience_stripe(Items.rabbit_hide);
experience_stripe(Items.ender_pearl);
experience_stripe(Items.slime_ball);
experience_stripe(Items.ghast_tear);
experience_stripe(Items.mutton);
experience_stripe(Items.porkchop);
experience_stripe(Items.beef);
experience_stripe(Items.chicken);
experience_stripe(Items.gold_nugget);
experience_stripe(Items.rabbit);
experience_stripe(new ItemStack(Items.dye,1,Reference.dye_incsac));
}
private static void experience_stripe(Item drop)
{
experience_stripe(new ItemStack(drop));
}
private static void experience_stripe(ItemStack drop)
{
GameRegistry.addRecipe(new ItemStack(Items.experience_bottle,8),
"bbb",
"bxb",
"bbb",
'x', drop,
'b', Items.glass_bottle);
}
public static void beetroot()
{
if(!ModMain.cfg.beetroot) {return;}
GameRegistry.addRecipe(new ItemStack(Blocks.red_mushroom_block),
"rrr",
"rrr",
" b ",
'r', ItemRegistry.beetrootItem,
'b', Items.bowl);
GameRegistry.addShapelessRecipe(new ItemStack(Items.dye,2,Reference.dye_red)
,ItemRegistry.beetrootItem);
}
public static void netherwartPurple()
{
if(!ModMain.cfg.netherwartPurpleDye) {return;}
GameRegistry.addShapelessRecipe(new ItemStack(Items.dye,2,Reference.dye_purple)
,Items.nether_wart
,new ItemStack(Items.dye,1,Reference.dye_bonemeal));
}
public static void mushroomBlocks()
{
if(!ModMain.cfg.craftableMushroomBlocks) {return;}
GameRegistry.addRecipe(new ItemStack(Blocks.red_mushroom_block),
"mm",
"mm",
'm', Blocks.red_mushroom);
GameRegistry.addRecipe(new ItemStack(Blocks.brown_mushroom_block),
"mm",
"mm",
'm', Blocks.brown_mushroom);
}
public static void uncrafting()
{
if(!ModMain.cfg.uncraftGeneral) {return;}
GameRegistry.addRecipe(new ItemStack(Blocks.sandstone, 6), "xx", "xx",
'x', Blocks.sandstone_stairs);
GameRegistry.addRecipe(new ItemStack(Blocks.stonebrick, 6), "xx", "xx",
'x', Blocks.stone_brick_stairs);
GameRegistry.addRecipe(new ItemStack(Blocks.cobblestone, 6), "xx", "xx",
'x', Blocks.stone_stairs);
GameRegistry.addRecipe(new ItemStack(Blocks.brick_block, 6), "xx",
"xx", 'x', Blocks.brick_stairs);
GameRegistry.addRecipe(new ItemStack(Blocks.quartz_block, 6), "xx", "xx",
'x', Blocks.quartz_stairs);
GameRegistry.addRecipe(new ItemStack(Blocks.nether_brick, 6), "xx", "xx",
'x', Blocks.nether_brick_stairs);
GameRegistry.addRecipe(new ItemStack(Blocks.planks, 6, Reference.planks_oak), "xx", "xx",
'x', Blocks.oak_stairs);
GameRegistry.addRecipe(new ItemStack(Blocks.planks, 6, Reference.planks_spruce), "xx",
"xx", 'x', Blocks.spruce_stairs);
GameRegistry.addRecipe(new ItemStack(Blocks.planks, 6, Reference.planks_birch), "xx",
"xx", 'x', Blocks.birch_stairs);
GameRegistry.addRecipe(new ItemStack(Blocks.planks, 6, Reference.planks_jungle), "xx",
"xx", 'x', Blocks.jungle_stairs);
GameRegistry.addRecipe(new ItemStack(Blocks.planks, 6, Reference.planks_acacia), "xx",
"xx", 'x', Blocks.acacia_stairs);
GameRegistry.addRecipe(new ItemStack(Blocks.planks, 6, Reference.planks_darkoak), "xx",
"xx", 'x', Blocks.dark_oak_stairs);
//turn slabs back into raw materials
GameRegistry.addRecipe(new ItemStack(Blocks.stone, 3), " ", "xxx","xxx",
'x', new ItemStack(Blocks.stone_slab, 1, Reference.stone_slab_stone));
GameRegistry.addRecipe(new ItemStack(Blocks.sandstone, 3), " ", "xxx","xxx",
'x', new ItemStack(Blocks.stone_slab, 1, Reference.stone_slab_sandstone));
GameRegistry.addRecipe(new ItemStack(Blocks.cobblestone, 3), " ", "xxx","xxx",
'x', new ItemStack(Blocks.stone_slab, 1, Reference.stone_slab_cobble));
GameRegistry.addRecipe(new ItemStack(Blocks.brick_block, 3), " ", "xxx", "xxx",
'x', new ItemStack(Blocks.stone_slab, 1,Reference.stone_slab_brickred));
GameRegistry.addRecipe(new ItemStack(Blocks.stonebrick, 3), " ", "xxx","xxx",
'x', new ItemStack(Blocks.stone_slab, 1,Reference.stone_slab_stonebrick));
GameRegistry.addRecipe(new ItemStack(Blocks.nether_brick, 3), " ","xxx", "xxx",
'x', new ItemStack(Blocks.stone_slab, 1, Reference.stone_slab_netehrbrick));
GameRegistry.addRecipe(new ItemStack(Blocks.quartz_block, 3), " ","xxx", "xxx",
'x', new ItemStack(Blocks.stone_slab, 1, Reference.stone_slab_quartz));
//get blanks back from wooden slabs
GameRegistry.addRecipe(new ItemStack(Blocks.planks, 3, Reference.planks_oak), " ","xxx", "xxx",
'x', new ItemStack(Blocks.wooden_slab, 1, Reference.planks_oak));
GameRegistry.addRecipe(new ItemStack(Blocks.planks, 3, Reference.planks_spruce), " ", "xxx", "xxx",
'x', new ItemStack(Blocks.wooden_slab, 1, Reference.planks_spruce));
GameRegistry.addRecipe(new ItemStack(Blocks.planks, 3, Reference.planks_birch), " ","xxx", "xxx",
'x', new ItemStack(Blocks.wooden_slab, 1, Reference.planks_birch));
GameRegistry.addRecipe(new ItemStack(Blocks.planks, 3, Reference.planks_jungle), " ", "xxx", "xxx",
'x', new ItemStack(Blocks.wooden_slab, 1, Reference.planks_jungle));
GameRegistry.addRecipe(new ItemStack(Blocks.planks, 3, Reference.planks_acacia), " ", "xxx", "xxx",
'x', new ItemStack(Blocks.wooden_slab, 1, Reference.planks_acacia));
GameRegistry.addRecipe(new ItemStack(Blocks.planks, 3, Reference.planks_darkoak), " ","xxx", "xxx",
'x', new ItemStack(Blocks.wooden_slab, 1, Reference.planks_darkoak));
//planks to logs
GameRegistry.addRecipe(new ItemStack(Blocks.log, 1, Reference.log_oak), "x ","x ","xx ", 'x', new ItemStack(Blocks.planks, 1, Reference.planks_oak));
GameRegistry.addRecipe(new ItemStack(Blocks.log, 1, Reference.log_spruce), "x ","x ","xx ", 'x', new ItemStack(Blocks.planks, 1, Reference.planks_spruce));
GameRegistry.addRecipe(new ItemStack(Blocks.log, 1, Reference.log_birch), "x ","x ","xx ", 'x', new ItemStack(Blocks.planks, 1, Reference.planks_birch));
GameRegistry.addRecipe(new ItemStack(Blocks.log, 1, Reference.log_jungle), "x ","x ","xx ", 'x', new ItemStack(Blocks.planks, 1, Reference.planks_jungle));
GameRegistry.addRecipe(new ItemStack(Blocks.log2,1, Reference.log2_acacia), "x ","x ","xx ", 'x', new ItemStack(Blocks.planks, 1,Reference.planks_acacia));
GameRegistry.addRecipe(new ItemStack(Blocks.log2,1, Reference.log2_darkoak),"x ","x ","xx ", 'x', new ItemStack(Blocks.planks, 1, Reference.planks_darkoak));
GameRegistry.addRecipe(new ItemStack(Blocks.log, 1, Reference.log_oak), " x "," x "," xx", 'x', new ItemStack(Blocks.planks, 1, Reference.planks_oak));
GameRegistry.addRecipe(new ItemStack(Blocks.log, 1, Reference.log_spruce), " x "," x "," xx", 'x', new ItemStack(Blocks.planks, 1, Reference.planks_spruce));
GameRegistry.addRecipe(new ItemStack(Blocks.log, 1, Reference.log_birch), " x "," x "," xx", 'x', new ItemStack(Blocks.planks, 1, Reference.planks_birch));
GameRegistry.addRecipe(new ItemStack(Blocks.log, 1, Reference.log_jungle), " x "," x "," xx", 'x', new ItemStack(Blocks.planks, 1, Reference.planks_jungle));
GameRegistry.addRecipe(new ItemStack(Blocks.log2,1, Reference.log2_acacia), " x "," x "," xx", 'x', new ItemStack(Blocks.planks, 1,Reference.planks_acacia));
GameRegistry.addRecipe(new ItemStack(Blocks.log2,1, Reference.log2_darkoak)," x "," x "," xx", 'x', new ItemStack(Blocks.planks, 1, Reference.planks_darkoak));
//four planks makes 3 fences
//so same in reverse
GameRegistry.addShapelessRecipe( new ItemStack(Blocks.planks, 4, Reference.planks_acacia)
,new ItemStack(Blocks.acacia_fence )
,new ItemStack(Blocks.acacia_fence )
,new ItemStack(Blocks.acacia_fence ));
GameRegistry.addShapelessRecipe( new ItemStack(Blocks.planks, 2, Reference.planks_acacia)
,new ItemStack(Blocks.acacia_fence_gate )
,new ItemStack(Blocks.acacia_fence_gate ) );
GameRegistry.addShapelessRecipe( new ItemStack(Blocks.planks, 4, Reference.planks_jungle)
,new ItemStack(Blocks.jungle_fence )
,new ItemStack(Blocks.jungle_fence )
,new ItemStack(Blocks.jungle_fence ));
GameRegistry.addShapelessRecipe( new ItemStack(Blocks.planks, 2, Reference.planks_jungle)
,new ItemStack(Blocks.jungle_fence_gate )
,new ItemStack(Blocks.jungle_fence_gate ) );
GameRegistry.addShapelessRecipe( new ItemStack(Blocks.planks, 4, Reference.planks_birch)
,new ItemStack(Blocks.birch_fence )
,new ItemStack(Blocks.birch_fence )
,new ItemStack(Blocks.birch_fence ));
GameRegistry.addShapelessRecipe( new ItemStack(Blocks.planks, 2, Reference.planks_birch)
,new ItemStack(Blocks.birch_fence_gate )
,new ItemStack(Blocks.birch_fence_gate ) );
GameRegistry.addShapelessRecipe( new ItemStack(Blocks.planks, 4, Reference.planks_oak)
,new ItemStack(Blocks.oak_fence )
,new ItemStack(Blocks.oak_fence )
,new ItemStack(Blocks.oak_fence ));
GameRegistry.addShapelessRecipe( new ItemStack(Blocks.planks, 2, Reference.planks_oak)
,new ItemStack(Blocks.oak_fence_gate )
,new ItemStack(Blocks.oak_fence_gate ) );
GameRegistry.addShapelessRecipe( new ItemStack(Blocks.planks, 4, Reference.planks_spruce)
,new ItemStack(Blocks.spruce_fence )
,new ItemStack(Blocks.spruce_fence )
,new ItemStack(Blocks.spruce_fence ));
GameRegistry.addShapelessRecipe( new ItemStack(Blocks.planks, 2, Reference.planks_spruce)
,new ItemStack(Blocks.spruce_fence_gate )
,new ItemStack(Blocks.spruce_fence_gate ) );
GameRegistry.addShapelessRecipe( new ItemStack(Blocks.planks, 4, Reference.planks_darkoak)
,new ItemStack(Blocks.dark_oak_fence )
,new ItemStack(Blocks.dark_oak_fence )
,new ItemStack(Blocks.dark_oak_fence ));
GameRegistry.addShapelessRecipe( new ItemStack(Blocks.planks, 2, Reference.planks_darkoak)
,new ItemStack(Blocks.dark_oak_fence_gate )
,new ItemStack(Blocks.dark_oak_fence_gate ) );
//6 planks => 3 doors. therefore 1 door = 2 planks
GameRegistry.addShapelessRecipe(new ItemStack(Blocks.planks, 2,Reference.planks_acacia),
new ItemStack(Blocks.acacia_door));
GameRegistry.addShapelessRecipe(new ItemStack(Blocks.planks, 2,Reference.planks_birch),
new ItemStack(Blocks.birch_door));
GameRegistry.addShapelessRecipe(new ItemStack(Blocks.planks, 2,Reference.planks_spruce),
new ItemStack(Blocks.spruce_door));
GameRegistry.addShapelessRecipe(new ItemStack(Blocks.planks, 2,Reference.planks_darkoak),
new ItemStack(Blocks.dark_oak_door));
GameRegistry.addShapelessRecipe(new ItemStack(Blocks.planks, 2,Reference.planks_oak),
new ItemStack(Blocks.oak_door));
GameRegistry.addShapelessRecipe(new ItemStack(Blocks.planks, 2,Reference.planks_jungle),
new ItemStack(Blocks.jungle_door));
GameRegistry.addShapelessRecipe(new ItemStack(Items.stick, 3)
, new ItemStack(Items.bowl)
, new ItemStack(Items.bowl));
// every two sticks is one plank. so 8 sticks plus one in the middle
// is five planks
GameRegistry.addRecipe(new ItemStack(Blocks.planks, 5, Reference.planks_oak),
"xxx","xpx", "xxx",
'x', Items.stick, 'p', new ItemStack(Blocks.planks, 1, Reference.planks_oak));
GameRegistry.addRecipe(new ItemStack(Blocks.planks, 5, Reference.planks_spruce),
"xxx","xpx", "xxx",
'x', Items.stick, 'p', new ItemStack(Blocks.planks, 1, Reference.planks_spruce));
GameRegistry.addRecipe(new ItemStack(Blocks.planks, 5, Reference.planks_birch),
"xxx","xpx", "xxx",
'x', Items.stick, 'p', new ItemStack(Blocks.planks, 1, Reference.planks_birch));
GameRegistry.addRecipe(new ItemStack(Blocks.planks, 5, Reference.planks_jungle),
"xxx","xpx", "xxx",
'x', Items.stick, 'p', new ItemStack(Blocks.planks, 1, Reference.planks_jungle));
GameRegistry.addRecipe(new ItemStack(Blocks.planks, 5, Reference.planks_acacia),
"xxx","xpx", "xxx",
'x', Items.stick, 'p', new ItemStack(Blocks.planks, 1, Reference.planks_acacia));
GameRegistry.addRecipe(new ItemStack(Blocks.planks, 5,Reference.planks_darkoak),
"xxx","xpx", "xxx",
'x', Items.stick, 'p', new ItemStack(Blocks.planks, 1, Reference.planks_darkoak));
// seven sticks make three ladders, therefore three ladders revert
// back into
GameRegistry.addShapelessRecipe(new ItemStack(Items.stick, 7),
new ItemStack(Blocks.ladder),
new ItemStack(Blocks.ladder),
new ItemStack(Blocks.ladder));
GameRegistry.addShapelessRecipe(new ItemStack(Items.stick, 13),
new ItemStack(Items.sign), new ItemStack(Items.sign), new ItemStack(Items.sign));
GameRegistry.addShapelessRecipe(new ItemStack(Items.stick, 8), new ItemStack(Blocks.crafting_table));
GameRegistry.addShapelessRecipe(new ItemStack(Items.stick, 16), new ItemStack(Blocks.chest));
GameRegistry.addShapelessRecipe(new ItemStack(Blocks.chest), new ItemStack(Blocks.trapped_chest));
GameRegistry.addShapelessRecipe(new ItemStack(Items.stick, 8), new ItemStack(Items.painting));
GameRegistry.addShapelessRecipe(new ItemStack(Items.stick, 8), new ItemStack(Items.item_frame));
// break down bookshelves
GameRegistry.addShapelessRecipe(new ItemStack(Items.book, 3), new ItemStack(Blocks.bookshelf));
GameRegistry.addShapelessRecipe(new ItemStack(Items.paper, 3), new ItemStack(Items.book));
// only if they have no damage
GameRegistry.addShapelessRecipe(new ItemStack(Items.string, 3), new ItemStack(Items.bow, 1, 0));
GameRegistry.addSmelting(new ItemStack(Items.flint_and_steel,1,0), new ItemStack(Items.iron_ingot, 1), EXP);
GameRegistry.addSmelting(Items.bucket, new ItemStack(Items.iron_ingot, 3, 0),EXP);
GameRegistry.addSmelting(Items.minecart, new ItemStack(Items.iron_ingot, 5, 0),EXP);
GameRegistry.addSmelting(Items.cauldron, new ItemStack(Items.iron_ingot, 7, 0),EXP);
GameRegistry.addSmelting(Items.compass, new ItemStack(Items.iron_ingot, 4, 0),EXP);
GameRegistry.addSmelting(Items.clock, new ItemStack(Items.gold_ingot, 4, 0),EXP);
GameRegistry.addSmelting(new ItemStack(Items.golden_pickaxe, 1, 0),
new ItemStack(Items.gold_ingot, 3, 0), 0);
GameRegistry.addSmelting(new ItemStack(Items.golden_axe, 1, 0),
new ItemStack(Items.gold_ingot, 3, 0), 0);
GameRegistry.addSmelting(new ItemStack(Items.golden_shovel, 1, 0),
new ItemStack(Items.gold_ingot, 1, 0), 0);
GameRegistry.addSmelting(new ItemStack(Items.golden_sword, 1, 0),
new ItemStack(Items.gold_ingot, 2, 0), 0);
GameRegistry.addSmelting(new ItemStack(Items.golden_hoe, 1, 0),
new ItemStack(Items.gold_ingot, 2, 0), 0);
GameRegistry.addSmelting(new ItemStack(Items.iron_pickaxe, 1, 0),
new ItemStack(Items.iron_ingot, 3, 0), 0);
GameRegistry.addSmelting(new ItemStack(Items.iron_axe, 1, 0),
new ItemStack(Items.iron_ingot, 3, 0), 0);
GameRegistry.addSmelting(new ItemStack(Items.iron_shovel, 1, 0),
new ItemStack(Items.iron_ingot, 1, 0), 0);
GameRegistry.addSmelting(new ItemStack(Items.iron_sword, 1, 0),
new ItemStack(Items.iron_ingot, 2, 0), 0);
GameRegistry.addSmelting(new ItemStack(Items.iron_hoe, 1, 0),
new ItemStack(Items.iron_ingot, 2, 0), 0);
GameRegistry.addSmelting(new ItemStack(Items.diamond_pickaxe, 1, 0),
new ItemStack(Items.diamond, 3, 0), 0);
GameRegistry.addSmelting(new ItemStack(Items.diamond_axe, 1, 0),
new ItemStack(Items.diamond, 3, 0), 0);
GameRegistry.addSmelting(new ItemStack(Items.diamond_shovel, 1, 0),
new ItemStack(Items.diamond, 1, 0), 0);
GameRegistry.addSmelting(new ItemStack(Items.diamond_sword, 1, 0),
new ItemStack(Items.diamond, 2, 0), 0);
GameRegistry.addSmelting(new ItemStack(Items.diamond_hoe, 1, 0),
new ItemStack(Items.diamond, 2, 0), 0);
GameRegistry.addSmelting(new ItemStack(Items.shears, 1, 0),
new ItemStack(Items.iron_ingot, 2, 0), 0);
GameRegistry.addSmelting(new ItemStack(Items.diamond_boots, 1, 0),
new ItemStack(Items.diamond, 4, 0), 0);
GameRegistry.addSmelting(new ItemStack(Items.diamond_leggings, 1, 0),
new ItemStack(Items.diamond, 7, 0), 0);
GameRegistry.addSmelting(new ItemStack(Items.diamond_chestplate, 1, 0),
new ItemStack(Items.diamond, 8, 0), 0);
GameRegistry.addSmelting(new ItemStack(Items.diamond_helmet, 1, 0),
new ItemStack(Items.diamond, 5, 0), 0);
GameRegistry.addSmelting(new ItemStack(Items.iron_boots, 1, 0),
new ItemStack(Items.iron_ingot, 4, 0), 0);
GameRegistry.addSmelting(new ItemStack(Items.iron_leggings, 1, 0),
new ItemStack(Items.iron_ingot, 7, 0), 0);
GameRegistry.addSmelting(new ItemStack(Items.iron_chestplate, 1, 0),
new ItemStack(Items.iron_ingot, 8, 0), 0);
GameRegistry.addSmelting(new ItemStack(Items.iron_helmet, 1, 0),
new ItemStack(Items.iron_ingot, 5, 0), 0);
GameRegistry.addSmelting(new ItemStack(Items.golden_boots, 1, 0),
new ItemStack(Items.gold_ingot, 4, 0), 0);
GameRegistry.addSmelting(new ItemStack(Items.golden_leggings, 1, 0),
new ItemStack(Items.gold_ingot, 7, 0), 0);
GameRegistry.addSmelting(new ItemStack(Items.golden_chestplate, 1, 0),
new ItemStack(Items.gold_ingot, 8, 0), 0);
GameRegistry.addSmelting(new ItemStack(Items.golden_helmet, 1, 0),
new ItemStack(Items.gold_ingot, 5, 0), 0);
GameRegistry.addSmelting(new ItemStack(Items.leather_boots, 1, 0),
new ItemStack(Items.leather, 4, 0), 0);
GameRegistry.addSmelting(new ItemStack(Items.leather_leggings, 1, 0),
new ItemStack(Items.leather, 7, 0), 0);
GameRegistry.addSmelting(new ItemStack(Items.leather_chestplate, 1, 0),
new ItemStack(Items.leather, 8, 0), 0);
GameRegistry.addSmelting(new ItemStack(Items.leather_helmet, 1, 0),
new ItemStack(Items.leather, 5, 0), 0);
// keeping it simple: buttons into sticks
// one blank = one button, and one plank = four sticks. so we should
// get 2 sticks per button
GameRegistry.addShapelessRecipe(new ItemStack(Blocks.piston),
new ItemStack(Blocks.sticky_piston));
GameRegistry.addShapelessRecipe(new ItemStack(Items.redstone),
new ItemStack(Blocks.piston));
GameRegistry.addSmelting(Items.iron_door, new ItemStack(Items.iron_ingot, 6), EXP);
GameRegistry.addSmelting(Blocks.daylight_detector, new ItemStack(Items.quartz, 3), EXP);
// peel the redstone off the lamp
GameRegistry.addShapelessRecipe(new ItemStack(Items.redstone, 4), new ItemStack(Blocks.redstone_lamp));
GameRegistry.addSmelting(Blocks.noteblock, new ItemStack(Items.redstone), EXP);
GameRegistry.addSmelting(Blocks.hopper, new ItemStack(Items.iron_ingot, 5), EXP);
GameRegistry.addSmelting(Blocks.redstone_lamp, new ItemStack(Blocks.glowstone), EXP);// the block
// crafting makes you lose the ball and keep piston, so this is
// reverse
GameRegistry.addSmelting(Blocks.sticky_piston, new ItemStack(Items.slime_ball), EXP);// the block
GameRegistry.addSmelting(Items.repeater, new ItemStack(Items.redstone, 3), EXP);
GameRegistry.addSmelting(Items.comparator, new ItemStack(Items.redstone, 3),EXP);
GameRegistry.addSmelting(Blocks.redstone_torch, new ItemStack(Items.redstone, 1), EXP);
GameRegistry.addShapelessRecipe(new ItemStack(Items.gold_ingot, 2),
new ItemStack(Blocks.light_weighted_pressure_plate));
GameRegistry.addShapelessRecipe(new ItemStack(Items.iron_ingot, 2),
new ItemStack(Blocks.heavy_weighted_pressure_plate));
GameRegistry.addShapelessRecipe(new ItemStack(Blocks.stone, 2),
new ItemStack(Blocks.stone_pressure_plate));
GameRegistry.addShapelessRecipe(new ItemStack(Items.stick, 4),
new ItemStack(Blocks.wooden_pressure_plate));
GameRegistry.addShapelessRecipe(new ItemStack(Items.redstone), new ItemStack(Blocks.dispenser));
GameRegistry.addShapelessRecipe(new ItemStack(Items.redstone), new ItemStack(Blocks.dropper));
GameRegistry.addShapelessRecipe(new ItemStack(Items.iron_ingot),
new ItemStack(Blocks.tripwire_hook), new ItemStack(Blocks.tripwire_hook));
// 6 planks = craft sticks three times = 12 sticks = 2 trapdoors
GameRegistry.addShapelessRecipe(new ItemStack(Items.stick, 12),
new ItemStack(Blocks.trapdoor), new ItemStack(Blocks.trapdoor));
// 6 sticks = 2 fence , therefore 1 fence becomes 3 sticks
// 8 sticks is one fence gate .
GameRegistry.addShapelessRecipe(new ItemStack(Items.stick, 4),
new ItemStack(Blocks.wooden_button),
new ItemStack(Blocks.wooden_button));
// stone buttons back to stone as well
GameRegistry.addShapelessRecipe(new ItemStack(Blocks.stone),
new ItemStack(Blocks.stone_button),
new ItemStack(Blocks.stone_button));
GameRegistry.addShapelessRecipe(new ItemStack(Items.quartz), new ItemStack(Items.comparator));
// SMELTING IS (input , output)
GameRegistry.addSmelting(Blocks.trapped_chest, new ItemStack(Blocks.tripwire_hook), EXP);
GameRegistry.addSmelting(Blocks.stone_pressure_plate, new ItemStack( Blocks.stone, 1), EXP);
GameRegistry.addSmelting(Blocks.wooden_pressure_plate, new ItemStack( Items.stick, 2), EXP);
// all the rails!!
GameRegistry.addShapelessRecipe(new ItemStack(Items.gold_ingot, 6),
new ItemStack(Blocks.golden_rail), new ItemStack(Blocks.golden_rail),
new ItemStack(Blocks.golden_rail), new ItemStack(Blocks.golden_rail),
new ItemStack(Blocks.golden_rail), new ItemStack(Blocks.golden_rail));
GameRegistry.addShapelessRecipe(new ItemStack(Items.iron_ingot, 6),
new ItemStack(Blocks.detector_rail), new ItemStack(Blocks.detector_rail),
new ItemStack(Blocks.detector_rail), new ItemStack(Blocks.detector_rail),
new ItemStack(Blocks.detector_rail), new ItemStack(Blocks.detector_rail));
GameRegistry.addShapelessRecipe(new ItemStack(Items.iron_ingot, 6),
new ItemStack(Blocks.activator_rail),
new ItemStack(Blocks.activator_rail),
new ItemStack(Blocks.activator_rail),
new ItemStack(Blocks.activator_rail),
new ItemStack(Blocks.activator_rail),
new ItemStack(Blocks.activator_rail));
GameRegistry.addShapelessRecipe(new ItemStack(Items.iron_ingot, 3),
new ItemStack(Blocks.rail)
, new ItemStack(Blocks.rail)
, new ItemStack(Blocks.rail)
, new ItemStack(Blocks.rail)
, new ItemStack(Blocks.rail)
, new ItemStack(Blocks.rail)
, new ItemStack(Blocks.rail)
, new ItemStack(Blocks.rail));
GameRegistry.addSmelting(Blocks.dropper, new ItemStack(Blocks.cobblestone, 8),EXP);
GameRegistry.addSmelting(Blocks.dispenser, new ItemStack(Blocks.cobblestone, 8),EXP);
GameRegistry.addSmelting(Blocks.piston, new ItemStack(Items.iron_ingot), EXP);
GameRegistry.addShapelessRecipe(new ItemStack(Blocks.pumpkin), new ItemStack(Blocks.lit_pumpkin));
GameRegistry.addShapelessRecipe(new ItemStack(Items.melon, 9), new ItemStack(Blocks.melon_block));
GameRegistry.addSmelting(Items.golden_carrot, new ItemStack(Items.gold_nugget, 8), EXP);
GameRegistry.addSmelting(new ItemStack(Items.golden_apple, 1, 0),
new ItemStack(Items.gold_ingot, 8), EXP);
GameRegistry.addSmelting(new ItemStack(Items.golden_apple, 1, 1),
new ItemStack(Blocks.gold_block, 8), EXP);
// get 4 string back from wool (white only, that's okay)
GameRegistry.addShapelessRecipe(new ItemStack(Items.string, 4), new ItemStack(Blocks.wool));
GameRegistry.addShapelessRecipe(new ItemStack(Blocks.wool, 3),
new ItemStack(Items.bed));
for (int color = 0; color < 16; color++)
{
// since normally we have 2 wool making 3 carpet, we do the
// reverse here
GameRegistry.addShapelessRecipe(new ItemStack(Blocks.wool, 2, color),
new ItemStack(Blocks.carpet, 1, color)
, new ItemStack(Blocks.carpet, 1, color)
, new ItemStack(Blocks.carpet, 1, color));
}
GameRegistry.addSmelting(Blocks.sandstone, new ItemStack(Blocks.sand, 4), EXP);
// all damage values into empty//1 for chiseled 2 for pillar
GameRegistry.addShapelessRecipe(new ItemStack(Blocks.quartz_block, 1, Reference.quartz_block),
new ItemStack(Blocks.quartz_block, 1, Reference.quartz_chiselled));
GameRegistry.addShapelessRecipe(new ItemStack(Blocks.quartz_block, 1, Reference.quartz_block),
new ItemStack(Blocks.quartz_block, 1, Reference.quartz_pillar));
GameRegistry.addShapelessRecipe(new ItemStack(Items.quartz, 4),
new ItemStack(Blocks.quartz_block));
GameRegistry.addShapelessRecipe(new ItemStack(Items.glowstone_dust, 4),
new ItemStack(Blocks.glowstone));
GameRegistry.addSmelting(Blocks.nether_brick, new ItemStack(Items.netherbrick, 4), EXP);
GameRegistry.addSmelting(Blocks.stained_hardened_clay, new ItemStack(Blocks.hardened_clay), EXP);
// smelt red brick into component parts
GameRegistry.addSmelting(Blocks.brick_block, new ItemStack(Items.brick, 4), EXP);
GameRegistry.addShapelessRecipe(new ItemStack(Blocks.dirt), new ItemStack(Blocks.grass));
GameRegistry.addShapelessRecipe(new ItemStack(Blocks.dirt), new ItemStack(Blocks.mycelium));
// smelt smoothstone to uncraft it into cobblestone
GameRegistry.addSmelting(Blocks.stone, new ItemStack(Blocks.cobblestone), 0);
GameRegistry.addShapelessRecipe(new ItemStack(Items.snowball, 4), new ItemStack(Blocks.snow));
// three blocks give us six layers, so this is reverse
GameRegistry.addRecipe(new ItemStack(Blocks.snow, 3), " ", "xxx", "xxx", 'x', Blocks.snow_layer);
GameRegistry.addRecipe(new ItemStack(Blocks.snow, 3), "xxx", "xxx", " ", 'x', Blocks.snow_layer);
// craft clay block into four balls, avoid using shovel
GameRegistry.addShapelessRecipe(new ItemStack(Items.clay_ball, 4), new ItemStack(Blocks.clay));
// remember, craft is output , input, OPPOSITE OF SMELT
GameRegistry.addRecipe(new ItemStack(Blocks.stone, 4), "xx", "xx", 'x', Blocks.stonebrick);
//three glass blocks makes three bottles, so this reverses it
GameRegistry.addSmelting(Items.glass_bottle, new ItemStack(Blocks.glass), EXP);
// also, since 6 blocks is 16 panes, we cut that in half and get 8
// panes into three blocks
GameRegistry.addShapelessRecipe(new ItemStack(Blocks.glass, 3),
new ItemStack(Blocks.glass_pane), new ItemStack(Blocks.glass_pane),
new ItemStack(Blocks.glass_pane), new ItemStack(Blocks.glass_pane),
new ItemStack(Blocks.glass_pane), new ItemStack(Blocks.glass_pane),
new ItemStack(Blocks.glass_pane), new ItemStack(Blocks.glass_pane));
GameRegistry.addSmelting(Blocks.glass, new ItemStack(Blocks.sand), EXP);
GameRegistry.addSmelting(Blocks.stained_glass, new ItemStack(Blocks.glass, 1, 0),EXP);
GameRegistry.addSmelting(Blocks.stained_glass_pane, new ItemStack(Blocks.glass_pane, 1, 0), EXP);
GameRegistry.addSmelting(Blocks.brewing_stand, new ItemStack(Items.blaze_rod), EXP);
GameRegistry.addShapelessRecipe(new ItemStack(Items.gunpowder, 5),
new ItemStack(Blocks.tnt));
// un damaged anvil gives all, damged gives you either one or two
GameRegistry.addShapelessRecipe(new ItemStack(Items.iron_ingot, 31),
new ItemStack(Blocks.anvil, 1, 0));
GameRegistry.addShapelessRecipe(new ItemStack(Items.iron_ingot, 18),
new ItemStack(Blocks.anvil, 1, 1));
GameRegistry.addShapelessRecipe(new ItemStack(Items.iron_ingot, 9),
new ItemStack(Blocks.anvil, 1, 2));
GameRegistry.addRecipe(new ItemStack(Blocks.nether_brick, 6), " ",
"xxx", "xxx", 'x', Blocks.nether_brick_fence);
GameRegistry.addSmelting(new ItemStack(Blocks.flower_pot), new ItemStack( Items.brick, 3), EXP);
GameRegistry.addSmelting(Items.magma_cream, new ItemStack(Items.slime_ball), EXP);
GameRegistry.addSmelting(Items.item_frame, new ItemStack(Items.leather), EXP);
GameRegistry.addSmelting(Blocks.jukebox, new ItemStack(Items.diamond), EXP);
// back into an eye
GameRegistry.addSmelting(Items.ender_eye, new ItemStack(Items.ender_pearl), EXP);
// only regular sandstone
GameRegistry.addSmelting(Blocks.furnace, new ItemStack(Blocks.cobblestone, 8),EXP);
// un-enchant any book
GameRegistry.addSmelting(Items.enchanted_book, new ItemStack(Items.book, 1, 0), EXP);
//2 diamonds from the table
GameRegistry.addSmelting(Blocks.enchanting_table, new ItemStack(Items.diamond,2), EXP);
// remove dye from hardened clay
GameRegistry.addSmelting(Items.book, new ItemStack(Items.leather, 1), EXP);
GameRegistry.addSmelting(Items.filled_map, new ItemStack(Items.compass), EXP);
GameRegistry.addSmelting(Items.map, new ItemStack(Items.compass), EXP);
// same setup for cobble wall, turn them back into blocks
GameRegistry.addRecipe(new ItemStack(Blocks.cobblestone, 6), " ", "xxx","xxx",
'x', new ItemStack(Blocks.cobblestone_wall, 1, Reference.cobblestone_wall_plain));
GameRegistry.addRecipe(new ItemStack(Blocks.mossy_cobblestone, 6), " ","xxx", "xxx",
'x', new ItemStack(Blocks.cobblestone_wall, 1, Reference.cobblestone_wall_mossy));
GameRegistry.addShapelessRecipe(new ItemStack(Blocks.obsidian, 8),
new ItemStack(Blocks.ender_chest));
// / lead to slime, since its one slime that gives 2 leads anyway
GameRegistry.addShapelessRecipe(new ItemStack(Items.slime_ball, 2),
new ItemStack(Items.lead), new ItemStack(Items.lead));
}
public static void records()
{
if(!ModMain.cfg.craftableTransmuteRecords) {return;}
// iterate down the list, 8 emeralds each time
GameRegistry.addRecipe(new ItemStack(Items.record_13), "xxx", "xsx","xxx"
, 'x', new ItemStack(Items.emerald)
, 's', new ItemStack(Items.record_blocks));
GameRegistry.addRecipe(new ItemStack(Items.record_blocks), "xxx", "xsx","xxx"
, 'x', new ItemStack(Items.emerald)
, 's', new ItemStack(Items.record_chirp));
GameRegistry.addRecipe(new ItemStack(Items.record_chirp), "xxx", "xsx","xxx"
, 'x', new ItemStack(Items.emerald)
, 's', new ItemStack(Items.record_far));
GameRegistry.addRecipe(new ItemStack(Items.record_far), "xxx", "xsx","xxx"
, 'x', new ItemStack(Items.emerald)
, 's', new ItemStack(Items.record_mall));
GameRegistry.addRecipe(new ItemStack(Items.record_mall), "xxx", "xsx",
"xxx", 'x', new ItemStack(Items.emerald), 's', new ItemStack(
Items.record_mellohi));
GameRegistry.addRecipe(new ItemStack(Items.record_mellohi), "xxx", "xsx",
"xxx", 'x', new ItemStack(Items.emerald), 's', new ItemStack(
Items.record_cat));
GameRegistry.addRecipe(new ItemStack(Items.record_cat), "xxx", "xsx",
"xxx", 'x', new ItemStack(Items.emerald), 's', new ItemStack(
Items.record_stal));
GameRegistry.addRecipe(new ItemStack(Items.record_stal), "xxx", "xsx",
"xxx", 'x', new ItemStack(Items.emerald), 's', new ItemStack(
Items.record_strad));
GameRegistry.addRecipe(new ItemStack(Items.record_strad), "xxx", "xsx",
"xxx", 'x', new ItemStack(Items.emerald), 's', new ItemStack(
Items.record_ward));
GameRegistry.addRecipe(new ItemStack(Items.record_ward), "xxx", "xsx",
"xxx", 'x', new ItemStack(Items.emerald), 's', new ItemStack(
Items.record_11));
GameRegistry.addRecipe(new ItemStack(Items.record_11), "xxx", "xsx",
"xxx", 'x', new ItemStack(Items.emerald), 's', new ItemStack(
Items.record_wait));
GameRegistry.addRecipe(new ItemStack(Items.record_wait), "xxx", "xsx",
"xxx", 'x', new ItemStack(Items.emerald), 's', new ItemStack(
Items.record_13));
}
public static void bonemealWool()
{
if(!ModMain.cfg.craftableBonemealColouredWool){return;}
//use bonemeal to bleach colored wool back to white
GameRegistry.addShapelessRecipe(new ItemStack(Blocks.wool, 1, 0),
new ItemStack(Blocks.wool, 1, 1), new ItemStack(Items.dye, 1, Reference.dye_bonemeal));
GameRegistry.addShapelessRecipe(new ItemStack(Blocks.wool, 1, 0),
new ItemStack(Blocks.wool, 1, 2), new ItemStack(Items.dye, 1, Reference.dye_bonemeal));
GameRegistry.addShapelessRecipe(new ItemStack(Blocks.wool, 1, 0),
new ItemStack(Blocks.wool, 1, 3), new ItemStack(Items.dye, 1, Reference.dye_bonemeal));
GameRegistry.addShapelessRecipe(new ItemStack(Blocks.wool, 1, 0),
new ItemStack(Blocks.wool, 1, 4), new ItemStack(Items.dye, 1, Reference.dye_bonemeal));
GameRegistry.addShapelessRecipe(new ItemStack(Blocks.wool, 1, 0),
new ItemStack(Blocks.wool, 1, 5), new ItemStack(Items.dye, 1, Reference.dye_bonemeal));
GameRegistry.addShapelessRecipe(new ItemStack(Blocks.wool, 1, 0),
new ItemStack(Blocks.wool, 1, 6), new ItemStack(Items.dye, 1, Reference.dye_bonemeal));
GameRegistry.addShapelessRecipe(new ItemStack(Blocks.wool, 1, 0),
new ItemStack(Blocks.wool, 1, 7), new ItemStack(Items.dye, 1, Reference.dye_bonemeal));
GameRegistry.addShapelessRecipe(new ItemStack(Blocks.wool, 1, 0),
new ItemStack(Blocks.wool, 1, 8), new ItemStack(Items.dye, 1, Reference.dye_bonemeal));
GameRegistry.addShapelessRecipe(new ItemStack(Blocks.wool, 1, 0),
new ItemStack(Blocks.wool, 1, 9), new ItemStack(Items.dye, 1, Reference.dye_bonemeal));
GameRegistry.addShapelessRecipe(new ItemStack(Blocks.wool, 1, 0),
new ItemStack(Blocks.wool, 1, 10), new ItemStack(Items.dye, 1, Reference.dye_bonemeal));
GameRegistry.addShapelessRecipe(new ItemStack(Blocks.wool, 1, 0),
new ItemStack(Blocks.wool, 1, 11), new ItemStack(Items.dye, 1, Reference.dye_bonemeal));
GameRegistry.addShapelessRecipe(new ItemStack(Blocks.wool, 1, 0),
new ItemStack(Blocks.wool, 1, 12), new ItemStack(Items.dye, 1, Reference.dye_bonemeal));
GameRegistry.addShapelessRecipe(new ItemStack(Blocks.wool, 1, 0),
new ItemStack(Blocks.wool, 1, 13), new ItemStack(Items.dye, 1, Reference.dye_bonemeal));
GameRegistry.addShapelessRecipe(new ItemStack(Blocks.wool, 1, 0),
new ItemStack(Blocks.wool, 1, 14), new ItemStack(Items.dye, 1, Reference.dye_bonemeal));
GameRegistry.addShapelessRecipe(new ItemStack(Blocks.wool, 1, 0),
new ItemStack(Blocks.wool, 1, 15), new ItemStack(Items.dye, 1, Reference.dye_bonemeal));
}
/*
public static void bookNoLeather()
{
if(!ModMain.cfg.craftBooksWithoutLeather) {return;}
GameRegistry.addShapelessRecipe(new ItemStack(Items.book,1)
,new ItemStack(Items.paper)
,new ItemStack(Items.paper)
,new ItemStack(Items.paper) );
}
*/
public static void repeaterSimple()
{
if(!ModMain.cfg.craftRepeaterSimple) {return;}
GameRegistry.addRecipe(new ItemStack(Items.repeater), "r r", "srs","ttt"
, 't', new ItemStack(Blocks.stone)
, 's', new ItemStack(Items.stick)
, 'r', new ItemStack(Items.redstone) );
}
public static void minecartsSimple()
{
if(!ModMain.cfg.craftMinecartsSimple){return;}
//normally you would need the minecart created in a different step. this is faster
GameRegistry.addRecipe(new ItemStack(Items.chest_minecart),
" ","ici", "iii",
'i', Items.iron_ingot,
'c', Blocks.chest);
GameRegistry.addRecipe(new ItemStack(Items.tnt_minecart),
" ","ici", "iii",
'i', Items.iron_ingot,
'c', Blocks.tnt);
GameRegistry.addRecipe(new ItemStack(Items.hopper_minecart),
" ","ici", "iii",
'i', Items.iron_ingot,
'c', Blocks.hopper);
GameRegistry.addRecipe(new ItemStack(Items.furnace_minecart),
" ","ici", "iii",
'i', Items.iron_ingot,
'c', Blocks.furnace);
}
public static void woolDyeSavings()
{
if(!ModMain.cfg.craftWoolDye8) {return;}
//so any color that is not white, add the new recipe with all 8 blocks
for(int dye = 0; dye < 15; dye++)//only since we know that the dyes are these numbers
{
if(dye != Reference.dye_bonemeal)
{
//removeRecipe(new ItemStack(Blocks.wool,1,dye));
GameRegistry.addRecipe(new ItemStack(Blocks.wool,8,dye),
"www","wdw", "www",
'w', new ItemStack(Blocks.wool,1,Reference.dye_bonemeal),
'd', new ItemStack(Items.dye,1, dye));
}
}
}
public static void furnaceNeedsCoal()
{
if(!ModMain.cfg.furnaceNeedsCoal) {return;}
removeRecipe(Blocks.furnace);
GameRegistry.addRecipe(new ItemStack(Blocks.furnace),
"bbb",
"bcb",
"bbb",
'b', Blocks.cobblestone,
'c', Items.coal );
}
public static void smoothstoneRequired()
{
if(!ModMain.cfg.smoothstoneTools) {return;}
removeRecipe(Items.stone_pickaxe);
GameRegistry.addRecipe(new ItemStack(Items.stone_pickaxe,1,Util.getMaxDmgFraction(Items.stone_pickaxe,4)),
"sss",
" t ",
" t ",
's', Blocks.cobblestone,
't', Items.stick );
GameRegistry.addRecipe(new ItemStack(Items.stone_pickaxe),
"sss",
" t ",
" t ",
's', Blocks.stone,
't', Items.stick );
removeRecipe(Items.stone_sword);
GameRegistry.addRecipe(new ItemStack(Items.stone_sword,1,Util.getMaxDmgFraction(Items.stone_sword,4)),
" s ",
" s ",
" t ",
's', Blocks.cobblestone,
't', Items.stick );
GameRegistry.addRecipe(new ItemStack(Items.stone_sword),
" s ",
" s ",
" t ",
's', Blocks.stone,
't', Items.stick );
removeRecipe(Items.stone_axe);
GameRegistry.addRecipe(new ItemStack(Items.stone_axe,1,Util.getMaxDmgFraction(Items.stone_axe,4)),
"ss ",
"st ",
" t ",
's', Blocks.cobblestone,
't', Items.stick );
GameRegistry.addRecipe(new ItemStack(Items.stone_axe,1,Util.getMaxDmgFraction(Items.stone_axe,4)),
" ss",
" ts",
" t ",
's', Blocks.cobblestone,
't', Items.stick );
GameRegistry.addRecipe(new ItemStack(Items.stone_axe),
"ss ",
"st ",
" t ",
's', Blocks.stone,
't', Items.stick );
GameRegistry.addRecipe(new ItemStack(Items.stone_axe),
" ss",
" ts",
" t ",
's', Blocks.stone,
't', Items.stick );
removeRecipe(Items.stone_hoe);
GameRegistry.addRecipe(new ItemStack(Items.stone_hoe,1,Util.getMaxDmgFraction(Items.stone_hoe,4)),
"ss ",
" t ",
" t ",
's', Blocks.cobblestone,
't', Items.stick );
GameRegistry.addRecipe(new ItemStack(Items.stone_hoe,1,Util.getMaxDmgFraction(Items.stone_hoe,4)),
" ss",
" t ",
" t ",
's', Blocks.cobblestone,
't', Items.stick );
GameRegistry.addRecipe(new ItemStack(Items.stone_hoe),
"ss ",
" t ",
" t ",
's', Blocks.stone,
't', Items.stick );
GameRegistry.addRecipe(new ItemStack(Items.stone_hoe),
" ss",
" t ",
" t ",
's', Blocks.stone,
't', Items.stick );
removeRecipe(Items.stone_shovel);
GameRegistry.addRecipe(new ItemStack(Items.stone_shovel,1,Util.getMaxDmgFraction(Items.stone_shovel,4)),
" s ",
" t ",
" t ",
's', Blocks.cobblestone,
't', Items.stick );
GameRegistry.addRecipe(new ItemStack(Items.stone_shovel),
" s ",
" t ",
" t ",
's', Blocks.stone,
't', Items.stick );
}
public static void tieredArmor()
{
if(ModMain.cfg.iron_armor_requires_leather)
{
removeRecipe(Items.iron_chestplate);
removeRecipe(Items.iron_boots);
removeRecipe(Items.iron_leggings);
removeRecipe(Items.iron_helmet);
GameRegistry.addRecipe(new ItemStack(Items.iron_chestplate),
"ixi",
"iii",
"iii",
'i', Items.iron_ingot,
'x', new ItemStack(Items.leather_chestplate ,1,OreDictionary.WILDCARD_VALUE));
GameRegistry.addRecipe(new ItemStack(Items.iron_boots),
" ",
"i i",
"ixi",
'i', Items.iron_ingot,
'x', new ItemStack(Items.leather_boots ,1,OreDictionary.WILDCARD_VALUE));
GameRegistry.addRecipe(new ItemStack(Items.iron_leggings),
"iii",
"ixi",
"i i",
'i', Items.iron_ingot,
'x', new ItemStack(Items.leather_leggings,1,OreDictionary.WILDCARD_VALUE));
GameRegistry.addRecipe(new ItemStack(Items.iron_helmet),
"iii",
"ixi",
" ",
'i', Items.iron_ingot,
'x', new ItemStack(Items.leather_helmet,1,OreDictionary.WILDCARD_VALUE));
}
if(ModMain.cfg.diamond_armor_requires_iron)
{
removeRecipe(Items.diamond_chestplate);
removeRecipe(Items.diamond_boots);
removeRecipe(Items.diamond_leggings);
removeRecipe(Items.diamond_helmet);
GameRegistry.addRecipe(new ItemStack(Items.diamond_chestplate),
"ixi",
"iii",
"iii",
'i', Items.diamond,
'x', new ItemStack(Items.iron_chestplate ,1,OreDictionary.WILDCARD_VALUE));
GameRegistry.addRecipe(new ItemStack(Items.diamond_boots),
" ",
"i i",
"ixi",
'i', Items.diamond,
'x', new ItemStack(Items.iron_boots ,1,OreDictionary.WILDCARD_VALUE));
GameRegistry.addRecipe(new ItemStack(Items.diamond_leggings),
"iii",
"ixi",
"i i",
'i', Items.diamond,
'x', new ItemStack(Items.iron_leggings ,1,OreDictionary.WILDCARD_VALUE));
GameRegistry.addRecipe(new ItemStack(Items.diamond_helmet),
"iii",
"ixi",
" ",
'i', Items.diamond,
'x', new ItemStack(Items.iron_helmet ,1,OreDictionary.WILDCARD_VALUE));
}
}
public static void simpleDispenser()
{
if(!ModMain.cfg.simpleDispenser) {return;}
GameRegistry.addRecipe(new ItemStack(Blocks.dispenser),
"ccc",
"csc",
"crc",
'c', Blocks.cobblestone,
's', Items.string,
'r', Items.redstone );
}
private static void removeRecipe(Item resultItem)
{
removeRecipe(new ItemStack(resultItem));
}
private static void removeRecipe(Block resultItem)
{
removeRecipe(new ItemStack(resultItem));
}
private static void removeRecipe(ItemStack resultItem)
{
//REFERENCES
List<IRecipe> recipes = CraftingManager.getInstance().getRecipeList();
IRecipe tmpRecipe;
ItemStack recipeResult;
for (int i = 0; i < recipes.size(); i++)
{
tmpRecipe = recipes.get(i);
recipeResult = tmpRecipe.getRecipeOutput();
if( recipeResult != null &&
ItemStack.areItemStacksEqual(resultItem, recipeResult))
{
recipes.remove(i
}
}
}
} |
// begin imports
import net.minecraft.client.model.ModelBase;
import net.minecraft.client.renderer.entity.RenderLiving;
import net.minecraft.util.ResourceLocation;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.EntityLivingBase;
// end imports
//begin class
public class EntityNoisestorm extends RenderLiving {
} |
package com.redhat.ceylon.compiler.js;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.io.Writer;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import net.minidev.json.JSONObject;
import com.redhat.ceylon.cmr.api.ArtifactContext;
import com.redhat.ceylon.cmr.api.RepositoryManager;
import com.redhat.ceylon.cmr.api.SourceArchiveCreator;
import com.redhat.ceylon.cmr.ceylon.CeylonUtils;
import com.redhat.ceylon.cmr.impl.JULLogger;
import com.redhat.ceylon.cmr.impl.ShaSigner;
import com.redhat.ceylon.compiler.Options;
import com.redhat.ceylon.compiler.typechecker.TypeChecker;
import com.redhat.ceylon.compiler.typechecker.analyzer.AnalysisError;
import com.redhat.ceylon.compiler.typechecker.analyzer.UsageWarning;
import com.redhat.ceylon.compiler.typechecker.context.PhasedUnit;
import com.redhat.ceylon.compiler.typechecker.model.Module;
import com.redhat.ceylon.compiler.typechecker.model.TypedDeclaration;
import com.redhat.ceylon.compiler.typechecker.model.Unit;
import com.redhat.ceylon.compiler.typechecker.parser.RecognitionError;
import com.redhat.ceylon.compiler.typechecker.tree.AnalysisMessage;
import com.redhat.ceylon.compiler.typechecker.tree.Message;
import com.redhat.ceylon.compiler.typechecker.tree.Node;
import com.redhat.ceylon.compiler.typechecker.tree.Tree;
import com.redhat.ceylon.compiler.typechecker.tree.UnexpectedError;
import com.redhat.ceylon.compiler.typechecker.tree.Visitor;
public class JsCompiler {
protected final TypeChecker tc;
protected final Options opts;
protected final RepositoryManager outRepo;
private boolean stopOnErrors = true;
private int errCount = 0;
protected Set<Message> errors = new HashSet<Message>();
protected Set<Message> unitErrors = new HashSet<Message>();
protected List<String> files;
private final Map<Module, JsOutput> output = new HashMap<Module, JsOutput>();
//You have to manually set this when compiling the language module
static boolean compilingLanguageModule;
private TypeUtils types;
private final Visitor unitVisitor = new Visitor() {
private boolean hasErrors(Node that) {
for (Message m: that.getErrors()) {
if (m instanceof AnalysisError) {
return true;
}
}
return false;
}
@Override
public void visitAny(Node that) {
super.visitAny(that);
for (Message err: that.getErrors()) {
unitErrors.add(err);
}
}
@Override
public void visit(Tree.ImportMemberOrType that) {
if (hasErrors(that)) return;
Unit u = that.getImportModel().getDeclaration().getUnit();
if ((u.getFilename() != null && !u.getFilename().endsWith(".ceylon"))
|| u.getPackage().getModule().isJava()) {
that.addUnexpectedError("cannot import Java declarations in Javascript");
}
super.visit(that);
}
@Override
public void visit(Tree.ImportModule that) {
if (hasErrors(that)) return;
if (((Module)that.getImportPath().getModel()).isJava()) {
that.getImportPath().addUnexpectedError("cannot import Java modules in Javascript");
}
super.visit(that);
}
@Override
public void visit(Tree.BaseMemberOrTypeExpression that) {
if (hasErrors(that)) return;
if (that.getDeclaration() != null && that.getDeclaration().getUnit() != null) {
Unit u = that.getDeclaration().getUnit();
if ((u.getFilename() != null && !u.getFilename().endsWith(".ceylon"))
|| (u.getPackage() != null && u.getPackage().getModule() != null && u.getPackage().getModule().isJava())) {
that.addUnexpectedError("cannot call Java declarations in Javascript");
}
}
super.visit(that);
}
@Override
public void visit(Tree.QualifiedMemberOrTypeExpression that) {
if (hasErrors(that)) return;
if (that.getDeclaration() != null && that.getDeclaration().getUnit() != null) {
Unit u = that.getDeclaration().getUnit();
if ((u.getFilename() != null && !u.getFilename().endsWith(".ceylon"))
|| (u.getPackage() != null && u.getPackage().getModule() != null && u.getPackage().getModule().isJava())) {
that.addUnexpectedError("cannot call Java declarations in Javascript");
}
}
super.visit(that);
}
};
public JsCompiler(TypeChecker tc, Options options) {
this.tc = tc;
opts = options;
outRepo = CeylonUtils.repoManager()
.outRepo(options.getOutDir())
.user(options.getUser())
.password(options.getPass())
.buildOutputManager();
String outDir = options.getOutDir();
if(!isURL(outDir)){
File root = new File(outDir);
if (root.exists()) {
if (!(root.isDirectory() && root.canWrite())) {
System.err.printf("Cannot write to %s. Stop.%n", root);
}
} else {
if (!root.mkdirs()) {
System.err.printf("Cannot create %s. Stop.%n", root);
}
}
}
types = new TypeUtils(tc.getContext().getModules().getLanguageModule());
}
private boolean isURL(String path) {
try {
new URL(path);
return true;
} catch (MalformedURLException e) {
return false;
}
}
/** Specifies whether the compiler should stop when errors are found in a compilation unit (default true). */
public JsCompiler stopOnErrors(boolean flag) {
stopOnErrors = flag;
return this;
}
/** Sets the names of the files to compile. By default this is null, which means all units from the typechecker
* will be compiled. */
public void setFiles(List<String> files) {
this.files = files;
}
public Set<Message> listErrors() {
return getErrors();
}
/** Compile one phased unit.
* @return The errors found for the unit. */
public Set<Message> compileUnit(PhasedUnit pu, JsIdentifierNames names) throws IOException {
unitErrors.clear();
pu.getCompilationUnit().visit(unitVisitor);
if (errCount == 0 || !stopOnErrors) {
if (opts.isVerbose()) {
System.out.printf("%nCompiling %s to JS%n", pu.getUnitFile().getPath());
}
//Perform capture analysis
for (com.redhat.ceylon.compiler.typechecker.model.Declaration d : pu.getDeclarations()) {
if (d instanceof TypedDeclaration && d instanceof com.redhat.ceylon.compiler.typechecker.model.Setter == false) {
pu.getCompilationUnit().visit(new ValueVisitor((TypedDeclaration)d));
}
}
JsOutput jsout = getOutput(pu);
GenerateJsVisitor jsv = new GenerateJsVisitor(jsout, opts, names, pu.getTokens(), types);
pu.getCompilationUnit().visit(jsv);
pu.getCompilationUnit().visit(unitVisitor);
}
return unitErrors;
}
/** Indicates if compilation should stop, based on whether there were errors
* in the last compilation unit and the stopOnErrors flag is set. */
protected boolean stopOnError() {
for (Message err : unitErrors) {
if (err instanceof AnalysisError ||
err instanceof UnexpectedError) {
errCount++;
}
errors.add(err);
}
return stopOnErrors && errCount > 0;
}
/** Compile all the phased units in the typechecker.
* @return true is compilation was successful (0 errors/warnings), false otherwise. */
public boolean generate() throws IOException {
errors.clear();
errCount = 0;
output.clear();
try {
if (opts.isVerbose()) {
System.out.println("Generating metamodel...");
}
//First generate the metamodel
for (PhasedUnit pu: tc.getPhasedUnits().getPhasedUnits()) {
String pathFromVFS = pu.getUnitFile().getPath();
// VFS talks in terms of URLs while files are platform-dependent, so make it
// platform-dependent too
String path = pathFromVFS.replace('/', File.separatorChar);
if (files == null || files.contains(path)) {
pu.getCompilationUnit().visit(getOutput(pu).mmg);
if (opts.isVerbose()) {
System.out.println(pu.getCompilationUnit());
}
}
}
//Then write it out
if (!compilingLanguageModule) {
for (Map.Entry<Module,JsOutput> e : output.entrySet()) {
e.getValue().getWriter().write("var $$METAMODEL$$=");
e.getValue().getWriter().write(JSONObject.toJSONString(e.getValue().mmg.getModel()));
e.getValue().getWriter().write(";\nexports.$$METAMODEL$$=function(){return $$METAMODEL$$;};\n");
}
}
//Then generate the JS code
JsIdentifierNames names = new JsIdentifierNames();
if (files == null) {
for (PhasedUnit pu: tc.getPhasedUnits().getPhasedUnits()) {
String pathFromVFS = pu.getUnitFile().getPath();
// VFS talks in terms of URLs while files are platform-dependent, so make it
// platform-dependent too
String path = pathFromVFS.replace('/', File.separatorChar);
if (files == null || files.contains(path)) {
compileUnit(pu, names);
if (stopOnError()) {
System.err.println("Errors found. Compilation stopped.");
break;
}
getOutput(pu).addSource(pu.getUnit().getFullPath());
} else {
if (opts.isVerbose()) {
System.err.println("Files does not contain "+path);
for (String p : files) {
System.err.println(" Files: "+p);
}
}
}
}
} else if(!tc.getPhasedUnits().getPhasedUnits().isEmpty()){
final List<PhasedUnit> units = tc.getPhasedUnits().getPhasedUnits();
PhasedUnit lastUnit = units.get(0);
for (String path : files) {
if (path.endsWith(".js")) {
//Just output the file
File f = new File(path);
final JsOutput lastOut = getOutput(lastUnit);
try (BufferedReader reader = new BufferedReader(new FileReader(f))) {
String line = null;
while ((line = reader.readLine()) != null) {
lastOut.getWriter().write(line);
lastOut.getWriter().write('\n');
}
} finally {
lastOut.addSource(path);
}
} else {
//Find the corresponding compilation unit
for (PhasedUnit pu : units) {
String unitPath = pu.getUnitFile().getPath().replace('/', File.separatorChar);
if (path.equals(unitPath)) {
compileUnit(pu, names);
if (stopOnError()) {
System.err.println("Errors found. Compilation stopped.");
break;
}
getOutput(pu).addSource(pu.getUnit().getFullPath());
lastUnit = pu;
}
}
}
}
}else{
System.err.println("No source units found to compile");
}
} finally {
finish();
}
return errCount == 0;
}
/** Creates a JsOutput if needed, for the PhasedUnit.
* Right now it's one file per module. */
private JsOutput getOutput(PhasedUnit pu) throws IOException {
Module mod = pu.getPackage().getModule();
JsOutput jsout = output.get(mod);
if (jsout==null) {
jsout = newJsOutput(mod);
output.put(mod, jsout);
if (opts.isModulify()) {
beginWrapper(jsout.getWriter());
}
}
return jsout;
}
/** This exists solely so that the web IDE can override it and use a different JsOutput */
protected JsOutput newJsOutput(Module m) throws IOException {
return new JsOutput(m, opts.getEncoding());
}
/** Closes all output writers and puts resulting artifacts in the output repo. */
protected void finish() throws IOException {
for (Map.Entry<Module,JsOutput> entry: output.entrySet()) {
JsOutput jsout = entry.getValue();
if (opts.isModulify()) {
endWrapper(jsout.getWriter());
}
String moduleName = entry.getKey().getNameAsString();
String moduleVersion = entry.getKey().getVersion();
//Create the JS file
File jsart = entry.getValue().close();
ArtifactContext artifact = new ArtifactContext(moduleName, moduleVersion, ArtifactContext.JS);
if (entry.getKey().isDefault()) {
System.err.println("Created module "+moduleName);
} else {
System.err.println("Created module "+moduleName+"/"+moduleVersion);
}
outRepo.putArtifact(artifact, jsart);
//js file signature
artifact.setForceOperation(true);
ArtifactContext sha1Context = artifact.getSha1Context();
sha1Context.setForceOperation(true);
File sha1File = ShaSigner.sign(jsart, new JULLogger(), opts.isVerbose());
outRepo.putArtifact(sha1Context, sha1File);
//Create the src archive
if (opts.isGenerateSourceArchive()) {
Set<File> sourcePaths = new HashSet<File>();
for (String sp : opts.getSrcDirs()) {
sourcePaths.add(new File(sp));
}
SourceArchiveCreator sac = CeylonUtils.makeSourceArchiveCreator(outRepo, sourcePaths,
moduleName, moduleVersion, opts.isVerbose(), new JULLogger());
sac.copySourceFiles(jsout.getSources());
}
sha1File.deleteOnExit();
jsart.deleteOnExit();
}
}
/** Print all the errors found during compilation to the specified stream. */
public int printErrors(PrintStream out) {
int count = 0;
for (Message err: errors) {
if (err instanceof UsageWarning) {
out.print("warning");
} else {
out.print("error");
}
out.printf(" encountered [%s]", err.getMessage());
if (err instanceof AnalysisMessage) {
Node n = ((AnalysisMessage)err).getTreeNode();
out.printf(" at %s of %s", n.getLocation(), n.getUnit().getFilename());
} else if (err instanceof RecognitionError) {
RecognitionError rer = (RecognitionError)err;
out.printf(" at %d:%d", rer.getLine(), rer.getCharacterInLine());
}
out.println();
count++;
}
return count;
}
/** Returns the list of errors found during compilation. */
public Set<Message> getErrors() {
return Collections.unmodifiableSet(errors);
}
public void printErrorsAndCount(PrintStream out) {
int count = printErrors(out);
out.printf("%d errors.%n", count);
}
/** Writes the beginning of the wrapper function for a JS module. */
public void beginWrapper(Writer writer) throws IOException {
writer.write("(function(define) { define(function(require, exports, module) {\n");
}
/** Writes the ending of the wrapper function for a JS module. */
public void endWrapper(Writer writer) throws IOException {
//Finish the wrapper
writer.write("});\n");
writer.write("}(typeof define==='function' && define.amd ? define : function (factory) {\n");
writer.write("if (typeof exports!=='undefined') { factory(require, exports, module);\n");
writer.write("} else { throw 'no module loader'; }\n");
writer.write("}));\n");
}
/** Returns true if the compiler is currently compiling the language module. */
public static boolean isCompilingLanguageModule() {
return compilingLanguageModule;
}
} |
package com.redhat.ceylon.compiler.js;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Writer;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Files;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.redhat.ceylon.cmr.api.ArtifactContext;
import com.redhat.ceylon.cmr.api.RepositoryManager;
import com.redhat.ceylon.cmr.api.SourceArchiveCreator;
import com.redhat.ceylon.cmr.ceylon.CeylonUtils;
import com.redhat.ceylon.cmr.impl.ShaSigner;
import com.redhat.ceylon.common.Constants;
import com.redhat.ceylon.common.FileUtil;
import com.redhat.ceylon.common.ModuleUtil;
import com.redhat.ceylon.common.log.Logger;
import com.redhat.ceylon.compiler.Options;
import com.redhat.ceylon.compiler.typechecker.TypeChecker;
import com.redhat.ceylon.compiler.typechecker.analyzer.AnalysisError;
import com.redhat.ceylon.compiler.typechecker.analyzer.UsageWarning;
import com.redhat.ceylon.compiler.typechecker.context.PhasedUnit;
import com.redhat.ceylon.compiler.typechecker.model.Module;
import com.redhat.ceylon.compiler.typechecker.model.TypedDeclaration;
import com.redhat.ceylon.compiler.typechecker.model.Unit;
import com.redhat.ceylon.compiler.typechecker.parser.RecognitionError;
import com.redhat.ceylon.compiler.typechecker.tree.AnalysisMessage;
import com.redhat.ceylon.compiler.typechecker.tree.Message;
import com.redhat.ceylon.compiler.typechecker.tree.Node;
import com.redhat.ceylon.compiler.typechecker.tree.Tree;
import com.redhat.ceylon.compiler.typechecker.tree.UnexpectedError;
import com.redhat.ceylon.compiler.typechecker.tree.Visitor;
public class JsCompiler {
protected final TypeChecker tc;
protected final Options opts;
protected final RepositoryManager outRepo;
private boolean stopOnErrors = true;
private int errCount = 0;
protected Set<Message> errors = new HashSet<Message>();
protected Set<Message> unitErrors = new HashSet<Message>();
protected List<File> srcFiles;
protected List<File> resFiles;
private final Map<Module, JsOutput> output = new HashMap<Module, JsOutput>();
//You have to manually set this when compiling the language module
static boolean compilingLanguageModule;
private TypeUtils types;
private int exitCode = 0;
private Logger logger;
public int getExitCode() {
return exitCode;
}
private final Visitor unitVisitor = new Visitor() {
private boolean hasErrors(Node that) {
for (Message m: that.getErrors()) {
if (m instanceof AnalysisError) {
return true;
}
}
return false;
}
@Override
public void visitAny(Node that) {
super.visitAny(that);
for (Message err: that.getErrors()) {
unitErrors.add(err);
}
}
@Override
public void visit(Tree.ImportMemberOrType that) {
if (hasErrors(that)) return;
Unit u = that.getImportModel().getDeclaration().getUnit();
if (nonCeylonUnit(u)) {
that.addUnexpectedError("cannot import Java declarations in Javascript");
}
super.visit(that);
}
@Override
public void visit(Tree.ImportModule that) {
if (hasErrors(that)) {
exitCode = 1;
} else if (that.getImportPath() != null && that.getImportPath().getModel() instanceof Module &&
((Module)that.getImportPath().getModel()).isJava()) {
that.getImportPath().addUnexpectedError("cannot import Java modules in Javascript");
} else {
super.visit(that);
}
}
@Override
public void visit(Tree.BaseMemberOrTypeExpression that) {
if (hasErrors(that)) return;
if (that.getDeclaration() != null && that.getDeclaration().getUnit() != null) {
Unit u = that.getDeclaration().getUnit();
if (nonCeylonUnit(u)) {
that.addUnexpectedError("cannot call Java declarations in Javascript");
}
}
super.visit(that);
}
@Override
public void visit(Tree.QualifiedMemberOrTypeExpression that) {
if (hasErrors(that)) return;
if (that.getDeclaration() != null && that.getDeclaration().getUnit() != null) {
Unit u = that.getDeclaration().getUnit();
if (nonCeylonUnit(u)) {
that.addUnexpectedError("cannot call Java declarations in Javascript");
}
}
super.visit(that);
}
};
public JsCompiler(TypeChecker tc, Options options) {
this.tc = tc;
opts = options;
outRepo = CeylonUtils.repoManager()
.cwd(options.getCwd())
.outRepo(options.getOutRepo())
.user(options.getUser())
.password(options.getPass())
.buildOutputManager();
logger = opts.getLogger();
if(logger == null)
logger = new JsLogger(opts);
String outDir = options.getOutRepo();
if(!isURL(outDir)){
File root = new File(outDir);
if (root.exists()) {
if (!(root.isDirectory() && root.canWrite())) {
logger.error("Cannot write to "+root+". Stop.");
exitCode = 1;
}
} else {
if (!root.mkdirs()) {
logger.error("Cannot create "+root+". Stop.");
exitCode = 1;
}
}
}
types = new TypeUtils(tc.getContext().getModules().getLanguageModule());
}
private boolean isURL(String path) {
try {
new URL(path);
return true;
} catch (MalformedURLException e) {
return false;
}
}
/** Specifies whether the compiler should stop when errors are found in a compilation unit (default true). */
public JsCompiler stopOnErrors(boolean flag) {
stopOnErrors = flag;
return this;
}
/** Sets the names of the files to compile. By default this is null, which means all units from the typechecker
* will be compiled. */
public void setSourceFiles(List<File> files) {
this.srcFiles = files;
}
/** Sets the names of the resources to pack with the compiler output. */
public void setResourceFiles(List<File> files) {
this.resFiles = files;
}
public Set<Message> listErrors() {
return getErrors();
}
/** Compile one phased unit.
* @return The errors found for the unit. */
public void compileUnit(PhasedUnit pu, JsIdentifierNames names) throws IOException {
unitErrors.clear();
pu.getCompilationUnit().visit(unitVisitor);
if (exitCode != 0)return;
if (errCount == 0 || !stopOnErrors) {
if (opts.isVerbose()) {
logger.debug("Compiling "+pu.getUnitFile().getPath()+" to JS");
}
//Perform capture analysis
for (com.redhat.ceylon.compiler.typechecker.model.Declaration d : pu.getDeclarations()) {
if (d instanceof TypedDeclaration && d instanceof com.redhat.ceylon.compiler.typechecker.model.Setter == false) {
pu.getCompilationUnit().visit(new ValueVisitor((TypedDeclaration)d));
}
}
JsOutput jsout = getOutput(pu);
GenerateJsVisitor jsv = new GenerateJsVisitor(jsout, opts, names, pu.getTokens(), types);
pu.getCompilationUnit().visit(jsv);
pu.getCompilationUnit().visit(unitVisitor);
if (jsv.getExitCode() != 0) {
exitCode = jsv.getExitCode();
}
}
}
/** Indicates if compilation should stop, based on whether there were errors
* in the last compilation unit and the stopOnErrors flag is set. */
protected boolean stopOnError() {
for (Message err : unitErrors) {
if (err instanceof AnalysisError ||
err instanceof UnexpectedError) {
errCount++;
}
errors.add(err);
}
return stopOnErrors && errCount > 0;
}
/** Compile all the phased units in the typechecker.
* @return true is compilation was successful (0 errors/warnings), false otherwise. */
public boolean generate() throws IOException {
errors.clear();
errCount = 0;
output.clear();
try {
if (opts.isVerbose()) {
logger.debug("Generating metamodel...");
}
List<PhasedUnit> phasedUnits = tc.getPhasedUnits().getPhasedUnits();
boolean generatedCode = false;
//First generate the metamodel
for (PhasedUnit pu: phasedUnits) {
File path = new File(pu.getUnitFile().getPath());
if (srcFiles == null || FileUtil.containsFile(srcFiles, path)) {
pu.getCompilationUnit().visit(getOutput(pu).mmg);
if (opts.isVerbose()) {
logger.debug(pu.getCompilationUnit().toString());
}
}
}
//Then write it out and output the reference in the module file
if (!compilingLanguageModule) {
for (Map.Entry<Module,JsOutput> e : output.entrySet()) {
e.getValue().encodeModel(e.getKey());
}
}
//Then generate the JS code
JsIdentifierNames names = new JsIdentifierNames();
if (srcFiles == null && !phasedUnits.isEmpty()) {
for (PhasedUnit pu: phasedUnits) {
compileUnit(pu, names);
generatedCode = true;
if (exitCode != 0) {
return false;
}
if (stopOnError()) {
logger.error("Errors found. Compilation stopped.");
break;
}
getOutput(pu).addSource(getFullPath(pu));
}
} else if(!phasedUnits.isEmpty() && !srcFiles.isEmpty()){
final List<PhasedUnit> units = tc.getPhasedUnits().getPhasedUnits();
PhasedUnit lastUnit = units.get(0);
for (File path : srcFiles) {
if (path.getPath().endsWith(".js")) {
//Just output the file
final JsOutput lastOut = getOutput(lastUnit);
try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
String line = null;
while ((line = reader.readLine()) != null) {
if (!opts.isIndent() || opts.isMinify()) {
line = line.trim();
if (!opts.isComment() && line.startsWith("//") && !line.contains("*/")) {
continue;
}
}
if (line.length()==0) {
continue;
}
lastOut.getWriter().write(line);
lastOut.getWriter().write('\n');
}
} finally {
lastOut.addSource(path);
}
generatedCode = true;
} else {
//Find the corresponding compilation unit
for (PhasedUnit pu : units) {
File unitFile = new File(pu.getUnitFile().getPath());
if (FileUtil.sameFile(path, unitFile)) {
compileUnit(pu, names);
generatedCode = true;
if (exitCode != 0) {
return false;
}
if (stopOnError()) {
logger.error("Errors found. Compilation stopped.");
break;
}
getOutput(pu).addSource(getFullPath(pu));
lastUnit = pu;
}
}
}
}
}
if(!generatedCode){
logger.error("No source units found to compile");
exitCode = 2;
}
} finally {
if (exitCode==0) {
finish();
}
}
return errCount == 0 && exitCode == 0;
}
public File getFullPath(PhasedUnit pu) {
return new File(pu.getUnit().getFullPath());
}
/** Creates a JsOutput if needed, for the PhasedUnit.
* Right now it's one file per module. */
private JsOutput getOutput(PhasedUnit pu) throws IOException {
Module mod = pu.getPackage().getModule();
JsOutput jsout = output.get(mod);
if (jsout==null) {
jsout = newJsOutput(mod);
output.put(mod, jsout);
if (opts.isModulify()) {
beginWrapper(jsout.getWriter());
}
}
return jsout;
}
/** This exists solely so that the web IDE can override it and use a different JsOutput */
protected JsOutput newJsOutput(Module m) throws IOException {
return new JsOutput(m, opts.getEncoding());
}
/** Closes all output writers and puts resulting artifacts in the output repo. */
protected void finish() throws IOException {
for (Map.Entry<Module,JsOutput> entry: output.entrySet()) {
JsOutput jsout = entry.getValue();
if (opts.isModulify()) {
endWrapper(jsout.getWriter());
}
String moduleName = entry.getKey().getNameAsString();
String moduleVersion = entry.getKey().getVersion();
if(opts.getDiagnosticListener() != null)
opts.getDiagnosticListener().moduleCompiled(moduleName, moduleVersion);
//Create the JS file
final File jsart = jsout.close();
final File modart = jsout.getModelFile();
if (entry.getKey().isDefault()) {
logger.info("Created module "+moduleName);
} else if (!compilingLanguageModule) {
logger.info("Created module "+moduleName+"/"+moduleVersion);
}
if (compilingLanguageModule) {
ArtifactContext artifact = new ArtifactContext("delete", "me", ArtifactContext.JS);
outRepo.putArtifact(artifact, jsart);
artifact.setForceOperation(true);
} else {
final ArtifactContext artifact = new ArtifactContext(moduleName, moduleVersion, ArtifactContext.JS);
outRepo.putArtifact(artifact, jsart);
final ArtifactContext martifact = new ArtifactContext(moduleName, moduleVersion, ArtifactContext.JS_MODEL);
outRepo.putArtifact(martifact, modart);
//js file signature
artifact.setForceOperation(true);
martifact.setForceOperation(true);
ArtifactContext sha1Context = artifact.getSha1Context();
sha1Context.setForceOperation(true);
File sha1File = ShaSigner.sign(jsart, logger, opts.isVerbose());
outRepo.putArtifact(sha1Context, sha1File);
sha1Context = martifact.getSha1Context();
sha1Context.setForceOperation(true);
sha1File = ShaSigner.sign(modart, new JsJULLogger(), opts.isVerbose());
outRepo.putArtifact(sha1Context, sha1File);
//Create the src archive
if (opts.isGenerateSourceArchive()) {
SourceArchiveCreator sac = CeylonUtils.makeSourceArchiveCreator(outRepo, opts.getSrcDirs(),
moduleName, moduleVersion, opts.isVerbose(), logger);
sac.copySourceFiles(FileUtil.filesToPathList(jsout.getSources()));
}
sha1File.deleteOnExit();
createResources(moduleName, moduleVersion);
}
jsart.deleteOnExit();
if (modart!=null)modart.deleteOnExit();
}
}
/** Print all the errors found during compilation to the specified stream.
* @throws IOException */
public int printErrors(Writer out) throws IOException {
int count = 0;
DiagnosticListener diagnosticListener = opts.getDiagnosticListener();
for (Message err: errors) {
if (err instanceof UsageWarning) {
out.write("warning");
} else {
out.write("error");
}
out.write(String.format(" encountered [%s]", err.getMessage()));
if (err instanceof AnalysisMessage) {
Node n = ((AnalysisMessage)err).getTreeNode();
if(n != null)
n = com.redhat.ceylon.compiler.typechecker.tree.Util.getIdentifyingNode(n);
out.write(String.format(" at %s of %s", n.getLocation(), n.getUnit().getFilename()));
} else if (err instanceof RecognitionError) {
RecognitionError rer = (RecognitionError)err;
out.write(String.format(" at %d:%d", rer.getLine(), rer.getCharacterInLine()));
}
out.write(System.lineSeparator());
count++;
if(diagnosticListener != null){
boolean warning = err instanceof UsageWarning;
int position = -1;
File file = null;
if(err instanceof AnalysisMessage){
Node node = ((AnalysisMessage) err).getTreeNode();
if(node != null)
node = com.redhat.ceylon.compiler.typechecker.tree.Util.getIdentifyingNode(node);
if(node != null && node.getToken() != null)
position = node.getToken().getCharPositionInLine();
if(node.getUnit() != null && node.getUnit().getFullPath() != null)
file = new File(node.getUnit().getFullPath()).getAbsoluteFile();
}else if(err instanceof RecognitionError){
// FIXME: file??
position = ((RecognitionError) err).getCharacterInLine();
}
if(position != -1)
position++; // make it 1-based
if(warning)
diagnosticListener.warning(file, err.getLine(), position, err.getMessage());
else
diagnosticListener.error(file, err.getLine(), position, err.getMessage());
}
}
out.flush();
return count;
}
/** Returns the list of errors found during compilation. */
public Set<Message> getErrors() {
return Collections.unmodifiableSet(errors);
}
public void printErrorsAndCount(Writer out) throws IOException {
int count = printErrors(out);
out.write(String.format("%d errors.%n", count));
}
/** Writes the beginning of the wrapper function for a JS module. */
public void beginWrapper(Writer writer) throws IOException {
writer.write("(function(define) { define(function(require, ex$, module) {\n");
}
/** Writes the ending of the wrapper function for a JS module. */
public void endWrapper(Writer writer) throws IOException {
//Finish the wrapper
writer.write("});\n");
writer.write("}(typeof define==='function' && define.amd ? define : function (factory) {\n");
writer.write("if (typeof exports!=='undefined') { factory(require, exports, module);\n");
writer.write("} else { throw 'no module loader'; }\n");
writer.write("}));\n");
}
protected boolean nonCeylonUnit(Unit u) {
return (u.getFilename() != null && !(u.getFilename().isEmpty()||u.getFilename().endsWith(".ceylon")))
|| (u.getPackage() != null && u.getPackage().getModule() != null && u.getPackage().getModule().isJava());
}
/** Returns true if the compiler is currently compiling the language module. */
public static boolean isCompilingLanguageModule() {
return compilingLanguageModule;
}
private void createResources(final String moduleName, final String moduleVersion) throws IOException {
if (resFiles == null || resFiles.isEmpty()) {
return;
}
final ArtifactContext ac = new ArtifactContext(moduleName, moduleVersion, ArtifactContext.RESOURCES);
ac.setThrowErrorIfMissing(false);
boolean isTemp = false;
File resDir = outRepo.getArtifact(ac);
if (resDir == null || !resDir.exists()) {
resDir = Files.createTempDirectory(moduleName + "-" + moduleVersion + "-resources").toFile();
isTemp = true;
}
for (File res : resFiles) {
File relRes = getDestinationFile(moduleName, res);
if (relRes != null) {
// Copy the file to the resource dir
FileUtil.copy(null, res, resDir, relRes);
}
}
outRepo.putArtifact(ac, resDir);
if (isTemp) {
FileUtil.deleteQuietly(resDir);
}
}
private File getDestinationFile(String moduleName, File file) {
File relRes = new File(FileUtil.relativeFile(opts.getResourceDirs(), file.getPath()));
// Check if the resource should be added for this module
String resModName = ModuleUtil.moduleName(opts.getSrcDirs(), relRes);
if (resModName.equals(moduleName)) {
return handleRoot(moduleName, relRes);
} else {
return null;
}
}
private File handleRoot(String moduleName, File relRes) {
if (!ModuleUtil.isDefaultModule(moduleName)) {
String rootName = opts.getResourceRootName();
if (rootName == null) {
rootName = Constants.DEFAULT_RESOURCE_ROOT;
}
if (!rootName.isEmpty()) {
File modulePath = ModuleUtil.moduleToPath(moduleName);
File rrp = new File(modulePath, rootName);
if (relRes.toPath().startsWith(rrp.toPath())) {
relRes = rrp.toPath().relativize(relRes.toPath()).toFile();
}
}
}
return relRes;
}
} |
package com.scaleset.search.mongo;
import com.mongodb.DB;
import com.scaleset.geo.geojson.GeoJsonModule;
import com.scaleset.search.AbstractSearchDao;
import com.scaleset.search.GenericSearchDao;
import com.scaleset.search.Query;
import com.scaleset.search.Results;
import org.jongo.Find;
import org.jongo.Jongo;
import org.jongo.MongoCollection;
import org.jongo.marshall.jackson.JacksonMapper;
import java.util.ArrayList;
import java.util.List;
public class MongoSearchDao<T, K> extends AbstractSearchDao<T, K> {
private MongoCollection collection;
private Class<T> typeClass;
public MongoSearchDao(DB db, String collectionName, Class<T> typeClass) {
this.typeClass = typeClass;
JacksonMapper.Builder mapperBuilder = new JacksonMapper.Builder().registerModule(new GeoJsonModule());
mapperBuilder.withQueryFactory(new LuceneJongoQueryFactory());
Jongo jongo = new Jongo(db, mapperBuilder.build());
collection = jongo.getCollection(collectionName);
}
@Override
public void close() throws Exception {
}
@Override
public Results<T> search(Query query) throws Exception {
Find find = collection
.find(query.getQ())
.limit(query.getLimit())
.skip(query.getOffset());
Results<T> results = new ResultsConverter<T, K>(query, find, typeClass).convert();
return results;
}
@Override
public T findById(K id) throws Exception {
return collection.findOne("_id:#", id).as(typeClass);
}
@Override
public List<T> saveBatch(List<T> entities) throws Exception {
List<T> results = new ArrayList<>();
for (T entity : entities) {
save(entity);
results.add(entity);
}
return results;
}
@Override
public void delete(T entity) throws Exception {
throw new UnsupportedOperationException();
}
@Override
public void deleteByKey(K id) throws Exception {
collection.remove("_id:
}
@Override
public void deleteByQuery(Query query) throws Exception {
collection.remove(query.getQ());
}
@Override
public T save(T entity) throws Exception {
collection.save(entity);
return entity;
}
} |
/*Tracking startet mit dem Aufruf einer Uebung. Dabei werden Veraenderungen ab dem geladenem File aufgezeichnet.
*/
package de.hhu.propra16.tddt.controller;
import java.io.File;
import java.util.ArrayList;
public class Tracking {
private String codefile = "";
private String testfile = "";
private ArrayList<String> codeList = new ArrayList<String>();
private ArrayList<String> testList = new ArrayList<String>();
public Tracking () {
codefile = this.codefile;
testfile = this.testfile;
}
/*
private String compareSheets(String editedCode) {
return "";
}*/
public void addToCodeList(String codefile) {
codeList.add(codefile);
}
public void addToTestList(String testfile) {
testList.add(testfile);
}
public String getCode(int index) {
return codeList.get(index);
}
public String getTest(int index) {
return testList.get(index);
}
public void setCodefile(String codefile) {
this.codefile = codefile;
}
public void setTestfile(String testfile) {
this.testfile = testfile;
}
public int getTestSize() {
return testList.size();
}
public int getCodeSize() {
return codeList.size();
}
/**
* method to clear lists
*/
public void clearLists(){
this.codeList.clear();
this.testList.clear();
}
} |
package elucent.roots.tileentity;
import java.util.ArrayList;
import java.util.Random;
import java.util.UUID;
import net.minecraft.util.text.TextFormatting;
import elucent.roots.Roots;
import elucent.roots.RegistryManager;
import elucent.roots.Util;
import elucent.roots.component.ComponentBase;
import elucent.roots.component.ComponentManager;
import elucent.roots.component.EnumCastType;
import elucent.roots.item.DustPetal;
import elucent.roots.item.ItemStaff;
import elucent.roots.ritual.RitualBase;
import elucent.roots.ritual.RitualManager;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.resources.I18n;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.network.NetworkManager;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.EnumParticleTypes;
import net.minecraft.util.ITickable;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TextComponentString;
import net.minecraft.world.World;
import net.minecraftforge.common.util.Constants;
public class TileEntityAltar extends TEBase implements ITickable {
public ArrayList<ItemStack> inventory = new ArrayList<ItemStack>();
public ArrayList<ItemStack> incenses = new ArrayList<ItemStack>();
Random random = new Random();
int ticker = 0;
int progress = 0;
String ritualName = null;
RitualBase ritual = null;
ItemStack resultItem = null;
public TileEntityAltar(){
super();
}
@Override
public void readFromNBT(NBTTagCompound tag){
super.readFromNBT(tag);
inventory = new ArrayList<ItemStack>();
if (tag.hasKey("inventory")){
NBTTagList list = tag.getTagList("inventory", Constants.NBT.TAG_COMPOUND);
for (int i = 0; i < list.tagCount(); i ++){
inventory.add(ItemStack.loadItemStackFromNBT(list.getCompoundTagAt(i)));
}
}
incenses = new ArrayList<ItemStack>();
if (tag.hasKey("incenses")){
NBTTagList list = tag.getTagList("incenses", Constants.NBT.TAG_COMPOUND);
for (int i = 0; i < list.tagCount(); i ++){
incenses.add(ItemStack.loadItemStackFromNBT(list.getCompoundTagAt(i)));
}
}
if (tag.hasKey("ritualName")){
ritualName = tag.getString("ritualName");
ritual = RitualManager.getRitualFromName(ritualName);
}
if (tag.hasKey("progress")){
progress = tag.getInteger("progress");
}
}
@Override
public NBTTagCompound writeToNBT(NBTTagCompound tag){
super.writeToNBT(tag);
if (inventory.size() > 0){
NBTTagList list = new NBTTagList();
for (int i = 0; i < inventory.size(); i ++){;
if (inventory.get(i) != null){
list.appendTag(inventory.get(i).writeToNBT(new NBTTagCompound()));
}
}
tag.setTag("inventory",list);
}
if (incenses.size() > 0){
NBTTagList list = new NBTTagList();
for (int i = 0; i < incenses.size(); i ++){;
if (incenses.get(i) != null){
list.appendTag(incenses.get(i).writeToNBT(new NBTTagCompound()));
}
}
tag.setTag("incenses",list);
}
if (ritualName != null){
tag.setString("ritualName", ritualName);
}
tag.setInteger("progress", progress);
return tag;
}
@Override
public void breakBlock(World world, BlockPos pos, IBlockState state, EntityPlayer player){
for (int i = 0; i < inventory.size(); i ++){
if (!world.isRemote){
world.spawnEntityInWorld(new EntityItem(world,pos.getX()+0.5,pos.getY()+0.5,pos.getZ()+0.5,inventory.get(i)));
}
}
this.invalidate();
}
public boolean activate(World world, BlockPos pos, IBlockState state, EntityPlayer player, EnumHand hand, ItemStack heldItem, EnumFacing side, float hitX, float hitY, float hitZ){
if (heldItem == null && !player.isSneaking() && this.progress == 0){
if (inventory.size() > 0){
if (!world.isRemote){
world.spawnEntityInWorld(new EntityItem(world, pos.getX()+0.5, pos.getY()+1.0, pos.getZ()+0.5, inventory.remove(inventory.size()-1)));
}
else {
inventory.remove(inventory.size()-1);
}
markDirty();
this.getWorld().notifyBlockUpdate(getPos(), state, world.getBlockState(pos), 3);
return true;
}
}
else if (player.isSneaking() && heldItem == null && this.progress == 0){
ritualName = null;
ritual = null;
for (int i = 0; i < RitualManager.rituals.size(); i ++){
if (RitualManager.rituals.get(i).matches(getWorld(), getPos())){
ritualName = RitualManager.rituals.get(i).name;
ritual = RitualManager.rituals.get(i);
incenses = RitualManager.getIncenses(world, getPos());
progress = 200;
markDirty();
this.getWorld().notifyBlockUpdate(getPos(), state, world.getBlockState(pos), 3);
return true;
}
}
if (ritualName == null){
if (world.isRemote){
player.addChatMessage(new TextComponentString(TextFormatting.RED+I18n.format("roots.error.noritual.name")));
}
markDirty();
this.getWorld().notifyBlockUpdate(getPos(), state, world.getBlockState(pos), 3);
return true;
}
}
else {
if (inventory.size() < 3){
ItemStack toAdd = new ItemStack(heldItem.getItem(),1,heldItem.getItemDamage());
if (heldItem.hasTagCompound()){
toAdd.setTagCompound(heldItem.getTagCompound());
}
inventory.add(toAdd);
heldItem.stackSize
markDirty();
this.getWorld().notifyBlockUpdate(getPos(), state, world.getBlockState(pos), 3);
return true;
}
}
return false;
}
@Override
public void update() {
ticker += 3.0;
if (ticker > 360){
ticker = 0;
}
if (progress > 0 && ritual != null){
progress
if (getWorld().isRemote){
if (ritual.positions.size() > 0){
BlockPos pos = ritual.positions.get(random.nextInt(ritual.positions.size())).up().add(getPos().getX(),getPos().getY(),getPos().getZ());
Roots.proxy.spawnParticleMagicAltarLineFX(getWorld(), pos.getX()+0.5, pos.getY()+0.125, pos.getZ()+0.5, getPos().getX()+0.5, getPos().getY()+0.875, getPos().getZ()+0.5, ritual.secondaryColor.xCoord, ritual.secondaryColor.yCoord, ritual.secondaryColor.zCoord);
if(random.nextInt(10) == 0){
Roots.proxy.spawnParticleMagicAltarLineFX(getWorld(), pos.getX()+0.5, pos.getY()+0.125, pos.getZ()+0.5, getPos().getX()+0.5, getPos().getY()+0.875, getPos().getZ()+0.5, ritual.color.xCoord, ritual.color.yCoord, ritual.color.zCoord);
}
}
Roots.proxy.spawnParticleMagicAltarFX(getWorld(), getPos().getX()+0.5, getPos().getY()+0.875, getPos().getZ()+0.5, 0.125*Math.sin(Math.toRadians(360.0*(progress % 100)/100.0)), 0, 0.125*Math.cos(Math.toRadians(360.0*(progress % 100)/100.0)), ritual.color.xCoord, ritual.color.yCoord, ritual.color.zCoord);
Roots.proxy.spawnParticleMagicAltarFX(getWorld(), getPos().getX()+0.5, getPos().getY()+0.875, getPos().getZ()+0.5, 0.125*Math.sin(Math.toRadians(90.0+360.0*(progress % 100)/100.0)), 0, 0.125*Math.cos(Math.toRadians(90.0+360.0*(progress % 100)/100.0)), ritual.color.xCoord, ritual.color.yCoord, ritual.color.zCoord);
Roots.proxy.spawnParticleMagicAltarFX(getWorld(), getPos().getX()+0.5, getPos().getY()+0.875, getPos().getZ()+0.5, 0.125*Math.sin(Math.toRadians(180.0+360.0*(progress % 100)/100.0)), 0, 0.125*Math.cos(Math.toRadians(180.0+360.0*(progress % 100)/100.0)), ritual.color.xCoord, ritual.color.yCoord, ritual.color.zCoord);
Roots.proxy.spawnParticleMagicAltarFX(getWorld(), getPos().getX()+0.5, getPos().getY()+0.875, getPos().getZ()+0.5, 0.125*Math.sin(Math.toRadians(270.0+360.0*(progress % 100)/100.0)), 0, 0.125*Math.cos(Math.toRadians(270.0+360.0*(progress % 100)/100.0)), ritual.color.xCoord, ritual.color.yCoord, ritual.color.zCoord);
}
if (progress % 40 == 0){
incenses = RitualManager.getIncenses(getWorld(), getPos());
boolean doesMatch = false;
for (int i = 0; i < RitualManager.rituals.size(); i ++){
if (RitualManager.rituals.get(i).matches(getWorld(), getPos())){
doesMatch = true;
}
}
if (!doesMatch){
ritual = null;
ritualName = null;
}
}
if (progress == 0 && ritual != null){
ritual.doEffect(getWorld(),getPos(),inventory,incenses);
ritualName = null;
ritual = null;
markDirty();
this.getWorld().notifyBlockUpdate(getPos(), getWorld().getBlockState(getPos()), getWorld().getBlockState(getPos()), 3);
}
}
}
} |
package org.eclipse.n4js.hlc.base;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import org.eclipse.emf.common.util.URI;
import org.eclipse.n4js.external.TargetPlatformInstallLocationProvider;
import org.eclipse.n4js.generator.headless.N4JSCompileException;
import org.eclipse.n4js.internal.FileBasedWorkspace;
import org.eclipse.n4js.n4mf.ProjectDescription;
import org.eclipse.n4js.n4mf.utils.parsing.ProjectDescriptionProviderUtil;
import org.eclipse.n4js.projectModel.IN4JSProject;
import org.eclipse.n4js.projectModel.dependencies.DependenciesCollectingUtil;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.base.Throwables;
import com.google.common.collect.Sets;
import com.google.inject.Inject;
/**
* Headless version of the org.eclipse.n4js.ui.handler.ProjectDependenciesHelper
*/
class DependenciesHelper {
@Inject
private TargetPlatformInstallLocationProvider installLocationProvider;
@Inject
private FileBasedWorkspace n4jsFileBasedWorkspace;
// TODO GH-651 partially copied from
// org.eclipse.n4js.generator.headless.N4HeadlessCompiler.collectAndRegisterProjects(List<File>,
// List<File>, List<File>)
Map<String, String> discoverMissingDependencies(String projectLocations, List<File> srcFiles) {
List<File> allProjectsRoots = new ArrayList<>();
List<File> discoveredProjectLocations = new ArrayList<>();
if (projectLocations != null) {
List<File> locations = convertToFilesAddTargetPlatformAndCheckWritableDir(projectLocations);
// Discover projects in search paths.
discoveredProjectLocations = collectAllProjectPaths(locations);
}
// Discover projects for single source files.
List<File> singleSourceProjectLocations = new ArrayList<>();
try {
singleSourceProjectLocations.addAll(findProjectsForSingleFiles(srcFiles));
} catch (N4JSCompileException e) {
System.err.println(Throwables.getStackTraceAsString(e));
}
allProjectsRoots.addAll(discoveredProjectLocations);
allProjectsRoots.addAll(singleSourceProjectLocations);
Map<String, String> dependencies = new HashMap<>();
DependenciesCollectingUtil.updateMissingDependneciesMap(dependencies,
getAvailableProjectsDescriptions(allProjectsRoots));
return dependencies;
}
private Iterable<ProjectDescription> getAvailableProjectsDescriptions(List<File> allProjectsRoots) {
List<ProjectDescription> descriptions = new ArrayList<>();
allProjectsRoots.forEach(root -> {
File manifest = new File(root, IN4JSProject.N4MF_MANIFEST);
if (!manifest.isFile()) {
System.out.println("Cannot read manifest at " + root);
return;
}
ProjectDescription projectDescription = ProjectDescriptionProviderUtil.getFromFile(manifest);
descriptions.add(projectDescription);
});
return descriptions;
}
/**
* Collects the projects containing the given single source files.
*
* @param sourceFiles
* the list of single source files
* @return list of N4JS project locations
* @throws N4JSCompileException
* if no project cannot be found for one of the given files
*/
// TODO GH-651 copied from
// org.eclipse.n4js.generator.headless.N4HeadlessCompiler.findProjectsForSingleFiles(List<File>)
private List<File> findProjectsForSingleFiles(List<File> sourceFiles)
throws N4JSCompileException {
Set<URI> result = Sets.newLinkedHashSet();
for (File sourceFile : sourceFiles) {
URI sourceFileURI = URI.createFileURI(sourceFile.toString());
URI projectURI = n4jsFileBasedWorkspace.findProjectWith(sourceFileURI);
if (projectURI == null) {
throw new N4JSCompileException("No project for file '" + sourceFile.toString() + "' found.");
}
result.add(projectURI);
}
// convert back to Files:
return result.stream().map(u -> new File(u.toFileString())).collect(Collectors.toList());
}
/**
* Searches for direct sub-folders containing a File named {@link IN4JSProject#N4MF_MANIFEST}
*
* @param absProjectRoots
* all project root (must be absolute)
* @return list of directories being a project
*/
// TODO GH-651 copied org.eclipse.n4js.generator.headless.HeadlessHelper.collectAllProjectPaths(List<File>)
static ArrayList<File> collectAllProjectPaths(List<File> absProjectRoots) {
ArrayList<File> pDir = new ArrayList<>();
for (File projectRoot : absProjectRoots) {
Arrays.asList(projectRoot.listFiles(f -> {
return f.isDirectory(); // all directrories
}))
.stream()
.filter(f -> {
File[] list = f.listFiles(f2 -> f2.getName().equals(IN4JSProject.N4MF_MANIFEST));
return list != null && list.length > 0; // only those with manifest.n4mf
})
.forEach(f -> pDir.add(f));
}
return pDir;
}
/**
* @param dirpaths
* one or more paths separated by {@link File#pathSeparatorChar} OR empty string if no paths given.
*/
// TODO GH-651 copied from
// org.eclipse.n4js.hlc.base.N4jscBase.convertToFilesAddTargetPlatformAndCheckWritableDir(String)
private List<File> convertToFilesAddTargetPlatformAndCheckWritableDir(String dirpaths) {
final List<File> retList = new ArrayList<>();
if (null != installLocationProvider.getTargetPlatformInstallLocation()) {
final File tpLoc = new File(installLocationProvider.getTargetPlatformNodeModulesLocation());
FileUtils.isExistingWriteableDir(tpLoc);
retList.add(tpLoc);
}
if (!Strings.isNullOrEmpty(dirpaths)) {
for (String dirpath : Splitter.on(File.pathSeparatorChar).split(dirpaths)) {
final File ret = new File(dirpath);
FileUtils.isExistingWriteableDir(ret);
retList.add(ret);
}
}
return retList;
}
} |
package exnihiloadscensio.registries;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import exnihiloadscensio.items.ore.ItemOre;
import exnihiloadscensio.items.ore.Ore;
import exnihiloadscensio.json.CustomBlockInfoJson;
import exnihiloadscensio.json.CustomItemInfoJson;
import exnihiloadscensio.json.CustomOreJson;
import exnihiloadscensio.texturing.Color;
import exnihiloadscensio.util.BlockInfo;
import exnihiloadscensio.util.ItemInfo;
import lombok.Getter;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.FurnaceRecipes;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import net.minecraftforge.oredict.OreDictionary;
public class OreRegistry {
private static List<Ore> registry = new ArrayList<>();
private static List<Ore> externalRegistry = new ArrayList<>();
@Getter
private static HashSet<ItemOre> itemOreRegistry = new HashSet<ItemOre>();
public static void registerDefaults()
{
registerOre("gold", new Color("FFFF00"), new ItemInfo(Items.GOLD_INGOT, 0));
registerOre("iron", new Color("BF8040"), new ItemInfo(Items.IRON_INGOT, 0));
if (OreDictionary.getOres("oreCopper").size() > 0)
{
registerOre("copper", new Color("FF9933"), null);
}
if (OreDictionary.getOres("oreTin").size() > 0)
{
registerOre("tin", new Color("E6FFF2"), null);
}
if (OreDictionary.getOres("oreAluminium").size() > 0 || OreDictionary.getOres("oreAluminum").size() > 0)
{
registerOre("aluminium", new Color("BFBFBF"), null);
}
if (OreDictionary.getOres("oreLead").size() > 0)
{
registerOre("lead", new Color("330066"), null);
}
if (OreDictionary.getOres("oreSilver").size() > 0)
{
registerOre("silver", new Color("F2F2F2"), null);
}
if (OreDictionary.getOres("oreNickel").size() > 0)
{
registerOre("nickel", new Color("FFFFCC"), null);
}
if (OreDictionary.getOres("oreArdite").size() > 0)
{
registerOre("ardite", new Color("FF751A"), null);
}
if (OreDictionary.getOres("oreCobalt").size() > 0)
{
registerOre("cobalt", new Color("3333FF"), null);
}
}
// Inconsistency at its finest
@Deprecated
/**
* Use register instead
*/
public static Ore registerOre(String name, Color color, ItemInfo info)
{
return register(name, color, info);
}
/**
* Registers a new custom piece, hunk, dust and potentially ingot to be generated by Ex Nihilo Adscensio.
* @param name Unique name for ore
* @param color Color for the pieces
* @param info Final result for the process. If null, an ingot is generated. Otherwise, the hunk will be
* smelted into this.
* @return Ore, containing the base Ore object.
*/
public static Ore register(String name, Color color, ItemInfo info)
{
Ore ore = registerInternal(name, color, info);
externalRegistry.add(ore);
return ore;
}
/**
* Registers a new custom piece, hunk, dust and potentially ingot to be generated by Ex Nihilo Adscensio.
* @param name Unique name for ore
* @param color Color for the pieces
* @param info Final result for the process. If null, an ingot is generated. Otherwise, the hunk will be
* smelted into this.
* @return Ore, containing the base Ore object.
*/
private static Ore registerInternal(String name, Color color, ItemInfo info)
{
Ore ore = new Ore(name, color, info);
registry.add(ore);
itemOreRegistry.add(new ItemOre(ore));
return new Ore(name, color, info);
}
public static void registerFromRegistry()
{
for (Ore ore : registry)
{
itemOreRegistry.add(new ItemOre(ore));
}
}
public static void doRecipes()
{
for (ItemOre ore : itemOreRegistry)
{
GameRegistry.addRecipe(new ItemStack(ore, 1, 1), new Object[] { "xx", "xx", 'x', new ItemStack(ore, 1, 0) });
ItemStack smeltingResult;
if (ore.isRegisterIngot())
{
smeltingResult = new ItemStack(ore, 1, 3);
OreDictionary.registerOre("ingot" + StringUtils.capitalize(ore.getOre().getName()), smeltingResult);
if (ore.getOre().getName().contains("aluminium"))
OreDictionary.registerOre("ingotAluminum", smeltingResult);
}
else
{
smeltingResult = ore.getOre().getResult().getItemStack();
}
FurnaceRecipes.instance().addSmeltingRecipe(new ItemStack(ore, 1, 1), smeltingResult, 0.7f);
}
}
@SideOnly(Side.CLIENT)
public static void initModels()
{
for (ItemOre ore : itemOreRegistry) {
ore.initModel();
}
}
private static Gson gson = new GsonBuilder().setPrettyPrinting().registerTypeAdapter(ItemInfo.class, new CustomItemInfoJson()).registerTypeAdapter(BlockInfo.class, new CustomBlockInfoJson()).registerTypeAdapter(Ore.class, new CustomOreJson()).create();
public static void loadJson(File file)
{
registry.clear();
itemOreRegistry.clear();
if (file.exists())
{
try
{
FileReader fr = new FileReader(file);
List<Ore> gsonInput = gson.fromJson(fr, new TypeToken<List<Ore>>(){}.getType());
registry.addAll(gsonInput);
registerFromRegistry();
registry.addAll(externalRegistry);
}
catch (Exception e)
{
e.printStackTrace();
}
}
else
{
registerDefaults();
//registerDefaults() will add everything to the external registry automatically.
saveJson(file);
}
}
public static void saveJson(File file)
{
try
{
FileWriter fw = new FileWriter(file);
gson.toJson(registry, fw);
fw.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
} |
package fi.fubar.bibtex.service;
import fi.fubar.bibtex.domain.Article;
import fi.fubar.bibtex.domain.Book;
import fi.fubar.bibtex.domain.InProceedings;
import fi.fubar.bibtex.domain.Reference;
import fi.fubar.bibtex.domain.UserAccount;
import fi.fubar.bibtex.repository.ReferenceRepository;
import fi.fubar.bibtex.repository.ArticleRepository;
import fi.fubar.bibtex.repository.BookRepository;
import fi.fubar.bibtex.repository.InProceedingsRepository;
import fi.fubar.bibtex.repository.UserRepository;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
/**
* Service for querying the different reference types.
*/
@Service
public class ReferenceService {
@Autowired
private ArticleRepository articleRepository;
@Autowired
private BookRepository bookRepository;
@Autowired
private InProceedingsRepository inproceedingsRepository;
@Autowired
private SecurityService securityService;
@Autowired
private UserRepository userRepository;
private ReferenceRepository[] referenceRepositories()
{
return new ReferenceRepository[] {
bookRepository, articleRepository, inproceedingsRepository
};
}
public List<Reference> findAll() {
List<Reference> references = new ArrayList();
UserAccount user = userRepository.findByUsername(securityService.findLoggedInUsername());
if(user == null)
// Abandon ship!
return references;
for (ReferenceRepository repository : referenceRepositories()) {
references.addAll(repository.findAllByOwner(user));
}
return references;
}
public List<Reference> findAllByUser(UserAccount user) {
List<Reference> references = new ArrayList();
for (ReferenceRepository repository : referenceRepositories()) {
references.addAll(repository.findAllByOwner(user));
}
return references;
}
public Reference findByTypeAndId(String type, Long id) {
switch (type) {
case "book":
return bookRepository.findOne(id);
case "article":
return articleRepository.findOne(id);
case "inproceedings":
return inproceedingsRepository.findOne(id);
default:
return null;
}
}
public void save(Reference ref) {
switch (ref.getType()) {
case "book":
bookRepository.save((Book) ref);
break;
case "article":
articleRepository.save((Article) ref);
break;
case "inproceedings":
inproceedingsRepository.save((InProceedings) ref);
break;
default:
break;
}
}
public String returnAllinBibTeXStrings() {
List<Reference> references = findAll();
String s = "";
for (Reference r : references) {
s += r.toBibTex() + "\n";
}
return s;
}
public List<Reference> search(String search) {
List<Reference> found = new ArrayList();
for (ReferenceRepository repository : referenceRepositories()) {
found.addAll(repository.searchAllColumns(search));
}
return found;
}
} |
package gr.iti.mklab.sfc.filters;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.core.LowerCaseFilter;
import org.apache.lucene.analysis.core.WhitespaceTokenizer;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import gr.iti.mklab.framework.common.domain.Item;
import gr.iti.mklab.framework.common.domain.config.Configuration;
public class SwearItemFilter extends ItemFilter {
private Set<String> swearwords = new HashSet<String>();
public SwearItemFilter(Configuration configuration) {
super(configuration);
List<String> swearWords = Arrays.asList("anal","anus","arse","ar5e","ass","assfucker","assfukka","asshole",
"ballsack","balls","bastard","bitch","biatch","bigtits","blowjob","bollock","bollok","boner","boob","bugger","bum","butt","buttplug","clitoris",
"cock","cocksuck","cocksucker","cocksucking","cockface","cockhead","cockmunch","c0cksucker",
"coon","crap","cum","cumshot","cummer","cunt","cuntlick","cuntlicking","damn","dick","dlck","dildo","dyke","ejaculate","ejaculation",
"fag","faggot","feck","fellate","fellatio","felching","fingerfuck","fistfuck","fuck","fuckme","fudgepacker","flange",
"gangbang","goddamn","handjob","homo","horny","jerk","jizz","knobend","labia","lmao","lmfao","muff","nigger","nigga","niggah","porn", "penis","pigfucker","piss","poop",
"prick","pube","pussy","queer","scrotum","sexxx","shemale","shit","sh1t","shitdick","shiting","shitter","slut","smegma","spunk","tit","titfuck","tittywank","tosser",
"turd","twat","vagina","vulva","wank","wanker","whore","wtf","xxx");
swearwords.addAll(swearWords);
}
@Override
public boolean accept(Item item) {
try {
String title = item.getTitle();
if(title == null) {
incrementDiscarded();
return false;
}
Reader reader = new StringReader(title);
TokenStream tokenizer = new WhitespaceTokenizer(reader);
TokenStream stream = new LowerCaseFilter(tokenizer);
List<String> tokens = new ArrayList<String>();
CharTermAttribute charTermAtt = stream.addAttribute(CharTermAttribute.class);
stream.reset();
while (stream.incrementToken()) {
String token = charTermAtt.toString();
if(token.contains("http") || token.contains(".") || token.length() <= 1) {
continue;
}
tokens.add(token);
}
stream.end();
stream.close();
for(String token : tokens) {
if(swearwords.contains(token)) {
incrementDiscarded();
return false;
}
}
} catch (Exception e) {
e.printStackTrace();
incrementDiscarded();
return false;
}
incrementAccepted();
return true;
}
@Override
public String name() {
return null;
}
} |
package hu.sztaki.ilab.longneck.process;
import hu.sztaki.ilab.longneck.process.block.BlockReference;
import hu.sztaki.ilab.longneck.process.constraint.ConstraintReference;
import hu.sztaki.ilab.longneck.process.constraint.EntityReference;
import java.io.File;
import java.nio.file.FileSystems;
import org.w3c.dom.Document;
public enum FileType {
Block,
Constraint,
Entity,
Process;
public static FileType forDocument(Document doc) {
String rootElementName = doc.getDocumentElement().getLocalName();
for (FileType ft : values()) {
if (ft.getRootElementName().equals(rootElementName)) {
return ft;
}
}
return null;
}
public static FileType forPath(String path) {
if (path.endsWith(".block.xml")) {
return Block;
}
else if (path.endsWith(".constraint.xml")) {
return Constraint;
}
else if (path.endsWith(".entity.xml")) {
return Entity;
}
return null;
}
public boolean isPackage() {
switch (this) {
case Block:
case Constraint:
case Entity:
return true;
default:
return false;
}
}
public static String getPackageId(String path) {
int dotIndex = path.lastIndexOf('.', path.lastIndexOf('.')-1);
return path.substring(0, dotIndex).replaceAll(File.separator, "/");
}
public static String getFullPackageId(String defaultdirectory, String pkg) {
return pkg.startsWith("/") ? pkg.substring(1):(defaultdirectory == null ?"":
defaultdirectory.replace(File.separatorChar, '/'))+pkg;
}
public static String normalizePackageId(String fullpackageid, String repositoryPath,
AbstractReference ref) {
return getPackageId(FileSystems.getDefault().getPath(
repositoryPath, forReference(ref).getFileName(fullpackageid)).normalize().toString()
.replaceFirst(repositoryPath+File.separator, ""));
}
public String getFileName(String baseName) {
String filepath = baseName.replaceAll("/", ("\\".equals(File.separator)?"\\":File.separator));
switch (this) {
case Block:
return String.format("%1$s.block.xml", filepath);
case Constraint:
return String.format("%1$s.constraint.xml", filepath);
case Entity:
return String.format("%1$s.entity.xml", filepath);
case Process:
return String.format("%1$s.process.xml", filepath);
default:
throw new RuntimeException("Invalid package type.");
}
}
public static FileType forReference(AbstractReference reference) {
if (reference instanceof BlockReference) {
return Block;
}
else if (reference instanceof ConstraintReference) {
return Constraint;
}
else if (reference instanceof EntityReference) {
return Entity;
}
return null;
}
public String getRootElementName() {
return this.toString().toLowerCase();
}
public Class getTargetClass() {
switch (this) {
case Block:
return BlockPackage.class;
case Constraint:
return ConstraintPackage.class;
case Entity:
return EntityPackage.class;
case Process:
return LongneckProcess.class;
default:
return null;
}
}
} |
package insynctive.utils.saucelabs;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import org.json.JSONException;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import com.saucelabs.saucerest.SauceREST;
import insynctive.utils.ExternalTestRunner;
import insynctive.utils.data.TestEnvironment;
public class SauceLabsUtil implements ExternalTestRunner {
private String username = "Insynctive2";
private String password = "d2f371f8-fc76-4b7c-9b60-e069c996c879";
private SauceREST rest;
private final int COMMAND_TIMEOUT = 420;
private final int IDLE_COMMAND_TIMEOUT = 300;
public SauceLabsUtil() {
rest = new SauceREST(username, password);
}
@Override
public String getRemoteTestingUsername() {
return username;
}
@Override
public void setRemoteTestingUsername(String username) {
this.username = username;
}
@Override
public String getRemoteTestingPassword() {
return password;
}
@Override
public void setRemoteTestingPassword(String password) {
this.password = password;
}
@Override
public RemoteWebDriver getRemoteWebDriver(String sessionName, TestEnvironment testEnvironment) throws MalformedURLException {
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("command-timeout", COMMAND_TIMEOUT);
capabilities.setCapability("commandTimeout", IDLE_COMMAND_TIMEOUT);
capabilities.setCapability("name", sessionName+" ["+testEnvironment+"]");
//Set BROWSER > VERSION > PLATAFORM
capabilities.setCapability(CapabilityType.BROWSER_NAME, testEnvironment.browserSauceLabs);
if (testEnvironment.versionSauceLabs != null) { capabilities.setCapability(CapabilityType.VERSION, testEnvironment.versionSauceLabs); }
capabilities.setCapability(CapabilityType.PLATFORM, testEnvironment.osSauceLabs);
if(!testEnvironment.isDesktop) {capabilities.setCapability("deviceOrientation", "portrait");}
return new RemoteWebDriver(new URL("http://" + username + ":" + password + "@ondemand.saucelabs.com:80/wd/hub"), capabilities);
}
@Override
public void changeStatusOfJob(String jobID, Boolean generalStatus) throws MalformedURLException, IOException, JSONException {
if(generalStatus) { rest.jobPassed(jobID); } else { rest.jobFailed(jobID);}
}
@Override
public String getPublicVideoLinkOfJob(String jobID) throws IOException, JSONException {
return "https://saucelabs.com/beta/tests/" + jobID + "/watch";
}
} |
package io.cfp.controller;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import com.fasterxml.jackson.dataformat.csv.CsvSchema;
import com.itextpdf.text.DocumentException;
import io.cfp.dto.EventSched;
import io.cfp.dto.TalkAdmin;
import io.cfp.dto.TalkAdminCsv;
import io.cfp.entity.Role;
import io.cfp.entity.Talk;
import io.cfp.model.User;
import io.cfp.service.PdfCardService;
import io.cfp.service.TalkAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
@Controller
@RequestMapping(value = { "/v0/admin", "/api/admin" }, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class AdminSessionController {
@Autowired
private TalkAdminService talkService;
@Autowired
private PdfCardService pdfCardService;
/**
* Get all sessions
*/
// @RequestMapping(value="/sessions", method= RequestMethod.GET)
// @Secured({Role.REVIEWER, Role.ADMIN})
// @ResponseBody
// @Deprecated
private List<TalkAdmin> getAllSessions(@AuthenticationPrincipal User user,
@RequestParam(name = "status", required = false) String status) {
Talk.State[] accept;
if (status == null) {
accept = new Talk.State[] { Talk.State.CONFIRMED, Talk.State.ACCEPTED, Talk.State.REFUSED, Talk.State.BACKUP };
} else {
accept = new Talk.State[] { Talk.State.valueOf(status) };
}
return talkService.findAll(user.getId(), accept);
}
/**
* Get a specific session
*/
// @RequestMapping(value= "/sessions/{talkId}", method= RequestMethod.GET)
// @Secured({Role.REVIEWER, Role.ADMIN})
// @ResponseBody
// public TalkAdmin getTalk(@PathVariable int talkId) {
// return talkService.getOne(talkId);
/**
* Edit a specific session
*/
// @RequestMapping(value= "/sessions/{talkId}", method= RequestMethod.PUT)
// @Secured(Role.ADMIN)
// @ResponseBody
// public TalkAdmin editTalk(@PathVariable int talkId, @RequestBody TalkAdmin talkAdmin) throws CospeakerNotFoundException, ParseException {
// talkAdmin.setId(talkId);
// return talkService.edit(talkAdmin);
// @RequestMapping(value= "/sessions/{talkId}/accept", method= RequestMethod.PUT)
// @Secured(Role.ADMIN)
// @ResponseBody
// public void accept(@PathVariable int talkId) throws CospeakerNotFoundException{
// talks.setState(talkId, Event.current(), Talk.State.ACCEPTED);
// @RequestMapping(value= "/sessions/{talkId}/backup", method= RequestMethod.PUT)
// @Secured(Role.ADMIN)
// @ResponseBody
// public void backup(@PathVariable int talkId) throws CospeakerNotFoundException{
// talks.setState(talkId, Event.current(), Talk.State.BACKUP);
// @RequestMapping(value= "/sessions/{talkId}/reject", method= RequestMethod.PUT)
// @Secured(Role.ADMIN)
// @ResponseBody
// public void reject(@PathVariable int talkId) throws CospeakerNotFoundException{
// talks.setState(talkId, Event.current(), Talk.State.REFUSED);
// @RequestMapping(value= "/sessions/rejectOthers", method= RequestMethod.PUT)
// @Secured(Role.ADMIN)
// @ResponseBody
// public void rejectOthers() throws CospeakerNotFoundException{
// talks.setStateWhere(Event.current(), Talk.State.REFUSED, Talk.State.CONFIRMED);
// @RequestMapping(value= "/sessions/{talkId}/retract", method= RequestMethod.PUT)
// @Secured(Role.ADMIN)
// @ResponseBody
// public void retract(@PathVariable int talkId) throws CospeakerNotFoundException{
// talks.setState(talkId, Event.current(), Talk.State.CONFIRMED);
/**
* Delete a session
*/
// @RequestMapping(value="/sessions/{talkId}", method= RequestMethod.DELETE)
// @Secured(Role.ADMIN)
// @ResponseBody
// public TalkAdmin delete(@PathVariable int talkId) {
// return talkService.delete(talkId);
/**
* Delete all sessions (aka reset CFP)
*/
// @RequestMapping(value="/sessions", method= RequestMethod.DELETE)
// @Secured(Role.ADMIN)
// @ResponseBody
// public void deleteAll() {
// talks.deleteAllByEventId(Event.current());
@RequestMapping(path = "/sessions/export/cards.pdf", produces = "application/pdf")
@Secured(Role.ADMIN)
public void exportPdf(@AuthenticationPrincipal User user,
HttpServletResponse response) throws IOException, DocumentException {
response.addHeader(HttpHeaders.CONTENT_TYPE, "application/pdf");
pdfCardService.export(user.getId(), response.getOutputStream());
}
@RequestMapping(path = "/sessions/export/sched.json", produces = "application/json")
@Secured(Role.ADMIN)
@ResponseBody
public List<EventSched> exportSched(@RequestParam(required = false) Talk.State[] states) {
if (states == null) {
states = new Talk.State[] { Talk.State.ACCEPTED };
}
return talkService.exportSched(states);
}
@RequestMapping(path = "/sessions/export/sessions.csv", produces = "text/csv")
@Secured(Role.ADMIN)
public void exportCsv(@AuthenticationPrincipal User user,
HttpServletResponse response, @RequestParam(name = "status", required = false) String status) throws IOException {
response.addHeader(HttpHeaders.CONTENT_TYPE, "text/csv");
CsvMapper mapper = new CsvMapper();
mapper.addMixIn(TalkAdmin.class, TalkAdminCsv.class);
CsvSchema schema = mapper.schemaFor(TalkAdmin.class).withHeader();
ObjectWriter writer = mapper.writer(schema);
writer.getFactory().disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET);
List<TalkAdmin> sessions = getAllSessions(user, status);
final ServletOutputStream out = response.getOutputStream();
for (TalkAdmin s : sessions) {
writer.writeValue(out, s);
}
}
} |
package io.featureflow.client;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class FeatureFlowContext{
String key;
Map<String, ? extends JsonElement> values = new HashMap<>();
public FeatureFlowContext(String key) {
this.key = key;
}
public static Builder keyedContext(String key){
return new Builder(key);
}
public static Builder context(){
return new Builder();
}
public Map<String,? extends JsonElement> getValues() {
return values;
}
public static class Builder{
private String key;
private Map<String, JsonElement> values = new HashMap<>();
public Builder() {}
public Builder(String key) {
this.key = key;
}
public Builder withValue(String key, JsonElement value){
this.values.put(key, value);
return this;
}
public Builder withValue(String key, String value){
JsonPrimitive jsonValue = new JsonPrimitive(value);
this.values.put(key, jsonValue);
return this;
}
public Builder withValue(String key, DateTime value){
JsonPrimitive jsonValue = new JsonPrimitive(toIso(value));
this.values.put(key, jsonValue);
return this;
}
public Builder withValue(String key, Number value){
JsonPrimitive jsonValue = new JsonPrimitive(value);
this.values.put(key, jsonValue);
return this;
}
public FeatureFlowContext build(){
if(key==null)key = "anonymous";
FeatureFlowContext context = new FeatureFlowContext(key);
context.values = values;
return context;
}
protected static String toIso(DateTime date) {
DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
String str = fmt.print(date);
return str;
}
protected static DateTime fromIso(String isoDate) {
DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
DateTime dt = fmt.parseDateTime(isoDate);
return dt;
}
}
} |
package io.foobot.maven.plugins.docker;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.List;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.model.Resource;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecution;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.settings.Settings;
import org.codehaus.plexus.util.DirectoryScanner;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.PushImageCmd;
import com.github.dockerjava.api.command.RemoveImageCmd;
import com.github.dockerjava.api.model.BuildResponseItem;
import com.github.dockerjava.core.DefaultDockerClientConfig;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.core.DockerClientConfig;
import com.github.dockerjava.core.command.BuildImageResultCallback;
import com.github.dockerjava.core.command.PushImageResultCallback;
@Mojo(name = "build")
public class BuildMojo extends AbstractMojo {
@Parameter(name = "${mojoExecution}", readonly = true)
protected MojoExecution execution;
@Parameter(name = "${session}", readonly = true)
protected MavenSession session;
@Parameter(name = "${settings}", readonly = true)
protected Settings settings;
@Parameter(property = "project.build.directory")
protected File buildDirectory;
@Parameter(property = "skipDocker", defaultValue = "false")
private boolean skipDocker;
@Parameter(property = "directory")
private File directory;
@Parameter(property = "forceRm", defaultValue = "false")
private boolean forceRm;
@Parameter(property = "noCache", defaultValue = "false")
private boolean noCache;
@Parameter(property = "pull", defaultValue = "false")
private boolean pull;
@Parameter(property = "imageName")
private String imageName;
@Parameter(property = "imageTags")
private List<String> imageTags;
@Parameter(property = "push", defaultValue = "false")
private boolean push;
@Parameter(property = "remove", defaultValue = "false")
private boolean remove;
@Parameter(property = "resources")
private List<Resource> resources;
public void execute() throws MojoExecutionException, MojoFailureException {
if (skipDocker) {
getLog().info("Skipping docker build");
return;
}
validateParameters();
DockerClientConfig dockerClientConfig = DefaultDockerClientConfig.createDefaultConfigBuilder()
.withDockerHost("unix:///var/run/docker.sock").withDockerTlsVerify(false).build();
DockerClient dockerClient = null;
try {
dockerClient = DockerClientBuilder.getInstance(dockerClientConfig).build();
build(dockerClient);
} catch (Exception e) {
throw new MojoExecutionException("Error during plugin execution", e);
} finally {
if (dockerClient != null) {
try {
dockerClient.close();
} catch (IOException e) {
}
}
}
}
private void validateParameters() throws MojoExecutionException {
if (directory == null) {
throw new MojoExecutionException("missing option 'directory'");
}
if (imageName == null) {
throw new MojoExecutionException("missing option 'imageName'");
}
}
private void build(DockerClient dockerClient) throws IOException {
getLog().info("Building image ...");
Resource dockerResource = new Resource();
dockerResource.setDirectory(directory.toString());
resources.add(dockerResource);
Path buildPath = Paths.get(buildDirectory.toString(), "docker");
for (Resource resource : resources) {
List<String> includes = resource.getIncludes();
List<String> excludes = resource.getExcludes();
DirectoryScanner scanner = new DirectoryScanner();
scanner.setBasedir(new File(resource.getDirectory()));
scanner.setIncludes(includes.isEmpty() ? null : includes.toArray(new String[includes.size()]));
scanner.setExcludes(excludes.isEmpty() ? null : excludes.toArray(new String[excludes.size()]));
scanner.scan();
String[] includedFiles = scanner.getIncludedFiles();
if (includedFiles.length == 0)
continue;
boolean copyDirectory = includes.isEmpty() && excludes.isEmpty() && (resource.getTargetPath() != null);
if (copyDirectory) {
Path source = Paths.get(resource.getDirectory());
Path destination = Paths.get(buildPath.toString(), resource.getTargetPath());
Files.createDirectories(destination);
Files.walkFileTree(source, new CopyDirectory(source, destination));
} else {
for (String file : includedFiles) {
Path source = Paths.get(resource.getDirectory()).resolve(file);
Path destination = Paths.get(buildPath.toString(),
(resource.getTargetPath() == null ? "" : resource.getTargetPath())).resolve(file);
Files.createDirectories(destination.getParent());
Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING,
StandardCopyOption.COPY_ATTRIBUTES);
}
}
}
BuildImageResultCallback callback = new BuildImageResultCallback() {
@Override
public void onNext(BuildResponseItem item) {
if (item.getStream() != null) {
getLog().info(item.getStream().trim());
}
super.onNext(item);
}
};
String imageId = dockerClient.buildImageCmd(buildPath.toFile()).withForcerm(forceRm).withNoCache(noCache)
.withPull(pull).exec(callback).awaitImageId();
if (imageTags.isEmpty()) {
dockerClient.tagImageCmd(imageId, imageName, "latest").exec();
} else {
for (String imageTag : imageTags) {
dockerClient.tagImageCmd(imageId, imageName, imageTag).exec();
}
}
if (push) {
getLog().info("Pushing image ...");
if (imageTags.isEmpty()) {
PushImageCmd cmd = dockerClient.pushImageCmd(imageName);
cmd.withTag("latest").exec(new PushImageResultCallback()).awaitSuccess();
} else {
for (String imageTag : imageTags) {
PushImageCmd cmd = dockerClient.pushImageCmd(imageName);
cmd.withTag(imageTag).exec(new PushImageResultCallback()).awaitSuccess();
}
}
}
if (remove) {
getLog().info("Removing image ...");
RemoveImageCmd cmd = dockerClient.removeImageCmd(imageId);
cmd.withForce(true).exec();
}
}
private static class CopyDirectory extends SimpleFileVisitor<Path> {
private Path sourcePath;
private Path destinationPath;
public CopyDirectory(Path sourcePath, Path destinationPath) {
this.sourcePath = sourcePath;
this.destinationPath = destinationPath;
}
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
Path target = destinationPath.resolve(sourcePath.relativize(dir));
if (Files.notExists(target)) {
Files.createDirectories(destinationPath.resolve(sourcePath.relativize(dir)));
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.copy(file, destinationPath.resolve(sourcePath.relativize(file)), StandardCopyOption.REPLACE_EXISTING,
StandardCopyOption.COPY_ATTRIBUTES);
return FileVisitResult.CONTINUE;
}
}
} |
package org.mwc.cmap.core.property_support;
import java.beans.*;
import java.lang.reflect.*;
import java.util.*;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.operations.AbstractOperation;
import org.eclipse.core.runtime.*;
import org.eclipse.jface.action.*;
import org.eclipse.swt.dnd.Clipboard;
import org.mwc.cmap.core.CorePlugin;
import org.mwc.cmap.core.operations.*;
import MWC.GUI.*;
import MWC.GUI.Editable.EditorType;
public class RightClickSupport
{
/**
* list of actions to be added to context-menu on right-click
*/
private static Vector _additionalRightClickItems = null;
/**
* add a right-click generator item to the list we manage
*
* @param generator
* the generator to add...
*/
public static void addRightClickGenerator(RightClickContextItemGenerator generator)
{
if (_additionalRightClickItems == null)
_additionalRightClickItems = new Vector(1, 1);
_additionalRightClickItems.add(generator);
}
/**
* @param manager
* @param hideClipboardOperations
* @param pw
*/
static public void getDropdownListFor(IMenuManager manager, Editable[] editables,
Layer[] topLevelLayers, Layer[] parentLayers, final Layers theLayers,
boolean hideClipboardOperations)
{
// sort out the top level layer, if we have one
Layer theTopLayer = null;
if (topLevelLayers != null)
if (topLevelLayers.length > 0)
theTopLayer = topLevelLayers[0];
// and now the editable bits
Editable p = null;
if (editables.length > 0)
{
p = editables[0];
EditorType editor = p.getInfo();
MenuManager subMenu = null;
// hmm does it have anything editable?
if (editor != null)
{
// and now the parameters
PropertyDescriptor[] pd = editor.getPropertyDescriptors();
for (int i = 0; i < pd.length; i++)
{
PropertyDescriptor thisP = pd[i];
// start off with the booleans
if (supportsBooleanEditor(thisP))
{
// generate boolean editors in the sub-menu
subMenu = generateBooleanEditorFor(manager, subMenu, thisP, p, theLayers,
theTopLayer);
}
else
{
// now the drop-down lists
if (supportsListEditor(thisP))
{
// generate boolean editors in the sub-menu
subMenu = generateListEditorFor(manager, subMenu, thisP, p, theLayers,
theTopLayer);
}
}
}
// hmm, have a go at methods for this item
// ok, try the methods
MethodDescriptor[] meths = editor.getMethodDescriptors();
if (meths != null)
{
for (int i = 0; i < meths.length; i++)
{
final Layer myTopLayer = theTopLayer;
final MethodDescriptor thisMethD = meths[i];
// create button for this method
Action doThisAction = new SubjectAction(thisMethD.getDisplayName(), p,
thisMethD.getMethod(), myTopLayer, theLayers);
// ok - add to the list.
manager.add(doThisAction);
}
}
}
}
Clipboard theClipboard = CorePlugin.getDefault().getClipboard();
// see if we're still looking at the parent element (we only show clipboard
// operations for item clicked on)
if (!hideClipboardOperations)
{
// hey, also see if we're going to do a cut/paste
RightClickCutCopyAdaptor.getDropdownListFor(manager, editables, topLevelLayers,
topLevelLayers, theLayers, theClipboard);
// what about paste?
Editable selectedItem = null;
if (editables.length == 1)
{
selectedItem = editables[0];
}
RightClickPasteAdaptor.getDropdownListFor(manager, selectedItem, topLevelLayers,
topLevelLayers, theLayers, theClipboard);
manager.add(new Separator());
}
// hmm, do we have any right-click generators?
if (_additionalRightClickItems != null)
{
for (Iterator thisItem = _additionalRightClickItems.iterator(); thisItem.hasNext();)
{
RightClickContextItemGenerator thisGen = (RightClickContextItemGenerator) thisItem
.next();
thisGen.generate(manager, theLayers, topLevelLayers, editables);
}
}
}
/**
* embedded class that encapsulates the information we need to fire an action.
* It was really only refactored to aid debugging.
*
* @author ian.mayo
*/
private static class SubjectAction extends Action
{
private Object _subject;
private Method _method;
private Layer _topLayer;
private Layers _theLayers;
/**
* @param title
* what to call the action
* @param subject
* the thing we're operating upon
* @param method
* what we're going to run
* @param topLayer
* the layer to update after the action is complete
* @param theLayers
* the host for the target layer
*/
public SubjectAction(String title, Object subject, Method method, Layer topLayer,
Layers theLayers)
{
super(title);
_subject = subject;
_method = method;
_topLayer = topLayer;
_theLayers = theLayers;
}
public void run()
{
try
{
_method.invoke(_subject, new Object[0]);
// hey, let's do a redraw aswell...
_theLayers.fireModified(_topLayer);
}
catch (IllegalArgumentException e)
{
CorePlugin.logError(Status.ERROR, "whilst firing method from right-click", e);
}
catch (IllegalAccessException e)
{
CorePlugin.logError(Status.ERROR, "whilst firing method from right-click", e);
}
catch (InvocationTargetException e)
{
CorePlugin.logError(Status.ERROR, "whilst firing method from right-click", e);
}
}
}
/**
* can we edit this property with a tick-box?
*
* @param thisP
* @return yes/no
*/
static private boolean supportsBooleanEditor(PropertyDescriptor thisP)
{
final boolean res;
// get the prop type
Class thisType = thisP.getPropertyType();
Class boolClass = Boolean.class;
// is it boolean?
if ((thisType == boolClass) || (thisType.equals(boolean.class)))
{
res = true;
}
else
{
res = false;
}
return res;
}
/**
* can we edit this property with a drop-down list?
*
* @param thisP
* @return yes/no
*/
static private boolean supportsListEditor(PropertyDescriptor thisP)
{
boolean res = false;
// find out the type of the editor
Method m = thisP.getReadMethod();
Class cl = m.getReturnType();
// is there a custom editor for this type?
Class c = thisP.getPropertyEditorClass();
PropertyEditor pe = null;
// try to create an editor for this class
try
{
if (c != null)
pe = (PropertyEditor) c.newInstance();
}
catch (Exception e)
{
MWC.Utilities.Errors.Trace.trace(e);
}
// did it work?
if (pe == null)
{
// try to find an editor for this through our manager
pe = PropertyEditorManager.findEditor(cl);
}
// have we managed to create an editor?
if (pe != null)
{
// retrieve the tags
String[] tags = pe.getTags();
// are there any tags for this class?
if (tags != null)
{
res = true;
}
}
return res;
}
static private MenuManager generateBooleanEditorFor(final IMenuManager manager,
MenuManager subMenu, final PropertyDescriptor thisP, final Editable p,
final Layers theLayers, final Layer topLevelLayer)
{
boolean currentVal = false;
final Method getter = thisP.getReadMethod();
final Method setter = thisP.getWriteMethod();
try
{
final Boolean valNow = (Boolean) getter.invoke(p, null);
currentVal = valNow.booleanValue();
}
catch (Exception e)
{
CorePlugin.logError(Status.ERROR,
"Failed to retrieve old value for:" + p.getName(), e);
}
IAction changeThis = new Action(thisP.getDisplayName(), IAction.AS_CHECK_BOX)
{
public void run()
{
try
{
ListPropertyAction la = new ListPropertyAction(thisP.getDisplayName(), p,
getter, setter, new Boolean(isChecked()), theLayers, topLevelLayer);
CorePlugin.run(la);
}
catch (Exception e)
{
CorePlugin.logError(IStatus.INFO,
"While executing boolean editor for:" + thisP, e);
}
}
};
changeThis.setChecked(currentVal);
changeThis.setToolTipText(thisP.getShortDescription());
// is our sub-menu already created?
if (subMenu == null)
{
subMenu = new MenuManager(p.getName());
manager.add(subMenu);
}
subMenu.add(changeThis);
return subMenu;
}
static private MenuManager generateListEditorFor(IMenuManager manager,
MenuManager subMenu, final PropertyDescriptor thisP, final Editable p,
final Layers theLayers, final Layer topLevelLayer)
{
// find out the type of the editor
Method m = thisP.getReadMethod();
Class cl = m.getReturnType();
// is there a custom editor for this type?
Class c = thisP.getPropertyEditorClass();
PropertyEditor pe = null;
// try to create an editor for this class
try
{
if (c != null)
pe = (PropertyEditor) c.newInstance();
}
catch (Exception e)
{
MWC.Utilities.Errors.Trace.trace(e);
}
// did it work?
if (pe == null)
{
// try to find an editor for this through our manager
pe = PropertyEditorManager.findEditor(cl);
}
// retrieve the tags
String[] tags = pe.getTags();
// are there any tags for this class?
if (tags != null)
{
// create a drop-down list
MenuManager thisChoice = new MenuManager(thisP.getDisplayName());
// sort out the setter details
final Method getter = thisP.getReadMethod();
// get the current value
Object val = null;
try
{
val = getter.invoke(p, null);
}
catch (Exception e)
{
MWC.Utilities.Errors.Trace.trace(e);
}
pe.setValue(val);
// convert the current value to text
String currentValue = pe.getAsText();
// and now a drop-down item for each options
for (int j = 0; j < tags.length; j++)
{
final String thisTag = tags[j];
pe.setAsText(thisTag);
final Object thisValue = pe.getValue();
// create the item
IAction thisA = new Action(thisTag, IAction.AS_RADIO_BUTTON)
{
public void run()
{
try
{
Method setter = thisP.getWriteMethod();
// ok, place the change in the action
ListPropertyAction la = new ListPropertyAction(thisP.getDisplayName(), p,
getter, setter, thisValue, theLayers, topLevelLayer);
// and add it to the history
CorePlugin.run(la);
}
catch (Exception e)
{
CorePlugin.logError(IStatus.INFO, "While executing select editor for:"
+ thisP, e);
}
};
};
// is this the current one?
if (thisTag.equals(currentValue))
{
thisA.setChecked(true);
}
// add it to the menu
thisChoice.add(thisA);
}
// is our sub-menu already created?
if (subMenu == null)
{
subMenu = new MenuManager(p.getName());
manager.add(subMenu);
}
subMenu.add(thisChoice);
}
return subMenu;
}
/**
* template provide by support units that want to add items to the right-click
* menu when something is selected
*
* @author ian.mayo
*/
public static interface RightClickContextItemGenerator
{
public void generate(IMenuManager parent, Layers theLayers, Layer[] parentLayers,
Editable[] subjects);
}
/**
* embedded class to store a property change in an action
*
* @author ian.mayo
*/
private static class ListPropertyAction extends AbstractOperation
{
private Object _oldValue;
private final Method _setter;
private final Layers _layers;
private final Layer _parentLayer;
private final Editable _subject;
private final Object _newValue;
public ListPropertyAction(final String propertyName, final Editable subject,
final Method getter, final Method setter, final Object newValue,
final Layers layers, final Layer parentLayer)
{
super(propertyName + " for " + subject.getName());
_setter = setter;
_layers = layers;
_parentLayer = parentLayer;
_subject = subject;
_newValue = newValue;
try
{
_oldValue = getter.invoke(subject, null);
}
catch (Exception e)
{
CorePlugin.logError(Status.ERROR, "Failed to retrieve old value for:"
+ _subject.getName(), e);
}
// put in the global context, for some reason
super.addContext(CorePlugin.CMAP_CONTEXT);
}
public IStatus execute(IProgressMonitor monitor, IAdaptable info)
throws ExecutionException
{
IStatus res = Status.OK_STATUS;
try
{
_setter.invoke(_subject, new Object[] { _newValue });
}
catch (InvocationTargetException e)
{
CorePlugin
.logError(Status.ERROR, "Setter call failed:" + _subject.getName()
+ " Error was:" + e.getTargetException().getMessage(), e
.getTargetException());
res = null;
}
catch (IllegalArgumentException e)
{
CorePlugin.logError(Status.ERROR, "Wrong parameters pass to:"
+ _subject.getName(), e);
res = null;
}
catch (IllegalAccessException e)
{
CorePlugin.logError(Status.ERROR, "Illegal access problem for:"
+ _subject.getName(), e);
res = null;
}
// and tell everybody
fireUpdate();
return res;
}
public IStatus redo(IProgressMonitor monitor, IAdaptable info)
throws ExecutionException
{
IStatus res = Status.OK_STATUS;
try
{
_setter.invoke(_subject, new Object[] { _newValue });
}
catch (Exception e)
{
CorePlugin.logError(Status.ERROR, "Failed to set new value for:"
+ _subject.getName(), e);
res = null;
}
// and tell everybody
fireUpdate();
return res;
}
public IStatus undo(IProgressMonitor monitor, IAdaptable info)
throws ExecutionException
{
IStatus res = Status.OK_STATUS;
try
{
_setter.invoke(_subject, new Object[] { _oldValue });
}
catch (Exception e)
{
CorePlugin.logError(Status.ERROR, "Failed to set new value for:"
+ _subject.getName(), e);
res = null;
}
// and tell everybody
fireUpdate();
return res;
}
private void fireUpdate()
{
_layers.fireModified(_parentLayer);
}
}
} |
package cz.habarta.typescript.generator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.Module;
import com.fasterxml.jackson.databind.ObjectMapper;
import cz.habarta.typescript.generator.compiler.ModelCompiler;
import cz.habarta.typescript.generator.compiler.SymbolTable.CustomTypeNamingFunction;
import cz.habarta.typescript.generator.emitter.EmitterExtension;
import cz.habarta.typescript.generator.emitter.EmitterExtensionFeatures;
import cz.habarta.typescript.generator.parser.JaxrsApplicationParser;
import cz.habarta.typescript.generator.parser.RestApplicationParser;
import cz.habarta.typescript.generator.parser.TypeParser;
import cz.habarta.typescript.generator.util.Pair;
import cz.habarta.typescript.generator.util.Utils;
import java.io.File;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.TypeVariable;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Predicate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Settings {
public String newline = String.format("%n");
public String quotes = "\"";
public String indentString = " ";
public TypeScriptFileType outputFileType = TypeScriptFileType.declarationFile;
public TypeScriptOutputKind outputKind = null;
public String module = null;
public String namespace = null;
public boolean mapPackagesToNamespaces = false;
public String umdNamespace = null;
public List<ModuleDependency> moduleDependencies = new ArrayList<>();
private LoadedModuleDependencies loadedModuleDependencies = null;
public JsonLibrary jsonLibrary = null;
public Jackson2ConfigurationResolved jackson2Configuration = null;
public GsonConfiguration gsonConfiguration = null;
public JsonbConfiguration jsonbConfiguration = null;
public List<String> additionalDataLibraries = new ArrayList<>();
private LoadedDataLibraries loadedDataLibrariesClasses = null;
private Predicate<String> excludeFilter = null;
public OptionalProperties optionalProperties; // default is OptionalProperties.useSpecifiedAnnotations
public OptionalPropertiesDeclaration optionalPropertiesDeclaration; // default is OptionalPropertiesDeclaration.questionMark
public NullabilityDefinition nullabilityDefinition; // default is NullabilityDefinition.nullInlineUnion
private TypeParser typeParser = null;
public boolean declarePropertiesAsReadOnly = false;
public String removeTypeNamePrefix = null;
public String removeTypeNameSuffix = null;
public String addTypeNamePrefix = null;
public String addTypeNameSuffix = null;
public Map<String, String> customTypeNaming = new LinkedHashMap<>();
public String customTypeNamingFunction = null;
public CustomTypeNamingFunction customTypeNamingFunctionImpl = null;
public List<String> referencedFiles = new ArrayList<>();
public List<String> importDeclarations = new ArrayList<>();
public Map<String, String> customTypeMappings = new LinkedHashMap<>();
private List<CustomTypeMapping> validatedCustomTypeMappings = null;
public Map<String, String> customTypeAliases = new LinkedHashMap<>();
private List<CustomTypeAlias> validatedCustomTypeAliases = null;
public DateMapping mapDate; // default is DateMapping.asDate
public MapMapping mapMap; // default is MapMapping.asIndexedArray
public EnumMapping mapEnum; // default is EnumMapping.asUnion
public IdentifierCasing enumMemberCasing; // default is IdentifierCasing.keepOriginal
public boolean nonConstEnums = false;
public List<Class<? extends Annotation>> nonConstEnumAnnotations = new ArrayList<>();
public ClassMapping mapClasses; // default is ClassMapping.asInterfaces
public List<String> mapClassesAsClassesPatterns;
private Predicate<String> mapClassesAsClassesFilter = null;
public boolean generateConstructors = false;
public List<Class<? extends Annotation>> disableTaggedUnionAnnotations = new ArrayList<>();
public boolean disableTaggedUnions = false;
public boolean generateReadonlyAndWriteonlyJSDocTags = false;
public boolean ignoreSwaggerAnnotations = false;
public boolean generateJaxrsApplicationInterface = false;
public boolean generateJaxrsApplicationClient = false;
public boolean generateSpringApplicationInterface = false;
public boolean generateSpringApplicationClient = false;
public boolean scanSpringApplication;
public RestNamespacing restNamespacing;
public Class<? extends Annotation> restNamespacingAnnotation = null;
public String restNamespacingAnnotationElement; // default is "value"
public String restResponseType = null;
public String restOptionsType = null;
public boolean restOptionsTypeIsGeneric;
private List<RestApplicationParser.Factory> restApplicationParserFactories;
public TypeProcessor customTypeProcessor = null;
public boolean sortDeclarations = false;
public boolean sortTypeDeclarations = false;
public boolean noFileComment = false;
public boolean noTslintDisable = false;
public boolean noEslintDisable = false;
public boolean tsNoCheck = false;
public List<File> javadocXmlFiles = null;
public List<EmitterExtension> extensions = new ArrayList<>();
public List<Class<? extends Annotation>> includePropertyAnnotations = new ArrayList<>();
public List<Class<? extends Annotation>> excludePropertyAnnotations = new ArrayList<>();
public List<Class<? extends Annotation>> optionalAnnotations = new ArrayList<>();
public List<Class<? extends Annotation>> requiredAnnotations = new ArrayList<>();
public List<Class<? extends Annotation>> nullableAnnotations = new ArrayList<>();
public boolean primitivePropertiesRequired = false;
public boolean generateInfoJson = false;
public boolean generateNpmPackageJson = false;
public String npmName = null;
public String npmVersion = null;
public Map<String, String> npmPackageDependencies = new LinkedHashMap<>();
public Map<String, String> npmDevDependencies = new LinkedHashMap<>();
public Map<String, String> npmPeerDependencies = new LinkedHashMap<>();
public String typescriptVersion = "^2.4";
public String npmTypescriptVersion = null;
public String npmBuildScript = null;
public boolean jackson2ModuleDiscovery = false;
public List<Class<? extends Module>> jackson2Modules = new ArrayList<>();
public ClassLoader classLoader = null;
private boolean defaultStringEnumsOverriddenByExtension = false;
public static class ConfiguredExtension {
public String className;
public Map<String, String> configuration;
}
public static class CustomTypeMapping {
public final Class<?> rawClass;
public final boolean matchSubclasses;
public final GenericName javaType;
public final GenericName tsType;
public CustomTypeMapping(Class<?> rawClass, boolean matchSubclasses, GenericName javaType, GenericName tsType) {
this.rawClass = rawClass;
this.matchSubclasses = matchSubclasses;
this.javaType = javaType;
this.tsType = tsType;
}
@Override
public String toString() {
return Utils.objectToString(this);
}
}
public static class CustomTypeAlias {
public final GenericName tsType;
public final String tsDefinition;
public CustomTypeAlias(GenericName tsType, String tsDefinition) {
this.tsType = tsType;
this.tsDefinition = tsDefinition;
}
}
public static class GenericName {
public final String rawName;
public final List<String> typeParameters;
public GenericName(String rawName, List<String> typeParameters) {
this.rawName = Objects.requireNonNull(rawName);
this.typeParameters = typeParameters;
}
public int indexOfTypeParameter(String typeParameter) {
return typeParameters != null ? typeParameters.indexOf(typeParameter) : -1;
}
}
private static class TypeScriptGeneratorURLClassLoader extends URLClassLoader {
private final String name;
public TypeScriptGeneratorURLClassLoader(String name, URL[] urls, ClassLoader parent) {
super(urls, parent);
this.name = name;
}
@Override
public String toString() {
return "TsGenURLClassLoader{" + name + ", parent: " + getParent() + "}";
}
}
public static URLClassLoader createClassLoader(String name, URL[] urls, ClassLoader parent) {
return new TypeScriptGeneratorURLClassLoader(name, urls, parent);
}
public void setStringQuotes(StringQuotes quotes) {
this.quotes = quotes == StringQuotes.singleQuotes ? "'" : "\"";
}
public void setIndentString(String indentString) {
this.indentString = indentString != null ? indentString : " ";
}
public void setJackson2Configuration(ClassLoader classLoader, Jackson2Configuration configuration) {
if (configuration != null) {
jackson2Configuration = Jackson2ConfigurationResolved.from(configuration, classLoader);
}
}
public void loadCustomTypeProcessor(ClassLoader classLoader, String customTypeProcessor) {
if (customTypeProcessor != null) {
this.customTypeProcessor = loadInstance(classLoader, customTypeProcessor, TypeProcessor.class);
}
}
public void loadExtensions(ClassLoader classLoader, List<String> extensions, List<Settings.ConfiguredExtension> extensionsWithConfiguration) {
this.extensions = new ArrayList<>();
this.extensions.addAll(loadInstances(classLoader, extensions, EmitterExtension.class));
if (extensionsWithConfiguration != null) {
for (ConfiguredExtension configuredExtension : extensionsWithConfiguration) {
final EmitterExtension emitterExtension = loadInstance(classLoader, configuredExtension.className, EmitterExtension.class);
if (emitterExtension instanceof Extension) {
final Extension extension = (Extension) emitterExtension;
extension.setConfiguration(Utils.mapFromNullable(configuredExtension.configuration));
}
this.extensions.add(emitterExtension);
}
}
}
public void loadNonConstEnumAnnotations(ClassLoader classLoader, List<String> stringAnnotations) {
this.nonConstEnumAnnotations = loadClasses(classLoader, stringAnnotations, Annotation.class);
}
public void loadIncludePropertyAnnotations(ClassLoader classLoader, List<String> includePropertyAnnotations) {
this.includePropertyAnnotations = loadClasses(classLoader, includePropertyAnnotations, Annotation.class);
}
public void loadExcludePropertyAnnotations(ClassLoader classLoader, List<String> excludePropertyAnnotations) {
this.excludePropertyAnnotations = loadClasses(classLoader, excludePropertyAnnotations, Annotation.class);
}
public void loadOptionalAnnotations(ClassLoader classLoader, List<String> optionalAnnotations) {
this.optionalAnnotations = loadClasses(classLoader, optionalAnnotations, Annotation.class);
}
public void loadRequiredAnnotations(ClassLoader classLoader, List<String> requiredAnnotations) {
this.requiredAnnotations = loadClasses(classLoader, requiredAnnotations, Annotation.class);
}
public void loadNullableAnnotations(ClassLoader classLoader, List<String> nullableAnnotations) {
this.nullableAnnotations = loadClasses(classLoader, nullableAnnotations, Annotation.class);
}
public void loadDisableTaggedUnionAnnotations(ClassLoader classLoader, List<String> disableTaggedUnionAnnotations) {
this.disableTaggedUnionAnnotations = loadClasses(classLoader, disableTaggedUnionAnnotations, Annotation.class);
}
public void loadJackson2Modules(ClassLoader classLoader, List<String> jackson2Modules) {
this.jackson2Modules = loadClasses(classLoader, jackson2Modules, Module.class);
}
public static Map<String, String> convertToMap(List<String> items, String itemName) {
final Map<String, String> result = new LinkedHashMap<>();
if (items != null) {
for (String item : items) {
final String[] values = item.split(":", 2);
if (values.length < 2) {
throw new RuntimeException(String.format("Invalid '%s' format: %s", itemName, item));
}
result.put(values[0].trim(), values[1].trim());
}
}
return result;
}
public void validate() {
if (classLoader == null) {
classLoader = Thread.currentThread().getContextClassLoader();
}
if (outputKind == null) {
throw new RuntimeException("Required 'outputKind' parameter is not configured. " + seeLink());
}
if (outputKind == TypeScriptOutputKind.ambientModule && outputFileType == TypeScriptFileType.implementationFile) {
throw new RuntimeException("Ambient modules are not supported in implementation files. " + seeLink());
}
if (outputKind == TypeScriptOutputKind.ambientModule && module == null) {
throw new RuntimeException("'module' parameter must be specified for ambient module. " + seeLink());
}
if (outputKind != TypeScriptOutputKind.ambientModule && module != null) {
throw new RuntimeException("'module' parameter is only applicable to ambient modules. " + seeLink());
}
if (outputKind != TypeScriptOutputKind.module && umdNamespace != null) {
throw new RuntimeException("'umdNamespace' parameter is only applicable to modules. " + seeLink());
}
if (outputFileType == TypeScriptFileType.implementationFile && umdNamespace != null) {
throw new RuntimeException("'umdNamespace' parameter is not applicable to implementation files. " + seeLink());
}
if (umdNamespace != null && !ModelCompiler.isValidIdentifierName(umdNamespace)) {
throw new RuntimeException("Value of 'umdNamespace' parameter is not valid identifier: " + umdNamespace + ". " + seeLink());
}
if (jsonLibrary == null) {
throw new RuntimeException("Required 'jsonLibrary' parameter is not configured.");
}
if (jackson2Configuration != null && jsonLibrary != JsonLibrary.jackson2) {
throw new RuntimeException("'jackson2Configuration' parameter is only applicable to 'jackson2' library.");
}
if (!generateNpmPackageJson && (!npmPackageDependencies.isEmpty() || !npmDevDependencies.isEmpty() || !npmPeerDependencies.isEmpty())) {
throw new RuntimeException("'npmDependencies', 'npmDevDependencies' and 'npmPeerDependencies' parameters are only applicable when generating NPM 'package.json'.");
}
getValidatedCustomTypeMappings();
getValidatedCustomTypeAliases();
for (EmitterExtension extension : extensions) {
final String extensionName = extension.getClass().getSimpleName();
final DeprecationText deprecation = extension.getClass().getAnnotation(DeprecationText.class);
if (deprecation != null) {
TypeScriptGenerator.getLogger().warning(String.format("Extension '%s' is deprecated: %s", extensionName, deprecation.value()));
}
final EmitterExtensionFeatures features = extension.getFeatures();
if (features.generatesRuntimeCode && outputFileType != TypeScriptFileType.implementationFile) {
throw new RuntimeException(String.format("Extension '%s' generates runtime code but 'outputFileType' parameter is not set to 'implementationFile'.", extensionName));
}
if (features.generatesModuleCode && outputKind != TypeScriptOutputKind.module) {
throw new RuntimeException(String.format("Extension '%s' generates code as module but 'outputKind' parameter is not set to 'module'.", extensionName));
}
if (!features.worksWithPackagesMappedToNamespaces && mapPackagesToNamespaces) {
throw new RuntimeException(String.format("Extension '%s' doesn't work with 'mapPackagesToNamespaces' parameter.", extensionName));
}
if (features.generatesJaxrsApplicationClient) {
reportConfigurationChange(extensionName, "generateJaxrsApplicationClient", "true");
generateJaxrsApplicationClient = true;
}
if (features.restResponseType != null) {
reportConfigurationChange(extensionName, "restResponseType", features.restResponseType);
restResponseType = features.restResponseType;
}
if (features.restOptionsType != null) {
reportConfigurationChange(extensionName, "restOptionsType", features.restOptionsType);
setRestOptionsType(features.restOptionsType);
}
if (features.npmPackageDependencies != null) {
npmPackageDependencies.putAll(features.npmPackageDependencies);
}
if (features.npmDevDependencies != null) {
npmDevDependencies.putAll(features.npmDevDependencies);
}
if (features.npmPeerDependencies != null) {
npmPeerDependencies.putAll(features.npmPeerDependencies);
}
if (features.overridesStringEnums) {
defaultStringEnumsOverriddenByExtension = true;
}
}
if (enumMemberCasing != null && mapEnum != EnumMapping.asEnum && mapEnum != EnumMapping.asNumberBasedEnum) {
throw new RuntimeException("'enumMemberCasing' parameter can only be used when 'mapEnum' parameter is set to 'asEnum' or 'asNumberBasedEnum'.");
}
if ((nonConstEnums || !nonConstEnumAnnotations.isEmpty()) && outputFileType != TypeScriptFileType.implementationFile) {
throw new RuntimeException("Non-const enums can only be used in implementation files but 'outputFileType' parameter is not set to 'implementationFile'.");
}
if (mapClasses == ClassMapping.asClasses && outputFileType != TypeScriptFileType.implementationFile) {
throw new RuntimeException("'mapClasses' parameter is set to 'asClasses' which generates runtime code but 'outputFileType' parameter is not set to 'implementationFile'.");
}
if (mapClassesAsClassesPatterns != null && mapClasses != ClassMapping.asClasses) {
throw new RuntimeException("'mapClassesAsClassesPatterns' parameter can only be used when 'mapClasses' parameter is set to 'asClasses'.");
}
if (generateConstructors && mapClasses != ClassMapping.asClasses) {
throw new RuntimeException("'generateConstructors' parameter can only be used when 'mapClasses' parameter is set to 'asClasses'.");
}
for (Class<? extends Annotation> annotation : optionalAnnotations) {
final Target target = annotation.getAnnotation(Target.class);
final List<ElementType> elementTypes = target != null ? Arrays.asList(target.value()) : Arrays.asList();
if (elementTypes.contains(ElementType.TYPE_PARAMETER) || elementTypes.contains(ElementType.TYPE_USE)) {
TypeScriptGenerator.getLogger().info(String.format(
"Suggestion: annotation '%s' supports 'TYPE_PARAMETER' or 'TYPE_USE' target. Consider using 'nullableAnnotations' parameter instead of 'optionalAnnotations'.",
annotation.getName()));
}
}
if (!optionalAnnotations.isEmpty() && !requiredAnnotations.isEmpty()) {
throw new RuntimeException("Only one of 'optionalAnnotations' and 'requiredAnnotations' can be used at the same time.");
}
if (primitivePropertiesRequired && requiredAnnotations.isEmpty()) {
throw new RuntimeException("'primitivePropertiesRequired' parameter can only be used with 'requiredAnnotations' parameter.");
}
for (Class<? extends Annotation> annotation : nullableAnnotations) {
final Target target = annotation.getAnnotation(Target.class);
final List<ElementType> elementTypes = target != null ? Arrays.asList(target.value()) : Arrays.asList();
if (!elementTypes.contains(ElementType.TYPE_PARAMETER) && !elementTypes.contains(ElementType.TYPE_USE)) {
throw new RuntimeException(String.format(
"'%s' annotation cannot be used as nullable annotation because it doesn't have 'TYPE_PARAMETER' or 'TYPE_USE' target.",
annotation.getName()));
}
}
if (generateJaxrsApplicationClient && outputFileType != TypeScriptFileType.implementationFile) {
throw new RuntimeException("'generateJaxrsApplicationClient' can only be used when generating implementation file ('outputFileType' parameter is 'implementationFile').");
}
if (generateSpringApplicationClient && outputFileType != TypeScriptFileType.implementationFile) {
throw new RuntimeException("'generateSpringApplicationClient' can only be used when generating implementation file ('outputFileType' parameter is 'implementationFile').");
}
if (restNamespacing != null && !isGenerateRest()) {
throw new RuntimeException("'restNamespacing' parameter can only be used when generating REST client or interface.");
}
if (restNamespacingAnnotation != null && restNamespacing != RestNamespacing.byAnnotation) {
throw new RuntimeException("'restNamespacingAnnotation' parameter can only be used when 'restNamespacing' parameter is set to 'byAnnotation'.");
}
if (restNamespacingAnnotation == null && restNamespacing == RestNamespacing.byAnnotation) {
throw new RuntimeException("'restNamespacingAnnotation' must be specified when 'restNamespacing' parameter is set to 'byAnnotation'.");
}
if (restResponseType != null && !isGenerateRest()) {
throw new RuntimeException("'restResponseType' parameter can only be used when generating REST client or interface.");
}
if (restOptionsType != null && !isGenerateRest()) {
throw new RuntimeException("'restOptionsType' parameter can only be used when generating REST client or interface.");
}
if (generateInfoJson && (outputKind != TypeScriptOutputKind.module && outputKind != TypeScriptOutputKind.global)) {
throw new RuntimeException("'generateInfoJson' can only be used when 'outputKind' parameter is 'module' or 'global'.");
}
if (generateNpmPackageJson && outputKind != TypeScriptOutputKind.module) {
throw new RuntimeException("'generateNpmPackageJson' can only be used when generating proper module ('outputKind' parameter is 'module').");
}
if (generateNpmPackageJson) {
if (npmName == null || npmVersion == null) {
throw new RuntimeException("'npmName' and 'npmVersion' must be specified when generating NPM 'package.json'.");
}
}
if (!generateNpmPackageJson) {
if (npmName != null || npmVersion != null) {
throw new RuntimeException("'npmName' and 'npmVersion' is only applicable when generating NPM 'package.json'.");
}
if (npmTypescriptVersion != null) {
throw new RuntimeException("'npmTypescriptVersion' is only applicable when generating NPM 'package.json'.");
}
if (npmBuildScript != null) {
throw new RuntimeException("'npmBuildScript' is only applicable when generating NPM 'package.json'.");
}
}
if (npmTypescriptVersion != null && outputFileType != TypeScriptFileType.implementationFile) {
throw new RuntimeException("'npmTypescriptVersion' can only be used when generating implementation file ('outputFileType' parameter is 'implementationFile').");
}
if (npmBuildScript != null && outputFileType != TypeScriptFileType.implementationFile) {
throw new RuntimeException("'npmBuildScript' can only be used when generating implementation file ('outputFileType' parameter is 'implementationFile').");
}
getModuleDependencies();
getLoadedDataLibraries();
}
public NullabilityDefinition getNullabilityDefinition() {
return nullabilityDefinition != null ? nullabilityDefinition : NullabilityDefinition.nullInlineUnion;
}
public TypeParser getTypeParser() {
if (typeParser == null) {
typeParser = new TypeParser(nullableAnnotations);
}
return typeParser;
}
public List<CustomTypeMapping> getValidatedCustomTypeMappings() {
if (validatedCustomTypeMappings == null) {
validatedCustomTypeMappings = Utils.concat(
validateCustomTypeMappings(customTypeMappings, false),
getLoadedDataLibraries().typeMappings);
}
return validatedCustomTypeMappings;
}
private List<CustomTypeMapping> validateCustomTypeMappings(Map<String, String> customTypeMappings, boolean matchSubclasses) {
final List<CustomTypeMapping> mappings = new ArrayList<>();
for (Map.Entry<String, String> entry : customTypeMappings.entrySet()) {
final String javaName = entry.getKey();
final String tsName = entry.getValue();
try {
final GenericName genericJavaName = parseGenericName(javaName);
final GenericName genericTsName = parseGenericName(tsName);
validateTypeParameters(genericJavaName.typeParameters);
validateTypeParameters(genericTsName.typeParameters);
final Class<?> cls = loadClass(classLoader, genericJavaName.rawName, null);
final int required = cls.getTypeParameters().length;
final int specified = genericJavaName.typeParameters != null ? genericJavaName.typeParameters.size() : 0;
if (specified != required) {
final String parameters = Stream.of(cls.getTypeParameters())
.map(TypeVariable::getName)
.collect(Collectors.joining(", "));
final String signature = cls.getName() + (parameters.isEmpty() ? "" : "<" + parameters + ">");
throw new RuntimeException(String.format(
"Wrong number of specified generic parameters, required: %s, found: %s. Correct format is: '%s'",
required, specified, signature));
}
mappings.add(new CustomTypeMapping(cls, matchSubclasses, genericJavaName, genericTsName));
} catch (Exception e) {
throw new RuntimeException(String.format("Failed to parse configured custom type mapping '%s:%s': %s", javaName, tsName, e.getMessage()), e);
}
}
return mappings;
}
public List<CustomTypeAlias> getValidatedCustomTypeAliases() {
if (validatedCustomTypeAliases == null) {
validatedCustomTypeAliases = Utils.concat(
validateCustomTypeAliases(customTypeAliases),
getLoadedDataLibraries().typeAliases);
}
return validatedCustomTypeAliases;
}
public List<CustomTypeAlias> validateCustomTypeAliases(Map<String, String> customTypeAliases) {
final List<CustomTypeAlias> aliases = new ArrayList<>();
for (Map.Entry<String, String> entry : customTypeAliases.entrySet()) {
final String tsName = entry.getKey();
final String tsDefinition = entry.getValue();
try {
final GenericName genericTsName = parseGenericName(tsName);
if (!ModelCompiler.isValidIdentifierName(genericTsName.rawName)) {
throw new RuntimeException(String.format("Invalid identifier: '%s'", genericTsName.rawName));
}
validateTypeParameters(genericTsName.typeParameters);
aliases.add(new CustomTypeAlias(genericTsName, tsDefinition));
} catch (Exception e) {
throw new RuntimeException(String.format("Failed to parse configured custom type alias '%s:%s': %s", tsName, tsDefinition, e.getMessage()), e);
}
}
return aliases;
}
private static GenericName parseGenericName(String name) {
// Class<T1, T2>
// Class[T1, T2]
final Matcher matcher = Pattern.compile("([^<\\[]+)(<|\\[)([^>\\]]+)(>|\\])").matcher(name);
final String rawName;
final List<String> typeParameters;
if (matcher.matches()) { // is generic?
rawName = matcher.group(1);
typeParameters = Stream.of(matcher.group(3).split(","))
.map(String::trim)
.collect(Collectors.toList());
} else {
rawName = name;
typeParameters = null;
}
return new GenericName(rawName, typeParameters);
}
private static void validateTypeParameters(List<String> typeParameters) {
if (typeParameters == null) {
return;
}
for (String typeParameter : typeParameters) {
if (!ModelCompiler.isValidIdentifierName(typeParameter)) {
throw new RuntimeException(String.format("Invalid generic type parameter: '%s'", typeParameter));
}
}
}
private static void reportConfigurationChange(String extensionName, String parameterName, String parameterValue) {
TypeScriptGenerator.getLogger().info(String.format("Configuration: '%s' extension set '%s' parameter to '%s'", extensionName, parameterName, parameterValue));
}
public String getExtension() {
return outputFileType == TypeScriptFileType.implementationFile ? ".ts" : ".d.ts";
}
public void validateFileName(File outputFile) {
if (outputFileType == TypeScriptFileType.declarationFile && !outputFile.getName().endsWith(".d.ts")) {
throw new RuntimeException("Declaration file must have 'd.ts' extension: " + outputFile);
}
if (outputFileType == TypeScriptFileType.implementationFile && (!outputFile.getName().endsWith(".ts") || outputFile.getName().endsWith(".d.ts"))) {
throw new RuntimeException("Implementation file must have 'ts' extension: " + outputFile);
}
}
public String getDefaultNpmVersion() {
return "1.0.0";
}
public LoadedModuleDependencies getModuleDependencies() {
if (loadedModuleDependencies == null) {
loadedModuleDependencies = new LoadedModuleDependencies(this, moduleDependencies);
}
return loadedModuleDependencies;
}
public LoadedDataLibraries getLoadedDataLibraries() {
if (loadedDataLibrariesClasses == null) {
loadedDataLibrariesClasses = loadDataLibrariesClasses();
}
return loadedDataLibrariesClasses;
}
private LoadedDataLibraries loadDataLibrariesClasses() {
if (additionalDataLibraries == null) {
return new LoadedDataLibraries();
}
final List<LoadedDataLibraries> loaded = new ArrayList<>();
final ObjectMapper objectMapper = Utils.getObjectMapper();
objectMapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
for (String library : additionalDataLibraries) {
final String resource = "datalibrary/" + library + ".json";
TypeScriptGenerator.getLogger().verbose("Loading resource " + resource);
final InputStream inputStream = classLoader.getResourceAsStream(resource);
if (inputStream == null) {
throw new RuntimeException("Resource not found: " + resource);
}
final DataLibraryJson dataLibrary = Utils.loadJson(objectMapper, inputStream, DataLibraryJson.class);
final Map<String, String> typeMappings = Utils.listFromNullable(dataLibrary.classMappings).stream()
.filter(mapping -> mapping.customType != null)
.collect(Utils.toMap(
mapping -> mapping.className,
mapping -> mapping.customType
));
final Map<String, String> typeAliases = Utils.listFromNullable(dataLibrary.typeAliases).stream()
.collect(Utils.toMap(
alias -> alias.name,
alias -> alias.definition
));
loaded.add(new LoadedDataLibraries(
loadDataLibraryClasses(dataLibrary, DataLibraryJson.SemanticType.String),
loadDataLibraryClasses(dataLibrary, DataLibraryJson.SemanticType.Number),
loadDataLibraryClasses(dataLibrary, DataLibraryJson.SemanticType.Boolean),
loadDataLibraryClasses(dataLibrary, DataLibraryJson.SemanticType.Date),
loadDataLibraryClasses(dataLibrary, DataLibraryJson.SemanticType.Any),
loadDataLibraryClasses(dataLibrary, DataLibraryJson.SemanticType.Void),
loadDataLibraryClasses(dataLibrary, DataLibraryJson.SemanticType.List),
loadDataLibraryClasses(dataLibrary, DataLibraryJson.SemanticType.Map),
loadDataLibraryClasses(dataLibrary, DataLibraryJson.SemanticType.Optional),
loadDataLibraryClasses(dataLibrary, DataLibraryJson.SemanticType.Wrapper),
validateCustomTypeMappings(typeMappings, true),
validateCustomTypeAliases(typeAliases)
));
}
return LoadedDataLibraries.join(loaded);
}
private List<Class<?>> loadDataLibraryClasses(DataLibraryJson dataLibrary, DataLibraryJson.SemanticType semanticType) {
final List<String> classNames = dataLibrary.classMappings.stream()
.filter(mapping -> mapping.semanticType == semanticType)
.map(mapping -> mapping.className)
.collect(Collectors.toList());
return loadClasses(classLoader, classNames, null);
}
public Predicate<String> getExcludeFilter() {
if (excludeFilter == null) {
setExcludeFilter(null, null);
}
return excludeFilter;
}
public void setExcludeFilter(List<String> excludedClasses, List<String> excludedClassPatterns) {
this.excludeFilter = createExcludeFilter(excludedClasses, excludedClassPatterns);
}
public static Predicate<String> createExcludeFilter(List<String> excludedClasses, List<String> excludedClassPatterns) {
final Set<String> names = new LinkedHashSet<>(excludedClasses != null ? excludedClasses : Collections.<String>emptyList());
names.add("java.lang.Record");
final List<Pattern> patterns = Utils.globsToRegexps(excludedClassPatterns != null ? excludedClassPatterns : Collections.<String>emptyList());
return new Predicate<String>() {
@Override
public boolean test(String className) {
return names.contains(className) || Utils.classNameMatches(className, patterns);
}
};
}
public Predicate<String> getMapClassesAsClassesFilter() {
if (mapClassesAsClassesFilter == null) {
final List<Pattern> patterns = Utils.globsToRegexps(mapClassesAsClassesPatterns);
mapClassesAsClassesFilter = new Predicate<String>() {
@Override
public boolean test(String className) {
return mapClasses == ClassMapping.asClasses &&
(patterns == null || Utils.classNameMatches(className, patterns));
}
};
}
return mapClassesAsClassesFilter;
}
public void setRestNamespacingAnnotation(ClassLoader classLoader, String restNamespacingAnnotation) {
final Pair<Class<? extends Annotation>, String> pair = resolveRestNamespacingAnnotation(classLoader, restNamespacingAnnotation);
if (pair != null) {
this.restNamespacingAnnotation = pair.getValue1();
this.restNamespacingAnnotationElement = pair.getValue2();
}
}
private static Pair<Class<? extends Annotation>, String> resolveRestNamespacingAnnotation(ClassLoader classLoader, String restNamespacingAnnotation) {
if (restNamespacingAnnotation == null) {
return null;
}
final String[] split = restNamespacingAnnotation.split("
final String className = split[0];
final String elementName = split.length > 1 ? split[1] : "value";
final Class<? extends Annotation> annotationClass = loadClass(classLoader, className, Annotation.class);
return Pair.of(annotationClass, elementName);
}
public void setRestOptionsType(String restOptionsType) {
if (restOptionsType != null) {
if (restOptionsType.startsWith("<") && restOptionsType.endsWith(">")) {
this.restOptionsType = restOptionsType.substring(1, restOptionsType.length() - 1);
this.restOptionsTypeIsGeneric = true;
} else {
this.restOptionsType = restOptionsType;
this.restOptionsTypeIsGeneric = false;
}
}
}
public List<RestApplicationParser.Factory> getRestApplicationParserFactories() {
if (restApplicationParserFactories == null) {
final List<RestApplicationParser.Factory> factories = new ArrayList<>();
if (isGenerateJaxrs() || !isGenerateSpring()) {
factories.add(new JaxrsApplicationParser.Factory());
}
if (isGenerateSpring()) {
final String springClassName = "cz.habarta.typescript.generator.spring.SpringApplicationParser$Factory";
final Class<?> springClass;
try {
springClass = Class.forName(springClassName);
} catch (ClassNotFoundException e) {
throw new RuntimeException("'generateStringApplicationInterface' or 'generateStringApplicationClient' parameter "
+ "was specified but '" + springClassName + "' was not found. "
+ "Please add 'cz.habarta.typescript-generator:typescript-generator-spring' artifact "
+ "to typescript-generator plugin dependencies (not module dependencies).");
}
try {
final Object instance = springClass.getConstructor().newInstance();
factories.add((RestApplicationParser.Factory) instance);
} catch (ReflectiveOperationException e) {
throw new RuntimeException(e);
}
}
restApplicationParserFactories = factories;
}
return restApplicationParserFactories;
}
public boolean isGenerateJaxrs() {
return generateJaxrsApplicationInterface || generateJaxrsApplicationClient;
}
public boolean isGenerateSpring() {
return generateSpringApplicationInterface || generateSpringApplicationClient;
}
public boolean isGenerateRest() {
return isGenerateJaxrs() || isGenerateSpring();
}
public boolean areDefaultStringEnumsOverriddenByExtension() {
return defaultStringEnumsOverriddenByExtension;
}
private String seeLink() {
return "For more information see 'http://vojtechhabarta.github.io/typescript-generator/doc/ModulesAndNamespaces.html'.";
}
private static <T> List<Class<? extends T>> loadClasses(ClassLoader classLoader, List<String> classNames, Class<T> requiredClassType) {
if (classNames == null) {
return Collections.emptyList();
}
final List<Class<? extends T>> classes = new ArrayList<>();
for (String className : classNames) {
classes.add(loadClass(classLoader, className, requiredClassType));
}
return classes;
}
static <T> Class<? extends T> loadClass(ClassLoader classLoader, String className, Class<T> requiredClassType) {
Objects.requireNonNull(classLoader, "classLoader");
Objects.requireNonNull(className, "className");
try {
TypeScriptGenerator.getLogger().verbose("Loading class " + className);
final Pair<String, Integer> pair = parseArrayClassDimensions(className);
final int arrayDimensions = pair.getValue2();
final Class<?> loadedClass;
if (arrayDimensions > 0) {
final String componentTypeName = pair.getValue1();
final Class<?> componentType = loadPrimitiveOrRegularClass(classLoader, componentTypeName);
loadedClass = Utils.getArrayClass(componentType, arrayDimensions);
} else {
loadedClass = loadPrimitiveOrRegularClass(classLoader, className);
}
if (requiredClassType != null && !requiredClassType.isAssignableFrom(loadedClass)) {
throw new RuntimeException(String.format("Class '%s' is not assignable to '%s'.", loadedClass, requiredClassType));
}
@SuppressWarnings("unchecked")
final Class<? extends T> castedClass = (Class<? extends T>) loadedClass;
if (requiredClassType != null && Annotation.class.isAssignableFrom(requiredClassType)) {
@SuppressWarnings("unchecked")
final Class<? extends Annotation> loadedAnnotationClass = (Class<? extends Annotation>) castedClass;
checkAnnotationHasRuntimeRetention(loadedAnnotationClass);
}
return castedClass;
} catch (ReflectiveOperationException e) {
throw new RuntimeException(e);
}
}
private static void checkAnnotationHasRuntimeRetention(Class<? extends Annotation> annotationClass) {
final Retention retention = annotationClass.getAnnotation(Retention.class);
if (retention.value() != RetentionPolicy.RUNTIME) {
TypeScriptGenerator.getLogger().warning(String.format(
"Annotation '%s' has no effect because it doesn't have 'RUNTIME' retention.",
annotationClass.getName()));
}
}
private static Pair<String, Integer> parseArrayClassDimensions(String className) {
int dimensions = 0;
while (className.endsWith("[]")) {
dimensions++;
className = className.substring(0, className.length() - 2);
}
return Pair.of(className, dimensions);
}
private static Class<?> loadPrimitiveOrRegularClass(ClassLoader classLoader, String className) throws ClassNotFoundException {
final Class<?> primitiveType = Utils.getPrimitiveType(className);
return primitiveType != null
? primitiveType
: classLoader.loadClass(className);
}
private static <T> List<T> loadInstances(ClassLoader classLoader, List<String> classNames, Class<T> requiredType) {
if (classNames == null) {
return Collections.emptyList();
}
final List<T> instances = new ArrayList<>();
for (String className : classNames) {
instances.add(loadInstance(classLoader, className, requiredType));
}
return instances;
}
private static <T> T loadInstance(ClassLoader classLoader, String className, Class<T> requiredType) {
try {
TypeScriptGenerator.getLogger().verbose("Loading class " + className);
return requiredType.cast(classLoader.loadClass(className).getConstructor().newInstance());
} catch (ReflectiveOperationException e) {
throw new RuntimeException(e);
}
}
public static int parseModifiers(String modifiers, int allowedModifiers) {
return Stream.of(modifiers.split("\\|"))
.map(String::trim)
.filter(s -> !s.isEmpty())
.map(s -> {
try {
return javax.lang.model.element.Modifier.valueOf(s.toUpperCase(Locale.US));
} catch (IllegalArgumentException e) {
throw new RuntimeException("Invalid modifier: " + s);
}
})
.mapToInt(modifier -> {
final int mod = Settings.modifierToBitMask(modifier);
if ((mod & allowedModifiers) == 0) {
throw new RuntimeException("Modifier not allowed: " + modifier);
}
return mod;
})
.reduce(0, (a, b) -> a | b);
}
private static int modifierToBitMask(javax.lang.model.element.Modifier modifier) {
switch (modifier) {
case PUBLIC: return java.lang.reflect.Modifier.PUBLIC;
case PROTECTED: return java.lang.reflect.Modifier.PROTECTED;
case PRIVATE: return java.lang.reflect.Modifier.PRIVATE;
case ABSTRACT: return java.lang.reflect.Modifier.ABSTRACT;
// case DEFAULT: no equivalent
case STATIC: return java.lang.reflect.Modifier.STATIC;
case FINAL: return java.lang.reflect.Modifier.FINAL;
case TRANSIENT: return java.lang.reflect.Modifier.TRANSIENT;
case VOLATILE: return java.lang.reflect.Modifier.VOLATILE;
case SYNCHRONIZED: return java.lang.reflect.Modifier.SYNCHRONIZED;
case NATIVE: return java.lang.reflect.Modifier.NATIVE;
case STRICTFP: return java.lang.reflect.Modifier.STRICT;
default: return 0;
}
}
} |
package edu.yu.einstein.wasp.service.impl;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.WordUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import edu.yu.einstein.wasp.MetaMessage;
import edu.yu.einstein.wasp.dao.WaspDao;
import edu.yu.einstein.wasp.exception.StatusMetaMessagingException;
import edu.yu.einstein.wasp.exception.WaspException;
import edu.yu.einstein.wasp.model.MetaBase;
import edu.yu.einstein.wasp.service.MetaMessageService;
/**
* Message metadata saving and retrieval. Can store chronological metadata about the status of an entity via a key - value system. Ideal for
* Displaying status information to users.
* @author andymac
*
*/
@Service
@Transactional("entityManager")
public class MetaMessageServiceImpl extends WaspServiceImpl implements MetaMessageService{
protected Logger logger = LoggerFactory.getLogger(MetaMessageServiceImpl.class);
private static final String STATUS_KEY_PREFIX = "statusMessage.";
private static final String DEFAULT_GROUP = "defaultGroup";
private static final String DELIMITER = "::";
/**
* {@inheritDoc}
*/
@Override
public <T extends MetaBase> MetaMessage saveToGroup(String group, String value, Integer modelParentId, Class<T> clazz, WaspDao<T> dao) throws StatusMetaMessagingException{
return saveToGroup(group, null, value, modelParentId,clazz, dao);
}
/**
* {@inheritDoc}
*/
@Override
public <T extends MetaBase> MetaMessage saveToGroup(String group, String name, String value, Integer modelParentId, Class<T> clazz, WaspDao<T> dao) throws StatusMetaMessagingException{
String parentClassName = StringUtils.substringBefore(clazz.getSimpleName(), "Meta");
String modelParentIdEntityName = null;
for (Field field : clazz.getDeclaredFields()){
if (StringUtils.equalsIgnoreCase(field.getName(), WordUtils.uncapitalize(parentClassName) + "Id")){
modelParentIdEntityName = field.getName();
break;
}
}
String modelParentIdEntityIdSetterMethodName = null;
for (Method method : clazz.getMethods()){
if (StringUtils.equalsIgnoreCase(method.getName(), "set" + parentClassName + "Id")){
modelParentIdEntityIdSetterMethodName = method.getName();
break;
}
}
T meta = null;
logger.debug("Creating new instance of Metadata for current message key '" + group + "' and " + modelParentIdEntityName + "=" + modelParentId );
try {
meta = clazz.newInstance(); // get an instance of class'clazz' via reflection
} catch (Exception e) {
throw new StatusMetaMessagingException("Cannot create a new instance of class '"+ clazz.getName()+"' ", e);
}
// use reflection to invoke method to set the id of the parent model object (UserId to UserMeta or JobId to JobMeta etc) at runtime
try {
clazz.getMethod(modelParentIdEntityIdSetterMethodName, Integer.class).invoke(meta, modelParentId);
} catch (Exception e) {
throw new StatusMetaMessagingException("Problem invoking method '" + modelParentIdEntityIdSetterMethodName + "'on instance of class '"+ clazz.getName()+"' ", e);
}
UUID uniqueId = UUID.randomUUID();
String metaKey = STATUS_KEY_PREFIX + group + DELIMITER + uniqueId;
meta.setK(metaKey);
MetaMessage message = null;
if (name != null){
meta.setV(name + DELIMITER + value);
message = new MetaMessage(metaKey, group, name, value);
} else {
meta.setV(value);
message = new MetaMessage(metaKey, group, "", value);
}
meta = dao.save(meta);
message.setDate(meta.getLastUpdTs());
return message;
}
/**
* {@inheritDoc}
*/
@Override
public <T extends MetaBase> MetaMessage save(String name, String value, Integer modelParentId, Class<T> clazz, WaspDao<T> dao) throws StatusMetaMessagingException{
return saveToGroup(DEFAULT_GROUP, name, value, modelParentId, clazz, dao);
}
/**
* {@inheritDoc}
*/
@Override
public <T extends MetaBase> MetaMessage save(String value, Integer modelParentId, Class<T> clazz, WaspDao<T> dao) throws StatusMetaMessagingException{
return saveToGroup(DEFAULT_GROUP, value, modelParentId, clazz, dao);
}
/**
* {@inheritDoc}
*/
@Override
public <T extends MetaBase> List<MetaMessage> read(String group, Integer modelParentId, Class<T> clazz, WaspDao<T> dao) {
List<MetaMessage> results = new ArrayList<MetaMessage>();
for (MetaMessage message : readAll(modelParentId, clazz, dao)){
if (message.getGroup().equals(group))
results.add(message);
}
return results;
}
/**
* {@inheritDoc}
*/
@Override
public <T extends MetaBase> List<MetaMessage> read(Integer modelParentId, Class<T> clazz, WaspDao<T> dao) {
return read(DEFAULT_GROUP, modelParentId, clazz, dao);
}
private <T extends MetaBase> MetaMessage getMetaMessage(T meta){
MetaMessage message = null;
String metaKey = meta.getK();
if (metaKey.startsWith(STATUS_KEY_PREFIX)){
String group = StringUtils.substringBetween(meta.getK(), STATUS_KEY_PREFIX, DELIMITER);
String[] valueComponents = StringUtils.split(meta.getV(), DELIMITER);
if (valueComponents.length == 1){
message = new MetaMessage(metaKey, group, "", valueComponents[0]);
} else if (valueComponents.length == 2){
message = new MetaMessage(metaKey, group, valueComponents[0], valueComponents[1]);
} else {
message = new MetaMessage(metaKey, group, "", "");
}
message.setDate(meta.getLastUpdTs());
}
return message;
}
/**
* {@inheritDoc}
*/
@Override
public <T extends MetaBase> List<MetaMessage> readAll(Integer modelParentId, Class<T> clazz, WaspDao<T> dao) {
List<MetaMessage> results = new ArrayList<MetaMessage>();
String parentClassName = StringUtils.substringBefore(clazz.getSimpleName(), "Meta");
String modelParentIdEntityName = null;
for (Field field : clazz.getDeclaredFields()){
if (StringUtils.equalsIgnoreCase(field.getName(), WordUtils.uncapitalize(parentClassName) + "Id")){
modelParentIdEntityName = field.getName();
break;
}
}
Map<String, Object> searchMap = new HashMap<String, Object>();
searchMap.put(modelParentIdEntityName, modelParentId);
List<String> orderByColumnNames = new ArrayList<String>();
orderByColumnNames.add("lastUpdTs");
List<T> metaMatches = dao.findByMapOrderBy(searchMap, orderByColumnNames, "ASC");
if (metaMatches != null && !metaMatches.isEmpty()){
for (T meta: metaMatches){
MetaMessage mm = getMetaMessage(meta);
if(mm != null){
results.add(mm);
}
}
}
return results;
}
/**
* {@inheritDoc}
*/
@Override
public <T extends MetaBase> MetaMessage edit(MetaMessage message, String newValue, Integer modelParentId, Class<T> clazz, WaspDao<T> dao) throws WaspException{
T meta = getUniqueMeta(message, modelParentId, clazz, dao);
meta.setV(newValue); // implicit save
return getMetaMessage(meta);
}
/**
* {@inheritDoc}
*/
@Override
public <T extends MetaBase> void delete(MetaMessage message, Integer modelParentId, Class<T> clazz, WaspDao<T> dao) throws WaspException{
dao.remove(getUniqueMeta(message, modelParentId, clazz, dao));
}
private <T extends MetaBase> T getUniqueMeta(MetaMessage message, Integer modelParentId, Class<T> clazz, WaspDao<T> dao) throws WaspException{
Map<String, Object> searchMap = new HashMap<String, Object>();
String parentClassName = StringUtils.substringBefore(clazz.getSimpleName(), "Meta");
String modelParentIdEntityName = null;
for (Field field : clazz.getDeclaredFields()){
if (StringUtils.equalsIgnoreCase(field.getName(), WordUtils.uncapitalize(parentClassName) + "Id")){
modelParentIdEntityName = field.getName();
break;
}
}
searchMap.put(modelParentIdEntityName, modelParentId);
searchMap.put("k", message.getUniqueKey());
List<T> metaMatches = dao.findByMap(searchMap);
if (metaMatches == null || metaMatches.isEmpty() || metaMatches.size() > 1)
throw new WaspException("Unable to retrieve MetaMessage");
return metaMatches.get(0);
}
} |
package org.jbehave.web.selenium;
import java.text.MessageFormat;
import java.util.UUID;
import org.jbehave.core.annotations.AfterScenario;
import org.jbehave.core.annotations.AfterScenario.Outcome;
import org.jbehave.core.failures.UUIDExceptionWrapper;
import org.jbehave.core.reporters.StoryReporterBuilder;
/**
* WebDriverSteps that save screenshot upon failure in a scenario outcome.
* Not all WebDriver implementations support the screenshot capability
*/
public class WebDriverScreenshotOnFailure extends WebDriverSteps {
public static final String DEFAULT_SCREENSHOT_PATH_PATTERN = "{0}/screenshots/failed-scenario-{1}.png";
protected final StoryReporterBuilder reporterBuilder;
protected final String screenshotPathPattern;
public WebDriverScreenshotOnFailure(WebDriverProvider driverProvider) {
this(driverProvider, new StoryReporterBuilder());
}
public WebDriverScreenshotOnFailure(WebDriverProvider driverProvider, StoryReporterBuilder reporterBuilder) {
this(driverProvider, reporterBuilder, DEFAULT_SCREENSHOT_PATH_PATTERN);
}
public WebDriverScreenshotOnFailure(WebDriverProvider driverProvider, StoryReporterBuilder reporterBuilder, String screenshotPathPattern) {
super(driverProvider);
this.reporterBuilder = reporterBuilder;
this.screenshotPathPattern = screenshotPathPattern;
}
@AfterScenario(uponOutcome = Outcome.FAILURE)
public void afterScenarioFailure(UUIDExceptionWrapper uuidWrappedFailure) throws Exception {
String screenshotPath = screenshotPath(uuidWrappedFailure.getUUID());
if ( driverProvider.saveScreenshotTo(screenshotPath) ) {
System.out.println("Screenshot of page '"+driverProvider.get().getCurrentUrl()+"' has been saved to '" + screenshotPath +"'");
} else {
System.out.println(driverProvider.get().getClass().getName() + " does not support taking screenshots.");
}
}
protected String screenshotPath(UUID uuid) {
return MessageFormat.format(screenshotPathPattern, reporterBuilder.outputDirectory(), uuid);
}
} |
package org.devgateway.ocds.web.flags.release;
import org.devgateway.ocds.persistence.mongo.FlaggedRelease;
import org.devgateway.ocds.persistence.mongo.flags.AbstractFlaggedReleaseFlagProcessor;
import org.devgateway.ocds.persistence.mongo.flags.Flag;
import org.devgateway.ocds.persistence.mongo.flags.preconditions.FlaggedReleasePredicates;
import org.devgateway.ocds.web.rest.controller.FrequentSuppliersTimeIntervalController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author mpostelnicu
* <p>
* i077 High number of contract awards to one supplier within a given time period by a single procurement entity
*/
@Component
public class ReleaseFlagI077Processor extends AbstractFlaggedReleaseFlagProcessor {
public static final Integer INTERVAL_DAYS = 365;
public static final Integer MAX_AWARDS = 3;
private ConcurrentHashMap<String, FrequentSuppliersTimeIntervalController.FrequentSuppliersTuple>
awardsMap;
@Autowired
private FrequentSuppliersTimeIntervalController frequentSuppliersTimeIntervalController;
@Override
protected void setFlag(Flag flag, FlaggedRelease flaggable) {
flaggable.getFlags().setI077(flag);
}
@Override
protected Boolean calculateFlag(FlaggedRelease flaggable, StringBuffer rationale) {
return flaggable.getAwards().stream().filter(award ->
awardsMap.get(award.getId()) != null).map(award -> rationale
.append("Award " + award.getId() + " flagged by tuple " + awardsMap.get(award.getId()) + "; "))
.count() > 0;
}
@PostConstruct
@Override
protected void setPredicates() {
preconditionsPredicates = Collections.synchronizedList(
Arrays.asList(FlaggedReleasePredicates.ACTIVE_AWARD_WITH_DATE,
FlaggedReleasePredicates.TENDER_PROCURING_ENTITY));
List<FrequentSuppliersTimeIntervalController.FrequentSuppliersTuple> frequentSuppliersTimeInterval
= frequentSuppliersTimeIntervalController.frequentSuppliersTimeInterval(INTERVAL_DAYS, MAX_AWARDS);
awardsMap = new ConcurrentHashMap<>();
frequentSuppliersTimeInterval.
forEach(tuple -> tuple.getAwardIds().forEach(awardId -> awardsMap.put(awardId, tuple)));
}
} |
package io.skelp.verifier;
import java.util.Arrays;
import java.util.Collection;
import io.skelp.verifier.util.Function;
import io.skelp.verifier.verification.Verification;
/**
* <p>
* An abstract implementation of {@link CustomVerifier} that fulfils the contract while also providing useful helper
* methods for its children to meet similar verification methods and other abstract implementations.
* </p>
*
* @param <T>
* the type of the value being verified
* @param <V>
* the type of the {@link AbstractCustomVerifier} for chaining purposes
* @author Alasdair Mercer
*/
public abstract class AbstractCustomVerifier<T, V extends AbstractCustomVerifier<T, V>> implements CustomVerifier<T, V> {
/**
* <p>
* Returns whether the specified {@code matcher} matches <b>all</b> of the {@code inputs} provided.
* </p>
* <p>
* This method will return {@literal true} if {@code inputs} is {@literal null} and will return {@literal false} if
* {@code matcher} returns {@literal false} for any {@code input}.
* </p>
*
* @param inputs
* the input values to be matched
* @param matcher
* the {@link Function} to be used to match each input value
* @param <I>
* the type of the input values
* @return {@literal true} if {@code inputs} is {@literal null} or {@code matcher} returns {@literal true} for all
* input values; otherwise {@literal false}.
* @see #matchAll(Collection, Function)
*/
protected static <I> boolean matchAll(final I[] inputs, final Function<Boolean, I> matcher) {
return inputs == null || matchAll(Arrays.asList(inputs), matcher);
}
/**
* <p>
* Returns whether the specified {@code matcher} matches <b>all</b> of the {@code inputs} provided.
* </p>
* <p>
* This method will return {@literal true} if {@code inputs} is {@literal null} and will return {@literal false} if
* {@code matcher} returns {@literal false} for any {@code input}.
* </p>
*
* @param inputs
* the input values to be matched
* @param matcher
* the {@link Function} to be used to match each input value
* @param <I>
* the type of the input values
* @return {@literal true} if {@code inputs} is {@literal null} or {@code matcher} returns {@literal true} for all
* input values; otherwise {@literal false}.
* @see #matchAll(Object[], Function)
*/
protected static <I> boolean matchAll(final Collection<I> inputs, final Function<Boolean, I> matcher) {
if (inputs == null) {
return true;
}
for (final I input : inputs) {
if (!matcher.apply(input)) {
return false;
}
}
return true;
}
/**
* <p>
* Returns whether the specified {@code matcher} matches <b>any</b> of the {@code inputs} provided.
* </p>
* <p>
* This method will return {@literal false} if {@code inputs} is {@literal null} and will return {@literal true} if
* {@code matcher} returns {@literal true} for any {@code input}.
* </p>
*
* @param inputs
* the input values to be matched
* @param matcher
* the {@link Function} to be used to match each input value
* @param <I>
* the type of the input values
* @return {@literal true} if {@code inputs} is not {@literal null} and {@code matcher} returns {@literal true} for
* any input value; otherwise {@literal false}.
* @see #matchAny(Collection, Function)
*/
protected static <I> boolean matchAny(final I[] inputs, final Function<Boolean, I> matcher) {
return inputs != null && matchAny(Arrays.asList(inputs), matcher);
}
/**
* <p>
* Returns whether the specified {@code matcher} matches <b>any</b> of the {@code inputs} provided.
* </p>
* <p>
* This method will return {@literal false} if {@code inputs} is {@literal null} and will return {@literal true} if
* {@code matcher} returns {@literal true} for any {@code input}.
* </p>
*
* @param inputs
* the input values to be matched
* @param matcher
* the {@link Function} to be used to match each input value
* @param <I>
* the type of the input values
* @return {@literal true} if {@code inputs} is not {@literal null} and {@code matcher} returns {@literal true} for
* any input value; otherwise {@literal false}.
* @see #matchAny(Object[], Function)
*/
protected static <I> boolean matchAny(final Collection<I> inputs, final Function<Boolean, I> matcher) {
if (inputs == null) {
return false;
}
for (final I input : inputs) {
if (matcher.apply(input)) {
return true;
}
}
return false;
}
private final Verification<T> verification;
/**
* <p>
* Creates an instance of {@link AbstractCustomVerifier} based on the {@code verification} provided.
* </p>
*
* @param verification
* the {@link Verification} to be used
*/
public AbstractCustomVerifier(final Verification<T> verification) {
this.verification = verification;
}
/**
* <p>
* Returns a reference to this {@link AbstractCustomVerifier} implementation which can be useful for chaining
* references while avoiding unchecked casting warnings.
* </p>
*
* @return A reference to this {@link AbstractCustomVerifier} implementation.
*/
protected V chain() {
@SuppressWarnings("unchecked")
final V chain = (V) this;
return chain;
}
@Override
public V equalTo(final Object other) throws VerifierException {
return equalTo(other, other);
}
@Override
public V equalTo(final Object other, final Object name) throws VerifierException {
final T value = verification.getValue();
final boolean result = isEqualTo(value, other);
verification.check(result, "be equal to '%s'", name);
return chain();
}
@Override
public V equalToAny(final Object... others) throws VerifierException {
final T value = verification.getValue();
final boolean result = matchAny(others, new Function<Boolean, Object>() {
@Override
public Boolean apply(final Object input) {
return isEqualTo(value, input);
}
});
verification.check(result, "be equal to any %s", verification.getMessageFormatter().formatArray(others));
return chain();
}
@Override
public V hashedAs(final int hashCode) throws VerifierException {
final T value = verification.getValue();
final boolean result = value != null && value.hashCode() == hashCode;
verification.check(result, "have hash code '%d'", hashCode);
return chain();
}
@Override
public V instanceOf(final Class<?> cls) throws VerifierException {
final boolean result = cls != null && cls.isInstance(verification.getValue());
verification.check(result, "be an instance of '%s'", cls);
return chain();
}
@Override
public V instanceOfAll(final Class<?>... classes) throws VerifierException {
final T value = verification.getValue();
final boolean result = value != null && matchAll(classes, new Function<Boolean, Class<?>>() {
@Override
public Boolean apply(final Class<?> input) {
return input != null && input.isInstance(value);
}
});
verification.check(result, "be an instance of all %s", verification.getMessageFormatter().formatArray(classes));
return chain();
}
@Override
public V instanceOfAny(final Class<?>... classes) throws VerifierException {
final T value = verification.getValue();
final boolean result = value != null && matchAny(classes, new Function<Boolean, Class<?>>() {
@Override
public Boolean apply(final Class<?> input) {
return input != null && input.isInstance(value);
}
});
verification.check(result, "be an instance of any %s", verification.getMessageFormatter().formatArray(classes));
return chain();
}
/**
* <p>
* Returns whether the specified {@code value} is equal to the {@code other} provided.
* </p>
* <p>
* {@literal null} references are handled gracefully without exceptions.
* </p>
*
* @param value
* the value being verified (may be {@literal null})
* @param other
* the object to compare against {@code value} (may be {@literal null})
* @return {@literal true} if {@code value} equals {@code other}; otherwise {@literal false}.
* @see Object#equals(Object)
*/
protected boolean isEqualTo(final T value, final Object other) {
return other == null ? value == null : other.equals(value);
}
@Override
public V not() {
verification.setNegated(!verification.isNegated());
return chain();
}
@Override
public V nulled() throws VerifierException {
final boolean result = verification.getValue() == null;
verification.check(result, "be null");
return chain();
}
@Override
public V sameAs(final Object other) throws VerifierException {
return sameAs(other, other);
}
@Override
public V sameAs(final Object other, final Object name) throws VerifierException {
final boolean result = verification.getValue() == other;
verification.check(result, "be same as '%s'", name);
return chain();
}
@Override
public V sameAsAny(final Object... others) throws VerifierException {
final T value = verification.getValue();
final boolean result = matchAny(others, new Function<Boolean, Object>() {
@Override
public Boolean apply(final Object input) {
return value == input;
}
});
verification.check(result, "be same as any %s", verification.getMessageFormatter().formatArray(others));
return chain();
}
@Override
public V that(final VerifierAssertion<T> assertion) throws VerifierException {
return that(assertion, null);
}
@Override
public V that(final VerifierAssertion<T> assertion, final String message, final Object... args) throws VerifierException {
Verifier.verify(assertion, "assertion")
.not().nulled();
final boolean result = assertion.verify(verification.getValue());
verification.check(result, message, args);
return chain();
}
@Override
public T value() {
return verification.getValue();
}
@Override
public Verification<T> verification() {
return verification;
}
} |
package org.opencode4workspace.endpoints;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.opencode4workspace.WWClient;
import org.opencode4workspace.WWException;
import org.opencode4workspace.graphql.GraphResultContainer;
import org.opencode4workspace.json.GraphQLRequest;
import org.opencode4workspace.json.RequestBuilder;
import org.opencode4workspace.json.ResultParser;
/**
* @author Paul Withers
* @since 0.5.0
*
* Abstract default implementation of IWWGraphQLEndpoint interface. In any overloaded object, a result needs constructing and passing into the object. The {@linkplain #parseResultContainer()}
* method needs to be overloaded.
*
*/
public abstract class AbstractWWGraphQLEndpoint implements IWWGraphQLEndpoint {
private final WWClient client;
private GraphQLRequest request;
private GraphResultContainer resultContainer;
private String resultContent;
private Boolean profileDump = false;
/**
* @param client
* WWClient containing authentication details and token
*/
public AbstractWWGraphQLEndpoint(WWClient client) {
this.client = client;
}
/*
* (non-Javadoc)
*
* @see org.opencode4workspace.endpoints.IWWGraphQLEndpoint#getClient()
*/
@Override
public WWClient getClient() {
return client;
}
/**
* Tests the token against its expireDate.
*
* @return boolean, whether or not the token should be valid
*/
private boolean isShouldBeValid() {
if (getClient().isValid()) {
return true;
} else {
return false;
}
}
/*
* (non-Javadoc)
*
* @see org.opencode4workspace.endpoints.IWWGraphQLEndpoint#getRequest()
*/
@Override
public GraphQLRequest getRequest() {
return request;
}
/*
* (non-Javadoc)
*
* @see org.opencode4workspace.endpoints.IWWGraphQLEndpoint#setRequest(org.opencode4workspace.json.GraphQLRequest)
*/
@Override
public void setRequest(GraphQLRequest request) {
this.request = request;
}
/*
* (non-Javadoc)
*
* @see org.opencode4workspace.endpoints.IWWGraphQLEndpoint#getResultContainer()
*/
@Override
public GraphResultContainer getResultContainer() {
return resultContainer;
}
/*
* (non-Javadoc)
*
* @see org.opencode4workspace.endpoints.IWWGraphQLEndpoint#setResultContainer(org.opencode4workspace.graphql.GraphResultContainer)
*/
@Override
public void setResultContainer(GraphResultContainer resultContainer) {
this.resultContainer = resultContainer;
}
/*
* (non-Javadoc)
*
* @see org.opencode4workspace.endpoints.IWWGraphQLEndpoint#executeRequest()
*/
@Override
public void executeRequest() throws WWException {
if (null == getRequest()) {
throw new WWException("A GraphQLRequest object must be loaded before calling the 'execute' method");
}
HttpPost post = preparePost();
CloseableHttpClient client = HttpClients.createDefault();
CloseableHttpResponse response = null;
try {
StringEntity postPayload = new StringEntity(new RequestBuilder<GraphQLRequest>(GraphQLRequest.class).buildJson(request), "UTF-8");
post.setEntity(postPayload);
if (getProfileDump()) {
System.out.println("[WWS Profiler] Query is " + postPayload);
}
long start = System.nanoTime();
response = client.execute(post);
if (getProfileDump()) {
long elapsed = System.nanoTime() - start;
System.out.println("[WWS Profiler] Query took " + elapsed / 1000000 + "ms");
}
if (response.getStatusLine().getStatusCode() == 200) {
// TODO: Handle if we need to re-authenticate
String content = EntityUtils.toString(response.getEntity());
setResultContent(content);
setResultContainer(new ResultParser<GraphResultContainer>(GraphResultContainer.class).parse(content));
} else {
throw new WWException("Failure during login" + response.getStatusLine().getReasonPhrase());
}
} catch (Exception e) {
throw new WWException(e);
} finally {
if (response != null) {
try {
response.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
/**
* @return String raw JSON results as String
*/
public String getResultContent() {
return resultContent;
}
/**
* @param resultContent
* String raw JSON results as string
*/
public void setResultContent(String resultContent) {
this.resultContent = resultContent;
}
/*
* (non-Javadoc)
*
* @see org.opencode4workspace.endpoints.IWWGraphQLEndpoint#parseResultContainer()
*/
@Override
public Object parseResultContainer() throws WWException {
if (null == getResultContainer()) {
throw new WWException("No result returned for query");
} else {
throw new UnsupportedOperationException("Method must be overloaded");
}
}
/**
* Prepares the HttpPost with relevant headers - JWT Token and Content-Type
*
* @return HttpPost containing the relevant headers
*/
private HttpPost preparePost() {
HttpPost post = new HttpPost(WWDefinedEndpoints.GRAPHQL);
post.addHeader("jwt", getClient().getJWTToken());
post.addHeader("content-type", ContentType.APPLICATION_JSON.toString());
return post;
}
/**
* @return Boolean whether or not to dump profile data of query and response time
*/
public Boolean getProfileDump() {
return profileDump;
}
/**
* @param profileDump
* Boolean whether or not to dump profile data of query and response time
*/
public void setProfileDump(Boolean profileDump) {
this.profileDump = profileDump;
}
} |
package org.knowm.xchange.bitmex.service;
import static org.knowm.xchange.bitmex.dto.trade.BitmexSide.fromOrderType;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import org.knowm.xchange.bitmex.BitmexAdapters;
import org.knowm.xchange.bitmex.BitmexExchange;
import org.knowm.xchange.bitmex.dto.marketdata.BitmexPrivateOrder;
import org.knowm.xchange.bitmex.dto.trade.BitmexExecutionInstruction;
import org.knowm.xchange.bitmex.dto.trade.BitmexOrderFlags;
import org.knowm.xchange.bitmex.dto.trade.BitmexPlaceOrderParameters;
import org.knowm.xchange.bitmex.dto.trade.BitmexReplaceOrderParameters;
import org.knowm.xchange.bitmex.dto.trade.BitmexPlaceOrderParameters.Builder;
import org.knowm.xchange.dto.Order;
import org.knowm.xchange.dto.marketdata.Trades.TradeSortType;
import org.knowm.xchange.dto.trade.LimitOrder;
import org.knowm.xchange.dto.trade.MarketOrder;
import org.knowm.xchange.dto.trade.OpenOrders;
import org.knowm.xchange.dto.trade.StopOrder;
import org.knowm.xchange.dto.trade.UserTrade;
import org.knowm.xchange.dto.trade.UserTrades;
import org.knowm.xchange.exceptions.ExchangeException;
import org.knowm.xchange.exceptions.NotYetImplementedForExchangeException;
import org.knowm.xchange.service.trade.TradeService;
import org.knowm.xchange.service.trade.params.CancelAllOrders;
import org.knowm.xchange.service.trade.params.CancelOrderParams;
import org.knowm.xchange.service.trade.params.DefaultCancelOrderParamId;
import org.knowm.xchange.service.trade.params.TradeHistoryParamCurrencyPair;
import org.knowm.xchange.service.trade.params.TradeHistoryParamOffset;
import org.knowm.xchange.service.trade.params.TradeHistoryParams;
import org.knowm.xchange.service.trade.params.TradeHistoryParamsTimeSpan;
import org.knowm.xchange.service.trade.params.orders.OpenOrdersParams;
public class BitmexTradeService extends BitmexTradeServiceRaw implements TradeService {
public BitmexTradeService(BitmexExchange exchange) {
super(exchange);
}
@Override
public OpenOrders getOpenOrders() throws ExchangeException {
List<BitmexPrivateOrder> bitmexOrders =
super.getBitmexOrders(null, "{\"open\": true}", null, null, null);
return new OpenOrders(
bitmexOrders.stream().map(BitmexAdapters::adaptOrder).collect(Collectors.toList()));
}
@Override
public OpenOrders getOpenOrders(OpenOrdersParams params) throws ExchangeException {
List<LimitOrder> limitOrders = new ArrayList<>();
for (LimitOrder order : getOpenOrders().getOpenOrders()) {
if (params.accept(order)) {
limitOrders.add(order);
}
}
return new OpenOrders(limitOrders);
}
@Override
public String placeMarketOrder(MarketOrder marketOrder) throws ExchangeException {
String symbol = BitmexAdapters.adaptCurrencyPairToSymbol(marketOrder.getCurrencyPair());
return placeOrder(
new BitmexPlaceOrderParameters.Builder(symbol)
.setSide(fromOrderType(marketOrder.getType()))
.setOrderQuantity(marketOrder.getOriginalAmount())
.build())
.getId();
}
@Override
public String placeLimitOrder(LimitOrder limitOrder) throws ExchangeException {
String symbol = BitmexAdapters.adaptCurrencyPairToSymbol(limitOrder.getCurrencyPair());
Builder b =
new BitmexPlaceOrderParameters.Builder(symbol)
.setOrderQuantity(limitOrder.getOriginalAmount())
.setPrice(limitOrder.getLimitPrice())
.setSide(fromOrderType(limitOrder.getType()))
.setClOrdId(limitOrder.getId());
if (limitOrder.hasFlag(BitmexOrderFlags.POST)) {
b.addExecutionInstruction(BitmexExecutionInstruction.PARTICIPATE_DO_NOT_INITIATE);
}
return placeOrder(b.build()).getId();
}
@Override
public String placeStopOrder(StopOrder stopOrder) throws ExchangeException {
String symbol = BitmexAdapters.adaptCurrencyPairToSymbol(stopOrder.getCurrencyPair());
return placeOrder(
new BitmexPlaceOrderParameters.Builder(symbol)
.setSide(fromOrderType(stopOrder.getType()))
.setOrderQuantity(stopOrder.getOriginalAmount())
.setStopPrice(stopOrder.getStopPrice())
.setClOrdId(stopOrder.getId())
.build())
.getId();
}
@Override
public String changeOrder(LimitOrder limitOrder) throws ExchangeException {
BitmexPrivateOrder order =
replaceOrder(
new BitmexReplaceOrderParameters.Builder()
.setOrderId(limitOrder.getId())
.setOrderQuantity(limitOrder.getOriginalAmount())
.setPrice(limitOrder.getLimitPrice())
.build());
return order.getId();
}
@Override
public boolean cancelOrder(String orderId) throws ExchangeException {
List<BitmexPrivateOrder> orders = cancelBitmexOrder(orderId);
if (orders.isEmpty()) {
return true;
}
return orders.get(0).getId().equals(orderId);
}
public boolean cancelOrder(CancelOrderParams params) throws ExchangeException {
if (params instanceof DefaultCancelOrderParamId) {
DefaultCancelOrderParamId paramsWithId = (DefaultCancelOrderParamId) params;
return cancelOrder(paramsWithId.getOrderId());
}
if (params instanceof CancelAllOrders) {
List<BitmexPrivateOrder> orders = cancelAllOrders();
return !orders.isEmpty();
}
throw new NotYetImplementedForExchangeException(
String.format("Unexpected type of parameter: %s", params));
}
@Override
public Collection<Order> getOrder(String... orderIds) throws ExchangeException {
String filter = "{\"orderID\": [\"" + String.join("\",\"", orderIds) + "\"]}";
List<BitmexPrivateOrder> privateOrders = getBitmexOrders(null, filter, null, null, null);
return privateOrders.stream().map(BitmexAdapters::adaptOrder).collect(Collectors.toList());
}
@Override
public UserTrades getTradeHistory(TradeHistoryParams params) throws IOException {
String symbol = null;
if (params instanceof TradeHistoryParamCurrencyPair) {
symbol =
BitmexAdapters.adaptCurrencyPairToSymbol(
((TradeHistoryParamCurrencyPair) params).getCurrencyPair());
}
Long start = null;
if (params instanceof TradeHistoryParamOffset) {
start = ((TradeHistoryParamOffset) params).getOffset();
}
Date startTime = null;
Date endTime = null;
if (params instanceof TradeHistoryParamsTimeSpan) {
TradeHistoryParamsTimeSpan timeSpan = (TradeHistoryParamsTimeSpan) params;
startTime = timeSpan.getStartTime();
endTime = timeSpan.getEndTime();
}
List<UserTrade> userTrades =
getTradeHistory(symbol, null, null, null, start, false, startTime, endTime).stream()
.map(BitmexAdapters::adoptUserTrade)
.filter(Objects::nonNull)
.collect(Collectors.toList());
return new UserTrades(userTrades, TradeSortType.SortByTimestamp);
}
} |
package kalang.compiler.compile;
import kalang.compiler.ast.ClassNode;
import kalang.compiler.util.AstUtil;
import kalang.compiler.util.NameUtil;
import javax.annotation.Nullable;
import java.util.*;
/**
*
* @author Kason Yang
*/
public class TypeNameResolver {
private Map<String, String> simpleToFullNames = new HashMap();
private List<String> importPackages = new LinkedList();
private AstLoader astLoader;
public TypeNameResolver() {
}
public void importClass(String className){
this.importClass(className,NameUtil.getSimpleClassName(className));
}
public void importClass(String className,String alias) {
this.simpleToFullNames.put(alias , className);
}
public void importPackage(String packageName) {
this.importPackages.add(packageName);
}
private String fixInnerClassName(String className) {
String name = "";
for (String n : className.split("\\.")) {
name += n;
if (astLoader !=null && astLoader.getAst(name) != null) {
name += "$";
} else {
name += ".";
}
}
return name.substring(0, name.length() - 1);
}
/**
*
* @param id
* @param topClass
* @param declaringClass
* @return full name of type,null if failed.
*/
@Nullable
public String resolve(String id,ClassNode topClass, ClassNode declaringClass) {
if(id.contains(".")) return id;
if (simpleToFullNames.containsKey(id)) {
return this.fixInnerClassName(simpleToFullNames.get(id));
} else if (id.contains("$")){
String[] idParts = id.split("\\$",2);
String outerClassName = simpleToFullNames.get(idParts[0]);
if (outerClassName==null){
return null;
}
return outerClassName + "$" + idParts[1];
}else {
String[] innerClassesNames = AstUtil.listInnerClassesNames(topClass, true);
String path = declaringClass.name;
while(!path.isEmpty()) {
String name = path + "$" + id;
for(String c:innerClassesNames) {
if (name.equals(c)) {
return c;
}
}
int last$ = path.lastIndexOf('$');
path = last$ > 0 ? path.substring(0,last$) : "";
}
List<String> paths = new ArrayList<>(importPackages.size() + 1);
paths.addAll(importPackages);
paths.add(NameUtil.getPackageName(topClass.name));
int pathSize = paths.size();
for (int i=pathSize-1;i>=0;i
String p = paths.get(i);
String clsName;
if (p != null && p.length() > 0) {
clsName = p + "." + id;
} else {
clsName = id;
}
if (astLoader!=null && astLoader.getAst(this.fixInnerClassName(clsName)) != null) {
return clsName;
}
}
}
return null;
}
public void setAstLoader(AstLoader astLoader) {
this.astLoader = astLoader;
}
} |
package com.thoughtworks.acceptance;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.io.StringReader;
import java.io.StringWriter;
import com.thoughtworks.acceptance.AbstractAcceptanceTest;
/**
* <p>
* A class {@link Serializable} {@link Parent} class implements
* <code>writeObject()</code> and holds a {@link Child} class that also
* implements <code>writeObject()</code>
* </p>
*
* @author <a href="mailto:cleclerc@pobox.com">Cyrille Le Clerc</a>
*/
public class SerializationNestedWriteObjectsTest extends AbstractAcceptanceTest {
public static class Child implements Serializable {
private int i = 3;
public Child(int i) {
this.i = i;
}
public int getI() {
return i;
}
private void readObject(java.io.ObjectInputStream in) throws IOException,
ClassNotFoundException {
in.defaultReadObject();
}
private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
}
}
public static class Parent implements Serializable {
private String name;
private transient Child child;
public Parent(String name, Child child) {
this.name = name;
this.child = child;
}
public Child getChild() {
return child;
}
public String getName() {
return name;
}
private void readObject(java.io.ObjectInputStream in) throws IOException,
ClassNotFoundException {
this.child = (Child) in.readObject();
in.defaultReadObject();
}
private void writeObject(ObjectOutputStream out) throws IOException {
out.writeObject(this.child);
out.defaultWriteObject();
}
}
public void testObjectInputStream() throws Exception {
xstream.alias("parent", Parent.class);
xstream.alias("child", Child.class);
String sourceXml = ""
+ "<object-stream>\n"
+ " <parent serialization=\"custom\">\n"
+ " <parent>\n"
+ " <child serialization=\"custom\">\n"
+ " <child>\n"
+ " <default>\n"
+ " <i>1</i>\n"
+ " </default>\n"
+ " </child>\n"
+ " </child>\n"
+ " <default>\n"
+ " <name>ze-name</name>\n"
+ " </default>\n"
+ " </parent>\n"
+ " </parent>\n"
+ "</object-stream>";
ObjectInputStream objectInputStream = xstream.createObjectInputStream(new StringReader(
sourceXml));
Parent parent = (Parent) objectInputStream.readObject();
assertEquals("ze-name", parent.getName());
assertEquals(1, parent.getChild().getI());
}
public void testObjectOutputStream() throws Exception {
xstream.alias("parent", Parent.class);
xstream.alias("child", Child.class);
String expectedXml = ""
+ "<object-stream>\n"
+ " <parent serialization=\"custom\">\n"
+ " <parent>\n"
+ " <child serialization=\"custom\">\n"
+ " <child>\n"
+ " <default>\n"
+ " <i>1</i>\n"
+ " </default>\n"
+ " </child>\n"
+ " </child>\n"
+ " <default>\n"
+ " <name>ze-name</name>\n"
+ " </default>\n"
+ " </parent>\n"
+ " </parent>\n"
+ "</object-stream>";
Parent parent = new Parent("ze-name", new Child(1));
StringWriter stringWriter = new StringWriter();
ObjectOutputStream os = xstream.createObjectOutputStream(stringWriter);
os.writeObject(parent);
os.close();
String actualXml = stringWriter.getBuffer().toString();
assertEquals(expectedXml, actualXml);
}
public void testToXML() {
xstream.alias("parent", Parent.class);
xstream.alias("child", Child.class);
String expected = ""
+ "<parent serialization=\"custom\">\n"
+ " <parent>\n"
+ " <child serialization=\"custom\">\n"
+ " <child>\n"
+ " <default>\n"
+ " <i>1</i>\n"
+ " </default>\n"
+ " </child>\n"
+ " </child>\n"
+ " <default>\n"
+ " <name>ze-name</name>\n"
+ " </default>\n"
+ " </parent>\n"
+ "</parent>";
Parent parent = new Parent("ze-name", new Child(1));
assertBothWays(parent, expected);
}
} |
package mcjty.rftools.blocks.screens;
import mcjty.rftools.blocks.ModBlocks;
import mcjty.rftools.crafting.PreservingShapedRecipe;
import mcjty.rftools.items.screenmodules.*;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
public class ScreenSetup {
public static ScreenBlock screenBlock;
public static ScreenHitBlock screenHitBlock;
public static ScreenControllerBlock screenControllerBlock;
public static TextModuleItem textModuleItem;
public static EnergyModuleItem energyModuleItem;
public static EnergyPlusModuleItem energyPlusModuleItem;
public static InventoryModuleItem inventoryModuleItem;
public static InventoryPlusModuleItem inventoryPlusModuleItem;
public static ClockModuleItem clockModuleItem;
public static FluidModuleItem fluidModuleItem;
public static FluidPlusModuleItem fluidPlusModuleItem;
public static MachineInformationModuleItem machineInformationModuleItem;
public static ButtonModuleItem buttonModuleItem;
public static RedstoneModuleItem redstoneModuleItem;
public static CounterModuleItem counterModuleItem;
public static CounterPlusModuleItem counterPlusModuleItem;
public static void init() {
screenBlock = new ScreenBlock();
screenHitBlock = new ScreenHitBlock();
screenControllerBlock = new ScreenControllerBlock();
textModuleItem = new TextModuleItem();
inventoryModuleItem = new InventoryModuleItem();
inventoryPlusModuleItem = new InventoryPlusModuleItem();
energyModuleItem = new EnergyModuleItem();
energyPlusModuleItem = new EnergyPlusModuleItem();
clockModuleItem = new ClockModuleItem();
fluidModuleItem = new FluidModuleItem();
fluidPlusModuleItem = new FluidPlusModuleItem();
machineInformationModuleItem = new MachineInformationModuleItem();
buttonModuleItem = new ButtonModuleItem();
redstoneModuleItem = new RedstoneModuleItem();
counterModuleItem = new CounterModuleItem();
counterPlusModuleItem = new CounterPlusModuleItem();
}
@SideOnly(Side.CLIENT)
public static void initClient() {
screenBlock.initModel();
screenHitBlock.initModel();
screenControllerBlock.initModel();
textModuleItem.initModel();
inventoryModuleItem.initModel();
inventoryPlusModuleItem.initModel();
energyModuleItem.initModel();
energyPlusModuleItem.initModel();
clockModuleItem.initModel();
fluidModuleItem.initModel();
fluidPlusModuleItem.initModel();
machineInformationModuleItem.initModel();
buttonModuleItem.initModel();
redstoneModuleItem.initModel();
counterModuleItem.initModel();
counterPlusModuleItem.initModel();
}
public static void initCrafting() {
GameRegistry.addRecipe(new ItemStack(screenControllerBlock), "ror", "gMg", "rgr", 'r', Items.redstone, 'o', Items.ender_pearl, 'M', ModBlocks.machineFrame,
'g', Blocks.glass);
GameRegistry.addRecipe(new ItemStack(screenBlock), "ggg", "gMg", "iii", 'M', ModBlocks.machineBase,
'g', Blocks.glass, 'i', Items.iron_ingot);
initScreenModuleCrafting();
}
private static void initScreenModuleCrafting() {
ItemStack inkSac = new ItemStack(Items.dye, 1, 0);
GameRegistry.addRecipe(new ItemStack(textModuleItem), " p ", "rir", " b ", 'p', Items.paper, 'r', Items.redstone, 'i', Items.iron_ingot,
'b', inkSac);
GameRegistry.addRecipe(new ItemStack(clockModuleItem), " c ", "rir", " b ", 'c', Items.clock, 'r', Items.redstone, 'i', Items.iron_ingot,
'b', inkSac);
GameRegistry.addRecipe(new ItemStack(energyModuleItem), " r ", "rir", " b ", 'r', Items.redstone, 'i', Items.iron_ingot,
'b', inkSac);
// GameRegistry.addRecipe(new ItemStack(dimensionModuleItem), " c ", "rir", " b ", 'c', Items.ender_pearl, 'r', Items.redstone, 'i', Items.iron_ingot,
// 'b', inkSac);
GameRegistry.addRecipe(new ItemStack(fluidModuleItem), " c ", "rir", " b ", 'c', Items.bucket, 'r', Items.redstone, 'i', Items.iron_ingot,
'b', inkSac);
GameRegistry.addRecipe(new ItemStack(inventoryModuleItem), " c ", "rir", " b ", 'c', Blocks.chest, 'r', Items.redstone, 'i', Items.iron_ingot,
'b', inkSac);
GameRegistry.addRecipe(new ItemStack(counterModuleItem), " c ", "rir", " b ", 'c', Items.comparator, 'r', Items.redstone, 'i', Items.iron_ingot,
'b', inkSac);
GameRegistry.addRecipe(new ItemStack(redstoneModuleItem), " c ", "rir", " b ", 'c', Items.repeater, 'r', Items.redstone, 'i', Items.iron_ingot,
'b', inkSac);
GameRegistry.addRecipe(new ItemStack(machineInformationModuleItem), " f ", "rir", " b ", 'f', Blocks.furnace, 'r', Items.redstone, 'i', Items.iron_ingot,
'b', inkSac);
// GameRegistry.addRecipe(new ItemStack(computerModuleItem), " f ", "rir", " b ", 'f', Blocks.quartz_block, 'r', Items.redstone, 'i', Items.iron_ingot,
// 'b', inkSac);
GameRegistry.addRecipe(new ItemStack(buttonModuleItem), " f ", "rir", " b ", 'f', Blocks.stone_button, 'r', Items.redstone, 'i', Items.iron_ingot,
'b', inkSac);
GameRegistry.addRecipe(new ItemStack(buttonModuleItem), "b", 'b', buttonModuleItem); // To clear it
GameRegistry.addRecipe(new PreservingShapedRecipe(3, 3, new ItemStack[] {
null, new ItemStack(Items.ender_pearl), null,
new ItemStack(Items.gold_ingot), new ItemStack(energyModuleItem), new ItemStack(Items.gold_ingot),
null, new ItemStack(Items.ender_pearl), null }, new ItemStack(energyPlusModuleItem), 4));
GameRegistry.addRecipe(new PreservingShapedRecipe(3, 3, new ItemStack[] {
null, new ItemStack(Items.ender_pearl), null,
new ItemStack(Items.gold_ingot), new ItemStack(fluidModuleItem), new ItemStack(Items.gold_ingot),
null, new ItemStack(Items.ender_pearl), null }, new ItemStack(fluidPlusModuleItem), 4));
GameRegistry.addRecipe(new PreservingShapedRecipe(3, 3, new ItemStack[] {
null, new ItemStack(Items.ender_pearl), null,
new ItemStack(Items.gold_ingot), new ItemStack(inventoryModuleItem), new ItemStack(Items.gold_ingot),
null, new ItemStack(Items.ender_pearl), null }, new ItemStack(inventoryPlusModuleItem), 4));
GameRegistry.addRecipe(new PreservingShapedRecipe(3, 3, new ItemStack[] {
null, new ItemStack(Items.ender_pearl), null,
new ItemStack(Items.gold_ingot), new ItemStack(counterModuleItem), new ItemStack(Items.gold_ingot),
null, new ItemStack(Items.ender_pearl), null }, new ItemStack(counterPlusModuleItem), 4));
}
} |
package org.zanata.client.commands.push;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.ws.rs.core.Response;
import org.apache.commons.lang.StringUtils;
import org.jboss.resteasy.client.ClientResponse;
import org.jboss.resteasy.client.ClientResponseFailure;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zanata.client.commands.PushPullCommand;
import org.zanata.client.config.LocaleMapping;
import org.zanata.client.exceptions.ConfigException;
import org.zanata.client.util.ConsoleUtils;
import org.zanata.common.LocaleId;
import org.zanata.common.MergeType;
import org.zanata.rest.RestUtil;
import org.zanata.rest.StringSet;
import org.zanata.rest.client.ClientUtility;
import org.zanata.rest.client.ISourceDocResource;
import org.zanata.rest.client.ITranslatedDocResource;
import org.zanata.rest.client.ZanataProxyFactory;
import org.zanata.rest.dto.CopyTransStatus;
import org.zanata.rest.dto.ProcessStatus;
import org.zanata.rest.dto.resource.Resource;
import org.zanata.rest.dto.resource.ResourceMeta;
import org.zanata.rest.dto.resource.TranslationsResource;
import org.zanata.rest.service.AsynchronousProcessResource;
import org.zanata.rest.service.CopyTransResource;
import static org.zanata.rest.dto.ProcessStatus.ProcessStatusCode;
import static org.zanata.rest.dto.ProcessStatus.ProcessStatusCode.Failed;
/**
* @author Sean Flanigan <a
* href="mailto:sflaniga@redhat.com">sflaniga@redhat.com</a>
*
*/
public class PushCommand extends PushPullCommand<PushOptions>
{
private static final Logger log = LoggerFactory.getLogger(PushCommand.class);
private static final String UTF_8 = "UTF-8";
private static final Map<String, AbstractPushStrategy> strategies = new HashMap<String, AbstractPushStrategy>();
private CopyTransResource copyTransResource;
private AsynchronousProcessResource asyncProcessResource;
public static interface TranslationResourcesVisitor
{
void visit(LocaleMapping locale, TranslationsResource targetDoc);
}
{
strategies.put(PROJECT_TYPE_UTF8_PROPERTIES, new PropertiesStrategy(UTF_8));
strategies.put(PROJECT_TYPE_PROPERTIES, new PropertiesStrategy());
strategies.put(PROJECT_TYPE_PUBLICAN, new GettextDirStrategy());
strategies.put(PROJECT_TYPE_XLIFF, new XliffStrategy());
strategies.put(PROJECT_TYPE_XML, new XmlStrategy());
}
public PushCommand(PushOptions opts)
{
super(opts);
copyTransResource = getRequestFactory().getCopyTransResource();
asyncProcessResource = getRequestFactory().getAsynchronousProcessResource();
}
public PushCommand(PushOptions opts, ZanataProxyFactory factory, ISourceDocResource sourceDocResource, ITranslatedDocResource translationResources, URI uri)
{
super(opts, factory, sourceDocResource, translationResources, uri);
copyTransResource = factory.getCopyTransResource();
asyncProcessResource = factory.getAsynchronousProcessResource();
}
private AbstractPushStrategy getStrategy(String strategyType)
{
AbstractPushStrategy strat = strategies.get(strategyType);
if (strat == null)
{
throw new RuntimeException("unknown project type: " + getOpts().getProjectType());
}
strat.setPushOptions(getOpts());
strat.init();
return strat;
}
public static void logOptions(Logger logger, PushOptions opts)
{
if (!logger.isInfoEnabled())
{
return;
}
logger.info("Server: {}", opts.getUrl());
logger.info("Project: {}", opts.getProj());
logger.info("Version: {}", opts.getProjectVersion());
logger.info("Username: {}", opts.getUsername());
logger.info("Project type: {}", opts.getProjectType());
logger.info("Source language: {}", opts.getSourceLang());
String copyTransMssg = "" + opts.getCopyTrans();
if( opts.getCopyTrans() && opts.getPushType() == PushPullType.Trans )
{
copyTransMssg = "disabled since pushType=Trans";
}
logger.info("Copy previous translations: {}", copyTransMssg);
logger.info("Merge type: {}", opts.getMergeType());
logger.info("Enable modules: {}", opts.getEnableModules());
if (opts.getEnableModules())
{
logger.info("Current module: {}", opts.getCurrentModule());
if (opts.isRootModule())
{
logger.info("Root module: YES");
if (logger.isDebugEnabled())
{
logger.debug("Modules: {}", StringUtils.join(opts.getAllModules(), ", "));
}
}
}
logger.info("Include patterns: {}", StringUtils.join(opts.getIncludes(), " "));
logger.info("Exclude patterns: {}", StringUtils.join(opts.getExcludes(), " "));
logger.info("Default excludes: {}", opts.getDefaultExcludes());
if (opts.getPushType() == PushPullType.Trans)
{
logger.info("Pushing target documents only");
logger.info("Locales to push: {}", opts.getLocaleMapList());
}
else if (opts.getPushType() == PushPullType.Source)
{
logger.info("Pushing source documents only");
}
else
{
logger.info("Pushing source and target documents");
logger.info("Locales to push: {}", opts.getLocaleMapList());
}
logger.info("Source directory (originals): {}", opts.getSrcDir());
if (opts.getPushType() == PushPullType.Both || opts.getPushType() == PushPullType.Trans)
{
logger.info("Target base directory (translations): {}", opts.getTransDir());
}
if (opts.isDryRun())
{
logger.info("DRY RUN: no permanent changes will be made");
}
}
private boolean mergeAuto()
{
return getOpts().getMergeType().toUpperCase().equals(MergeType.AUTO.name());
}
private boolean pushSource()
{
return getOpts().getPushType() == PushPullType.Both || getOpts().getPushType() == PushPullType.Source;
}
private boolean pushTrans()
{
return getOpts().getPushType() == PushPullType.Both || getOpts().getPushType() == PushPullType.Trans;
}
@Override
public void run() throws Exception
{
logOptions(log, getOpts());
pushCurrentModule();
if (pushSource() && getOpts().getEnableModules() && getOpts().isRootModule())
{
List<String> obsoleteDocs = getObsoleteDocNamesForProjectIterationFromServer();
log.info("found {} docs in obsolete modules (or no module): {}", obsoleteDocs.size(), obsoleteDocs);
if (getOpts().getDeleteObsoleteModules() && !obsoleteDocs.isEmpty())
{
// offer to delete obsolete documents
confirmWithUser("Do you want to delete all documents from the server which don't belong to any module in the Maven reactor?\n");
deleteSourceDocsFromServer(obsoleteDocs);
}
else
{
log.warn("found {} docs in obsolete modules (or no module). use -Dzanata.deleteObsoleteModules to delete them", obsoleteDocs.size());
}
}
}
/**
* gets doc list from server, returns a list of qualified doc names from
* obsolete modules, or from no module.
*/
protected List<String> getObsoleteDocNamesForProjectIterationFromServer()
{
if (!getOpts().getEnableModules())
return Collections.emptyList();
List<ResourceMeta> remoteDocList = getDocListForProjectIterationFromServer();
Pattern p = Pattern.compile(getOpts().getDocNameRegex());
Set<String> modules = new HashSet<String>(getOpts().getAllModules());
List<String> obsoleteDocs = new ArrayList<String>();
for (ResourceMeta doc : remoteDocList)
{
// NB ResourceMeta.name == HDocument.docId
String docName = doc.getName();
Matcher matcher = p.matcher(docName);
if (matcher.matches())
{
String module = matcher.group(1);
if (modules.contains(module))
{
log.debug("doc {} belongs to non-obsolete module {}", docName, module);
}
else
{
obsoleteDocs.add(docName);
log.info("doc {} belongs to obsolete module {}", docName, module);
}
}
else
{
obsoleteDocs.add(docName);
log.warn("doc {} doesn't belong to any module", docName);
}
}
return obsoleteDocs;
}
private void pushCurrentModule() throws IOException
{
File sourceDir = getOpts().getSrcDir();
if (!sourceDir.exists())
{
if (getOpts().getEnableModules())
{
log.info("source directory '" + sourceDir + "' not found; skipping docs push for module " + getOpts().getCurrentModule());
return;
}
else
{
throw new RuntimeException("directory '" + sourceDir + "' does not exist - check srcDir option");
}
}
AbstractPushStrategy strat = getStrategy(getOpts().getProjectType());
final StringSet extensions = strat.getExtensions();
// to save memory, we don't load all the docs into a HashMap
Set<String> localDocNames = strat.findDocNames(sourceDir, getOpts().getIncludes(), getOpts().getExcludes(), getOpts().getDefaultExcludes());
for (String docName : localDocNames)
{
log.info("Found source document: {}", docName);
}
List<String> obsoleteDocs = Collections.emptyList();
if (pushSource())
{
obsoleteDocs = getObsoleteDocsInModuleFromServer(localDocNames);
}
if (obsoleteDocs.isEmpty())
{
if (localDocNames.isEmpty())
{
log.info("no documents in module: {}; nothing to do", getOpts().getCurrentModule());
return;
}
else
{
// nop
}
}
else
{
log.warn("Found {} obsolete docs on the server which will be DELETED", obsoleteDocs.size());
log.info("Obsolete docs: {}", obsoleteDocs);
}
if (pushTrans())
{
if (getOpts().getLocaleMapList() == null)
throw new ConfigException("pushType set to '" + getOpts().getPushType() + "', but zanata.xml contains no <locales>");
log.warn("pushType set to '" + getOpts().getPushType() + "': existing translations on server may be overwritten/deleted");
if (getOpts().getPushType() == PushPullType.Both)
{
confirmWithUser("This will overwrite existing documents AND TRANSLATIONS on the server, and delete obsolete documents.\n");
}
else if (getOpts().getPushType() == PushPullType.Trans)
{
confirmWithUser("This will overwrite existing TRANSLATIONS on the server.\n");
}
}
else
{
confirmWithUser("This will overwrite existing source documents on the server, and delete obsolete documents.\n");
}
for (String localDocName : localDocNames)
{
final Resource srcDoc = strat.loadSrcDoc(sourceDir, localDocName);
String qualifiedDocName = qualifiedDocName(localDocName);
final String docUri = RestUtil.convertToDocumentURIId(qualifiedDocName);
srcDoc.setName(qualifiedDocName);
debug(srcDoc);
if (pushSource())
{
pushSrcDocToServer(docUri, srcDoc, extensions);
}
if (pushTrans())
{
strat.visitTranslationResources(localDocName, srcDoc, new TranslationResourcesVisitor()
{
@Override
public void visit(LocaleMapping locale, TranslationsResource targetDoc)
{
debug(targetDoc);
pushTargetDocToServer(docUri, locale, srcDoc, targetDoc, extensions);
}
});
}
// Copy Trans after pushing (only when pushing source)
if( getOpts().getCopyTrans() &&
(getOpts().getPushType() == PushPullType.Both || getOpts().getPushType() == PushPullType.Source) )
{
this.copyTransForDocument(qualifiedDocName);
}
}
deleteSourceDocsFromServer(obsoleteDocs);
}
/**
* Returns obsolete docs which belong to the current module. Returns any docs
* in the current module from the server, unless they are found in the
* localDocNames set.
*
* @param localDocNames
*/
private List<String> getObsoleteDocsInModuleFromServer(Set<String> localDocNames)
{
List<String> qualifiedDocNames = getQualifiedDocNamesForCurrentModuleFromServer();
List<String> obsoleteDocs = new ArrayList<String>(qualifiedDocNames.size());
for (String qualifiedDocName : qualifiedDocNames)
{
String unqualifiedDocName = unqualifiedDocName(qualifiedDocName);
if (!localDocNames.contains(unqualifiedDocName))
{
obsoleteDocs.add(qualifiedDocName);
}
}
return obsoleteDocs;
}
/**
* @param qualifiedDocNames
*/
private void deleteSourceDocsFromServer(List<String> qualifiedDocNames)
{
for (String qualifiedDocName : qualifiedDocNames)
{
deleteSourceDocFromServer(qualifiedDocName);
}
}
private void pushSrcDocToServer(final String docUri, final Resource srcDoc, final StringSet extensions)
{
if (!getOpts().isDryRun())
{
log.info("pushing source doc [name={} size={}] to server", srcDoc.getName(), srcDoc.getTextFlows().size());
ConsoleUtils.startProgressFeedback();
// NB: Copy trans is set to false as using copy trans in this manner is deprecated.
// see PushCommand.copyTransForDocument
ProcessStatus status =
asyncProcessResource.startSourceDocCreationOrUpdate(
docUri, getOpts().getProj(), getOpts().getProjectVersion(), srcDoc, extensions, false);
boolean waitForCompletion = true;
while( waitForCompletion )
{
switch (status.getStatusCode())
{
case Failed:
throw new RuntimeException("Failed while pushing document: " + status.getMessages());
case Finished:
waitForCompletion = false;
break;
case Running:
ConsoleUtils.setProgressFeedbackMessage("Pushing ...");
break;
case Waiting:
ConsoleUtils.setProgressFeedbackMessage("Waiting to start ...");
break;
case NotAccepted:
// try to submit the process again
status = asyncProcessResource.startSourceDocCreationOrUpdate(
docUri, getOpts().getProj(), getOpts().getProjectVersion(), srcDoc, extensions, false);
ConsoleUtils.setProgressFeedbackMessage("Waiting for other clients ...");
break;
}
wait(2000); // Wait before retrying
status =
asyncProcessResource.getProcessStatus(status.getUrl());
}
ConsoleUtils.endProgressFeedback();
}
else
{
log.info("pushing source doc [name={} size={}] to server (skipped due to dry run)", srcDoc.getName(), srcDoc.getTextFlows().size());
}
}
/**
* Split TranslationsResource into List<TranslationsResource> according to
* maxBatchSize, but only if mergeType=AUTO
*
* @param doc
* @param maxBatchSize
* @return list of TranslationsResource, each containing up to maxBatchSize TextFlowTargets
*/
public List<TranslationsResource> splitIntoBatch(TranslationsResource doc, int maxBatchSize)
{
List<TranslationsResource> targetDocList = new ArrayList<TranslationsResource>();
int numTargets = doc.getTextFlowTargets().size();
if (numTargets > maxBatchSize && mergeAuto())
{
int numBatches = numTargets / maxBatchSize;
if (numTargets % maxBatchSize != 0)
{
++numBatches;
}
int fromIndex = 0;
int toIndex = 0;
for (int i = 1; i <= numBatches; i++)
{
// make a dummy TranslationsResource to hold just the TextFlowTargets for each batch
TranslationsResource resource = new TranslationsResource();
resource.setExtensions(doc.getExtensions());
resource.setLinks(doc.getLinks());
resource.setRevision(doc.getRevision());
if ((i * maxBatchSize) > numTargets)
{
toIndex = numTargets;
}
else
{
toIndex = i * maxBatchSize;
}
resource.getTextFlowTargets().addAll(doc.getTextFlowTargets().subList(fromIndex, toIndex));
fromIndex = i * maxBatchSize;
targetDocList.add(resource);
}
}
else
{
targetDocList.add(doc);
}
return targetDocList;
}
private void pushTargetDocToServer(final String docUri, LocaleMapping locale, final Resource srcDoc, TranslationsResource targetDoc, final StringSet extensions)
{
if (!getOpts().isDryRun())
{
log.info("Pushing target doc [name={} size={} client-locale={}] to server [locale={}]", new Object[] { srcDoc.getName(), targetDoc.getTextFlowTargets().size(), locale.getLocalLocale(), locale.getLocale() });
ConsoleUtils.startProgressFeedback();
ProcessStatus status =
asyncProcessResource.startTranslatedDocCreationOrUpdate(docUri, getOpts().getProj(), getOpts().getProjectVersion(),
new LocaleId(locale.getLocale()), targetDoc, extensions, getOpts().getMergeType());
boolean waitForCompletion = true;
while( waitForCompletion )
{
switch (status.getStatusCode())
{
case Failed:
throw new RuntimeException("Failed while pushing document translations: " + status.getMessages());
case Finished:
waitForCompletion = false;
break;
case Running:
ConsoleUtils.setProgressFeedbackMessage(status.getPercentageComplete() + "%");
break;
case Waiting:
ConsoleUtils.setProgressFeedbackMessage("Waiting to start ...");
break;
case NotAccepted:
// try to submit the process again
status = asyncProcessResource.startTranslatedDocCreationOrUpdate(
docUri, getOpts().getProj(), getOpts().getProjectVersion(),
new LocaleId(locale.getLocale()), targetDoc, extensions, getOpts().getMergeType());
ConsoleUtils.setProgressFeedbackMessage("Waiting for other clients ...");
break;
}
wait(2000); // Wait before retrying
status =
asyncProcessResource.getProcessStatus(status.getUrl());
}
ConsoleUtils.endProgressFeedback();
// Show warning messages
if( status.getMessages().size() > 0 )
{
log.warn("Pushed translations with warnings:");
for( String mssg : status.getMessages() )
{
log.warn(mssg);
}
}
}
else
{
log.info("pushing target doc [name={} size={} client-locale={}] to server [locale={}] (skipped due to dry run)", new Object[] { srcDoc.getName(), targetDoc.getTextFlowTargets().size(), locale.getLocalLocale(), locale.getLocale() });
}
}
private void deleteSourceDocFromServer(String qualifiedDocName)
{
if (!getOpts().isDryRun())
{
log.info("deleting resource {} from server", qualifiedDocName);
String docUri = RestUtil.convertToDocumentURIId(qualifiedDocName);
ClientResponse<String> deleteResponse = sourceDocResource.deleteResource(docUri);
ClientUtility.checkResult(deleteResponse, uri);
}
else
{
log.info("deleting resource {} from server (skipped due to dry run)", qualifiedDocName);
}
}
private void copyTransForDocument(String docName)
{
log.info("Running Copy Trans for " + docName);
try
{
this.copyTransResource.startCopyTrans(getOpts().getProj(), getOpts().getProjectVersion(), docName);
}
catch( Exception ex )
{
log.warn("Could not start Copy Trans for above document. Proceeding");
return;
}
CopyTransStatus copyTransStatus = null;
try
{
copyTransStatus = this.copyTransResource.getCopyTransStatus(getOpts().getProj(), getOpts().getProjectVersion(), docName);
}
catch (ClientResponseFailure failure)
{
// 404 - Probably because of an old server
if( failure.getResponse().getResponseStatus() == Response.Status.NOT_FOUND )
{
if( getRequestFactory().compareToServerVersion("1.8.0-SNAPSHOT") < 0 )
{
log.warn("Copy Trans not started (Incompatible server version.)");
return;
}
else
{
throw new RuntimeException("Could not invoke copy trans. The service was not available (404)");
}
}
else if( failure.getCause() != null )
{
throw new RuntimeException("Problem invoking copy trans.", failure.getCause());
}
else
{
throw new RuntimeException(
"Problem invoking copy trans: [Server response code:"
+ failure.getResponse().getResponseStatus().getStatusCode() + "]");
}
}
ConsoleUtils.startProgressFeedback();
while( copyTransStatus.isInProgress() )
{
try
{
Thread.sleep(2000);
}
catch (InterruptedException e)
{
log.warn("Interrupted while waiting for Copy Trans to finish.");
}
ConsoleUtils.setProgressFeedbackMessage(copyTransStatus.getPercentageComplete() + "%");
copyTransStatus =
this.copyTransResource.getCopyTransStatus(getOpts().getProj(), getOpts().getProjectVersion(), docName);
}
ConsoleUtils.endProgressFeedback();
if( copyTransStatus.getPercentageComplete() < 100 )
{
log.warn("Copy Trans for the above document stopped unexpectedly.");
}
}
// TODO Perhaps move this to ConsoleUtils
private static void wait( int millis )
{
try
{
Thread.sleep(millis);
}
catch (InterruptedException e)
{
log.warn("Interrupted while waiting");
}
}
} |
package net.onrc.onos.apps.forwarding;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import net.floodlightcontroller.core.FloodlightContext;
import net.floodlightcontroller.core.IFloodlightProviderService;
import net.floodlightcontroller.core.IOFMessageListener;
import net.floodlightcontroller.core.IOFSwitch;
import net.floodlightcontroller.core.module.FloodlightModuleContext;
import net.floodlightcontroller.core.module.IFloodlightModule;
import net.floodlightcontroller.core.module.IFloodlightService;
import net.floodlightcontroller.util.MACAddress;
import net.onrc.onos.apps.proxyarp.IProxyArpService;
import net.onrc.onos.core.datagrid.IDatagridService;
import net.onrc.onos.core.datagrid.IEventChannel;
import net.onrc.onos.core.datagrid.IEventChannelListener;
import net.onrc.onos.core.devicemanager.IOnosDeviceService;
import net.onrc.onos.core.flowprogrammer.IFlowPusherService;
import net.onrc.onos.core.intent.Intent;
import net.onrc.onos.core.intent.Intent.IntentState;
import net.onrc.onos.core.intent.IntentMap;
import net.onrc.onos.core.intent.IntentOperation;
import net.onrc.onos.core.intent.IntentOperationList;
import net.onrc.onos.core.intent.PathIntent;
import net.onrc.onos.core.intent.ShortestPathIntent;
import net.onrc.onos.core.intent.runtime.IPathCalcRuntimeService;
import net.onrc.onos.core.intent.runtime.IntentStateList;
import net.onrc.onos.core.packet.Ethernet;
import net.onrc.onos.core.packetservice.BroadcastPacketOutNotification;
import net.onrc.onos.core.registry.IControllerRegistryService;
import net.onrc.onos.core.topology.Device;
import net.onrc.onos.core.topology.INetworkGraphService;
import net.onrc.onos.core.topology.LinkEvent;
import net.onrc.onos.core.topology.NetworkGraph;
import net.onrc.onos.core.topology.Switch;
import net.onrc.onos.core.util.Dpid;
import net.onrc.onos.core.util.FlowPath;
import net.onrc.onos.core.util.Port;
import net.onrc.onos.core.util.SwitchPort;
import org.openflow.protocol.OFMessage;
import org.openflow.protocol.OFPacketIn;
import org.openflow.protocol.OFPacketOut;
import org.openflow.protocol.OFPort;
import org.openflow.protocol.OFType;
import org.openflow.protocol.action.OFAction;
import org.openflow.protocol.action.OFActionOutput;
import org.openflow.util.HexString;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.LinkedListMultimap;
import com.google.common.collect.ListMultimap;
public class Forwarding implements IOFMessageListener, IFloodlightModule,
IForwardingService, IEventChannelListener<Long, IntentStateList> {
private static final Logger log = LoggerFactory.getLogger(Forwarding.class);
private static final int SLEEP_TIME_FOR_DB_DEVICE_INSTALLED = 100; // milliseconds
private static final int NUMBER_OF_THREAD_FOR_EXECUTOR = 1;
private static final ScheduledExecutorService EXECUTOR_SERVICE = Executors.newScheduledThreadPool(NUMBER_OF_THREAD_FOR_EXECUTOR);
private final String callerId = "Forwarding";
private IFloodlightProviderService floodlightProvider;
private IFlowPusherService flowPusher;
private IDatagridService datagrid;
private IEventChannel<Long, BroadcastPacketOutNotification> eventChannel;
private static final String SINGLE_PACKET_OUT_CHANNEL_NAME = "onos.forwarding.packet_out";
private IControllerRegistryService controllerRegistryService;
private INetworkGraphService networkGraphService;
private NetworkGraph networkGraph;
private IPathCalcRuntimeService pathRuntime;
private IntentMap intentMap;
// TODO it seems there is a Guava collection that will time out entries.
// We should see if this will work here.
private Map<Path, PushedFlow> pendingFlows;
private ListMultimap<String, PacketToPush> waitingPackets;
private final Object lock = new Object();
private static class PacketToPush {
public final OFPacketOut packet;
public final long dpid;
public PacketToPush(OFPacketOut packet, long dpid) {
this.packet = packet;
this.dpid = dpid;
}
}
private static class PushedFlow {
public final String intentId;
public boolean installed = false;
public short firstOutPort;
public PushedFlow(String flowId) {
this.intentId = flowId;
}
}
private static final class Path {
public final MACAddress srcMac;
public final MACAddress dstMac;
public Path(MACAddress srcMac, MACAddress dstMac) {
this.srcMac = srcMac;
this.dstMac = dstMac;
}
@Override
public boolean equals(Object other) {
if (!(other instanceof Path)) {
return false;
}
Path otherPath = (Path) other;
return srcMac.equals(otherPath.srcMac) &&
dstMac.equals(otherPath.dstMac);
}
@Override
public int hashCode() {
int hash = 17;
hash = 31 * hash + srcMac.hashCode();
hash = 31 * hash + dstMac.hashCode();
return hash;
}
@Override
public String toString() {
return "(" + srcMac + ") => (" + dstMac + ")";
}
}
@Override
public Collection<Class<? extends IFloodlightService>> getModuleServices() {
List<Class<? extends IFloodlightService>> services =
new ArrayList<Class<? extends IFloodlightService>>(1);
services.add(IForwardingService.class);
return services;
}
@Override
public Map<Class<? extends IFloodlightService>, IFloodlightService> getServiceImpls() {
Map<Class<? extends IFloodlightService>, IFloodlightService> impls =
new HashMap<Class<? extends IFloodlightService>, IFloodlightService>(1);
impls.put(IForwardingService.class, this);
return impls;
}
@Override
public Collection<Class<? extends IFloodlightService>> getModuleDependencies() {
List<Class<? extends IFloodlightService>> dependencies =
new ArrayList<Class<? extends IFloodlightService>>();
dependencies.add(IFloodlightProviderService.class);
dependencies.add(IFlowPusherService.class);
dependencies.add(IControllerRegistryService.class);
dependencies.add(IOnosDeviceService.class);
dependencies.add(IDatagridService.class);
dependencies.add(INetworkGraphService.class);
dependencies.add(IPathCalcRuntimeService.class);
// We don't use the IProxyArpService directly, but reactive forwarding
// requires it to be loaded and answering ARP requests
dependencies.add(IProxyArpService.class);
return dependencies;
}
@Override
public void init(FloodlightModuleContext context) {
floodlightProvider =
context.getServiceImpl(IFloodlightProviderService.class);
flowPusher = context.getServiceImpl(IFlowPusherService.class);
datagrid = context.getServiceImpl(IDatagridService.class);
controllerRegistryService = context.getServiceImpl(IControllerRegistryService.class);
networkGraphService = context.getServiceImpl(INetworkGraphService.class);
pathRuntime = context.getServiceImpl(IPathCalcRuntimeService.class);
floodlightProvider.addOFMessageListener(OFType.PACKET_IN, this);
pendingFlows = new HashMap<Path, PushedFlow>();
waitingPackets = LinkedListMultimap.create();
}
@Override
public void startUp(FloodlightModuleContext context) {
eventChannel = datagrid.createChannel(SINGLE_PACKET_OUT_CHANNEL_NAME,
Long.class,
BroadcastPacketOutNotification.class);
networkGraph = networkGraphService.getNetworkGraph();
intentMap = pathRuntime.getPathIntents();
datagrid.addListener("onos.pathintent_state", this, Long.class, IntentStateList.class);
}
@Override
public String getName() {
return "onosforwarding";
}
@Override
public boolean isCallbackOrderingPrereq(OFType type, String name) {
return (type == OFType.PACKET_IN) &&
(name.equals("devicemanager") || name.equals("proxyarpmanager")
|| name.equals("onosdevicemanager"));
}
@Override
public boolean isCallbackOrderingPostreq(OFType type, String name) {
return false;
}
@Override
public Command receive(
IOFSwitch sw, OFMessage msg, FloodlightContext cntx) {
if (msg.getType() != OFType.PACKET_IN || !(msg instanceof OFPacketIn)) {
return Command.CONTINUE;
}
OFPacketIn pi = (OFPacketIn) msg;
Ethernet eth = IFloodlightProviderService.bcStore.
get(cntx, IFloodlightProviderService.CONTEXT_PI_PAYLOAD);
log.debug("Receive PACKET_IN swId {}, portId {}", sw.getId(), pi.getInPort());
if (eth.getEtherType() != Ethernet.TYPE_IPV4) {
return Command.CONTINUE;
}
if (eth.isBroadcast() || eth.isMulticast()) {
handleBroadcast(sw, pi, eth);
} else {
// Unicast
handlePacketIn(sw, pi, eth);
}
return Command.STOP;
}
private void handleBroadcast(IOFSwitch sw, OFPacketIn pi, Ethernet eth) {
if (log.isTraceEnabled()) {
log.trace("Sending broadcast packet to other ONOS instances");
}
//We don't use address information, so 0 is put into the third argument.
BroadcastPacketOutNotification key =
new BroadcastPacketOutNotification(
eth.serialize(),
0, sw.getId(),
pi.getInPort());
eventChannel.addTransientEntry(eth.getDestinationMAC().toLong(), key);
}
private void handlePacketIn(IOFSwitch sw, OFPacketIn pi, Ethernet eth) {
log.debug("Start handlePacketIn swId {}, portId {}", sw.getId(), pi.getInPort());
String destinationMac =
HexString.toHexString(eth.getDestinationMACAddress());
//FIXME getDeviceByMac() is a blocking call, so it may be better way to handle it to avoid the condition.
Device deviceObject = networkGraph.getDeviceByMac(MACAddress.valueOf(destinationMac));
if (deviceObject == null) {
log.debug("No device entry found for {}",
destinationMac);
//Device is not in the DB, so wait it until the device is added.
EXECUTOR_SERVICE.schedule(new WaitDeviceArp(sw, pi, eth), SLEEP_TIME_FOR_DB_DEVICE_INSTALLED, TimeUnit.MILLISECONDS);
return;
}
continueHandlePacketIn(sw, pi, eth, deviceObject);
}
private class WaitDeviceArp implements Runnable {
IOFSwitch sw;
OFPacketIn pi;
Ethernet eth;
public WaitDeviceArp(IOFSwitch sw, OFPacketIn pi, Ethernet eth) {
super();
this.sw = sw;
this.pi = pi;
this.eth = eth;
}
@Override
public void run() {
Device deviceObject = networkGraph.getDeviceByMac(MACAddress.valueOf(eth.getDestinationMACAddress()));
if (deviceObject == null) {
log.debug("wait {}ms and device was not found. Send broadcast packet and the thread finish.", SLEEP_TIME_FOR_DB_DEVICE_INSTALLED);
handleBroadcast(sw, pi, eth);
return;
}
log.debug("wait {}ms and device {} was found, continue", SLEEP_TIME_FOR_DB_DEVICE_INSTALLED, deviceObject.getMacAddress());
continueHandlePacketIn(sw, pi, eth, deviceObject);
}
}
private void continueHandlePacketIn(IOFSwitch sw, OFPacketIn pi, Ethernet eth, Device deviceObject) {
log.debug("Start continuehandlePacketIn");
//Iterator<IPortObject> ports = deviceObject.getAttachedPorts().iterator();
Iterator<net.onrc.onos.core.topology.Port> ports = deviceObject.getAttachmentPoints().iterator();
if (!ports.hasNext()) {
log.debug("No attachment point found for device {} - broadcasting packet",
deviceObject.getMacAddress());
handleBroadcast(sw, pi, eth);
return;
}
//This code assumes the device has only one port. It should be problem.
net.onrc.onos.core.topology.Port portObject = ports.next();
short destinationPort = portObject.getNumber().shortValue();
Switch switchObject = portObject.getSwitch();
long destinationDpid = switchObject.getDpid();
// TODO SwitchPort, Dpid and Port should probably be immutable
SwitchPort srcSwitchPort = new SwitchPort(
new Dpid(sw.getId()), new Port(pi.getInPort()));
SwitchPort dstSwitchPort = new SwitchPort(
new Dpid(destinationDpid), new Port(destinationPort));
MACAddress srcMacAddress = MACAddress.valueOf(eth.getSourceMACAddress());
MACAddress dstMacAddress = MACAddress.valueOf(eth.getDestinationMACAddress());
synchronized (lock) {
//TODO check concurrency
Path pathspec = new Path(srcMacAddress, dstMacAddress);
PushedFlow existingFlow = pendingFlows.get(pathspec);
//A path is installed side by side to reduce a path timeout and a wrong state.
if (existingFlow != null) {
// We've already start to install a flow for this pair of MAC addresses
if (log.isDebugEnabled()) {
log.debug("Found existing the same pathspec {}, intent ID is {}",
pathspec,
existingFlow.intentId);
}
OFPacketOut po = constructPacketOut(pi, sw);
// Find the correct port here. We just assume the PI is from
// the first hop switch, but this is definitely not always
// the case. We'll have to retrieve the flow from HZ every time
// because it could change (be rerouted) sometimes.
if (existingFlow.installed) {
// Flow has been sent to the switches so it is safe to
// send a packet out now
Intent intent = intentMap.getIntent(existingFlow.intentId);
PathIntent pathIntent = null;
if (intent instanceof PathIntent) {
pathIntent = (PathIntent) intent;
} else {
log.debug("Intent {} is not PathIntent. Return.", intent.getId());
return;
}
Boolean isflowEntryForThisSwitch = false;
net.onrc.onos.core.topology.Path path = pathIntent.getPath();
for (Iterator<LinkEvent> i = path.iterator(); i.hasNext();) {
LinkEvent le = (LinkEvent) i.next();
if (le.getSrc().dpid == sw.getId()) {
log.debug("src {} dst {}", le.getSrc(), le.getDst());
isflowEntryForThisSwitch = true;
break;
}
}
if (!isflowEntryForThisSwitch) {
// If we don't find a flow entry for that switch, then we're
// in the middle of a rerouting (or something's gone wrong).
// This packet will be dropped as a victim of the rerouting.
log.debug("Dropping packet on flow {} between {}-{}",
existingFlow.intentId,
srcMacAddress, dstMacAddress);
} else {
log.debug("Sending packet out from sw {}, outport{}", sw, existingFlow.firstOutPort);
sendPacketOut(sw, po, existingFlow.firstOutPort);
}
} else {
// Flow path has not yet been installed to switches so save the
// packet out for later
log.debug("Put a packet into the waitng list. flowId {}", existingFlow.intentId);
waitingPackets.put(existingFlow.intentId, new PacketToPush(po, sw.getId()));
}
return;
}
log.debug("Adding new flow between {} at {} and {} at {}",
new Object[]{srcMacAddress, srcSwitchPort, dstMacAddress, dstSwitchPort});
String intentId = callerId + ":" + controllerRegistryService.getNextUniqueId();
IntentOperationList operations = new IntentOperationList();
ShortestPathIntent intent = new ShortestPathIntent(intentId,
sw.getId(), pi.getInPort(), srcMacAddress.toLong(),
destinationDpid, destinationPort, dstMacAddress.toLong());
IntentOperation.Operator operator = IntentOperation.Operator.ADD;
operations.add(operator, intent);
pathRuntime.executeIntentOperations(operations);
OFPacketOut po = constructPacketOut(pi, sw);
// Add to waiting lists
pendingFlows.put(pathspec, new PushedFlow(intentId));
log.debug("Put a Path {} in the pending flow, intent ID {}", pathspec, intentId);
waitingPackets.put(intentId, new PacketToPush(po, sw.getId()));
log.debug("Put a Packet in the wating list. related pathspec {}", pathspec);
}
}
private OFPacketOut constructPacketOut(OFPacketIn pi, IOFSwitch sw) {
OFPacketOut po = new OFPacketOut();
po.setInPort(OFPort.OFPP_NONE)
.setInPort(pi.getInPort())
.setActions(new ArrayList<OFAction>())
.setLengthU(OFPacketOut.MINIMUM_LENGTH);
if (sw.getBuffers() == 0) {
po.setBufferId(OFPacketOut.BUFFER_ID_NONE)
.setPacketData(pi.getPacketData())
.setLengthU(po.getLengthU() + po.getPacketData().length);
} else {
po.setBufferId(pi.getBufferId());
}
return po;
}
@Override
public void flowsInstalled(Collection<FlowPath> installedFlowPaths) {
}
@Override
public void flowRemoved(FlowPath removedFlowPath) {
}
public void flowRemoved(PathIntent removedIntent) {
if (log.isTraceEnabled()) {
log.trace("Path {} was removed", removedIntent.getParentIntent().getId());
}
ShortestPathIntent spfIntent = (ShortestPathIntent) removedIntent.getParentIntent();
MACAddress srcMacAddress = MACAddress.valueOf(spfIntent.getSrcMac());
MACAddress dstMacAddress = MACAddress.valueOf(spfIntent.getDstMac());
Path removedPath = new Path(srcMacAddress, dstMacAddress);
synchronized (lock) {
// There *shouldn't* be any packets queued if the flow has
// just been removed.
List<PacketToPush> packets = waitingPackets.removeAll(spfIntent.getId());
if (!packets.isEmpty()) {
log.warn("Removed flow {} has packets queued.", spfIntent.getId());
}
pendingFlows.remove(removedPath);
log.debug("Removed from the pendingFlow: Path {}, Flow ID {}", removedPath, spfIntent.getId());
}
}
private void flowInstalled(PathIntent installedPath) {
if (log.isTraceEnabled()) {
log.trace("Path {} was installed", installedPath.getParentIntent().getId());
}
ShortestPathIntent spfIntent = (ShortestPathIntent) installedPath.getParentIntent();
MACAddress srcMacAddress = MACAddress.valueOf(spfIntent.getSrcMac());
MACAddress dstMacAddress = MACAddress.valueOf(spfIntent.getDstMac());
Path path = new Path(srcMacAddress, dstMacAddress);
log.debug("Path spec {}", path);
// TODO waiting packets should time out. We could request a path that
// can't be installed right now because of a network partition. The path
// may eventually be installed, but we may have received thousands of
// packets in the meantime and probably don't want to send very old packets.
List<PacketToPush> packets = null;
net.onrc.onos.core.topology.Path graphPath = installedPath.getPath();
short outPort;
if (graphPath.isEmpty()) {
outPort = (short) spfIntent.getDstPortNumber();
log.debug("Path is empty. Maybe devices on the same switch. outPort {}", outPort);
} else {
outPort = graphPath.get(0).getSrc().getNumber().shortValue();
log.debug("path{}, outPort {}", graphPath, outPort);
}
PushedFlow existingFlow = null;
synchronized (lock) {
existingFlow = pendingFlows.get(path);
if (existingFlow != null) {
existingFlow.installed = true;
existingFlow.firstOutPort = outPort;
} else {
log.debug("ExistingFlow {} is null", path);
return;
}
//Check both existing flow are installed status.
if (existingFlow.installed) {
packets = waitingPackets.removeAll(existingFlow.intentId);
if (log.isDebugEnabled()) {
log.debug("removed my packets {} to push from waitingPackets. outPort {} size {}",
existingFlow.intentId, existingFlow.firstOutPort, packets.size());
}
} else {
log.debug("Forward or reverse flows hasn't been pushed yet. return");
return;
}
}
for (PacketToPush packet : packets) {
log.debug("Start packetToPush to sw {}, outPort {}, path {}", packet.dpid, existingFlow.firstOutPort, path);
IOFSwitch sw = floodlightProvider.getSwitches().get(packet.dpid);
sendPacketOut(sw, packet.packet, existingFlow.firstOutPort);
}
}
private void sendPacketOut(IOFSwitch sw, OFPacketOut po, short outPort) {
po.getActions().add(new OFActionOutput(outPort));
po.setActionsLength((short)
(po.getActionsLength() + OFActionOutput.MINIMUM_LENGTH));
po.setLengthU(po.getLengthU() + OFActionOutput.MINIMUM_LENGTH);
flowPusher.add(sw, po);
}
@Override
public void entryAdded(IntentStateList value) {
entryUpdated(value);
}
@Override
public void entryRemoved(IntentStateList value) {
//no-op
}
@Override
public void entryUpdated(IntentStateList value) {
for (Entry<String, IntentState> entry : value.entrySet()) {
log.debug("path intent key {}, value {}", entry.getKey(), entry.getValue());
PathIntent pathIntent = (PathIntent) intentMap.getIntent(entry.getKey());
if (pathIntent == null) {
continue;
}
if (!(pathIntent.getParentIntent() instanceof ShortestPathIntent)) {
continue;
}
IntentState state = entry.getValue();
switch (state) {
case INST_REQ:
break;
case INST_ACK:
flowInstalled(pathIntent);
break;
case INST_NACK:
break;
case DEL_REQ:
break;
case DEL_ACK:
flowRemoved(pathIntent);
break;
case DEL_PENDING:
break;
default:
break;
}
}
}
} |
package net.breakinbad.securitycraft.blocks;
import java.util.List;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IIcon;
public class BlockReinforcedSandstone extends BlockOwnable {
private static final String[] sideIconSuffixes = new String[] {"normal", "carved", "smooth"};
@SideOnly(Side.CLIENT)
private IIcon[] sideIcons;
@SideOnly(Side.CLIENT)
private IIcon topIcon;
@SideOnly(Side.CLIENT)
private IIcon bottomIcon;
public BlockReinforcedSandstone(){
super(Material.rock);
}
@SideOnly(Side.CLIENT)
public void getSubBlocks(Item par1Item, CreativeTabs par2CreativeTabs, List par3List){
par3List.add(new ItemStack(par1Item, 1, 0));
par3List.add(new ItemStack(par1Item, 1, 1));
par3List.add(new ItemStack(par1Item, 1, 2));
}
public int damageDropped(int par1){
return par1;
}
@SideOnly(Side.CLIENT)
public IIcon getIcon(int par1, int par2){
if(par1 != 1 && (par1 != 0 || par2 != 1 && par2 != 2)){
if(par1 == 0){
return this.bottomIcon;
}else{
if(par2 < 0 || par2 >= this.sideIcons.length){
par2 = 0;
}
return this.sideIcons[par2];
}
}else{
return this.topIcon;
}
}
@SideOnly(Side.CLIENT)
public void registerBlockIcons(IIconRegister par1IIconRegister){
this.sideIcons = new IIcon[sideIconSuffixes.length];
for(int i = 0; i < this.sideIcons.length; i++){
this.sideIcons[i] = par1IIconRegister.registerIcon(this.getTextureName() + "_" + sideIconSuffixes[i]);
}
this.topIcon = par1IIconRegister.registerIcon(this.getTextureName() + "_top");
this.bottomIcon = par1IIconRegister.registerIcon(this.getTextureName() + "_bottom");
}
} |
package net.raumzeitfalle.timeseries;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
public class EwmaExample {
/**
* Simple EWMA Example
* @param args
*/
public static void main(String[] args){
System.out.println("Starting test...");
Random random = new Random();
List<Double> values = new LinkedList<>();
double[] offsets = new double[]{0.5,-0.1,0.2};
double offset = 0.0;
for (int i = 0; i < 2_00; i++){
if (i > 75) offset = offsets[0];
if (i > 130) offset = offsets[1];
if (i > 150) offset = offsets[2];
values.add( Double.valueOf(random.nextDouble() + offset));
}
System.out.println("n\tValue\tEWMA applied");
List<Double> ewma = EwmaFunctions.applyToStream(values.stream()).collect(Collectors.toList());
int minSize = Math.min(values.size(), ewma.size());
for (int i = 0; i < minSize; i++){
System.out.print( i + "\t" + values.get(i) + "\t");
System.out.println( ewma.get(i) + "\t");
}
}
} |
package net.sf.gaboto.generation;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
import java.util.Map.Entry;
import javax.xml.parsers.ParserConfigurationException;
import net.sf.gaboto.node.GabotoBean;
import net.sf.gaboto.util.XMLUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
* Generates specialised classes from the Gaboto config file.
*
* <p>
* This class is very scripty and should be redone in an orderly fashion.
* </p>
*
* @author Arno Mittelbach
*
*/
public class GabotoGenerator {
private File config = null;
private File outputDir;
private File entityOutputDir;
private File beanOutputDir;
private String packageName = null;
private String entitiesPackageName = null;
private String beansPackageName = null;
private String lookupClassName = null;
private String entityClassNames = "";
private Collection<String> entityNames = new HashSet<String>();
private Collection<String> entityTypes = new HashSet<String>();
private Map<String, String> entityClassLookup = new HashMap<String, String>();
// Type 2 uri
private Map<String, String> entityTypeURILookup = new HashMap<String, String>();
public final static int LITERAL_TYPE_STRING = 1;
public final static int LITERAL_TYPE_INTEGER = 2;
public final static int LITERAL_TYPE_FLOAT = 3;
public final static int LITERAL_TYPE_DOUBLE = 4;
public final static int LITERAL_TYPE_BOOLEAN = 5;
public final static int SIMPLE_LITERAL_PROPERTY = 1;
public final static int SIMPLE_URI_PROPERTY = 2;
public final static int SIMPLE_COMPLEX_PROPERTY = 3;
public final static int BAG_LITERAL_PROPERTY = 4;
public final static int BAG_URI_PROPERTY = 5;
public final static int BAG_COMPLEX_PROPERTY = 6;
public GabotoGenerator(File config, File outputDir, String packageName) {
String packageRelativeDirectoryName = packageName.replace('.', '/');
this.config = config;
this.entityOutputDir = new File(outputDir, packageRelativeDirectoryName + "/entities");
this.beanOutputDir = new File(outputDir, packageRelativeDirectoryName + "/beans");
this.outputDir = new File(outputDir, packageRelativeDirectoryName + "/");
this.entitiesPackageName = packageName + ".entities";
this.beansPackageName = packageName + ".beans";
this.packageName = packageName ;
}
public void run() throws ParserConfigurationException, SAXException, IOException {
// load document
Document doc = XMLUtils.readInputFileIntoJAXPDoc(config);
Element root = doc.getDocumentElement();
NodeList children = root.getChildNodes();
// load entity types first as they can be referred to in any order
for (int i = 0; i < children.getLength(); i++) {
if (!(children.item(i) instanceof Element))
continue;
Element el = (Element)children.item(i);
System.err.println("Name " + el.getNodeName());
if (el.getNodeName().equals("GabotoEntities")) {
NodeList entities = el.getChildNodes();
// now generate the entities
for (int j = 0; j < entities.getLength(); j++) {
if (!(entities.item(j) instanceof Element))
continue;
Element entityEl = (Element) entities.item(j);
readConfigFile(entityEl);
}
} else if (el.getNodeName().equals("config")) {
NodeList entities = el.getChildNodes();
// now generate the entities
for (int j = 0; j < entities.getLength(); j++) {
if (!(entities.item(j) instanceof Element))
continue;
Element entityEl = (Element) entities.item(j);
if (entityEl.getNodeName().equals("lookupClass")) {
String fullClassName = entityEl.getAttribute("class");
this.lookupClassName = fullClassName.substring(fullClassName.lastIndexOf('.') + 1);
}
}
}
}
// Generate classes from loaded entities
for (int i = 0; i < children.getLength(); i++) {
if (!(children.item(i) instanceof Element))
continue;
// cast
Element el = (Element) children.item(i);
if (el.getNodeName().equals("GabotoEntities")) {
NodeList entities = el.getChildNodes();
// generate the entities
for (int j = 0; j < entities.getLength(); j++) {
if (!(entities.item(j) instanceof Element))
continue;
Element entityEl = (Element) entities.item(j);
generateEntity(entityEl, "GabotoEntity");
}
} else if (el.getNodeName().equals("GabotoBeans")) {
NodeList beans = el.getChildNodes();
// generate the beans
for (int j = 0; j < beans.getLength(); j++) {
if (!(beans.item(j) instanceof Element))
continue;
Element beanEl = (Element) beans.item(j);
generateBean(beanEl);
}
}
}
generateLookup();
}
private void readConfigFile(Element entityEl) {
entityNames.add(entityEl.getAttribute("name"));
entityTypeURILookup.put(entityEl.getAttribute("name"), entityEl.getAttribute("type"));
// recursion
NodeList children = entityEl.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
if (!(children.item(i) instanceof Element))
continue;
if (children.item(i).getNodeName().equals("GabotoEntities")) {
NodeList entities = children.item(i).getChildNodes();
for (int j = 0; j < entities.getLength(); j++) {
if (!(entities.item(j) instanceof Element))
continue;
if (entities.item(j).getNodeName().equals("GabotoEntity")) {
readConfigFile((Element) entities.item(j));
}
}
}
}
}
private void generateBean(Element beanEl) {
if (!beanEl.getNodeName().equals("GabotoBean"))
return;
JavaText classText = new JavaText();
classText.addImport("net.sf.gaboto.node.pool.EntityPool");
classText.addImport("net.sf.gaboto.node.annotation.SimpleLiteralProperty");
classText.addImport("net.sf.gaboto.model.GabotoSnapshot");
classText.addImport("net.sf.gaboto.node.GabotoBean");
classText.addImport("com.hp.hpl.jena.rdf.model.Literal");
classText.addImport("com.hp.hpl.jena.rdf.model.Resource");
classText.addImport("com.hp.hpl.jena.rdf.model.Statement");
// get name
String name = beanEl.getAttribute("name");
System.out.println("Generate java file for bean : " + name);
// type definition
String beanType = beanEl.getAttribute("type");
String typeDef = "\n" + " @Override\n" + " public String getType(){\n" + " return \"" + beanType + "\";\n"
+ " }\n" + "\n";
// loadEntityMethod
boolean bBeanHasProperty = false;
String loadBeanMethod = " public void loadFromResource(Resource res, GabotoSnapshot snapshot, EntityPool pool) {\n";
loadBeanMethod += " super.loadFromResource(res, snapshot, pool);\n";
loadBeanMethod += " Statement stmt;\n\n";
// custom methods
String customMethods = "";
// get properties
String propertyDefinitions = "";
String methodDefinitions = "";
List<String> propertyNames = new ArrayList<String>();
NodeList children = beanEl.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
if (!(children.item(i) instanceof Element))
continue;
if (children.item(i).getNodeName().equals("properties")) {
NodeList properties = children.item(i).getChildNodes();
for (int j = 0; j < properties.getLength(); j++) {
if (!(properties.item(j) instanceof Element))
continue;
if (properties.item(j).getNodeName().equals("property")) {
bBeanHasProperty = true;
// cast property
Element property = (Element) properties.item(j);
PropertyJavaText text = createEntityJavaText(property, classText, null, null, null, null);
propertyDefinitions += text.getPropertyDefinitions();
methodDefinitions += text.getMethodDefinitions();
loadBeanMethod += text.getLoadMethod();
propertyNames.add(property.getAttribute("name"));
}
}
} else if (children.item(i).getNodeName().equals("customMethods")) {
NodeList methods = children.item(i).getChildNodes();
for (int j = 0; j < methods.getLength(); j++) {
if (!(methods.item(j) instanceof Element))
continue;
if (methods.item(j).getNodeName().equals("method")) {
customMethods += ((Element) methods.item(j)).getTextContent();
}
}
}
}
loadBeanMethod += " }\n";
// load entity method
String clazz = "package " + beansPackageName + ";\n\n";
clazz += classText.getImports() + "\n\n";
clazz += // class comment
"/**\n"
+ " * Gaboto generated bean.\n"
+ " * @see " + this.getClass().getCanonicalName() + "\n"
+ " */\n";
clazz += "public class ";
clazz += name + " extends GabotoBean {\n";
clazz += propertyDefinitions;
clazz += typeDef;
clazz += methodDefinitions + "\n\n";
clazz += customMethods + "\n\n";
if (bBeanHasProperty)
clazz += loadBeanMethod;
clazz += " public String toString() {\n" + " return ";
boolean seenOne = false;
for (String pName : propertyNames) {
if (seenOne)
clazz += " + \", \" + ";
seenOne = true;
clazz += "this." + pName;
}
// this.streetAddress + \", \" + this.postCode;\n" +
clazz += " ;\n" + " }\n";
clazz += "}";
// write file
try {
File outputFile = new File(beanOutputDir.getAbsolutePath() + File.separator + name + ".java");
System.out.println("Write java class to: " + outputFile.getAbsolutePath());
BufferedWriter out = new BufferedWriter(new FileWriter(outputFile));
out.write(clazz);
out.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private void generateEntity(Element entityEl, String extendsClassName) {
if (!entityEl.getNodeName().equals("GabotoEntity"))
return;
JavaText cText = new JavaText();
cText.addImport("java.lang.reflect.Method");
cText.addImport("java.util.HashMap");
cText.addImport("java.util.List");
cText.addImport("java.util.Map");
if (extendsClassName.equals("GabotoEntity"))
cText.addImport("net.sf.gaboto.node." + extendsClassName);
else
cText.addImport(entitiesPackageName + "." + extendsClassName);
// get name
String entityName = entityEl.getAttribute("name");
System.out.println("Generate entity for file: " + entityName);
// type definition
String entityType = entityEl.getAttribute("type");
String typeDef = " @Override\n";
typeDef += " public String getType(){\n";
typeDef += " return \"" + entityType + "\";\n";
typeDef += " }\n";
entityTypes.add(entityType);
// add line to classname collection
entityClassNames += " entityClassNames.add(\"" + entityName + "\");\n";
// add line to lookup
entityClassLookup.put(entityType, entityName);
boolean entityHasEntity = false;
boolean entityHasProperty = false;
boolean entityHasPassiveProperty = false;
String loadEntityMethod =
" public void loadFromSnapshot(Resource res, GabotoSnapshot snapshot, EntityPool pool) {\n" +
" super.loadFromSnapshot(res, snapshot, pool);\n" +
" Statement stmt;\n\n";
// passive entity requests
String passiveEntityRequests =
" public Collection<PassiveEntitiesRequest> getPassiveEntitiesRequest(){\n" +
" Collection<PassiveEntitiesRequest> requests = super.getPassiveEntitiesRequest();\n" +
" if(requests == null)\n" +
" requests = new HashSet<PassiveEntitiesRequest>();\n";
// custom methods
String customMethods = "";
// indirect methods
Map<String, List<String>> indirectMethodLookup = new HashMap<String, List<String>>();
Map<String, String> indirectMethods = new HashMap<String, String>();
// unstored methods
Map<String, String> unstoredMethods = new HashMap<String, String>();
// get properties
String propertyDefinitions = "";
String methodDefinitions = "";
NodeList children = entityEl.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
if (!(children.item(i) instanceof Element))
continue;
if (children.item(i).getNodeName().equals("properties")) {
NodeList properties = children.item(i).getChildNodes();
for (int j = 0; j < properties.getLength(); j++) {
if (!(properties.item(j) instanceof Element))
continue;
if (properties.item(j).getNodeName().equals("property")) {
entityHasProperty = true;
cText.addImport("com.hp.hpl.jena.rdf.model.Resource");
cText.addImport("com.hp.hpl.jena.rdf.model.Statement");
cText.addImport("net.sf.gaboto.model.GabotoSnapshot");
// cast property
Element property = (Element) properties.item(j);
PropertyJavaText text = createEntityJavaText(property, cText, unstoredMethods, indirectMethods,
indirectMethodLookup, entityName);
propertyDefinitions += text.getPropertyDefinitions();
methodDefinitions += text.getMethodDefinitions();
loadEntityMethod += text.getLoadMethod();
} else if (properties.item(j).getNodeName().equals("passiveProperty")) {
entityHasPassiveProperty = true;
cText.addImport("net.sf.gaboto.node.pool.PassiveEntitiesRequest");
cText.addImport("net.sf.gaboto.node.annotation.PassiveProperty");
// cast property
Element property = (Element) properties.item(j);
String[] processedProperty = processPassiveProperty(property, cText, indirectMethods, indirectMethodLookup,
entityName);
propertyDefinitions += processedProperty[1];
methodDefinitions += processedProperty[2];
passiveEntityRequests += processedProperty[3];
}
}
} else if (children.item(i).getNodeName().equals("GabotoEntities")) {
entityHasEntity = true;
NodeList entities = children.item(i).getChildNodes();
for (int j = 0; j < entities.getLength(); j++) {
if (!(entities.item(j) instanceof Element))
continue;
if (entities.item(j).getNodeName().equals("GabotoEntity")) {
generateEntity((Element) entities.item(j), entityName);
}
}
} else if (children.item(i).getNodeName().equals("customMethods")) {
NodeList methods = children.item(i).getChildNodes();
for (int j = 0; j < methods.getLength(); j++) {
if (!(methods.item(j) instanceof Element))
continue;
if (methods.item(j).getNodeName().equals("method")) {
customMethods += ((Element) methods.item(j)).getTextContent();
}
}
}
}
// indirect properties
String indirectPropertyMethods = "";
for (String method : indirectMethods.values())
indirectPropertyMethods += method;
// unstored properties
String unstoredPropertyMethods = "";
for (String method : unstoredMethods.values())
unstoredPropertyMethods += method;
// indirect property position lookup
String indirectPropertyLookupTable = " private static Map<String, List<Method>> indirectPropertyLookupTable;\n";
indirectPropertyLookupTable += " static{\n";
indirectPropertyLookupTable += " indirectPropertyLookupTable = new HashMap<String, List<Method>>();\n";
if (indirectMethodLookup.size() > 0) {
cText.addImport("java.util.ArrayList");
cText.addImport("net.sf.gaboto.GabotoRuntimeException");
indirectPropertyLookupTable += " List<Method> list;\n\n";
indirectPropertyLookupTable += " try {\n";
for (Entry<String, List<String>> entry : indirectMethodLookup.entrySet()) {
indirectPropertyLookupTable += " list = new ArrayList<Method>();\n";
for (String property : entry.getValue()) {
if (property != null)
indirectPropertyLookupTable += " list.add(" + property + ");\n";
}
indirectPropertyLookupTable += " indirectPropertyLookupTable.put(\"" + entry.getKey() + "\", list);\n\n";
}
indirectPropertyLookupTable += " } catch (Exception e) {\n";
indirectPropertyLookupTable += " throw new GabotoRuntimeException(e);\n";
indirectPropertyLookupTable += " }\n";
}
indirectPropertyLookupTable += " }\n\n";
// indirect property method
String indirectPropertyLoookupMethod = " protected List<Method> getIndirectMethodsForProperty(String propertyURI){\n";
indirectPropertyLoookupMethod += " List<Method> list = super.getIndirectMethodsForProperty(propertyURI);\n";
indirectPropertyLoookupMethod += " if(list == null)\n";
indirectPropertyLoookupMethod += " return indirectPropertyLookupTable.get(propertyURI);\n";
indirectPropertyLoookupMethod += " \n";
indirectPropertyLoookupMethod += " else{\n";
indirectPropertyLoookupMethod += " List<Method> tmp = indirectPropertyLookupTable.get(propertyURI);\n";
indirectPropertyLoookupMethod += " if(tmp != null)\n";
indirectPropertyLoookupMethod += " list.addAll(tmp);\n";
indirectPropertyLoookupMethod += " }\n";
indirectPropertyLoookupMethod += " return list;\n";
indirectPropertyLoookupMethod += " }\n\n";
// load entity method
loadEntityMethod += " }\n";
// passive entity request
passiveEntityRequests += " return requests;\n";
passiveEntityRequests += " }\n";
// add some newlines
propertyDefinitions += "\n\n";
methodDefinitions += "\n\n";
typeDef += "\n";
// abstract
boolean abstractClass = entityEl.hasAttribute("abstract") ? entityEl.getAttribute("abstract").equals("true")
: false;
if (entityHasEntity | entityHasPassiveProperty)
cText.addImport("net.sf.gaboto.node.GabotoEntity");
if (customMethods.contains("StaticProperty"))
cText.addImport("net.sf.gaboto.node.annotation.StaticProperty");
if (entityHasPassiveProperty)
cText.addImport("net.sf.gaboto.node.pool.EntityPool");
// build it all together
String clazz = "package " + entitiesPackageName + ";\n\n";
clazz += cText.getImports() + "\n\n";
clazz += // class comment
"/**\n"
+ " * Gaboto generated Entity.\n"
+ " * @see " + this.getClass().getCanonicalName() + "\n"
+ " */\n";
if (abstractClass)
clazz += "abstract ";
clazz += "public class ";
clazz += entityName + " extends " + extendsClassName + " {\n";
clazz += propertyDefinitions;
clazz += indirectPropertyLookupTable;
clazz += typeDef;
clazz += methodDefinitions + "\n\n";
clazz += indirectPropertyMethods;
clazz += unstoredPropertyMethods;
clazz += customMethods + "\n\n";
if (entityHasPassiveProperty)
clazz += passiveEntityRequests + "\n\n";
if (entityHasProperty)
clazz += loadEntityMethod;
clazz += indirectPropertyLoookupMethod;
clazz += "}";
// write file
try {
File outputFile = new File(entityOutputDir.getAbsolutePath() + File.separator + entityName + ".java");
System.out.println("Write java class to: " + outputFile.getAbsolutePath());
BufferedWriter out = new BufferedWriter(new FileWriter(outputFile));
out.write(clazz);
out.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private PropertyJavaText createEntityJavaText(Element property, JavaText classText, Map<String, String> unstoredMethods,
Map<String, String> indirectMethods, Map<String, List<String>> indirectMethodLookup, String entityName) {
PropertyJavaText pt = new PropertyJavaText();
pt.propName = property.getAttribute("name").substring(0, 1).toLowerCase()
+ property.getAttribute("name").substring(1);
pt.propNameUCFirst = pt.propName.substring(0, 1).toUpperCase() + pt.propName.substring(1);
pt.propType = property.getAttribute("type");
pt.collection = property.getAttribute("collection").toLowerCase();
pt.uri = property.getAttribute("uri");
// real prop type
pt.realPropTypeInterface = pt.propType;
pt.realPropTypeImpl = pt.propType;
if (pt.collection.equals("bag")) {
pt.realPropTypeInterface = "Collection<" + pt.propType + ">";
pt.realPropTypeImpl = "HashSet<" + pt.propType + ">";
}
pt.getMethodName = "get" + pt.propNameUCFirst;
// annotations
pt.propertyAnnotation = getPropertyAnnotation(pt.propType, pt.uri, pt.collection);
pt.indirectAnnotation = getIndirectAnnotation(property, indirectMethods, indirectMethodLookup, entityName,
pt.getMethodName);
if (!pt.indirectAnnotation.equals("")) {
classText.addImport("net.sf.gaboto.node.annotation.IndirectProperty");
}
pt.unstoredAnnotation = getUnstoredAnnotation(property, unstoredMethods, pt.realPropTypeImpl);
if (!pt.unstoredAnnotation.equals(""))
classText.addImport("net.sf.gaboto.node.annotation.UnstoredProperty");
// property definition
pt.propertyDefinitions += " private " + pt.realPropTypeInterface + " " + pt.propName + ";\n";
// add additional imports
//pt.importDefinitions += addBeanImport(pt.propType, classText);
addBeanImport(pt.propType, classText);
// get method
if (!pt.unstoredAnnotation.equals(""))
pt.methodDefinitions += " " + pt.unstoredAnnotation + "\n";
if (!pt.indirectAnnotation.equals(""))
pt.methodDefinitions += " " + pt.indirectAnnotation + "\n";
pt.methodDefinitions += " " + pt.propertyAnnotation + "\n";
switch (getPropertyAnnotationType(property)) {
case BAG_URI_PROPERTY:
case SIMPLE_URI_PROPERTY:
pt.methodDefinitions +=
getGetMethodForDirectReference(pt.realPropTypeInterface, pt.getMethodName, pt.propName);
break;
default:
pt.methodDefinitions +=
getGetMethod(pt.realPropTypeInterface, pt.getMethodName, pt.propName);
break;
}
// set method
String setMethodName = "set" + pt.propNameUCFirst;
pt.methodDefinitions += " " + pt.propertyAnnotation + "\n";
switch (getPropertyAnnotationType(property)) {
case SIMPLE_URI_PROPERTY:
pt.methodDefinitions +=
getSetMethodForSimpleURIProperty("public", setMethodName, pt.realPropTypeInterface, pt.propName,
pt.propName);
break;
case BAG_URI_PROPERTY:
pt.methodDefinitions +=
getSetMethodForBagURIProperty("public", setMethodName, pt.realPropTypeInterface, pt.propName,
pt.propName);
break;
default:
pt.methodDefinitions +=
getSetMethod("public", setMethodName, pt.realPropTypeInterface, pt.propName, pt.propName);
break;
}
// add method
String addMethodName = "add";
if (pt.collection.equals("bag")) {
String parameterName = "";
if (pt.propNameUCFirst.endsWith("s")) {
addMethodName += pt.propNameUCFirst.substring(0, pt.propNameUCFirst.length() - 1);
parameterName = pt.propName.substring(0, pt.propName.length() - 1);
} else {
addMethodName += pt.propNameUCFirst;
parameterName = pt.propName;
}
switch (getPropertyAnnotationType(property)) {
case BAG_URI_PROPERTY:
pt.methodDefinitions += getAddMethodForBagURI("public", addMethodName, pt.propType,
pt.realPropTypeImpl,
parameterName, pt.propName);
break;
default:
pt.methodDefinitions +=
getAddMethod("public", addMethodName, pt.propType, pt.realPropTypeImpl, parameterName,
pt.propName);
break;
}
}
System.err.println("Prop type " + pt.propType);
// load entity snippet
pt.loadMethod =
getLoadPropertySnippet(classText, property, pt.uri, pt.propType, pt.realPropTypeInterface, pt.realPropTypeImpl,
pt.propName, setMethodName, addMethodName);
return pt;
}
private String[] processPassiveProperty(Element property, JavaText cText, Map<String, String> indirectMethods,
Map<String, List<String>> indirectMethodLookup, String entityName) {
String importDefinitions = "";
String propertyDefinitionss = "";
String methodDefinitions = "";
String passiveEntityRequests = "";
String relationshipType = property.getAttribute("relationshipType");
String propType = property.getAttribute("type");
String uri = property.getAttribute("uri");
String propName = property.getAttribute("name");
String propNameUCFirst = propName.substring(0, 1).toUpperCase() + propName.substring(1);
// build annotation
String annotation =
" @PassiveProperty(\n" +
" uri = \"" + uri + "\",\n" +
" entity = \"" + propType + "\"\n" +
" )\n";
String getMethodName = "", setMethodName = "", addMethodName = "";
// what relationship type do we have
if (relationshipType.equals("1:N") || relationshipType.equals("N:M")) {
cText.addImport("java.util.Collection");
cText.addImport("java.util.HashSet");
// we can have N propTypes
String realPropTypeInterface = "Collection<" + propType + ">";
String realPropTypeImpl = "HashSet<" + propType + ">";
// add member property
propertyDefinitionss += " private " + realPropTypeInterface + " " + propName + ";\n";
// generate get/set/add method
// get method
getMethodName = "get" + propNameUCFirst;
// indirect annotation
String indirectAnnotation = getIndirectAnnotation(property, indirectMethods, indirectMethodLookup, entityName,
getMethodName);
if (!"".equals(indirectAnnotation))
methodDefinitions += " " + indirectAnnotation + "\n";
methodDefinitions += annotation;
methodDefinitions += " public " + realPropTypeInterface + " " + getMethodName + "(){\n";
methodDefinitions += " if(! isPassiveEntitiesLoaded() )\n";
methodDefinitions += " loadPassiveEntities();\n";
methodDefinitions += " return this." + propName + ";\n";
methodDefinitions += " }\n\n";
// set method
setMethodName = "set" + propNameUCFirst;
methodDefinitions += annotation;
methodDefinitions += getSetMethod("private", setMethodName, realPropTypeInterface, propName, propName);
// add method
addMethodName = "add";
String parameterName = "";
if (propNameUCFirst.endsWith("s")) { // FIXME Hack
addMethodName += propNameUCFirst.substring(0, propNameUCFirst.length() - 1);
parameterName = propName.substring(0, propName.length() - 1);
} else {
addMethodName += propNameUCFirst;
parameterName = propName;
}
methodDefinitions += getAddMethod("private", addMethodName, propType, realPropTypeImpl, parameterName,
propName);
} else {
throw new RuntimeException("Illegal relationship type: " + relationshipType);
}
// requests
if (relationshipType.equals("1:N")) {
// request
passiveEntityRequests += " requests.add(new PassiveEntitiesRequest(){\n";
passiveEntityRequests += " public String getType() {\n";
passiveEntityRequests += " return \"" + entityTypeURILookup.get(propType) + "\";\n";
passiveEntityRequests += " }\n\n";
passiveEntityRequests += " public String getUri() {\n";
passiveEntityRequests += " return \"" + uri + "\";\n";
passiveEntityRequests += " }\n\n";
passiveEntityRequests += " public int getCollectionType() {\n";
passiveEntityRequests += " return EntityPool.PASSIVE_PROPERTY_COLLECTION_TYPE_NONE;\n";
passiveEntityRequests += " }\n\n";
passiveEntityRequests += " public void passiveEntityLoaded(GabotoEntity entity) {\n";
passiveEntityRequests += " " + addMethodName + "((" + propType + ")entity);\n";
passiveEntityRequests += " }\n";
passiveEntityRequests += " });\n";
} else if (relationshipType.equals("N:M")) {
// request
passiveEntityRequests += " requests.add(new PassiveEntitiesRequest(){\n";
passiveEntityRequests += " public String getType() {\n";
passiveEntityRequests += " return \"" + entityTypeURILookup.get(propType) + "\";\n";
passiveEntityRequests += " }\n\n";
passiveEntityRequests += " public String getUri() {\n";
passiveEntityRequests += " return \"" + uri + "\";\n";
passiveEntityRequests += " }\n\n";
passiveEntityRequests += " public int getCollectionType() {\n";
passiveEntityRequests += " return EntityPool.PASSIVE_PROPERTY_COLLECTION_TYPE_BAG;\n";
passiveEntityRequests += " }\n\n";
passiveEntityRequests += " public void passiveEntityLoaded(GabotoEntity entity) {\n";
passiveEntityRequests += " " + addMethodName + "((" + propType + ")entity);\n";
passiveEntityRequests += " }\n";
passiveEntityRequests += " });\n";
} else throw new RuntimeException("Unrecognised relationship type" + relationshipType);
return new String[] { importDefinitions, propertyDefinitionss, methodDefinitions, passiveEntityRequests };
}
private String getGetMethod(String returnType, String methodName, String memberName) {
String methodDefinition = "";
methodDefinition += " public " + returnType + " " + methodName + "(){\n";
methodDefinition += " return this." + memberName + ";\n";
methodDefinition += " }\n\n";
return methodDefinition;
}
private String getGetMethodForDirectReference(String returnType, String methodName, String memberName) {
String methodDefinition = "";
methodDefinition += " public " + returnType + " " + methodName + "(){\n";
methodDefinition += " if(! this.isDirectReferencesResolved())\n";
methodDefinition += " this.resolveDirectReferences();\n";
methodDefinition += " return this." + memberName + ";\n";
methodDefinition += " }\n\n";
return methodDefinition;
}
private String getSetMethod(String visibility, String methodName, String parameterType, String parameterName,
String memberName) {
String methodDefinition = "";
if (visibility.equals("package"))
visibility = "";
methodDefinition += " " + visibility + " void " + methodName + "(" + parameterType + " " + parameterName + "){\n";
methodDefinition += " this." + memberName + " = " + parameterName + ";\n";
methodDefinition += " }\n\n";
return methodDefinition;
}
private String getSetMethodForSimpleURIProperty(String visibility, String methodName, String parameterType,
String parameterName, String memberName) {
String methodDefinition = "";
if (visibility.equals("package"))
visibility = "";
methodDefinition += " " + visibility + " void " + methodName + "(" + parameterType + " " + parameterName + "){\n";
methodDefinition += " if( " + parameterName + " != null )\n";
methodDefinition += " this.removeMissingReference( " + parameterName + ".getUri() );\n";
methodDefinition += " this." + memberName + " = " + parameterName + ";\n";
methodDefinition += " }\n\n";
return methodDefinition;
}
private String getSetMethodForBagURIProperty(String visibility, String methodName, String parameterType,
String parameterName, String memberName) {
String methodDefinition = "";
if (visibility.equals("package"))
visibility = "";
methodDefinition += " " + visibility + " void " + methodName + "(" + parameterType + " " + parameterName + "){\n";
methodDefinition += " if( " + parameterName + " != null ){\n";
methodDefinition += " for( GabotoEntity _entity : " + parameterName + ")\n";
methodDefinition += " this.removeMissingReference( _entity.getUri() );\n";
methodDefinition += " }\n\n";
methodDefinition += " this." + memberName + " = " + parameterName + ";\n";
methodDefinition += " }\n\n";
return methodDefinition;
}
private String getAddMethod(String visibility, String methodName, String propType, String realPropTypeImpl,
String parameterName, String memberName) {
String methodDefinition = "";
if (visibility.equals("package"))
visibility = "";
methodDefinition += " " + visibility + " void " + methodName + "(" + propType + " " + parameterName + "P){\n";
methodDefinition += " if(this." + memberName + " == null)\n";
methodDefinition += " set" + ucFirstLetter(memberName) + "( new " + realPropTypeImpl + "() );\n";
methodDefinition += " this." + memberName + ".add(" + parameterName + "P);\n";
methodDefinition += " }\n\n";
return methodDefinition;
}
String ucFirstLetter(String s) {
return s.substring(0, 1).toUpperCase() + s.substring(1);
}
private String getAddMethodForBagURI(String visibility, String methodName, String propType,
String realPropTypeImpl, String parameterName, String memberName) {
String methodDefinition = "";
if (visibility.equals("package"))
visibility = "";
methodDefinition += " " + visibility + " void " + methodName + "(" + propType + " " + parameterName + "){\n";
methodDefinition += " if( " + parameterName + " != null )\n";
methodDefinition += " this.removeMissingReference( " + parameterName + ".getUri() );\n";
methodDefinition += " if(this." + memberName + " == null )\n";
methodDefinition += " this." + memberName + " = new " + realPropTypeImpl + "();\n";
methodDefinition += " this." + memberName + ".add(" + parameterName + ");\n";
methodDefinition += " }\n\n";
return methodDefinition;
}
private String getLoadPropertySnippet(JavaText cText, Element property, String uri, String propType, String realPropTypeInterface,
String realPropTypeImpl, String propertyName, String setMethodName, String addMethodName) {
String loadEntity = "";
System.err.println("Property " + propType + " - " + realPropTypeImpl);
System.err.println("Property " + propertyName + " - " + getPropertyAnnotationType(property));
switch (getPropertyAnnotationType(property)) {
case SIMPLE_LITERAL_PROPERTY:
cText.addImport("com.hp.hpl.jena.rdf.model.Literal");
cText.addImport("net.sf.gaboto.node.annotation.SimpleLiteralProperty");
cText.addImport("net.sf.gaboto.node.pool.EntityPool");
loadEntity += " // Load SIMPLE_LITERAL_PROPERTY " + propertyName + "\n";
loadEntity += " stmt = res.getProperty(snapshot.getProperty(\"" + uri + "\"));\n";
loadEntity += " if(stmt != null && stmt.getObject().isLiteral())\n";
loadEntity += " this." + setMethodName + "(((Literal)stmt.getObject())." + getLiteralGetMethod(property)
+ ");\n";
break;
case SIMPLE_URI_PROPERTY:
cText.addImport("net.sf.gaboto.node.annotation.SimpleURIProperty");
cText.addImport("net.sf.gaboto.node.pool.EntityExistsCallback");
cText.addImport("net.sf.gaboto.node.pool.EntityPool");
cText.addImport("net.sf.gaboto.node.GabotoEntity");
loadEntity += " // Load SIMPLE_URI_PROPERTY " + propertyName + "\n";
loadEntity += " stmt = res.getProperty(snapshot.getProperty(\"" + uri + "\"));\n";
loadEntity += " if(stmt != null && stmt.getObject().isResource()){\n";
loadEntity += " Resource missingReference = (Resource)stmt.getObject();\n";
loadEntity += " EntityExistsCallback callback = new EntityExistsCallback(){\n";
loadEntity += " public void entityExists(EntityPool p, GabotoEntity entity) {\n";
loadEntity += " " + setMethodName + "((" + realPropTypeInterface + ")entity);\n";
loadEntity += " }\n";
loadEntity += " };\n";
loadEntity += " this.addMissingReference(missingReference, callback);\n";
loadEntity += " }\n";
break;
case SIMPLE_COMPLEX_PROPERTY:
cText.addImport("com.hp.hpl.jena.rdf.model.Resource");
cText.addImport("net.sf.gaboto.node.annotation.ComplexProperty");
loadEntity += " // Load SIMPLE_COMPLEX_PROPERTY " + propertyName + "\n";
loadEntity += " stmt = res.getProperty(snapshot.getProperty(\"" + uri + "\"));\n";
loadEntity += " if(stmt != null && stmt.getObject().isAnon()){\n";
loadEntity += " " + realPropTypeInterface + " bean = new " + realPropTypeInterface + "();\n";
loadEntity += " " + "bean.loadFromResource((Resource)stmt.getObject(), snapshot, pool);\n";
loadEntity += " " + setMethodName + "(bean);\n";
loadEntity += " }\n";
break;
case BAG_URI_PROPERTY:
cText.addImport("java.util.Collection");
cText.addImport("java.util.HashSet");
cText.addImport("com.hp.hpl.jena.rdf.model.RDFNode");
cText.addImport("com.hp.hpl.jena.rdf.model.Bag");
cText.addImport("com.hp.hpl.jena.rdf.model.Resource");
cText.addImport("com.hp.hpl.jena.rdf.model.NodeIterator");
cText.addImport("net.sf.gaboto.node.pool.EntityPool");
cText.addImport("net.sf.gaboto.node.pool.EntityExistsCallback");
cText.addImport("net.sf.gaboto.node.annotation.BagURIProperty");
loadEntity += " // Load BAG_URI_PROPERTY " + propertyName + "\n";
loadEntity += " stmt = res.getProperty(snapshot.getProperty(\"" + uri + "\"));\n";
loadEntity += " if(stmt != null && stmt.getObject().isResource() && null != stmt.getBag()){\n";
loadEntity += " Bag bag = stmt.getBag();\n";
loadEntity += " NodeIterator nodeIt = bag.iterator();\n";
loadEntity += " while(nodeIt.hasNext()){\n";
loadEntity += " RDFNode node = nodeIt.nextNode();\n";
loadEntity += " if(! node.isResource())\n";
loadEntity += " throw new IllegalArgumentException(\"node should be a resource\");\n\n";
loadEntity += " Resource missingReference = (Resource)node;\n";
loadEntity += " EntityExistsCallback callback = new EntityExistsCallback(){\n";
loadEntity += " public void entityExists(EntityPool p, GabotoEntity entity) {\n";
loadEntity += " " + addMethodName + "((" + propType + ") entity);\n";
loadEntity += " }\n";
loadEntity += " };\n";
loadEntity += " this.addMissingReference(missingReference, callback);\n";
loadEntity += " }\n";
loadEntity += " }\n";
break;
case BAG_LITERAL_PROPERTY:
cText.addImport("java.util.Collection");
cText.addImport("java.util.HashSet");
cText.addImport("com.hp.hpl.jena.rdf.model.Bag");
cText.addImport("com.hp.hpl.jena.rdf.model.NodeIterator");
cText.addImport("com.hp.hpl.jena.rdf.model.RDFNode");
cText.addImport("net.sf.gaboto.node.annotation.BagLiteralProperty");
loadEntity += " // Load BAG_LITERAL_PROPERTY " + propertyName + "\n";
loadEntity += " stmt = res.getProperty(snapshot.getProperty(\"" + uri + "\"));\n";
loadEntity += " if(stmt != null && stmt.getObject().isResource() && stmt.getBag() != null){\n";
loadEntity += " Bag bag = stmt.getBag();\n";
loadEntity += " NodeIterator nodeIt = bag.iterator();\n";
loadEntity += " while(nodeIt.hasNext()){\n";
loadEntity += " RDFNode node = nodeIt.nextNode();\n";
loadEntity += " if(! node.isLiteral())\n";
loadEntity += " throw new IllegalArgumentException(\"node should be a literal\");\n\n";
loadEntity += " " + addMethodName + "(((Literal)node)." + getLiteralGetMethod(property) + ");\n";
loadEntity += " }\n\n";
loadEntity += " }\n";
break;
case BAG_COMPLEX_PROPERTY:
cText.addImport("java.util.Collection");
cText.addImport("java.util.HashSet");
cText.addImport("net.sf.gaboto.node.annotation.BagComplexProperty");
cText.addImport("com.hp.hpl.jena.rdf.model.Bag");
cText.addImport("com.hp.hpl.jena.rdf.model.RDFNode");
cText.addImport("com.hp.hpl.jena.rdf.model.NodeIterator");
loadEntity += " // Load BAG_COMPLEX_PROPERTY " + propertyName + "\n";
loadEntity += " stmt = res.getProperty(snapshot.getProperty(\"" + uri + "\"));\n";
loadEntity += " if(stmt != null && stmt.getObject().isResource() && stmt.getBag() != null){\n";
loadEntity += " Bag bag = stmt.getBag();\n";
loadEntity += " NodeIterator nodeIt = bag.iterator();\n";
loadEntity += " while(nodeIt.hasNext()){\n";
loadEntity += " RDFNode node = nodeIt.nextNode();\n";
loadEntity += " if(! node.isAnon())\n";
loadEntity += " throw new IllegalArgumentException(\"node should be a blank node\");\n\n";
loadEntity += " " + realPropTypeInterface + " " + propertyName + " = new " + realPropTypeInterface
+ "();\n";
loadEntity += " " + propertyName + ".loadFromResource((Resource)node, snapshot, pool);\n";
loadEntity += " " + addMethodName + "(" + propertyName + ");\n";
loadEntity += " }\n\n";
loadEntity += " }\n";
break;
}
return loadEntity + "\n";
}
private void addBeanImport(String propType, JavaText classText) {
System.err.println("Here:" + propType);
if(propType.equals("String")){}
else if (propType.equals("Int")) {}
else if (propType.equals("Integer")) {}
else if (propType.equals("Long")) {}
else if (propType.equals("Double")) {}
else if (propType.equals("Float")) {}
else if (propType.equals("Boolean")) {}
else {
// Check if this is a bean
String beanName = beansPackageName + "." + propType;
try {
Class<?> clazz = Class.forName(beanName);
if (clazz.newInstance() instanceof GabotoBean)
classText.addImport(beanName);
System.err.println(propType + " is a bean");
} catch (ClassNotFoundException e) {
// Simple types eg String
System.err.println("Class not found " + beanName);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
private String getIndirectAnnotation(Element property, Map<String, String> indirectMethods,
Map<String, List<String>> indirectMethodLookup, String entityName, String getMethodName) {
String anno = "";
NodeList nodeList = property.getElementsByTagName("indirectProperty");
boolean bFirst = true;
for (int i = 0; i < nodeList.getLength(); i++) {
Element propEl = (Element) nodeList.item(i);
String uri = propEl.getAttribute("uri");
if (bFirst) {
anno = "\"" + uri + "\"";
bFirst = false;
} else
anno += ",\"" + uri + "\"";
// store position
if (indirectMethodLookup != null) {
int position = propEl.hasAttribute("n") ? Integer.valueOf(propEl.getAttribute("n")) - 1 : 0;
if (!indirectMethodLookup.containsKey(uri))
indirectMethodLookup.put(uri, new ArrayList<String>());
List<String> list = indirectMethodLookup.get(uri);
if (list.size() <= position) {
for (int j = list.size(); j < position; j++)
list.add(null);
list.add(entityName + ".class.getMethod(\"" + getMethodName + "\", (Class<?>[])null)");
} else {
list.add(position, entityName + ".class.getMethod(\"" + getMethodName + "\", (Class<?>[])null)");
}
}
// indirect methods
if (!indirectMethods.containsKey(uri) && propEl.hasAttribute("name")) {
String propName = propEl.getAttribute("name").substring(0, 1).toLowerCase()
+ propEl.getAttribute("name").substring(1);
String propNameUCFirst = propName.substring(0, 1).toUpperCase() + propName.substring(1);
String method = " public Object get" + propNameUCFirst + "(){\n";
method += " return this.getPropertyValue(\"" + uri + "\", false, true);\n";
method += " }\n\n";
indirectMethods.put(uri, method);
}
}
if (!anno.equals("")) {
anno = "@IndirectProperty({" + anno + "})";
}
return anno;
}
private String getUnstoredAnnotation(Element property, Map<String, String> unstoredMethods, String parentPropTypeImpl) {
String anno = "";
NodeList nodeList = property.getElementsByTagName("unstoredProperty");
boolean bFirst = true;
for (int i = 0; i < nodeList.getLength(); i++) {
Element propEl = (Element) nodeList.item(i);
String uri = propEl.getAttribute("uri");
if (bFirst) {
anno = "\"" + uri + "\"";
bFirst = false;
} else
anno += ",\"" + uri + "\"";
// indirect methods
if (propEl.hasAttribute("name")) {
String propName = propEl.getAttribute("name").substring(0, 1).toLowerCase()
+ propEl.getAttribute("name").substring(1);
String propNameUCFirst = propName.substring(0, 1).toUpperCase() + propName.substring(1);
String method = " public " + parentPropTypeImpl + " get" + propNameUCFirst + "(){\n";
method += " return (" + parentPropTypeImpl + ") this.getPropertyValue(\"" + uri + "\", false, true);\n";
method += " }\n\n";
unstoredMethods.put(uri, method);
}
}
if (!anno.equals("")) {
anno = "@UnstoredProperty({" + anno + "})";
}
return anno;
}
private String getPropertyAnnotation(String propType, String uri, String collection) {
switch (getPropertyAnnotationType(propType, collection)) {
case SIMPLE_URI_PROPERTY:
return "@SimpleURIProperty(\"" + uri + "\")";
case SIMPLE_LITERAL_PROPERTY:
return "@SimpleLiteralProperty(\n" + " value = \"" + uri + "\",\n" + " datatypeType = \"" + "javaprimitive"
+ "\",\n" + " javaType = \"" + propType + "\"\n" + " )";
case SIMPLE_COMPLEX_PROPERTY:
return "@ComplexProperty(\"" + uri + "\")";
case BAG_URI_PROPERTY:
return "@BagURIProperty(\"" + uri + "\")";
case BAG_LITERAL_PROPERTY:
return "@BagLiteralProperty(\n" + " value = \"" + uri + "\",\n" + " datatypeType = \"" + "javaprimitive"
+ "\",\n" + " javaType = \"" + propType + "\"\n" + " )";
case BAG_COMPLEX_PROPERTY:
return "@BagComplexProperty(\"" + uri + "\")";
}
return "";
}
/**
* Returns the appropriate method name for returning a literals value.
*
* @param property
* @return
*/
private String getLiteralGetMethod(Element property) {
switch (getLiteralType(property)) {
case LITERAL_TYPE_STRING:
return "getString()";
case LITERAL_TYPE_INTEGER:
return "getInt()";
case LITERAL_TYPE_FLOAT:
return "getFloat()";
case LITERAL_TYPE_DOUBLE:
return "getDouble()";
case LITERAL_TYPE_BOOLEAN:
return "getBoolean()";
}
return null;
}
private int getLiteralType(Element property) {
String propType = property.getAttribute("type");
return getLiteralType(propType);
}
private int getLiteralType(String propType) {
propType = propType.toLowerCase();
if (propType.equals("string"))
return LITERAL_TYPE_STRING;
if (propType.equals("int") || propType.equals("integer"))
return LITERAL_TYPE_INTEGER;
if (propType.equals("double"))
return LITERAL_TYPE_DOUBLE;
if (propType.equals("float"))
return LITERAL_TYPE_FLOAT;
if (propType.equals("boolean"))
return LITERAL_TYPE_BOOLEAN;
throw new IllegalArgumentException("Unknown literal type: " + propType);
}
private int getPropertyAnnotationType(Element property) {
String propType = property.getAttribute("type");
String collection = property.getAttribute("collection").toLowerCase();
return getPropertyAnnotationType(propType, collection);
}
private int getPropertyAnnotationType(String propType, String collection) {
if (collection != null) {
if (collection.equals(""))
collection = null;
else
collection = collection.toLowerCase();
}
if (entityNames.contains(propType) || propType.equals("GabotoEntity")) {
if (collection == null)
return SIMPLE_URI_PROPERTY;
else if (collection.equals("bag"))
return BAG_URI_PROPERTY;
}
// Check if this is a bean
String beanName = beansPackageName + "." + propType;
// FIXME There is a bootstrap problem here
try {
Class<?> clazz = Class.forName(beanName);
if (clazz.newInstance() instanceof GabotoBean)
if (collection == null)
return SIMPLE_COMPLEX_PROPERTY;
else if (collection.equals("bag"))
return BAG_COMPLEX_PROPERTY;
} catch (ClassNotFoundException e) {
// Simple type eg String
// or non bean property
} catch (NoClassDefFoundError e) {
throw new RuntimeException("Delete generated code with errors " + beanName, e);
} catch (Exception e) {
throw new RuntimeException(e);
}
if (collection == null)
return SIMPLE_LITERAL_PROPERTY;
else if (collection.equals("bag"))
return BAG_LITERAL_PROPERTY;
throw new RuntimeException("No property annotation found for: " + propType);
}
private void generateLookup() {
// generate lookup class
// FIXME This should perhaps be generated for each ontology and then aggregated
String lookupClass = "package " + packageName + ";\n\n";
lookupClass += "import java.util.Collection;\n" +
"import java.util.HashMap;\n" +
"import java.util.HashSet;\n" +
"import java.util.Map;\n" +
"import java.util.Set;\n" +
"\n" +
"import net.sf.gaboto.node.GabotoEntity;\n" +
"import net.sf.gaboto.GabotoRuntimeException;\n" +
"\n" +
"import net.sf.gaboto.model.OntologyLookup;\n" +
"\n" ;
lookupClass += "\n\n";
lookupClass += // class comment
"/**\n"
+ " * Gaboto generated ontology lookup utility.\n"
+ " * @see " + this.getClass().getCanonicalName() + "\n"
+ " */\n";
lookupClass += "@SuppressWarnings(\"unchecked\")\n";
lookupClass += "public class " + lookupClassName + " implements OntologyLookup {\n";
lookupClass += " private static Map<String,String> entityClassLookupNames;\n";
lookupClass += " private static Map<String,Class<? extends GabotoEntity>> entityClassLookupClass;\n";
lookupClass += " private static Map<Class<? extends GabotoEntity>, String> classToURILookup;\n";
lookupClass += " private static Collection<String> entityClassNames;\n";
lookupClass += " private static Set<String> entityTypes;\n\n";
lookupClass += " static{\n";
lookupClass += " entityClassLookupNames = new HashMap<String,String>();\n\n";
for (Entry<String, String> entry : entityClassLookup.entrySet()) {
lookupClass += " entityClassLookupNames.put(\"" + entry.getKey() + "\", \"" + entry.getValue() + "\");\n";
}
lookupClass += " }\n\n";
lookupClass += " static{\n";
lookupClass += " entityClassLookupClass = new HashMap<String,Class<? extends GabotoEntity>>();\n\n";
lookupClass += " try {\n";
for (Entry<String, String> entry : entityClassLookup.entrySet()) {
lookupClass += " entityClassLookupClass.put(\"" + entry.getKey()
+ "\", (Class<? extends GabotoEntity>) Class.forName(\"" + entitiesPackageName + "." + entry.getValue()
+ "\"));\n";
}
lookupClass += " } catch (ClassNotFoundException e) {\n";
lookupClass += " throw new GabotoRuntimeException(e);\n";
lookupClass += " }\n";
lookupClass += " }\n\n";
lookupClass += " static{\n";
lookupClass += " classToURILookup = new HashMap<Class<? extends GabotoEntity>, String>();\n\n";
lookupClass += " try {\n";
for (Entry<String, String> entry : entityClassLookup.entrySet()) {
lookupClass += " classToURILookup.put((Class<? extends GabotoEntity>) Class.forName(\"" + entitiesPackageName
+ "." + entry.getValue() + "\"), \"" + entry.getKey() + "\");\n";
}
lookupClass += " } catch (ClassNotFoundException e) {\n";
lookupClass += " throw new GabotoRuntimeException(e);\n";
lookupClass += " }\n";
lookupClass += " }\n\n";
lookupClass += " static{\n";
lookupClass += " entityTypes = new HashSet<String>();\n\n";
for (String type : entityTypes) {
lookupClass += " entityTypes.add(\"" + type + "\");\n";
}
lookupClass += " }\n\n";
lookupClass += " static{\n";
lookupClass += " entityClassNames = new HashSet<String>();\n\n";
lookupClass += entityClassNames;
lookupClass += " }\n\n";
lookupClass += " public Set<String> getRegisteredClassesAsURIs(){\n";
lookupClass += " return entityTypes;\n";
lookupClass += " }\n\n";
lookupClass += " public Collection<String> getRegisteredEntityClassesAsClassNames(){\n";
lookupClass += " return entityClassNames;\n";
lookupClass += " }\n\n";
lookupClass += " public Class<? extends GabotoEntity> getEntityClassFor(String typeURI){\n";
lookupClass += " return entityClassLookupClass.get(typeURI);\n";
lookupClass += " }\n\n";
lookupClass += " public String getLocalName(String typeURI){\n";
lookupClass += " return entityClassLookupNames.get(typeURI);\n";
lookupClass += " }\n\n";
lookupClass += " public boolean isValidName(String name) {\n";
lookupClass += " return entityClassNames.contains(name);\n";
lookupClass += " }\n\n";
lookupClass += " public String getTypeURIForEntityClass(Class<? extends GabotoEntity> clazz){\n";
lookupClass += " return classToURILookup.get(clazz);\n";
lookupClass += " }\n\n";
lookupClass += "}\n";
// write file
try {
File outputFile = new File(outputDir.getAbsolutePath() + File.separator + lookupClassName + ".java" );
System.out.println("Write java class to: " + outputFile.getAbsolutePath());
BufferedWriter out = new BufferedWriter(new FileWriter(outputFile));
out.write(lookupClass);
out.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* @param args
*/
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
generate(new File("src/main/conf/Gaboto.xml"), new File("examples/oxpoints/src/main/java"), "uk.ac.ox.oucs.oxpoints.gaboto");
}
public static void generate(File config, File outputDir, String packageName) throws ParserConfigurationException,
SAXException, IOException {
new GabotoGenerator(config, outputDir, packageName).run();
}
class JavaText {
TreeSet<String> imports = new TreeSet<String>();
boolean addImport(String imp) {
return imports.add(imp);
}
String getImports() {
String importsString = "";
String packageString= "";
String thisPackageString= "";
for (String imp : imports) {
thisPackageString = imp.substring(0, imp.lastIndexOf('.'));
if (!thisPackageString.equals(packageString)) {
importsString += "\n";
packageString = thisPackageString;
}
importsString += "import " + imp + ";\n";
}
return importsString;
}
}
class PropertyJavaText {
String importDefinitions = "";
String propertyDefinitions = "";
String methodDefinitions = "";
String loadMethod = "";
String propName = "";
String propNameUCFirst = "";
String propType = "";
String collection = "";
String uri = "";
String realPropTypeInterface = "";
String realPropTypeImpl = "";
String getMethodName = "";
String propertyAnnotation = "";
String indirectAnnotation = "";
String unstoredAnnotation = "";
String setMethodName = "";
String addMethodName = "";
String parameterName = "";
/**
* @return the importDefinitions
*/
public String getImportDefinitions() {
return importDefinitions;
}
/**
* @return the propertyDefinitionss
*/
public String getPropertyDefinitions() {
return propertyDefinitions;
}
/**
* @return the methodDefinitions
*/
public String getMethodDefinitions() {
return methodDefinitions;
}
/**
* @return the loadEntitySnippet
*/
public String getLoadMethod() {
return loadMethod;
}
}
} |
package net.sf.xenqtt.proxy;
/**
* Handles messages from proxy client connections
*/
final class ClientMessageHandler {
// FIXME [jim] - implement proxy
// final class ClientMessageHandler implements MessageHandler {
// // FIXME [jim] - need to deal with what happens if an ID for an inflight message becomes needed again because it is still outstanding after all other IDs
// // have been used.
// private int nextMessageId = 1;
// // FIXME [jim] - this needs to have the original message ID in the value as well
// private final Map<Integer, ChannelAndId> clientChannelsByMessageId;
// private final MqttChannel brokerChannel;
// public ClientMessageHandler(Map<Integer, ChannelAndId> clientChannelsByMessageId, MqttChannel brokerChannel) {
// this.clientChannelsByMessageId = clientChannelsByMessageId;
// this.brokerChannel = brokerChannel;
// /**
// * @see net.sf.xenqtt.message.MessageHandler#handle(net.sf.xenqtt.message.MqttChannel, net.sf.xenqtt.message.ConnectMessage)
// */
// @Override
// public void handle(MqttChannel channel, ConnectMessage message) throws Exception {
// // this should only happen if the message is getting resent so ignore it
// /**
// * @see net.sf.xenqtt.message.MessageHandler#handle(net.sf.xenqtt.message.MqttChannel, net.sf.xenqtt.message.ConnAckMessage)
// */
// @Override
// public void handle(MqttChannel channel, ConnAckMessage message) throws Exception {
// // should never be received from the client
// /**
// * @see net.sf.xenqtt.message.MessageHandler#handle(net.sf.xenqtt.message.MqttChannel, net.sf.xenqtt.message.PublishMessage)
// */
// @Override
// public void handle(MqttChannel channel, PublishMessage message) throws Exception {
// changeMessageId(channel, message);
// brokerChannel.send(message);
// /**
// * @see net.sf.xenqtt.message.MessageHandler#handle(net.sf.xenqtt.message.MqttChannel, net.sf.xenqtt.message.PubAckMessage)
// */
// @Override
// public void handle(MqttChannel channel, PubAckMessage message) throws Exception {
// brokerChannel.send(message);
// /**
// * @see net.sf.xenqtt.message.MessageHandler#handle(net.sf.xenqtt.message.MqttChannel, net.sf.xenqtt.message.PubRecMessage)
// */
// @Override
// public void handle(MqttChannel channel, PubRecMessage message) throws Exception {
// brokerChannel.send(message);
// /**
// * @see net.sf.xenqtt.message.MessageHandler#handle(net.sf.xenqtt.message.MqttChannel, net.sf.xenqtt.message.PubRelMessage)
// */
// @Override
// public void handle(MqttChannel channel, PubRelMessage message) throws Exception {
// brokerChannel.send(message);
// /**
// * @see net.sf.xenqtt.message.MessageHandler#handle(net.sf.xenqtt.message.MqttChannel, net.sf.xenqtt.message.PubCompMessage)
// */
// @Override
// public void handle(MqttChannel channel, PubCompMessage message) throws Exception {
// brokerChannel.send(message);
// /**
// * @see net.sf.xenqtt.message.MessageHandler#handle(net.sf.xenqtt.message.MqttChannel, net.sf.xenqtt.message.SubscribeMessage)
// */
// @Override
// public void handle(MqttChannel channel, SubscribeMessage message) throws Exception {
// changeMessageId(channel, message);
// brokerChannel.send(message);
// /**
// * @see net.sf.xenqtt.message.MessageHandler#handle(net.sf.xenqtt.message.MqttChannel, net.sf.xenqtt.message.SubAckMessage)
// */
// @Override
// public void handle(MqttChannel channel, SubAckMessage message) throws Exception {
// // should never be received from the subscriber
// /**
// * @see net.sf.xenqtt.message.MessageHandler#handle(net.sf.xenqtt.message.MqttChannel, net.sf.xenqtt.message.UnsubscribeMessage)
// */
// @Override
// public void handle(MqttChannel channel, UnsubscribeMessage message) throws Exception {
// changeMessageId(channel, message);
// brokerChannel.send(message);
// /**
// * @see net.sf.xenqtt.message.MessageHandler#handle(net.sf.xenqtt.message.MqttChannel, net.sf.xenqtt.message.UnsubAckMessage)
// */
// @Override
// public void handle(MqttChannel channel, UnsubAckMessage message) throws Exception {
// brokerChannel.send(message);
// /**
// * @see net.sf.xenqtt.message.MessageHandler#handle(net.sf.xenqtt.message.MqttChannel, net.sf.xenqtt.message.PingReqMessage)
// */
// @Override
// public void handle(MqttChannel channel, PingReqMessage message) throws Exception {
// brokerChannel.send(new PingRespMessage());
// /**
// * @see net.sf.xenqtt.message.MessageHandler#handle(net.sf.xenqtt.message.MqttChannel, net.sf.xenqtt.message.PingRespMessage)
// */
// @Override
// public void handle(MqttChannel channel, PingRespMessage message) throws Exception {
// // should never be received from the client
// /**
// * @see net.sf.xenqtt.message.MessageHandler#handle(net.sf.xenqtt.message.MqttChannel, net.sf.xenqtt.message.DisconnectMessage)
// */
// @Override
// public void handle(MqttChannel channel, DisconnectMessage message) throws Exception {
// // FIXME [jim] - need to close this channel and if the last client then need to disconnect from the broker
// /**
// * @see net.sf.xenqtt.message.MessageHandler#channelClosed(net.sf.xenqtt.message.MqttChannel)
// */
// @Override
// public void channelClosed(MqttChannel channel) {
// // TODO [jeremy] - Implement this method.
// private void changeMessageId(MqttChannel channel, IdentifiableMqttMessage message) {
// int newId = getNextMessageId();
// if (message.getQoSLevel() > 0) {
// clientChannelsByMessageId.put(newId, new ChannelAndId(channel, message.getMessageId()));
// message.setMessageId(newId);
// private int getNextMessageId() {
// int next = nextMessageId++;
// if (nextMessageId > 0xffff) {
// nextMessageId = 1;
// return next;
} |
package objective.taskboard.issueBuffer;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.StopWatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import objective.taskboard.data.Issue;
public class CardRepo {
private static final Logger log = LoggerFactory.getLogger(CardRepo.class);
private CardStorage db;
private Date lastRemoteUpdatedDate;
private Map<String, Issue> cardByKey = new ConcurrentHashMap<>();
private Set<String> unsavedCards = new HashSet<>();
private Set<String> currentProjects = new HashSet<>();
public CardRepo(CardStorage repodb) {
this.db = repodb;
if (repodb.issues().size() > 0)
cardByKey.putAll(repodb.issues());
this.lastRemoteUpdatedDate = repodb.getLastRemoteUpdatedDate();
this.currentProjects = repodb.getCurrentProjects();
}
public CardRepo() {
}
public Issue get(String key) {
return cardByKey.get(key);
}
public synchronized boolean putOnlyIfNewer(Issue newValue) {
Issue current = cardByKey.get(newValue.getIssueKey());
if (current == null) {
put(newValue.getIssueKey(), newValue);
return true;
}
if (current.getRemoteIssueUpdatedDate().compareTo(newValue.getRemoteIssueUpdatedDate()) >= 0
&& current.getChangelog().size() >= newValue.getChangelog().size())
return false;
put(newValue.getIssueKey(), newValue);
return true;
}
synchronized void put(String key, Issue value) {
if (lastRemoteUpdatedDate == null)
lastRemoteUpdatedDate = value.getRemoteIssueUpdatedDate();
if (lastRemoteUpdatedDate.before(value.getRemoteIssueUpdatedDate()))
lastRemoteUpdatedDate = value.getRemoteIssueUpdatedDate();
Issue old = cardByKey.put(key, value);
if(old != null)
old.unlinkParent();
if (!StringUtils.isEmpty(value.getParent())) {
value.setParentCard(cardByKey.get(value.getParent()));
unsavedCards.add(value.getParent());
}
cardByKey.values().stream()
.filter(issue -> value.getIssueKey().equals(issue.getParent()))
.forEach(subtask -> {
subtask.setParentCard(value);
unsavedCards.add(subtask.getIssueKey());
});
unsavedCards.add(key);
addProject(value.getProjectKey());
}
public Optional<Date> getLastUpdatedDate() {
return Optional.ofNullable(lastRemoteUpdatedDate);
}
public synchronized Optional<Set<String>> getCurrentProjects() {
return Optional.ofNullable(currentProjects);
}
private void addProject(String projectKey) {
if (currentProjects == null)
currentProjects = new HashSet<>();
currentProjects.add(projectKey);
}
public synchronized void clear() {
cardByKey.clear();
lastRemoteUpdatedDate = null;
}
public synchronized Issue remove(String key) {
unsavedCards.add(key);
Issue old = cardByKey.remove(key);
if(old != null)
old.unlinkParent();
return old;
}
public int size() {
return cardByKey.size();
}
public Collection<Issue> values() {
return cardByKey.values();
}
public Collection<String> keySet() {
return cardByKey.keySet();
}
public synchronized void commit() {
if (db == null)
return;
if (unsavedCards.size() == 0)
return;
StopWatch stopWatch = new StopWatch();
stopWatch.start();
int unsavedIssueCount = unsavedCards.size();
try {
for (String key : unsavedCards)
if (cardByKey.get(key) == null)
db.removeIssue(key);
else
db.storeIssue(key, cardByKey.get(key));
db.setLastRemoteUpdatedDate(this.lastRemoteUpdatedDate);
db.putProjects(currentProjects);
db.commit();
unsavedCards.clear();
}catch(Exception e) {
log.error("Failed to load save issues", e);
db.rollback();
return;
}
log.info("Data written in " + stopWatch.getTime() + " ms. Stored issues: " + unsavedIssueCount);
}
public synchronized void setChanged(String issueKey) {
unsavedCards.add(issueKey);
}
} |
package org.animotron.bridge.web;
import org.animotron.exception.AnimoException;
import org.animotron.expression.AnimoExpression;
import org.animotron.expression.BinaryExpression;
import org.animotron.expression.DefaultDescription;
import org.animotron.statement.operator.AN;
import org.animotron.statement.operator.REF;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import static org.animotron.bridge.web.AbstractRequestExpression.URI;
import static org.animotron.expression.Expression.__;
/**
* @author <a href="mailto:gazdovsky@gmail.com">Evgeny Gazdovsky</a>
*
*/
public class ResourcesBridge extends AbstractResourcesBridge {
public ResourcesBridge(String uriContext) {
super(uriContext);
}
@Override
protected void loadFile(final File file) throws IOException {
InputStream is = new FileInputStream(file);
if (file.getName().endsWith(".animo")) {
System.out.println("animo loading "+file.getName());
__(new AnimoExpression(is));
} else {
__(
new BinaryExpression(is, true) {
@Override
protected void description() throws AnimoException, IOException {
DefaultDescription.create(builder, path(file));
builder.start(AN._);
builder._(REF._, URI);
builder._(uriContext + id());
builder.end();
}
}
);
}
}
} |
package org.cyclops.integrateddynamics;
/**
* Class that can hold basic static things that are better not hard-coded
* like mod details, texture paths, ID's...
* @author rubensworks
*/
public final class Reference {
// Mod info
public static final String MOD_ID = "integrateddynamics";
public static final String MOD_NAME = "Integrated Dynamics";
public static final String MOD_VERSION = "@VERSION@";
public static final String MOD_BUILD_NUMBER = "@BUILD_NUMBER@";
public static final String MOD_MC_VERSION = "@MC_VERSION@";
public static final String GA_TRACKING_ID = "UA-65307010-4";
public static final String VERSION_URL = "https://raw.githubusercontent.com/CyclopsMC/Versions/master/1.8/IntegratedDynamics.txt";
// Biome ID's
public static final int BIOME_MENEGLIN = 193;
// OREDICT NAMES
public static final String DICT_WOODLOG = "logWood";
public static final String DICT_TREELEAVES = "treeLeaves";
public static final String DICT_SAPLINGTREE = "treeSapling";
public static final String DICT_WOODPLANK = "plankWood";
// MOD ID's
public static final String MOD_FORGE = "Forge";
public static final String MOD_FORGE_VERSION = "@FORGE_VERSION@";
public static final String MOD_FORGE_VERSION_MIN = "11.15.1.1722";
public static final String MOD_CYCLOPSCORE = "cyclopscore";
public static final String MOD_CYCLOPSCORE_VERSION = "@CYCLOPSCORE_VERSION@";
public static final String MOD_CYCLOPSCORE_VERSION_MIN = "0.5.2";
public static final String MOD_CHARSETPIPES = "CharsetPipes";
public static final String MOD_MCMULTIPART = "mcmultipart";
public static final String MOD_WAILA = "Waila";
public static final String MOD_THAUMCRAFT = "Thaumcraft";
public static final String MOD_JEI = "JEI";
public static final String MOD_RF_API = "CoFHAPI";
public static final String MOD_DEPENDENCIES =
"required-after:" + MOD_FORGE + "@[" + MOD_FORGE_VERSION_MIN + ",);" +
"required-after:" + MOD_CYCLOPSCORE + "@[" + MOD_CYCLOPSCORE_VERSION_MIN + ",);";
} |
package org.example.seed.logger;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.async.DeferredResult;
import java.util.Arrays;
@Aspect
@Component
public class RESTAspectLogger {
private final Logger log = LoggerFactory.getLogger(this.getClass());
private final ObjectMapper objectMapper = new ObjectMapper();
public RESTAspectLogger() {
this.objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
}
@Pointcut("within(org.example.seed.rest..*)")
public void rest() { }
@Pointcut("execution(public * *(..))")
protected void allMethod() { }
@Before("rest() && allMethod()")
public void logBefore(JoinPoint joinPoint) throws JsonProcessingException {
log.warn("Entering in Method : " + joinPoint.getSignature().getName());
log.warn("Class Name : " + joinPoint.getSignature().getDeclaringTypeName());
log.warn("Arguments : " + this.objectMapper.writeValueAsString(joinPoint.getArgs()));
}
@AfterReturning(pointcut = "rest() && allMethod()", returning = "deferred")
public void logAfter(JoinPoint joinPoint, Object deferred) throws Exception {
final DeferredResult<Object> response = (DeferredResult<Object>) deferred;
log.warn("Method Return value : " + this.objectMapper.writeValueAsString(response.getResult()));
}
@AfterThrowing(pointcut = "rest() && allMethod()", throwing = "exception")
public void logAfterThrowing(JoinPoint joinPoint, Throwable exception) {
log.error("An exception has been thrown in " + joinPoint.getSignature().getName() + " ()");
log.error("Cause : " + Arrays.toString(exception.getStackTrace()));
}
@Around("rest() && allMethod()")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
final long start = System.currentTimeMillis();
try {
final String className = joinPoint.getSignature().getDeclaringTypeName();
final String methodName = joinPoint.getSignature().getName();
final Object result = joinPoint.proceed();
final long elapsedTime = System.currentTimeMillis() - start;
log.warn("Method " + className + "." + methodName + " ()" + " execution time : " + elapsedTime + " ms");
return result;
} catch (final IllegalArgumentException e) {
log.error("Illegal argument " + Arrays.toString(joinPoint.getArgs()) + " in " + joinPoint.getSignature().getName() + "()");
throw e;
}
}
} |
package org.lightmare.deploy.management;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import javax.servlet.http.HttpServletRequest;
import org.lightmare.config.ConfigKeys;
import org.lightmare.config.Configuration;
import org.lightmare.utils.CollectionUtils;
import org.lightmare.utils.IOUtils;
import org.lightmare.utils.ObjectUtils;
import org.lightmare.utils.StringUtils;
/**
* Manages container administrator users for
* {@link org.lightmare.deploy.management.DeployManager} service
*
* @author Levan
* @since 0.0.45-SNAPSHOT
*/
public class Security {
private Properties cache;
public static final String DEPLOY_PASS_KEY = "deploy_manager_pass";
private static final String PROXY_HEADER = "x-forwarded-for";
public Security() throws IOException {
cacheUsers();
}
/**
* Loads administrator user information from passed {@link File} parameter
*
* @param file
* @throws IOException
*/
private void loadUsers(File file) throws IOException {
cache = new Properties();
InputStream stream = new FileInputStream(file);
try {
cache.load(stream);
} finally {
IOUtils.close(stream);
}
}
/**
* Caches administrator users
*
* @throws IOException
*/
public void cacheUsers() throws IOException {
String path = Configuration.getAdminUsersPath();
if (StringUtils.invalid(path)) {
path = ConfigKeys.ADMIN_USERS_PATH.getValue();
}
File file = new File(path);
if (file.exists()) {
loadUsers(file);
}
}
/**
* Checks if administrator users cache is valid
*
* @return <code>boolean</code>
*/
public boolean check() {
return CollectionUtils.invalid(cache);
}
/**
* Checks if container allows remote control
*
* @param request
* @return <code>boolean</code>
*/
public boolean controlAllowed(HttpServletRequest request) {
boolean valid = Configuration.getRemoteControl();
if (ObjectUtils.notTrue(valid)) {
String header = request.getHeader(PROXY_HEADER);
valid = (header == null);
if (valid) {
header = request.getHeader(PROXY_HEADER.toUpperCase());
valid = (header == null);
}
if (valid) {
String host = request.getRemoteAddr();
String localhost = request.getLocalAddr();
valid = StringUtils.validAll(host, localhost)
&& host.equals(localhost);
}
}
return valid;
}
/**
* Authenticates passed user name and password
*
* @param user
* @param pass
* @return <code>boolean</code>
*/
public boolean authenticate(String user, String pass) {
boolean valid;
if (CollectionUtils.valid(cache)) {
Object cacheData = cache.get(user);
String cachedPass = ObjectUtils.cast(cacheData, String.class);
valid = (StringUtils.valid(cachedPass) && cachedPass.equals(pass));
} else {
valid = Boolean.TRUE;
}
return valid;
}
} |
package org.lightmare.ejb.interceptors;
import java.io.Serializable;
import java.util.Date;
import javax.ejb.EJBException;
import javax.ejb.NoMoreTimeoutsException;
import javax.ejb.NoSuchObjectLocalException;
import javax.ejb.ScheduleExpression;
import javax.ejb.Timer;
import javax.ejb.TimerHandle;
/**
* Implementation of {@link Timer} of intercept timer task
*
* @author levan
* @since 0.0.65-SNAPSHOT
*/
// TODO: Need proper implementation of Timer interface
public class TimerImpl implements Timer {
private TimerHandle handle;
private ScheduleExpression schedule;
private Date nextTimeout;
private boolean persistent;
private boolean calendarTimer;
private Serializable info;
private TimerImpl() {
handle = new TimerHandleImpl(this);
}
@Override
public void cancel() throws IllegalStateException,
NoSuchObjectLocalException, EJBException {
}
@Override
public long getTimeRemaining() throws IllegalStateException,
NoSuchObjectLocalException, NoMoreTimeoutsException, EJBException {
return 0;
}
@Override
public Date getNextTimeout() throws IllegalStateException,
NoSuchObjectLocalException, NoMoreTimeoutsException, EJBException {
return nextTimeout;
}
@Override
public ScheduleExpression getSchedule() throws IllegalStateException,
NoSuchObjectLocalException, EJBException {
return schedule;
}
@Override
public boolean isPersistent() throws IllegalStateException,
NoSuchObjectLocalException, EJBException {
return persistent;
}
@Override
public boolean isCalendarTimer() throws IllegalStateException,
NoSuchObjectLocalException, EJBException {
return calendarTimer;
}
@Override
public Serializable getInfo() throws IllegalStateException,
NoSuchObjectLocalException, EJBException {
return info;
}
@Override
public TimerHandle getHandle() throws IllegalStateException,
NoSuchObjectLocalException, EJBException {
return handle;
}
} |
package org.opennars.control.concept;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.opennars.control.DerivationContext;
import org.opennars.entity.BudgetValue;
import org.opennars.entity.Concept;
import org.opennars.entity.Sentence;
import org.opennars.entity.Stamp;
import org.opennars.entity.Stamp.BaseEntry;
import org.opennars.entity.Task;
import org.opennars.entity.TruthValue;
import org.opennars.inference.LocalRules;
import static org.opennars.inference.LocalRules.revisible;
import static org.opennars.inference.LocalRules.revision;
import static org.opennars.inference.LocalRules.trySolution;
import org.opennars.inference.TemporalRules;
import org.opennars.inference.TruthFunctions;
import org.opennars.io.Symbols;
import org.opennars.io.events.Events;
import org.opennars.language.CompoundTerm;
import org.opennars.language.Conjunction;
import org.opennars.language.Equivalence;
import org.opennars.language.Implication;
import org.opennars.language.Interval;
import org.opennars.language.Product;
import org.opennars.language.Term;
import org.opennars.language.Variable;
import org.opennars.language.Variables;
import org.opennars.main.MiscFlags;
import org.opennars.operator.FunctionOperator;
import org.opennars.operator.Operation;
import org.opennars.operator.Operator;
import org.opennars.plugin.mental.InternalExperience;
/**
*
* @author Patrick Hammer
*/
public class ProcessGoal {
/**
* To accept a new goal, and check for revisions and realization, then
* decide whether to actively pursue it, potentially executing in case of an operation goal
*
* @param concept The concept of the goal
* @param nal The derivation context
* @param task The goal task to be processed
*/
protected static void processGoal(final Concept concept, final DerivationContext nal, final Task task) {
final Sentence goal = task.sentence;
final Task oldGoalT = concept.selectCandidate(task, concept.desires, nal.time); // revise with the existing desire values
Sentence oldGoal = null;
final Stamp newStamp = goal.stamp;
if (oldGoalT != null) {
oldGoal = oldGoalT.sentence;
final Stamp oldStamp = oldGoal.stamp;
if (newStamp.equals(oldStamp,false,false,true)) {
return; // duplicate
}
}
Task beliefT = null;
if(task.aboveThreshold()) {
beliefT = concept.selectCandidate(task, concept.beliefs, nal.time);
for (final Task iQuest : concept.quests ) {
trySolution(task.sentence, iQuest, nal, true);
}
// check if the Goal is already satisfied
if (beliefT != null) {
// check if the Goal is already satisfied (manipulate budget)
trySolution(beliefT.sentence, task, nal, true);
}
}
if (oldGoalT != null && revisible(goal, oldGoal, nal.narParameters)) {
final Stamp oldStamp = oldGoal.stamp;
nal.setTheNewStamp(newStamp, oldStamp, nal.time.time());
final Sentence projectedGoal = oldGoal.projection(task.sentence.getOccurenceTime(), newStamp.getOccurrenceTime(), concept.memory);
if (projectedGoal!=null) {
nal.setCurrentBelief(projectedGoal);
final boolean wasRevised = revision(task.sentence, projectedGoal, concept, false, nal);
if (wasRevised) {
return;
}
}
}
final Stamp s2=goal.stamp.clone();
s2.setOccurrenceTime(nal.time.time());
if(s2.after(task.sentence.stamp, nal.narParameters.DURATION)) {
// this task is not up to date we have to project it first
final Sentence projGoal = task.sentence.projection(nal.time.time(), nal.narParameters.DURATION, nal.memory);
if(projGoal!=null && projGoal.truth.getExpectation() > nal.narParameters.DECISION_THRESHOLD) {
// keep goal updated
nal.singlePremiseTask(projGoal, task.budget.clone());
// we don't return here, allowing "roundtrips now", relevant for executing multiple steps of learned implication chains
}
}
if (!task.aboveThreshold()) {
return;
}
double AntiSatisfaction = 0.5f; // we dont know anything about that goal yet
if (beliefT != null) {
final Sentence belief = beliefT.sentence;
final Sentence projectedBelief = belief.projection(task.sentence.getOccurenceTime(), nal.narParameters.DURATION, nal.memory);
AntiSatisfaction = task.sentence.truth.getExpDifAbs(projectedBelief.truth);
}
task.setPriority(task.getPriority()* (float)AntiSatisfaction);
if (!task.aboveThreshold()) {
return;
}
final boolean isFullfilled = AntiSatisfaction < nal.narParameters.SATISFACTION_TRESHOLD;
final Sentence projectedGoal = goal.projection(nal.time.time(), nal.time.time(), nal.memory);
if (!(projectedGoal != null && task.aboveThreshold() && !isFullfilled)) {
return;
}
bestReactionForGoal(concept, nal, projectedGoal, task);
questionFromGoal(task, nal);
concept.addToTable(task, false, concept.desires, nal.narParameters.CONCEPT_GOALS_MAX, Events.ConceptGoalAdd.class, Events.ConceptGoalRemove.class);
InternalExperience.InternalExperienceFromTask(concept.memory, task, false, nal.time);
if(!(task.sentence.getTerm() instanceof Operation)) {
return;
}
processOperationGoal(projectedGoal, nal, concept, oldGoalT, task);
}
/**
* To process an operation for potential execution
* only called by processGoal
*
* @param projectedGoal The current goal
* @param nal The derivation context
* @param concept The concept of the current goal
* @param oldGoalT The best goal in the goal table
* @param task The goal task
*/
protected static void processOperationGoal(final Sentence projectedGoal, final DerivationContext nal, final Concept concept, final Task oldGoalT, final Task task) {
if(projectedGoal.truth.getExpectation() > nal.narParameters.DECISION_THRESHOLD) {
//see whether the goal evidence is fully included in the old goal, if yes don't execute
//as execution for this reason already happened (or did not since there was evidence against it)
final Set<BaseEntry> oldEvidence = new LinkedHashSet<>();
boolean Subset=false;
if(oldGoalT != null) {
Subset = true;
for(final BaseEntry l: oldGoalT.sentence.stamp.evidentialBase) {
oldEvidence.add(l);
}
for(final BaseEntry l: task.sentence.stamp.evidentialBase) {
if(!oldEvidence.contains(l)) {
Subset = false;
break;
}
}
}
if(!Subset && !executeOperation(nal, task)) {
concept.memory.emit(Events.UnexecutableGoal.class, task, concept, nal);
return; //it was made true by itself
}
}
}
/**
* Generate <?how =/> g>? question for g! goal.
* only called by processGoal
*
* @param task the task for which the question should be processed
* @param nal The derivation context
*/
public static void questionFromGoal(final Task task, final DerivationContext nal) {
if(nal.narParameters.QUESTION_GENERATION_ON_DECISION_MAKING || nal.narParameters.HOW_QUESTION_GENERATION_ON_DECISION_MAKING) {
//ok, how can we achieve it? add a question of whether it is fullfilled
final List<Term> qu= new ArrayList<>();
if(nal.narParameters.HOW_QUESTION_GENERATION_ON_DECISION_MAKING) {
if(!(task.sentence.term instanceof Equivalence) && !(task.sentence.term instanceof Implication)) {
final Variable how=new Variable("?how");
//Implication imp=Implication.make(how, task.sentence.term, TemporalRules.ORDER_CONCURRENT);
final Implication imp2=Implication.make(how, task.sentence.term, TemporalRules.ORDER_FORWARD);
//qu.add(imp);
if(!(task.sentence.term instanceof Operation)) {
qu.add(imp2);
}
}
}
if(nal.narParameters.QUESTION_GENERATION_ON_DECISION_MAKING) {
qu.add(task.sentence.term);
}
for(final Term q : qu) {
if(q!=null) {
final Stamp st = new Stamp(task.sentence.stamp, nal.time.time());
st.setOccurrenceTime(task.sentence.getOccurenceTime()); //set tense of question to goal tense
final Sentence s = new Sentence(
q,
Symbols.QUESTION_MARK,
null,
st);
if(s!=null) {
final BudgetValue budget=new BudgetValue(task.getPriority()*nal.narParameters.CURIOSITY_DESIRE_PRIORITY_MUL,
task.getDurability()*nal.narParameters.CURIOSITY_DESIRE_DURABILITY_MUL,
1, nal.narParameters);
nal.singlePremiseTask(s, budget);
}
}
}
}
}
private static class ExecutablePrecondition {
public Operation bestop = null;
public float bestop_truthexp = 0.0f;
public TruthValue bestop_truth = null;
public Task executable_precond = null;
public long mintime = -1;
public long maxtime = -1;
public Map<Term,Term> substitution;
}
/**
* When a goal is processed, use the best memorized reaction
* that is applicable to the current context (recent events) in case that it exists.
* This is a special case of the choice rule and allows certain behaviors to be automated.
*
* @param concept The concept of the goal to realize
* @param nal The derivation context
* @param projectedGoal The current goal
* @param task The goal task
*/
public static void bestReactionForGoal(final Concept concept, final DerivationContext nal, final Sentence projectedGoal, final Task task) {
concept.incAcquiredQuality(); //useful as it is represents a goal concept that can hold important procedure knowledge
//1. pull up variable based preconditions from component concepts without replacing them
Map<Term, Integer> ret = (projectedGoal.getTerm()).countTermRecursively(null);
List<Task> allPreconditions = new ArrayList<Task>();
for(Term t : ret.keySet()) {
final Concept get_concept = nal.memory.concept(t); //the concept to pull preconditions from
if(get_concept == null || get_concept == concept) { //target concept does not exist or is the same as the goal concept
continue;
}
//pull variable based preconditions from component concepts
synchronized(get_concept) {
boolean useful_component = false;
for(Task precon : get_concept.general_executable_preconditions) {
//check whether the conclusion matches
if(Variables.findSubstitute(nal.memory.randomNumber, Symbols.VAR_INDEPENDENT, ((Implication)precon.sentence.term).getPredicate(), projectedGoal.term, new LinkedHashMap<>(), new LinkedHashMap<>())) {
for(Task prec : get_concept.general_executable_preconditions) {
allPreconditions.add(prec);
useful_component = true;
}
}
}
if(useful_component) {
get_concept.incAcquiredQuality(); //useful as it contributed predictive hypotheses
}
}
}
//2. Accumulate all preconditions of itself too
Map<Operation,List<ExecutablePrecondition>> anticipationsToMake = new LinkedHashMap<>();
allPreconditions.addAll(concept.executable_preconditions);
allPreconditions.addAll(concept.general_executable_preconditions);
//3. Apply choice rule, using the highest truth expectation solution and anticipate the results
ExecutablePrecondition bestOpWithMeta = calcBestExecutablePrecondition(nal, concept, projectedGoal, allPreconditions, anticipationsToMake);
//4. And executing it, also forming an expectation about the result
if(executePrecondition(nal, bestOpWithMeta, concept, projectedGoal, task)) {
System.out.println("Executed based on: " + bestOpWithMeta.executable_precond);
for(ExecutablePrecondition precon : anticipationsToMake.get(bestOpWithMeta.bestop)) {
ProcessAnticipation.anticipate(nal, precon.executable_precond.sentence, precon.executable_precond.budget, precon.mintime, precon.maxtime, 2, precon.substitution);
}
}
}
/**
* Search for the best precondition that best matches recent events, and is most successful in leading to goal fulfilment
*
* @param nal The derivation context
* @param concept The goal concept
* @param projectedGoal The goal projected to the current time
* @param execPreconditions The procedural hypotheses with the executable preconditions
* @return The procedural hypothesis with the highest result truth expectation
*/
private static ExecutablePrecondition calcBestExecutablePrecondition(final DerivationContext nal, final Concept concept, final Sentence projectedGoal, List<Task> execPreconditions, Map<Operation,List<ExecutablePrecondition>> anticipationsToMake) {
ExecutablePrecondition result = new ExecutablePrecondition();
for(final Task t: execPreconditions) {
final CompoundTerm precTerm = ((Conjunction) ((Implication) t.getTerm()).getSubject());
final Term[] prec = precTerm.term;
final Term[] newprec = new Term[prec.length-3];
System.arraycopy(prec, 0, newprec, 0, prec.length - 3);
float timeOffset = (long) (((Interval)prec[prec.length-1]).time);
float timeWindowHalf = timeOffset * nal.narParameters.ANTICIPATION_TOLERANCE;
final Operation op = (Operation) prec[prec.length-2];
final Term precondition = Conjunction.make(newprec,TemporalRules.ORDER_FORWARD);
long newesttime = -1;
Task bestsofar = null;
List<Float> prec_intervals = new ArrayList<Float>();
for(Long l : CompoundTerm.extractIntervals(nal.memory, precTerm)) {
prec_intervals.add((float) l);
}
//ok we can look now how much it is fullfilled
//check recent events in event bag
Map<Term,Term> subsBest = new LinkedHashMap<>();
synchronized(concept.memory.seq_current) {
for(final Task p : concept.memory.seq_current) {
Map<Term,Term> subs = new LinkedHashMap<>();
if(p.sentence.isJudgment() && !p.sentence.isEternal() && p.sentence.getOccurenceTime() > newesttime && p.sentence.getOccurenceTime() <= nal.time.time()) {
boolean preconditionMatches = Variables.findSubstitute(nal.memory.randomNumber, Symbols.VAR_INDEPENDENT,
CompoundTerm.replaceIntervals(precondition),
CompoundTerm.replaceIntervals(p.sentence.term), subs, new LinkedHashMap<>());
boolean conclusionMatches = Variables.findSubstitute(nal.memory.randomNumber, Symbols.VAR_INDEPENDENT,
CompoundTerm.replaceIntervals(((Implication) t.getTerm()).getPredicate()),
CompoundTerm.replaceIntervals(projectedGoal.getTerm()), subs, new LinkedHashMap<>());
if(preconditionMatches && conclusionMatches){
newesttime = p.sentence.getOccurenceTime();
//Apply interval penalty for interval differences in the precondition
Task pNew = new Task(p.sentence.clone(), p.budget.clone(), p.isInput() ? Task.EnumType.INPUT : Task.EnumType.DERIVED);
LocalRules.intervalProjection(nal, pNew.sentence.term, precondition, prec_intervals, pNew.sentence.truth);
bestsofar = pNew;
subsBest = subs;
//ok now we can take the desire value:
final TruthValue A = projectedGoal.getTruth();
//and the truth of the hypothesis:
final TruthValue Hyp = t.sentence.truth;
//overlap will almost never happen, but to make sure
if(Stamp.baseOverlap(projectedGoal.stamp, t.sentence.stamp) ||
Stamp.baseOverlap(bestsofar.sentence.stamp, t.sentence.stamp) ||
Stamp.baseOverlap(projectedGoal.stamp, bestsofar.sentence.stamp)) {
continue;
}
//and the truth of the precondition:
final Sentence projectedPrecon = bestsofar.sentence.projection(nal.time.time() /*- distance*/, nal.time.time(), concept.memory);
if(projectedPrecon.isEternal()) {
continue; //projection wasn't better than eternalization, too long in the past
}
final TruthValue precon = projectedPrecon.truth;
//and derive the conjunction of the left side:
final TruthValue leftside = TruthFunctions.desireDed(A, Hyp, concept.memory.narParameters);
//in order to derive the operator desire value:
final TruthValue opdesire = TruthFunctions.desireDed(precon, leftside, concept.memory.narParameters);
final float expecdesire = opdesire.getExpectation();
Operation bestop = (Operation) ((CompoundTerm)op).applySubstitute(subsBest);
long mintime = (long) (nal.time.time() + timeOffset - timeWindowHalf);
long maxtime = (long) (nal.time.time() + timeOffset + timeWindowHalf);
if(expecdesire > result.bestop_truthexp) {
result.bestop = bestop;
result.bestop_truthexp = expecdesire;
result.bestop_truth = opdesire;
result.executable_precond = t;
result.substitution = subsBest;
result.mintime = mintime;
result.maxtime = maxtime;
if(anticipationsToMake.get(result.bestop) == null) {
anticipationsToMake.put(result.bestop, new ArrayList<ExecutablePrecondition>());
}
anticipationsToMake.get(result.bestop).add(result);
}
}
}
}
}
}
if (result.executable_precond != null) {
System.out.println( result.executable_precond );
}
return result;
}
/**
* Execute the operation suggested by the most applicable precondition
*
* @param nal The derivation context
* @param precon The procedural hypothesis leading to goal
* @param concept The concept of the goal
* @param projectedGoal The goal projected to the current time
* @param task The goal task
*/
private static boolean executePrecondition(final DerivationContext nal, ExecutablePrecondition precon, final Concept concept, final Sentence projectedGoal, final Task task) {
if(precon.bestop != null && precon.bestop_truthexp > nal.narParameters.DECISION_THRESHOLD /*&& Math.random() < bestop_truthexp */) {
final Sentence createdSentence = new Sentence(
precon.bestop,
Symbols.JUDGMENT_MARK,
precon.bestop_truth,
projectedGoal.stamp);
final Task t = new Task(createdSentence,
new BudgetValue(1.0f,1.0f,1.0f, nal.narParameters),
Task.EnumType.DERIVED);
//System.out.println("used " +t.getTerm().toString() + String.valueOf(nal.memory.randomNumber.nextInt()));
if(!task.sentence.stamp.evidenceIsCyclic()) {
if(!executeOperation(nal, t)) { //this task is just used as dummy
concept.memory.emit(Events.UnexecutableGoal.class, task, concept, nal);
return false;
}
return true;
}
}
return false;
}
/**
* Entry point for all potentially executable operation tasks.
* Returns true if the Task has a Term which can be executed
*
* @param nal The derivation concept
* @param t The operation goal task
*/
public static boolean executeOperation(final DerivationContext nal, final Task t) {
final Term content = t.getTerm();
if(!(nal.memory.allowExecution) || !(content instanceof Operation)) {
return false;
}
final Operation op=(Operation)content;
final Operator oper = op.getOperator();
final Product prod = (Product) op.getSubject();
final Term arg = prod.term[0];
if(oper instanceof FunctionOperator) {
for(int i=0;i<prod.term.length-1;i++) { //except last one, the output arg
if(prod.term[i].hasVarDep() || prod.term[i].hasVarIndep()) {
return false;
}
}
} else {
if(content.hasVarDep() || content.hasVarIndep()) {
return false;
}
}
if(!arg.equals(Term.SELF)) { //will be deprecated in the future
return false;
}
op.setTask(t);
if(!oper.call(op, nal.memory, nal.time)) {
return false;
}
if (MiscFlags.DEBUG) {
System.out.println(t.toStringLong());
}
return true;
}
} |
package org.verdictdb.sqlwriter;
import java.util.List;
import java.util.Set;
import org.verdictdb.core.sqlobject.AbstractRelation;
import org.verdictdb.core.sqlobject.AliasReference;
import org.verdictdb.core.sqlobject.AliasedColumn;
import org.verdictdb.core.sqlobject.AsteriskColumn;
import org.verdictdb.core.sqlobject.BaseColumn;
import org.verdictdb.core.sqlobject.BaseTable;
import org.verdictdb.core.sqlobject.ColumnOp;
import org.verdictdb.core.sqlobject.ConstantColumn;
import org.verdictdb.core.sqlobject.GroupingAttribute;
import org.verdictdb.core.sqlobject.JoinTable;
import org.verdictdb.core.sqlobject.OrderbyAttribute;
import org.verdictdb.core.sqlobject.SelectItem;
import org.verdictdb.core.sqlobject.SelectQuery;
import org.verdictdb.core.sqlobject.SetOperationRelation;
import org.verdictdb.core.sqlobject.SubqueryColumn;
import org.verdictdb.core.sqlobject.UnnamedColumn;
import org.verdictdb.exception.VerdictDBException;
import org.verdictdb.exception.VerdictDBTypeException;
import org.verdictdb.exception.VerdictDBValueException;
import org.verdictdb.sqlsyntax.PostgresqlSyntax;
import org.verdictdb.sqlsyntax.SqlSyntax;
import com.google.common.base.Optional;
import com.google.common.collect.Sets;
public class SelectQueryToSql {
SqlSyntax syntax;
Set<String> opTypeNotRequiringParentheses = Sets.newHashSet(
"sum", "avg", "count", "max", "min", "std", "sqrt", "isnotnull", "isnull", "rand", "floor");
public SelectQueryToSql(SqlSyntax syntax) {
this.syntax = syntax;
}
public String toSql(AbstractRelation relation) throws VerdictDBException {
if (!(relation instanceof SelectQuery)) {
throw new VerdictDBTypeException("Unexpected type: " + relation.getClass().toString());
}
return selectQueryToSql((SelectQuery) relation);
}
String selectItemToSqlPart(SelectItem item) throws VerdictDBException {
if (item instanceof AliasedColumn) {
return aliasedColumnToSqlPart((AliasedColumn) item);
} else if (item instanceof UnnamedColumn) {
return unnamedColumnToSqlPart((UnnamedColumn) item);
} else {
throw new VerdictDBTypeException("Unexpceted argument type: " + item.getClass().toString());
}
}
String aliasedColumnToSqlPart(AliasedColumn acolumn) throws VerdictDBException {
String aliasName = acolumn.getAliasName();
return unnamedColumnToSqlPart(acolumn.getColumn()) + " as " + quoteName(aliasName);
}
String groupingAttributeToSqlPart(GroupingAttribute column) throws VerdictDBException {
if (column instanceof AsteriskColumn) {
throw new VerdictDBTypeException("asterisk is not expected in the groupby clause.");
}
if (column instanceof AliasReference) {
AliasReference aliasedColumn = (AliasReference) column;
return quoteName(aliasedColumn.getAliasName());
} else {
return unnamedColumnToSqlPart((UnnamedColumn) column);
}
}
String unnamedColumnToSqlPart(UnnamedColumn column) throws VerdictDBException {
if (column instanceof BaseColumn) {
BaseColumn base = (BaseColumn) column;
if (base.getTableSourceAlias().equals("")) {
return quoteName(base.getColumnName());
}
else return base.getTableSourceAlias() + "." + quoteName(base.getColumnName());
} else if (column instanceof ConstantColumn) {
return ((ConstantColumn) column).getValue().toString();
} else if (column instanceof AsteriskColumn) {
return "*";
} else if (column instanceof ColumnOp) {
ColumnOp columnOp = (ColumnOp) column;
if (columnOp.getOpType().equals("avg")) {
return "avg(" + unnamedColumnToSqlPart(columnOp.getOperand()) + ")";
} else if (columnOp.getOpType().equals("sum")) {
return "sum(" + unnamedColumnToSqlPart(columnOp.getOperand()) + ")";
} else if (columnOp.getOpType().equals("count")) {
return "count(*)";
} else if (columnOp.getOpType().equals("stddev_pop")) {
String stddevPopulationFunctionName = syntax.getStddevPopulationFunctionName();
return String.format("%s(", stddevPopulationFunctionName)
+ unnamedColumnToSqlPart(columnOp.getOperand()) + ")";
} else if (columnOp.getOpType().equals("sqrt")) {
return "sqrt(" + unnamedColumnToSqlPart(columnOp.getOperand()) + ")";
} else if (columnOp.getOpType().equals("add")) {
return withParentheses(columnOp.getOperand(0)) + " + " + withParentheses(columnOp.getOperand(1));
} else if (columnOp.getOpType().equals("subtract")) {
return withParentheses(columnOp.getOperand(0)) + " - " + withParentheses(columnOp.getOperand(1));
} else if (columnOp.getOpType().equals("multiply")) {
return withParentheses(columnOp.getOperand(0)) + " * " + withParentheses(columnOp.getOperand(1));
} else if (columnOp.getOpType().equals("divide")) {
return withParentheses(columnOp.getOperand(0)) + " / " + withParentheses(columnOp.getOperand(1));
} else if (columnOp.getOpType().equals("pow")) {
return "pow(" + unnamedColumnToSqlPart(columnOp.getOperand(0)) + ", "
+ unnamedColumnToSqlPart(columnOp.getOperand(1)) + ")";
} else if (columnOp.getOpType().equals("equal")) {
return withParentheses(columnOp.getOperand(0)) + " = " + withParentheses(columnOp.getOperand(1));
} else if (columnOp.getOpType().equals("and")) {
return withParentheses(columnOp.getOperand(0)) + " and " + withParentheses(columnOp.getOperand(1));
} else if (columnOp.getOpType().equals("or")) {
return withParentheses(columnOp.getOperand(0)) + " or " + withParentheses(columnOp.getOperand(1));
}
// else if (columnOp.getOpType().equals("casewhenelse")) {
// return "case " + withParentheses(columnOp.getOperand(0))
// + " when " + withParentheses(columnOp.getOperand(1))
// + " else " + withParentheses(columnOp.getOperand(2))
// + " end";
else if (columnOp.getOpType().equals("casewhen")) {
String sql = "case";
for (int i=0; i<columnOp.getOperands().size()-1;i=i+2) {
sql = sql + " when " + withParentheses(columnOp.getOperand(i)) + " then " + withParentheses(columnOp.getOperand(i+1));
}
sql = sql + " else " + withParentheses(columnOp.getOperand(columnOp.getOperands().size()-1)) + " end";
return sql;
} else if (columnOp.getOpType().equals("notequal")) {
return withParentheses(columnOp.getOperand(0)) + " <> " + withParentheses(columnOp.getOperand(1));
} else if (columnOp.getOpType().equals("isnull")) {
return withParentheses(columnOp.getOperand(0)) + " is null";
} else if (columnOp.getOpType().equals("isnotnull")) {
return withParentheses(columnOp.getOperand(0)) + " is not null";
} else if (columnOp.getOpType().equals("interval")) {
return "interval " + withParentheses(columnOp.getOperand(0)) + " " + withParentheses(columnOp.getOperand(1));
} else if (columnOp.getOpType().equals("date")) {
return "date " + withParentheses(columnOp.getOperand());
} else if (columnOp.getOpType().equals("greater")) {
return withParentheses(columnOp.getOperand(0)) + " > " + withParentheses(columnOp.getOperand(1));
} else if (columnOp.getOpType().equals("less")) {
return withParentheses(columnOp.getOperand(0)) + " < " + withParentheses(columnOp.getOperand(1));
} else if (columnOp.getOpType().equals("greaterequal")) {
return withParentheses(columnOp.getOperand(0)) + " >= " + withParentheses(columnOp.getOperand(1));
} else if (columnOp.getOpType().equals("lessequal")) {
return withParentheses(columnOp.getOperand(0)) + " <= " + withParentheses(columnOp.getOperand(1));
} else if (columnOp.getOpType().equals("min")) {
return "min(" + selectItemToSqlPart(columnOp.getOperand()) + ")";
} else if (columnOp.getOpType().equals("max")) {
return "max(" + selectItemToSqlPart(columnOp.getOperand()) + ")";
} else if (columnOp.getOpType().equals("min")) {
return "max(" + selectItemToSqlPart(columnOp.getOperand()) + ")";
} else if (columnOp.getOpType().equals("floor")) {
return "floor(" + selectItemToSqlPart(columnOp.getOperand()) + ")";
// } else if (columnOp.getOpType().equals("is")) {
// return withParentheses(columnOp.getOperand(0)) + " is " + withParentheses(columnOp.getOperand(1));
} else if (columnOp.getOpType().equals("like")) {
return withParentheses(columnOp.getOperand(0)) + " like " + withParentheses(columnOp.getOperand(1));
} else if (columnOp.getOpType().equals("notlike")) {
return withParentheses(columnOp.getOperand(0)) + " not like " + withParentheses(columnOp.getOperand(1));
} else if (columnOp.getOpType().equals("exists")) {
return "exists " + withParentheses(columnOp.getOperand());
} else if (columnOp.getOpType().equals("notexists")) {
return "not exists " + withParentheses(columnOp.getOperand());
} else if (columnOp.getOpType().equals("between")) {
return withParentheses(columnOp.getOperand(0))
+ " between "
+ withParentheses(columnOp.getOperand(1))
+ " and "
+ withParentheses(columnOp.getOperand(2));
} else if (columnOp.getOpType().equals("in")) {
List<UnnamedColumn> columns = columnOp.getOperands();
if (columns.size()==2 && columns.get(1) instanceof SubqueryColumn) {
return withParentheses(columns.get(0)) + " in " + withParentheses(columns.get(1));
}
String temp = "";
for (int i = 1; i < columns.size(); i++) {
if (i != columns.size() - 1) {
temp = temp + withParentheses(columns.get(i)) + ", ";
} else temp = temp + withParentheses(columns.get(i));
}
return withParentheses(columns.get(0)) + " in (" + temp + ")";
} else if (columnOp.getOpType().equals("notin")) {
List<UnnamedColumn> columns = columnOp.getOperands();
if (columns.size()==2 && columns.get(1) instanceof SubqueryColumn) {
return withParentheses(columns.get(0)) + " not in " + withParentheses(columns.get(1));
}
String temp = "";
for (int i = 1; i < columns.size(); i++) {
if (i != columns.size() - 1) {
temp = temp + withParentheses(columns.get(i)) + ", ";
} else temp = temp + withParentheses(columns.get(i));
}
return withParentheses(columns.get(0)) + " not in (" + temp + ")";
} else if (columnOp.getOpType().equals("countdistinct")) {
return "count(distinct " + withParentheses(columnOp.getOperand()) + ")";
} else if (columnOp.getOpType().equals("substr")) {
return "substr(" + withParentheses(columnOp.getOperand(0)) + ", " +
withParentheses(columnOp.getOperand(1)) + ", " + withParentheses(columnOp.getOperand(2)) + ")";
} else if (columnOp.getOpType().equals("rand")) {
return syntax.randFunction();
} else if (columnOp.getOpType().equals("cast")) {
return "cast(" + withParentheses(columnOp.getOperand(0)) + " as " + withParentheses(columnOp.getOperand(1)) + ")";
} else if (columnOp.getOpType().equals("extract")) {
return "extract(" + withParentheses(columnOp.getOperand(0)) + " from " + withParentheses(columnOp.getOperand(1)) + ")";
} else if (columnOp.getOpType().equals("||") || columnOp.getOpType().equals("|")
|| columnOp.getOpType().equals("&") || columnOp.getOpType().equals("
|| columnOp.getOpType().equals(">>") || columnOp.getOpType().equals("<<")) {
return withParentheses(columnOp.getOperand(0)) + " " + columnOp.getOpType() + " " + withParentheses(columnOp.getOperand(1));
} else if (columnOp.getOpType().equals("overlay")) {
return "overlay(" + withParentheses(columnOp.getOperand(0)) + " placing " + withParentheses(columnOp.getOperand(1))
+ " from " + withParentheses(columnOp.getOperand(2)) + ")";
} else if (columnOp.getOpType().equals("substring") && syntax instanceof PostgresqlSyntax) {
String temp = "substring(" + withParentheses(columnOp.getOperand(0)) + " from " + withParentheses(columnOp.getOperand(1));
if (columnOp.getOperands().size()==2) {
return temp + ")";
}
else return temp + " for " + withParentheses(columnOp.getOperand(2)) + ")";
}
else {
List<UnnamedColumn> columns = columnOp.getOperands();
String temp = columnOp.getOpType() + "(";
for (int i = 0; i < columns.size(); i++) {
if (i != columns.size() - 1) {
temp = temp + withParentheses(columns.get(i)) + ", ";
} else temp = temp + withParentheses(columns.get(i));
}
return temp + ")";
}
//else {
// throw new VerdictDBTypeException("Unexpceted opType of column: " + columnOp.getOpType().toString());
} else if (column instanceof SubqueryColumn) {
return "(" + selectQueryToSql(((SubqueryColumn) column).getSubquery()) + ")";
}
throw new VerdictDBTypeException("Unexpceted argument type: " + column.getClass().toString());
}
String withParentheses(UnnamedColumn column) throws VerdictDBException {
String sql = unnamedColumnToSqlPart(column);
if (column instanceof ColumnOp && !opTypeNotRequiringParentheses.contains(((ColumnOp) column).getOpType())) {
sql = "(" + sql + ")";
}
return sql;
}
String selectQueryToSql(SelectQuery sel) throws VerdictDBException {
StringBuilder sql = new StringBuilder();
// select
sql.append("select");
List<SelectItem> columns = sel.getSelectList();
boolean isFirstColumn = true;
for (SelectItem a : columns) {
if (isFirstColumn) {
sql.append(" " + selectItemToSqlPart(a));
isFirstColumn = false;
} else {
sql.append(", " + selectItemToSqlPart(a));
}
}
// from
List<AbstractRelation> rels = sel.getFromList();
if (rels.size() > 0) {
sql.append(" from");
boolean isFirstRel = true;
for (AbstractRelation r : rels) {
if (isFirstRel) {
sql.append(" " + relationToSqlPart(r));
isFirstRel = false;
} else {
sql.append(", " + relationToSqlPart(r));
}
}
}
// where
Optional<UnnamedColumn> filter = sel.getFilter();
if (filter.isPresent()) {
sql.append(" where ");
sql.append(unnamedColumnToSqlPart(filter.get()));
}
// groupby
List<GroupingAttribute> groupby = sel.getGroupby();
boolean isFirstGroup = true;
for (GroupingAttribute a : groupby) {
if (isFirstGroup) {
sql.append(" group by ");
sql.append(groupingAttributeToSqlPart(a));
isFirstGroup = false;
} else {
sql.append(", " + groupingAttributeToSqlPart(a));
}
}
//having
Optional<UnnamedColumn> having = sel.getHaving();
if (having.isPresent()) {
sql.append(" having ");
sql.append(unnamedColumnToSqlPart(having.get()));
}
//orderby
List<OrderbyAttribute> orderby = sel.getOrderby();
boolean isFirstOrderby = true;
for (OrderbyAttribute a : orderby) {
if (isFirstOrderby) {
sql.append(" order by ");
sql.append(quoteName(a.getAttributeName()));
sql.append(" " + a.getOrder());
isFirstOrderby = false;
} else {
sql.append(", " + quoteName(a.getAttributeName()));
sql.append(" " + a.getOrder());
}
}
//Limit
Optional<UnnamedColumn> limit = sel.getLimit();
if (limit.isPresent()) {
sql.append(" limit " + unnamedColumnToSqlPart(limit.get()));
}
return sql.toString();
}
String relationToSqlPart(AbstractRelation relation) throws VerdictDBException {
StringBuilder sql = new StringBuilder();
if (relation instanceof BaseTable) {
BaseTable base = (BaseTable) relation;
sql.append(quoteName(base.getSchemaName()) + "." + quoteName(base.getTableName()));
if (base.getAliasName().isPresent()) {
sql.append(" as " + base.getAliasName().get());
}
return sql.toString();
}
if (relation instanceof JoinTable) {
//sql.append("(");
sql.append(relationToSqlPart(((JoinTable) relation).getJoinList().get(0)));
for (int i = 1; i < ((JoinTable) relation).getJoinList().size(); i++) {
if (((JoinTable) relation).getJoinTypeList().get(i - 1).equals(JoinTable.JoinType.inner)) {
sql.append(" inner join ");
} else if (((JoinTable) relation).getJoinTypeList().get(i - 1).equals(JoinTable.JoinType.outer)) {
sql.append(" outer join ");
} else if (((JoinTable) relation).getJoinTypeList().get(i - 1).equals(JoinTable.JoinType.left)) {
sql.append(" left join ");
} else if (((JoinTable) relation).getJoinTypeList().get(i - 1).equals(JoinTable.JoinType.leftouter)) {
sql.append(" left outer join ");
} else if (((JoinTable) relation).getJoinTypeList().get(i - 1).equals(JoinTable.JoinType.right)) {
sql.append(" right join ");
} else if (((JoinTable) relation).getJoinTypeList().get(i - 1).equals(JoinTable.JoinType.rightouter)) {
sql.append(" right outer join ");
} else if (((JoinTable) relation).getJoinTypeList().get(i - 1).equals(JoinTable.JoinType.cross)) {
sql.append(" cross join ");
}
sql.append(relationToSqlPart(((JoinTable) relation).getJoinList().get(i)));
if (((JoinTable) relation).getCondition().get(i-1)!=null)
sql.append(" on " + withParentheses(((JoinTable) relation).getCondition().get(i - 1)));
}
//sql.append(")");
if (((JoinTable) relation).getAliasName().isPresent()) {
sql.append(" as " + ((JoinTable) relation).getAliasName().toString());
}
return sql.toString();
}
if (relation instanceof SetOperationRelation) {
sql.append("(");
sql.append(selectQueryToSql((SelectQuery) ((SetOperationRelation) relation).getLeft()));
sql.append(" ");
sql.append(((SetOperationRelation) relation).getSetOpType());
sql.append(" ");
sql.append(selectQueryToSql((SelectQuery) ((SetOperationRelation) relation).getRight()));
sql.append(")");
if (relation.getAliasName().isPresent()) {
sql.append(" as " + relation.getAliasName().get());
}
return sql.toString();
}
if (!(relation instanceof SelectQuery)) {
throw new VerdictDBTypeException("Unexpected relation type: " + relation.getClass().toString());
}
SelectQuery sel = (SelectQuery) relation;
Optional<String> aliasName = sel.getAliasName();
if (!aliasName.isPresent()) {
throw new VerdictDBValueException("An inner select query must be aliased.");
}
return "(" + selectQueryToSql(sel) + ") as " + aliasName.get();
}
String quoteName(String name) {
String quoteString = syntax.getQuoteString();
// already quoted
if (name.startsWith(quoteString)&&name.endsWith(quoteString)) {
return name;
}
else return quoteString + name + quoteString;
}
} |
package com.salesforce.dva.argus.service.tsdb;
import static com.salesforce.dva.argus.system.SystemAssert.requireArgument;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.MethodNotSupportedException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.inject.Inject;
import com.salesforce.dva.argus.entity.Annotation;
import com.salesforce.dva.argus.entity.Metric;
import com.salesforce.dva.argus.service.DefaultService;
import com.salesforce.dva.argus.service.MonitorService;
import com.salesforce.dva.argus.service.TSDBService;
import com.salesforce.dva.argus.system.SystemConfiguration;
import com.salesforce.dva.argus.system.SystemException;
/**
* TSDB abstract class, where the put methods are implemented, and the get methods are overridden by specific implementation.
*
* @author Tom Valine (tvaline@salesforce.com), Bhinav Sura (bhinav.sura@salesforce.com)
*/
public class AbstractTSDBService extends DefaultService implements TSDBService {
private static final int CHUNK_SIZE = 50;
private static final int TSDB_DATAPOINTS_WRITE_MAX_SIZE = 100;
private static final String QUERY_LATENCY_COUNTER = "query.latency";
private static final String QUERY_COUNT_COUNTER = "query.count";
static final String DELIMITER = "-__-";
private final ObjectMapper _mapper;
protected final Logger _logger = LoggerFactory.getLogger(getClass());
private final String[] _writeEndpoints;
protected final CloseableHttpClient _writeHttpClient;
protected final List<String> _readEndPoints;
protected final List<String> _readBackupEndPoints;
protected final Map<String, CloseableHttpClient> _readPortMap = new HashMap<>();
protected final Map<String, String> _readBackupEndPointsMap = new HashMap<>();
/** Round robin iterator for write endpoints.
* We will cycle through this iterator to select an endpoint from the set of available endpoints */
private final Iterator<String> _roundRobinIterator;
protected final ExecutorService _executorService;
protected final MonitorService _monitorService;
private final int RETRY_COUNT;
/**
* Creates a new Default TSDB Service having an equal number of read and write routes.
*
* @param config The system _configuration used to configure the service.
* @param monitorService The monitor service used to collect query time window counters. Cannot be null.
* @param transformFactory Transform Factory
*
* @throws SystemException If an error occurs configuring the service.
*/
@Inject
public AbstractTSDBService(SystemConfiguration config, MonitorService monitorService) {
super(config);
requireArgument(config != null, "System configuration cannot be null.");
requireArgument(monitorService != null, "Monitor service cannot be null.");
_monitorService = monitorService;
_mapper = getMapper();
int connCount = Integer.parseInt(config.getValue(Property.TSD_CONNECTION_COUNT.getName(),
Property.TSD_CONNECTION_COUNT.getDefaultValue()));
int connTimeout = Integer.parseInt(config.getValue(Property.TSD_ENDPOINT_CONNECTION_TIMEOUT.getName(),
Property.TSD_ENDPOINT_CONNECTION_TIMEOUT.getDefaultValue()));
int socketTimeout = Integer.parseInt(config.getValue(Property.TSD_ENDPOINT_SOCKET_TIMEOUT.getName(),
Property.TSD_ENDPOINT_SOCKET_TIMEOUT.getDefaultValue()));
_readEndPoints = Arrays.asList(config.getValue(Property.TSD_ENDPOINT_READ.getName(), Property.TSD_ENDPOINT_READ.getDefaultValue()).split(","));
for(String readEndPoint : _readEndPoints) {
requireArgument((readEndPoint != null) && (!readEndPoint.isEmpty()), "Illegal read endpoint URL.");
}
_readBackupEndPoints = Arrays.asList(config.getValue(Property.TSD_ENDPOINT_BACKUP_READ.getName(), Property.TSD_ENDPOINT_BACKUP_READ.getDefaultValue()).split(","));
if(_readBackupEndPoints.size() < _readEndPoints.size()){
for(int i=0; i< _readEndPoints.size() - _readBackupEndPoints.size();i++)
_readBackupEndPoints.add("");
}
_writeEndpoints = config.getValue(Property.TSD_ENDPOINT_WRITE.getName(), Property.TSD_ENDPOINT_WRITE.getDefaultValue()).split(",");
RETRY_COUNT = Integer.parseInt(config.getValue(Property.TSD_RETRY_COUNT.getName(),
Property.TSD_RETRY_COUNT.getDefaultValue()));
for(String writeEndpoint : _writeEndpoints) {
requireArgument((writeEndpoint != null) && (!writeEndpoint.isEmpty()), "Illegal write endpoint URL.");
}
requireArgument(connCount >= 2, "At least two connections are required.");
requireArgument(connTimeout >= 1, "Timeout must be greater than 0.");
try {
int index = 0;
for (String readEndpoint : _readEndPoints) {
_readPortMap.put(readEndpoint, getClient(connCount / 2, connTimeout, socketTimeout,readEndpoint));
_readBackupEndPointsMap.put(readEndpoint, _readBackupEndPoints.get(index));
index ++;
}
for (String readBackupEndpoint : _readBackupEndPoints) {
if (!readBackupEndpoint.isEmpty())
_readPortMap.put(readBackupEndpoint, getClient(connCount / 2, connTimeout, socketTimeout,readBackupEndpoint));
}
_writeHttpClient = getClient(connCount / 2, connTimeout, socketTimeout, _writeEndpoints);
_roundRobinIterator = Iterables.cycle(_writeEndpoints).iterator();
_executorService = Executors.newFixedThreadPool(connCount);
} catch (MalformedURLException ex) {
throw new SystemException("Error initializing the TSDB HTTP Client.", ex);
}
}
/* Generates the metric names for metrics used for annotations. */
static String toAnnotationKey(String scope, String metric, String type, Map<String, String> tags) {
int hash = 7;
hash = 71 * hash + (scope != null ? scope.hashCode() : 0);
hash = 71 * hash + (metric != null ? metric.hashCode() : 0);
hash = 71 * hash + (type != null ? type.hashCode() : 0);
hash = 71 * hash + (tags != null ? tags.hashCode() : 0);
StringBuilder sb = new StringBuilder();
sb.append(scope).append(".").append(Integer.toHexString(hash));
return sb.toString();
}
private static String toAnnotationKey(Annotation annotation) {
String scope = annotation.getScope();
String metric = annotation.getMetric();
String type = annotation.getType();
Map<String, String> tags = annotation.getTags();
return toAnnotationKey(scope, metric, type, tags);
}
/**
* We construct OpenTSDB metric name as a combination of Argus metric, scope and namespace as follows:
*
* metric(otsdb) = metric(argus)<DELIMITER>scope(argus)<DELIMITER>namespace(argus)
*
* @param metric
* @return OpenTSDB metric name constructed from scope, metric and namespace.
*/
public static String constructTSDBMetricName(Metric metric) {
StringBuilder sb = new StringBuilder();
sb.append(metric.getMetric()).append(DELIMITER).append(metric.getScope());
if (metric.getNamespace() != null && !metric.getNamespace().isEmpty()) {
sb.append(DELIMITER).append(metric.getNamespace());
}
return sb.toString();
}
/**
* Given otsdb metric name, return argus metric.
* We construct OpenTSDB metric name as a combination of Argus metric, scope and namespace as follows:
*
* metric(otsdb) = metric(argus)<DELIMITER>scope(argus)<DELIMITER>namespace(argus)
*
*
* @param tsdbMetricName
* @return Argus metric name.
*/
public static String getMetricFromTSDBMetric(String tsdbMetricName) {
return tsdbMetricName.split(DELIMITER)[0];
}
/**
* Given otsdb metric name, return argus scope.
* We construct OpenTSDB metric name as a combination of Argus metric, scope and namespace as follows:
*
* metric(otsdb) = metric(argus)<DELIMITER>scope(argus)<DELIMITER>namespace(argus)
*
*
* @param tsdbMetricName
* @return Argus scope.
*/
public static String getScopeFromTSDBMetric(String tsdbMetricName) {
return tsdbMetricName.split(DELIMITER)[1];
}
/**
* Given otsdb metric name, return argus namespace.
* We construct OpenTSDB metric name as a combination of Argus metric, scope and namespace as follows:
*
* metric(otsdb) = metric(argus)<DELIMITER>scope(argus)<DELIMITER>namespace(argus)
*
*
* @param tsdbMetricName
* @return Argus namespace.
*/
public static String getNamespaceFromTSDBMetric(String tsdbMetricName) {
String[] splits = tsdbMetricName.split(DELIMITER);
return (splits.length == 3) ? splits[2] : null;
}
/** @see TSDBService#dispose() */
@Override
public void dispose() {
}
/** @see TSDBService#putMetrics(java.util.List) */
@Override
public void putMetrics(List<Metric> metrics) {
requireNotDisposed();
requireArgument(TSDB_DATAPOINTS_WRITE_MAX_SIZE > 0, "Max Chunk size can not be less than 1");
requireArgument(metrics != null, "Metrics can not be null");
String endpoint = _roundRobinIterator.next();
_logger.debug("Pushing {} metrics to TSDB using endpoint {}.", metrics.size(), endpoint);
List<Metric> fracturedList = new ArrayList<>();
for (Metric metric : metrics) {
if (metric.getDatapoints().size() <= TSDB_DATAPOINTS_WRITE_MAX_SIZE) {
fracturedList.add(metric);
} else {
fracturedList.addAll(fractureMetric(metric));
}
}
try {
put(fracturedList, endpoint + "/api/put", HttpMethod.POST);
} catch(IOException ex) {
_logger.warn("IOException while trying to push metrics", ex);
_retry(fracturedList, _roundRobinIterator);
}
}
public <T> void _retry(List<T> objects, Iterator<String> endPointIterator) {
for(int i=0;i<RETRY_COUNT;i++) {
try {
String endpoint=endPointIterator.next();
_logger.info("Retrying using endpoint {}.", endpoint);
put(objects, endpoint + "/api/put", HttpMethod.POST);
return;
} catch(IOException ex) {
_logger.warn("IOException while trying to push data. We will retry for {} more times",RETRY_COUNT-i);
}
}
_logger.error("Retried for {} times and we still failed. Dropping this chunk of data.", RETRY_COUNT);
}
/** @see TSDBService#putAnnotations(java.util.List) */
@Override
public void putAnnotations(List<Annotation> annotations) {
requireNotDisposed();
if (annotations != null) {
List<AnnotationWrapper> wrappers = reconcileWrappers(toAnnotationWrappers(annotations));
String endpoint = _roundRobinIterator.next();
try {
put(wrappers, endpoint + "/api/annotation/bulk", HttpMethod.POST);
} catch(IOException ex) {
_logger.warn("IOException while trying to push annotations", ex);
_retry(wrappers, _roundRobinIterator);
}
}
}
private ObjectMapper getMapper() {
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(Metric.class, new MetricTransform.Serializer());
module.addDeserializer(ResultSet.class, new MetricTransform.MetricListDeserializer());
module.addSerializer(AnnotationWrapper.class, new AnnotationTransform.Serializer());
module.addDeserializer(AnnotationWrappers.class, new AnnotationTransform.Deserializer());
module.addSerializer(MetricQuery.class, new MetricQueryTransform.Serializer());
mapper.registerModule(module);
return mapper;
}
/* Writes objects in chunks. */
private <T> void put(List<T> objects, String endpoint, HttpMethod method) throws IOException {
if (objects != null) {
int chunkEnd = 0;
while (chunkEnd < objects.size()) {
int chunkStart = chunkEnd;
chunkEnd = Math.min(objects.size(), chunkStart + CHUNK_SIZE);
try {
StringEntity entity = new StringEntity(fromEntity(objects.subList(chunkStart, chunkEnd)));
HttpResponse response = executeHttpRequest(method, endpoint, _writeHttpClient, entity);
extractResponse(response);
} catch (UnsupportedEncodingException ex) {
throw new SystemException("Error posting data", ex);
}
}
}
}
/* Helper to create the read and write clients. */
protected CloseableHttpClient getClient(int connCount, int connTimeout, int socketTimeout, String...endpoints) throws MalformedURLException {
PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager();
connMgr.setMaxTotal(connCount);
for(String endpoint : endpoints) {
URL url = new URL(endpoint);
int port = url.getPort();
requireArgument(port != -1, "TSDB endpoint must include explicit port.");
HttpHost host = new HttpHost(url.getHost(), url.getPort());
connMgr.setMaxPerRoute(new HttpRoute(host), connCount / endpoints.length);
}
RequestConfig reqConfig = RequestConfig.custom().setConnectionRequestTimeout(connTimeout).setConnectTimeout(connTimeout).setSocketTimeout(
socketTimeout).build();
return HttpClients.custom().setConnectionManager(connMgr).setDefaultRequestConfig(reqConfig).build();
}
/* Converts a list of annotations into a list of annotation wrappers for use in serialization. Resulting list is sorted by target annotation
* scope and timestamp.
*/
private List<AnnotationWrapper> toAnnotationWrappers(List<Annotation> annotations) {
Map<String, Set<Annotation>> sortedByUid = new TreeMap<>();
for (Annotation annotation : annotations) {
String key = toAnnotationKey(annotation);
Set<Annotation> items = sortedByUid.get(key);
if (items == null) {
items = new HashSet<>();
sortedByUid.put(key, items);
}
items.add(annotation);
}
List<AnnotationWrapper> result = new LinkedList<>();
for (Set<Annotation> items : sortedByUid.values()) {
Map<Long, Set<Annotation>> sortedByUidAndTimestamp = new HashMap<>();
for (Annotation item : items) {
Long timestamp = item.getTimestamp();
Set<Annotation> itemsByTimestamp = sortedByUidAndTimestamp.get(timestamp);
if (itemsByTimestamp == null) {
itemsByTimestamp = new HashSet<>();
sortedByUidAndTimestamp.put(timestamp, itemsByTimestamp);
}
itemsByTimestamp.add(item);
}
for (Set<Annotation> itemsByTimestamp : sortedByUidAndTimestamp.values()) {
result.add(new AnnotationWrapper(itemsByTimestamp, this));
}
}
return result;
}
/* This method should merge and update existing annotations rather than adding a duplicate annotation. */
private List<AnnotationWrapper> reconcileWrappers(List<AnnotationWrapper> wrappers) {
_logger.debug("Reconciling and merging of duplicate annotations is not yet implemented.");
return wrappers;
}
/*
* Helper method to extract the HTTP response and close the client connection. Please note that <tt>ByteArrayOutputStreams</tt> do not require to
* be closed.
*/
private String extractStringResponse(HttpResponse content) {
requireArgument(content != null, "Response content is null.");
String result;
HttpEntity entity = null;
try {
entity = content.getEntity();
if (entity == null) {
result = "";
} else {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
entity.writeTo(baos);
result = baos.toString("UTF-8");
}
return result;
} catch (IOException ex) {
throw new SystemException(ex);
} finally {
if (entity != null) {
try {
EntityUtils.consume(entity);
} catch (IOException ex) {
_logger.warn("Failed to close entity stream.", ex);
}
}
}
}
/* Helper method to convert JSON String representation to the corresponding Java entity. */
protected <T> T toEntity(String content, TypeReference<T> type) {
try {
return _mapper.readValue(content, type);
} catch (IOException ex) {
throw new SystemException(ex);
}
}
/* Helper method to convert a Java entity to a JSON string. */
protected <T> String fromEntity(T type) {
try {
return _mapper.writeValueAsString(type);
} catch (JsonProcessingException ex) {
throw new SystemException(ex);
}
}
/* Helper to process the response. */
protected String extractResponse(HttpResponse response) {
if (response != null) {
int status = response.getStatusLine().getStatusCode();
if ((status < HttpStatus.SC_OK) || (status >= HttpStatus.SC_MULTIPLE_CHOICES)) {
Map<String, Map<String, String>> errorMap = toEntity(extractStringResponse(response),
new TypeReference<Map<String, Map<String, String>>>() { });
if (errorMap != null) {
throw new SystemException("Error : " + errorMap.toString());
} else {
throw new SystemException("Status code: " + status + " . Unknown error occurred. ");
}
} else {
return extractStringResponse(response);
}
}
return null;
}
/* Execute a request given by type requestType. */
protected HttpResponse executeHttpRequest(HttpMethod requestType, String url, CloseableHttpClient client, StringEntity entity) throws IOException {
HttpResponse httpResponse = null;
if (entity != null) {
entity.setContentType("application/json");
}
try {
switch (requestType) {
case POST:
HttpPost post = new HttpPost(url);
post.setEntity(entity);
httpResponse = client.execute(post);
break;
case GET:
HttpGet httpGet = new HttpGet(url);
httpResponse = client.execute(httpGet);
break;
case DELETE:
HttpDelete httpDelete = new HttpDelete(url);
httpResponse = client.execute(httpDelete);
break;
case PUT:
HttpPut httpput = new HttpPut(url);
httpput.setEntity(entity);
httpResponse = client.execute(httpput);
break;
default:
throw new MethodNotSupportedException(requestType.toString());
}
} catch (MethodNotSupportedException ex) {
throw new SystemException(ex);
}
return httpResponse;
}
/**
* This method partitions data points of a given metric.
*
* @param metric - metric whose data points to be fractured
*
* @return - list of chunks in descending order so that the last chunk will be of size of "firstChunkSize"
*/
private List<Metric> fractureMetric(Metric metric) {
List<Metric> result = new ArrayList<>();
if (metric.getDatapoints().size() <= TSDB_DATAPOINTS_WRITE_MAX_SIZE) {
result.add(metric);
return result;
}
Metric tempMetric = new Metric(metric);
Map<Long, Double> dataPoints = new LinkedHashMap<>();
int tempChunkSize = TSDB_DATAPOINTS_WRITE_MAX_SIZE;
for (Map.Entry<Long, Double> dataPoint : metric.getDatapoints().entrySet()) {
dataPoints.put(dataPoint.getKey(), dataPoint.getValue());
if (--tempChunkSize == 0) {
tempMetric.setDatapoints(dataPoints);
result.add(tempMetric);
tempMetric = new Metric(metric);
tempChunkSize = TSDB_DATAPOINTS_WRITE_MAX_SIZE;
dataPoints = new LinkedHashMap<>();
}
}
if (!dataPoints.isEmpty()) {
tempMetric.setDatapoints(dataPoints);
result.add(tempMetric);
}
return result;
}
/**
* Enumerates the implementation specific configuration properties.
*
* @author Tom Valine (tvaline@salesforce.com)
*/
public enum Property {
/** The TSDB read endpoint. */
TSD_ENDPOINT_READ("service.property.tsdb.endpoint.read", "http:
/** The TSDB write endpoint. */
TSD_ENDPOINT_WRITE("service.property.tsdb.endpoint.write", "http:
/** The TSDB connection timeout. */
TSD_ENDPOINT_CONNECTION_TIMEOUT("service.property.tsdb.endpoint.connection.timeout", "10000"),
/** The TSDB socket connection timeout. */
TSD_ENDPOINT_SOCKET_TIMEOUT("service.property.tsdb.endpoint.socket.timeout", "10000"),
/** The TSDB connection count. */
TSD_CONNECTION_COUNT("service.property.tsdb.connection.count", "2"),
TSD_RETRY_COUNT("service.property.tsdb.retry.count", "3"),
/** The TSDB backup read endpoint. */
TSD_ENDPOINT_BACKUP_READ("service.property.tsdb.endpoint.backup.read", "http:
private final String _name;
private final String _defaultValue;
private Property(String name, String defaultValue) {
_name = name;
_defaultValue = defaultValue;
}
/**
* Returns the property name.
*
* @return The property name.
*/
public String getName() {
return _name;
}
/**
* Returns the default value for the property.
*
* @return The default value.
*/
public String getDefaultValue() {
return _defaultValue;
}
}
protected void instrumentQueryLatency(final MonitorService monitorService, final AnnotationQuery query, final long start,
final String measurementType) {
String timeWindow = QueryTimeWindow.getWindow(query.getEndTimestamp() - query.getStartTimestamp());
Map<String, String> tags = new HashMap<String, String>();
tags.put("type", measurementType);
tags.put("timeWindow", timeWindow);
tags.put("cached", "false");
monitorService.modifyCustomCounter(QUERY_LATENCY_COUNTER, (System.currentTimeMillis() - start), tags);
monitorService.modifyCustomCounter(QUERY_COUNT_COUNTER, 1, tags);
}
/**
* Enumeration of supported HTTP methods.
*
* @author Tom Valine (tvaline@salesforce.com), Bhinav Sura (bhinav.sura@salesforce.com)
*/
protected enum HttpMethod {
/** POST operation. */
POST,
/** GET operation. */
GET,
/** DELETE operation. */
DELETE,
/** PUT operation. */
PUT;
}
/**
* Helper entity to wrap multiple Annotation entities into a form closer to the TSDB metric form.
*
* @author Tom Valine (tvaline@salesforce.com), Bhinav Sura (bhinav.sura@salesforce.com)
*/
static class AnnotationWrapper {
String _uid;
Long _timestamp;
Map<String, Annotation> _custom;
private TSDBService _service;
/** Creates a new AnnotationWrapper object. */
AnnotationWrapper() {
_custom = new HashMap<>();
}
/* Annotations should have the same scope, metric, type and tags and timestamp. */
private AnnotationWrapper(Set<Annotation> annotations, TSDBService service) {
this();
_service = service;
for (Annotation annotation : annotations) {
if (_uid == null) {
_uid = getUid(annotation);
_timestamp = annotation.getTimestamp();
}
_custom.put(annotation.getSource() + "." + annotation.getId(), annotation);
}
}
List<Annotation> getAnnotations() {
return new ArrayList<>(_custom.values());
}
private String getUid(Annotation annotation) {
String scope = toAnnotationKey(annotation);
String type = annotation.getType();
Map<String, String> tags = annotation.getTags();
MetricQuery query = new MetricQuery(scope, type, tags, 0L, 2L);
long backOff = 1000L;
for (int attempts = 0; attempts < 3; attempts++) {
try {
return _service.getMetrics(Arrays.asList(query)).get(query).get(0).getUid();
} catch (Exception e) {
Metric metric = new Metric(scope, type);
Map<Long, Double> datapoints = new HashMap<>();
datapoints.put(1L, 0.0);
metric.setDatapoints(datapoints);
metric.setTags(annotation.getTags());
_service.putMetrics(Arrays.asList(new Metric[] { metric }));
try {
Thread.sleep(backOff);
} catch (InterruptedException ex) {
break;
}
backOff += 1000L;
}
}
throw new SystemException("Failed to create new annotation metric.");
}
String getUid() {
return _uid;
}
Long getTimestamp() {
return _timestamp;
}
Map<String, Annotation> getCustom() {
return Collections.unmodifiableMap(_custom);
}
void setUid(String uid) {
_uid = uid;
}
void setTimestamp(Long timestamp) {
_timestamp = timestamp;
}
void setCustom(Map<String, Annotation> custom) {
_custom = custom;
}
}
/**
* Helper entity to facilitate de-serialization.
*
* @author Tom Valine (tvaline@salesforce.com), Bhinav Sura (bhinav.sura@salesforce.com)
*/
static class AnnotationWrappers extends ArrayList<AnnotationWrapper> {
/** Comment for <code>serialVersionUID.</code> */
private static final long serialVersionUID = 1L;
}
/**
* Helper class used to parallelize query execution.
*
* @author Bhinav Sura (bhinav.sura@salesforce.com)
*/
class QueryWorker implements Callable<List<Metric>> {
private final String _requestUrl;
private final String _requestEndPoint;
private final String _requestBody;
/**
* Creates a new QueryWorker object.
*
* @param requestUrl The URL to which the request will be issued.
* @param requestEndPoint The endpoint to which the request will be issued.
* @param requestBody The request body.
*/
public QueryWorker(String requestUrl, String requestEndPoint, String requestBody) {
this._requestUrl = requestUrl;
this._requestEndPoint = requestEndPoint;
this._requestBody = requestBody;
}
@Override
public List<Metric> call() {
_logger.debug("TSDB Query = " + _requestBody);
try {
HttpResponse response = executeHttpRequest(HttpMethod.POST, _requestUrl, _readPortMap.get(_requestEndPoint), new StringEntity(_requestBody));
List<Metric> metrics = toEntity(extractResponse(response), new TypeReference<ResultSet>() { }).getMetrics();
return metrics;
} catch (IOException e) {
throw new SystemException("Failed to retrieve metrics.", e);
}
}
}
@Override
public Properties getServiceProperties() {
throw new UnsupportedOperationException("This method should be overriden by a specific implementation.");
}
@Override
public Map<MetricQuery, List<Metric>> getMetrics(List<MetricQuery> queries) {
throw new UnsupportedOperationException("This method should be overriden by a specific implementation.");
}
@Override
public List<Annotation> getAnnotations(List<AnnotationQuery> queries) {
throw new UnsupportedOperationException("This method should be overriden by a specific implementation.");
}
} |
package org.xtx.ut4converter.t3d;
import org.xtx.ut4converter.MapConverter;
import org.xtx.ut4converter.UTGames.UnrealEngine;
import org.xtx.ut4converter.export.UTPackageExtractor;
import org.xtx.ut4converter.t3d.iface.T3D;
import org.xtx.ut4converter.ucore.UPackageRessource;
import javax.vecmath.Vector3d;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import static org.xtx.ut4converter.t3d.T3DObject.IDT;
/**
* Since T3DMover extends T3DBrush for Unreal Engine 1 and T3DMover extends
* T3DStaticMesh for Unreal Engine > 1 Need to have a common "class" for both
* actors for sharing same properties
*
* @author XtremeXp
*/
public class MoverProperties implements T3D {
/**
* Sounds used by movers when it started moving, is moving ... TODO make a
* list of UPackageRessource binded with some property name
*/
private UPackageRessource closedSound, closingSound, openedSound, openingSound, moveAmbientSound;
/**
* CHECK usage?
*/
private List<Vector3d> savedPositions = new ArrayList<>();
/**
* List of positions where mover moves UTUE4: Lift
* Destination=(X=0.000000,Y=0.000000,Z=730.000000) (no support for several
* nav localisations unlike UE1/2) UT99: KeyPos(1)=(Y=72.000000)
*/
private List<Vector3d> positions = new LinkedList<>();
private List<Vector3d> rotations = new LinkedList<>();
/**
* CHECK usage? U1: BaseRot=(Yaw=-49152)
*/
private List<Vector3d> savedRotations = new ArrayList<>();
/**
* How long it takes for the mover to get to next position
*/
private Double moveTime;
/**
* How long the mover stay static in his final position before returning to
* home
*/
private Double stayOpenTime;
/**
* How long time the mover is available again after getting back to home
* position
*/
private Double delayTime;
private T3DActor mover;
/**
* Default state for Unreal 1
* TODO check for other games
* Depending on state mover will stay open, loop, be controled by trigger only and so on...
*/
private InitialState initialState;
private BumpType bumpType;
private MoverEncroachType moverEncroachType;
private MoverGlideType moverGlideType;
/**
* Reference to converter
*/
private MapConverter mapConverter;
private List<T3DSimpleProperty> simpleProperties = new LinkedList<>();
public MoverProperties(T3DActor mover, MapConverter mapConverter) {
this.mover = mover;
this.mapConverter = mapConverter;
mover.registerSimpleProperty("bDamageTriggered", Boolean.class, Boolean.FALSE);
mover.registerSimpleProperty("bDirectionalPushoff", Boolean.class, Boolean.FALSE);
mover.registerSimpleProperty("bSlave", Boolean.class, Boolean.FALSE);
mover.registerSimpleProperty("bTriggerOnceOnly", Boolean.class, Boolean.FALSE);
mover.registerSimpleProperty("BumpEvent", String.class, null);
mover.registerSimpleProperty("bUseTriggered", Boolean.class, Boolean.FALSE);
mover.registerSimpleProperty("DamageTreshold", Float.class, 0f);
mover.registerSimpleProperty("EncroachDamage", Float.class, 0f);
mover.registerSimpleProperty("OtherTime", Float.class, 0f);
mover.registerSimpleProperty("PlayerBumpEvent", String.class, null);
}
enum BumpType {
BT_PlayerBump, BT_PawnBump, BT_AnyBump
}
enum MoverEncroachType {
ME_StopWhenEncroach, ME_ReturnWhenEncroach, ME_CrushWhenEncroach, ME_IgnoreWhenEncroach
}
enum MoverGlideType {
MV_GlideByTime, MV_MoveByTime
}
enum InitialState {
StandOpenTimed, BumpButton, BumpOpenTimed, ConstantLoop, TriggerPound, TriggerControl, TriggerToggle, TriggerOpenTimed, None
}
@Override
public boolean analyseT3DData(String line) {
/**
* OpenSound=SoundCue'A_Movers.Movers.Elevator01_StartCue'
OpenedSound=SoundCue'A_Movers.Movers.Elevator01_StopCue'
CloseSound=SoundCue'A_Movers.Movers.Elevator01_StartCue'
*/
// UE1 -> 'Wait at top time' (UE4)
if (line.contains("StayOpenTime")) {
stayOpenTime = T3DUtils.getDouble(line);
}
// UE1 -> 'Lift Time' (UE4)
else if (line.contains("MoveTime")) {
moveTime = T3DUtils.getDouble(line);
}
// UE1 -> 'Retrigger Delay' (UE4)
else if (line.contains("DelayTime")) {
delayTime = T3DUtils.getDouble(line);
}
// UE1 -> 'CloseStartSound' ? (UE4)
else if (line.startsWith("ClosedSound=")) {
closedSound = mover.mapConverter.getUPackageRessource(line.split("\'")[1], T3DRessource.Type.SOUND);
}
// UE1 -> 'CloseStopSound' ? (UE4)
else if (line.startsWith("ClosingSound=") || line.startsWith("ClosingAmbientSound=")) {
closingSound = mover.mapConverter.getUPackageRessource(line.split("\'")[1], T3DRessource.Type.SOUND);
}
// UE1 -> 'OpenStartSound' ? (UE4)
else if (line.startsWith("OpeningSound=") || line.startsWith("OpeningAmbientSound=")) {
openingSound = mover.mapConverter.getUPackageRessource(line.split("\'")[1], T3DRessource.Type.SOUND);
}
// UE1 -> 'OpenStopSound' ? (UE4)
else if (line.startsWith("OpenedSound=")) {
openedSound = mover.mapConverter.getUPackageRessource(line.split("\'")[1], T3DRessource.Type.SOUND);
}
// UE1 -> 'Closed Sound' (UE4)
else if (line.startsWith("MoveAmbientSound=") || line.startsWith("OpenSound=")) {
moveAmbientSound = mover.mapConverter.getUPackageRessource(line.split("\'")[1], T3DRessource.Type.SOUND);
}
// UE1 -> 'Lift Destination' (UE12)
else if (line.contains("SavedPos=")) {
savedPositions.add(T3DUtils.getVector3d(line.split("SavedPos")[1], 0D));
}
// UE1 -> 'Saved Positions' (UE12)
else if (line.contains("SavedRot=")) {
savedRotations.add(T3DUtils.getVector3dRot(line.split("SavedRot")[1]));
}
else if (line.contains("InitialState=")) {
this.initialState = InitialState.valueOf(T3DUtils.getString(line));
}
else if (line.contains("BumpType=")) {
this.bumpType = BumpType.valueOf(T3DUtils.getString(line));
}
else if (line.contains("MoverEncroachType=")) {
this.moverEncroachType = MoverEncroachType.valueOf(T3DUtils.getString(line));
}
else if (line.contains("MoverGlideType=")) {
this.moverGlideType = MoverGlideType.valueOf(T3DUtils.getString(line));
}
else if(line.startsWith("KeyRot")){
rotations.add(T3DUtils.getVector3dRot(line.split("\\)=")[1]));
}
// UE1 -> 'Saved Positions' (UE12)
else if (line.contains("KeyPos")) {
positions.add(T3DUtils.getVector3d(line.split("\\)=")[1], 0D));
} else {
return mover.parseSimpleProperty(line);
}
return true;
}
public void writeMoverProperties(final StringBuilder sbf) {
// Write the mover as Destination Lift
// TODO write as well matinee actor (once implementation done)
// because it's impossible to know ("guess") if a mover is a lift or
// another kind of mover (button, door, ...)
// TODO use UBMover once UBMover blueprint done
sbf.append(IDT).append("Begin Actor Class=Generic_Lift_C Name=").append(mover.name).append("_Lift\n");
sbf.append(IDT).append("\tBegin Object Name=\"Scene1\"\n");
mover.writeLocRotAndScale();
sbf.append(IDT).append("\tEnd Object\n");
sbf.append(IDT).append("\tScene1=Scene\n");
sbf.append(IDT).append("\tRootComponent=Scene1\n");
if (moveTime != null) {
sbf.append(IDT).append("\tLift Time=").append(moveTime).append("\n");
}
// TODO handle multi position / rotation later
// because we use last position but there might more than one position !
if (!positions.isEmpty()) {
final Vector3d v = new Vector3d();
// all positions are relative to previous one
// since then need to sum them all
// TODO remove this when blueprint handle multi-position
for(final Vector3d position : positions){
v.add(position);
}
sbf.append(IDT).append("\tLift Destination=(X=").append(T3DActor.fmt(v.x)).append(",Y=").append(T3DActor.fmt(v.y)).append(",Z=").append(T3DActor.fmt(v.z)).append(")\n");
}
if(!rotations.isEmpty()){
final Vector3d v = new Vector3d();
// same comment as above
for(final Vector3d rotation : rotations){
v.add(rotation);
}
sbf.append(IDT).append("\tLift Destination Rot=(Pitch=").append(T3DActor.fmt(v.x)).append(",Yaw=").append(T3DActor.fmt(v.y)).append(",Roll=").append(T3DActor.fmt(v.z)).append(")\n");
}
if (openingSound != null) {
sbf.append(IDT).append("\tOpenStartSound=SoundCue'").append(openingSound.getConvertedName(mover.mapConverter)).append("'\n");
} else if(mapConverter.convertSounds()) {
sbf.append(IDT).append("\tOpenStartSound=None\n");
}
if (openedSound != null) {
sbf.append(IDT).append("\tOpenStopSound=SoundCue'").append(openedSound.getConvertedName(mover.mapConverter)).append("'\n");
} else if(mapConverter.convertSounds()) {
sbf.append(IDT).append("\tOpenStopSound=None\n");
}
if (closingSound != null) {
sbf.append(IDT).append("\tCloseStartSound=SoundCue'").append(closingSound.getConvertedName(mover.mapConverter)).append("'\n");
} else if(mapConverter.convertSounds()) {
sbf.append(IDT).append("\tCloseStartSound=None\n");
}
if (closedSound != null) {
sbf.append(IDT).append("\tCloseStopSound=SoundCue'").append(closedSound.getConvertedName(mover.mapConverter)).append("'\n");
} else if(mapConverter.convertSounds()) {
sbf.append(IDT).append("\tCloseStopSound=None\n");
}
if (moveAmbientSound != null) {
sbf.append(IDT).append("\tMoveLoopSound=SoundCue'").append(moveAmbientSound.getConvertedName(mover.mapConverter)).append("'\n");
} else if(mapConverter.convertSounds()) {
sbf.append(IDT).append("\tMoveLoopSound=None\n");
}
if (stayOpenTime != null) {
sbf.append(IDT).append("\tWait at top time=").append(stayOpenTime).append("\n");
}
if (delayTime != null) {
sbf.append(IDT).append("\tRetrigger Delay=").append(delayTime).append("\n");
}
if (initialState != null) {
sbf.append(IDT).append("\tInitialState=").append("NewEnumerator").append(initialState.ordinal()).append("\n");
}
if (bumpType != null) {
sbf.append(IDT).append("\tBumpType=").append("NewEnumerator").append(bumpType.ordinal()).append("\n");
}
if (moverEncroachType != null) {
sbf.append(IDT).append("\tMoverEncroachType=").append("NewEnumerator").append(moverEncroachType.ordinal()).append("\n");
}
if (moverGlideType != null) {
sbf.append(IDT).append("\tMoverGlideType=").append("NewEnumerator").append(moverGlideType.ordinal()).append("\n");
}
if (mover instanceof T3DMoverSM) {
T3DMoverSM moverSm = (T3DMoverSM) mover;
if (moverSm.staticMesh != null && moverSm.getMapConverter().convertStaticMeshes()) {
sbf.append(IDT).append("\tLift Mesh=StaticMesh'").append(moverSm.staticMesh.getConvertedName(moverSm.getMapConverter())).append("'\n");
}
}
mover.writeSimpleProperties();
mover.writeEndActor();
}
@Override
public void convert() {
// used to match very similar sound resources by name (e.g:
// A_Movers.Movers.Elevator01.Loop -> A_Movers.Movers.Elevator01.LoopCue
final boolean isFromUe3 = mapConverter.isFrom(UnrealEngine.UE3);
if(stayOpenTime == null){
// default stay open time with UE1 (TODO check UE2/UE3)
stayOpenTime = 4d;
}
// mover might be rotated only
// so we don't want to have the default 200 Z axis offset
// by adding a 0 destination position
if(this.positions.isEmpty()){
this.positions.add(new Vector3d(0, 0, 0));
}
if(mapConverter.convertSounds()) {
if (openingSound != null) {
openingSound.export(UTPackageExtractor.getExtractor(mover.mapConverter, openingSound), !isFromUe3);
}
if (openedSound != null) {
openedSound.export(UTPackageExtractor.getExtractor(mover.mapConverter, openedSound), !isFromUe3);
}
if (closingSound != null) {
closingSound.export(UTPackageExtractor.getExtractor(mover.mapConverter, closingSound), !isFromUe3);
}
if (closedSound != null) {
closedSound.export(UTPackageExtractor.getExtractor(mover.mapConverter, closedSound), !isFromUe3);
}
if (moveAmbientSound != null) {
moveAmbientSound.export(UTPackageExtractor.getExtractor(mover.mapConverter, moveAmbientSound), !isFromUe3);
}
}
for(Vector3d rotator : rotations){
// convert 65536 rotator old range to UE4 range
if(mapConverter.isFrom(UnrealEngine.UE1, UnrealEngine.UE3, UnrealEngine.UE3)){
T3DUtils.convertRotatorTo360Format(rotator);
}
}
}
@Override
public void scale(Double newScale) {
for( Vector3d position : positions ) {
position.scale(newScale);
}
}
@Override
public String getName() {
return mover.name;
}
public T3DActor getMover() {
return mover;
}
@Override
public void toT3d(StringBuilder sb, String prefix) {
}
} |
package org.bimserver.database.actions;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.bimserver.BimServer;
import org.bimserver.BimserverDatabaseException;
import org.bimserver.ServerIfcModel;
import org.bimserver.database.BimserverLockConflictException;
import org.bimserver.database.DatabaseSession;
import org.bimserver.database.OldQuery;
import org.bimserver.database.queries.QueryObjectProvider;
import org.bimserver.database.queries.om.CanInclude;
import org.bimserver.database.queries.om.Include;
import org.bimserver.database.queries.om.Include.TypeDef;
import org.bimserver.database.queries.om.JsonQueryObjectModelConverter;
import org.bimserver.database.queries.om.Query;
import org.bimserver.database.queries.om.QueryException;
import org.bimserver.database.queries.om.QueryPart;
import org.bimserver.database.queries.om.Reference;
import org.bimserver.emf.IdEObject;
import org.bimserver.emf.IdEObjectImpl;
import org.bimserver.emf.IfcModelInterface;
import org.bimserver.emf.IfcModelInterfaceException;
import org.bimserver.emf.PackageMetaData;
import org.bimserver.models.geometry.GeometryPackage;
import org.bimserver.models.log.AccessMethod;
import org.bimserver.models.store.PluginConfiguration;
import org.bimserver.models.store.Project;
import org.bimserver.models.store.Revision;
import org.bimserver.models.store.StorePackage;
import org.bimserver.plugins.IfcModelSet;
import org.bimserver.plugins.ModelHelper;
import org.bimserver.plugins.modelmerger.MergeException;
import org.bimserver.plugins.serializers.SerializerPlugin;
import org.bimserver.shared.HashMapVirtualObject;
import org.bimserver.shared.HashMapWrappedVirtualObject;
import org.bimserver.shared.exceptions.UserException;
import org.bimserver.webservices.authorization.Authorization;
import org.eclipse.emf.common.util.AbstractEList;
import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EReference;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.base.Joiner;
public class DownloadByNewJsonQueryDatabaseAction extends AbstractDownloadDatabaseAction<IfcModelInterface> {
private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(DownloadByNewJsonQueryDatabaseAction.class);
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private final Set<Long> roids;
private int progress;
private String json;
private long serializerOid;
public DownloadByNewJsonQueryDatabaseAction(BimServer bimServer, DatabaseSession databaseSession, AccessMethod accessMethod, Set<Long> roids, String json, long serializerOid, Authorization authorization) {
super(bimServer, databaseSession, accessMethod, authorization);
this.roids = roids;
this.json = json;
this.serializerOid = serializerOid;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public IfcModelInterface execute() throws UserException, BimserverLockConflictException, BimserverDatabaseException {
List<String> projectNames = new ArrayList<>();
PluginConfiguration serializerPluginConfiguration = getDatabaseSession().get(StorePackage.eINSTANCE.getPluginConfiguration(), serializerOid, OldQuery.getDefault());
SerializerPlugin serializerPlugin = (SerializerPlugin) getBimServer().getPluginManager().getPlugin(serializerPluginConfiguration.getPluginDescriptor().getPluginClassName(), true);
Set<String> geometryFields = serializerPlugin.getRequiredGeometryFields();
setProgress("Querying database...", -1);
for (long roid : roids) {
Revision revision = getDatabaseSession().get(StorePackage.eINSTANCE.getRevision(), roid, OldQuery.getDefault());
projectNames.add(revision.getProject().getName() + "." + revision.getId());
}
String name = Joiner.on("-").join(projectNames);
PackageMetaData lastPackageMetaData = null;
Project lastProject = null;
IfcModelSet ifcModelSet = new IfcModelSet();
Map<Integer, Long> pidRoidMap = new HashMap<>();
Set<CanInclude> updatedIncludes = new HashSet<>();
for (long roid : roids) {
Revision revision = getDatabaseSession().get(StorePackage.eINSTANCE.getRevision(), roid, OldQuery.getDefault());
lastProject = revision.getProject();
PackageMetaData packageMetaData = getBimServer().getMetaDataManager().getPackageMetaData(revision.getProject().getSchema());
lastPackageMetaData = packageMetaData;
JsonQueryObjectModelConverter converter = new JsonQueryObjectModelConverter(packageMetaData);
ObjectNode queryObject;
try {
queryObject = OBJECT_MAPPER.readValue(json, ObjectNode.class);
converter.setCopyExternalDefines(true);
Query query = converter.parseJson("query", (ObjectNode) queryObject);
// We now have the original user query, we'll amend it a little bit to include geometry, but only if the serializer requires certain fields
// TODO only checking the base level of the query now, should check recursive and possibly more
if (geometryFields != null) {
for (QueryPart queryPart : query.getQueryParts()) {
if (queryPart.hasReferences()) {
for (Reference reference : queryPart.getReferences()) {
apply(geometryFields, packageMetaData, reference.getInclude(), updatedIncludes);
}
}
if (queryPart.hasIncludes()) {
apply(geometryFields, packageMetaData, queryPart, updatedIncludes);
}
if (queryPart.hasTypes()) {
for (TypeDef typeDef : queryPart.getTypes()) {
if (packageMetaData.getEClass("IfcProduct").isSuperTypeOf(typeDef.geteClass())) {
Include include = queryPart.createInclude();
applyFields(geometryFields, new TypeDef(packageMetaData.getEClass("IfcProduct"), true), include);
}
}
}
if (queryPart.isIncludeAllFields()) {
Include newInclude = queryPart.createInclude();
applyFields(geometryFields, new TypeDef(packageMetaData.getEClass("IfcProduct"), true), newInclude);
}
}
}
// System.out.println(new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(new JsonQueryObjectModelConverter(packageMetaData).toJson(query)));
pidRoidMap.put(revision.getProject().getId(), roid);
IfcModelInterface ifcModel = new ServerIfcModel(packageMetaData, pidRoidMap, getDatabaseSession());
ifcModelSet.add(ifcModel);
QueryObjectProvider queryObjectProvider = new QueryObjectProvider(getDatabaseSession(), getBimServer(), query, Collections.singleton(roid), packageMetaData);
HashMapVirtualObject next = queryObjectProvider.next();
while (next != null) {
IdEObject newObject = packageMetaData.create(next.eClass());
IdEObjectImpl idEObjectImpl = (IdEObjectImpl)newObject;
idEObjectImpl.setPid(revision.getProject().getId());
idEObjectImpl.setOid(next.getOid());
for (EAttribute eAttribute : newObject.eClass().getEAllAttributes()) {
Object value = next.eGet(eAttribute);
if (eAttribute.isMany()) {
List<?> list = (List<?>)value;
if (list != null) {
AbstractEList targetList = (AbstractEList)newObject.eGet(eAttribute);
for (Object item : list) {
targetList.addUnique(item);
}
}
} else {
if (value != null || eAttribute.isUnsettable()) {
newObject.eSet(eAttribute, value);
}
}
}
ifcModel.add(next.getOid(), newObject);
next = queryObjectProvider.next();
}
queryObjectProvider = new QueryObjectProvider(getDatabaseSession(), getBimServer(), query, Collections.singleton(roid), packageMetaData);
next = queryObjectProvider.next();
while (next != null) {
IdEObject idEObject = ifcModel.get(next.getOid());
if (idEObject.eClass() != next.eClass()) {
// Something is wrong
throw new RuntimeException("Classes not the same");
}
for (EReference eReference : idEObject.eClass().getEAllReferences()) {
if (eReference.isMany()) {
List refOids = (List)next.eGet(eReference);
AbstractEList<IdEObject> list = (AbstractEList<IdEObject>)idEObject.eGet(eReference);
if (refOids != null) {
for (Object refOid : refOids) {
if (refOid instanceof Long) {
IdEObject ref = ifcModel.get((long) refOid);
if (ref != null) {
if (eReference.isUnique()) {
list.add(ref);
} else {
list.addUnique(ref);
}
// } else {
// throw new BimserverDatabaseException("Could not find reference to " + eReference.getName() + " " + refOid);
}
} else if (refOid instanceof HashMapWrappedVirtualObject) {
// IdEObject ref = ifcModel.get(((HashMapWrappedVirtualObject) refOid).get);
// if (ref != null) {
// list.add(ref);
} else if (refOid instanceof HashMapVirtualObject) {
HashMapVirtualObject hashMapVirtualObject = (HashMapVirtualObject)refOid;
IdEObject listObject = packageMetaData.create(hashMapVirtualObject.eClass());
List subList = (List<?>) hashMapVirtualObject.get("List");
List newList = (List<?>) listObject.eGet(listObject.eClass().getEStructuralFeature("List"));
for (Object o : subList) {
if (o instanceof HashMapWrappedVirtualObject) {
newList.add(convertWrapped(revision, ifcModel, (HashMapWrappedVirtualObject)o));
} else {
newList.add(o);
}
}
list.addUnique(listObject);
} else {
throw new BimserverDatabaseException("Unimplemented");
}
}
}
} else {
Object r = next.eGet(eReference);
if (r instanceof Long) {
long refOid = (Long)r;
IdEObject referred = ifcModel.get(refOid);
idEObject.eSet(eReference, referred);
} else if (r instanceof HashMapWrappedVirtualObject) {
idEObject.eSet(eReference, convertWrapped(revision, ifcModel, (HashMapWrappedVirtualObject) r));
} else if (r instanceof HashMapVirtualObject) {
throw new BimserverDatabaseException("Unimplemented");
} else if (r == null) {
} else {
throw new BimserverDatabaseException("Unimplemented");
}
}
}
next = queryObjectProvider.next();
}
ifcModel.getModelMetaData().setName(name);
ifcModel.getModelMetaData().setRevisionId(1);
if (getAuthorization().getUoid() != -1) {
ifcModel.getModelMetaData().setAuthorizedUser(getUserByUoid(getAuthorization().getUoid()).getName());
}
ifcModel.getModelMetaData().setDate(new Date());
} catch (Throwable e) {
throw new BimserverDatabaseException(e);
}
}
IfcModelInterface ifcModel = new ServerIfcModel(lastPackageMetaData, pidRoidMap, 0, getDatabaseSession());
if (ifcModelSet.size() > 1) {
setProgress("Merging IFC data...", -1);
try {
ifcModel = getBimServer().getMergerFactory().createMerger(getDatabaseSession(), getAuthorization().getUoid()).merge(lastProject, ifcModelSet, new ModelHelper(getBimServer().getMetaDataManager(), ifcModel));
} catch (MergeException e) {
throw new UserException(e);
}
} else {
ifcModel = ifcModelSet.iterator().next();
}
ifcModel.getModelMetaData().setName(name);
// ifcModel.getModelMetaData().setRevisionId(project.getRevisions().indexOf(virtualRevision) + 1);
if (getAuthorization().getUoid() != -1) {
ifcModel.getModelMetaData().setAuthorizedUser(getUserByUoid(getAuthorization().getUoid()).getName());
}
ifcModel.getModelMetaData().setDate(new Date());
return ifcModel;
// for (Long roid : roids) {
// Revision virtualRevision = getRevisionByRoid(roid);
// pidRoidMap.put(virtualRevision.getProject().getId(), virtualRevision.getOid());
// project = virtualRevision.getProject();
// name += project.getName() + "-" + virtualRevision.getId() + "-";
// try {
// getAuthorization().canDownload(roid);
// } catch (UserException e) {
// if (!getAuthorization().hasRightsOnProjectOrSuperProjectsOrSubProjects(user, project)) {
// throw new UserException("User has insufficient rights to download revisions from this project");
// if (!getAuthorization().hasRightsOnProjectOrSuperProjectsOrSubProjects(user, project)) {
// throw new UserException("User has insufficient rights to download revisions from this project");
// int size = 0;
// for (ConcreteRevision concreteRevision : virtualRevision.getConcreteRevisions()) {
// try {
// int highestStopId = findHighestStopRid(project, concreteRevision);
// PackageMetaData packageMetaData = getBimServer().getMetaDataManager().getPackageMetaData(concreteRevision.getProject().getSchema());
// lastPackageMetaData = packageMetaData;
// IfcModelInterface subModel = new ServerIfcModel(packageMetaData, pidRoidMap, getDatabaseSession());
// OldQuery databaseQuery = new OldQuery(packageMetaData, concreteRevision.getProject().getId(), concreteRevision.getId(), virtualRevision.getOid(), null, Deep.NO, highestStopId);
// databaseQuery.updateOidCounters(concreteRevision, getDatabaseSession());
// JsonObject queryObject = (JsonObject)query;
// JsonArray queries = queryObject.get("queries").getAsJsonArray();
// for (JsonElement queryElement : queries) {
// processQueryPart(packageMetaData, queryObject, (JsonObject) queryElement, subModel, databaseQuery);
// size += subModel.size();
// subModel.getModelMetaData().setDate(concreteRevision.getDate());
// subModel.fixInverseMismatches();
// checkGeometry(serializerPluginConfiguration, getBimServer().getPluginManager(), subModel, project, concreteRevision, virtualRevision);
// ifcModelSet.add(subModel);
// } catch (GeometryGeneratingException | IfcModelInterfaceException e) {
// throw new UserException(e);
// TODO check, double merging??
// IfcModelInterface ifcModel = new BasicIfcModel(lastPackageMetaData, pidRoidMap);
// if (ifcModelSet.size() > 1) {
// try {
// ifcModel = getBimServer().getMergerFactory().createMerger(getDatabaseSession(), getAuthorization().getUoid()).merge(project, ifcModelSet, new ModelHelper(getBimServer().getMetaDataManager(), ifcModel));
// } catch (MergeException e) {
// throw new UserException(e);
// } else {
// ifcModel = ifcModelSet.iterator().next();
// if (name.endsWith("-")) {
// name = name.substring(0, name.length()-1);
}
private void apply(Set<String> geometryFields, PackageMetaData packageMetaData, CanInclude canInclude, Set<CanInclude> updatedIncludes)
throws QueryException {
if (updatedIncludes.contains(canInclude)) {
return;
}
EClass ifcProduct = packageMetaData.getEClass("IfcProduct");
updatedIncludes.add(canInclude);
if (canInclude.hasIncludes()) {
for (Include existingInclude : canInclude.getIncludes()) {
apply(geometryFields, packageMetaData, existingInclude, updatedIncludes);
}
}
if (canInclude.hasReferences()) {
for (Reference reference : canInclude.getReferences()) {
apply(geometryFields, packageMetaData, reference.getInclude(), updatedIncludes);
}
}
if (canInclude instanceof Include) {
Include inc = ((Include)canInclude);
if (inc.hasFields()) {
for (EReference field : inc.getFields()) {
if (ifcProduct.isSuperTypeOf((EClass)field.getEType()) || ((EClass)field.getEType()).isSuperTypeOf(ifcProduct)) {
Include newInclude = inc.createInclude();
applyFields(geometryFields, new TypeDef(ifcProduct, true), newInclude);
}
}
}
}
if (canInclude.hasTypes()) {
for (TypeDef typeDef : canInclude.getTypes()) {
if (ifcProduct.isSuperTypeOf(typeDef.geteClass()) || ((EClass)typeDef.geteClass()).isSuperTypeOf(ifcProduct)) {
Include include = canInclude.createInclude();
applyFields(geometryFields, new TypeDef(ifcProduct, true), include);
}
}
}
}
private void applyFields(Set<String> geometryFields, TypeDef typeDef, Include include) throws QueryException {
include.addType(typeDef);
include.addField("geometry");
Include geometryInclude = include.createInclude();
geometryInclude.addType(GeometryPackage.eINSTANCE.getGeometryInfo(), false);
geometryInclude.addField("data");
Include geometryData = geometryInclude.createInclude();
geometryData.addType(GeometryPackage.eINSTANCE.getGeometryData(), false);
geometryData.addField("color");
for (String field : geometryFields) {
geometryData.addField(field);
}
}
private IdEObject convertWrapped(Revision revision, IfcModelInterface ifcModel, HashMapWrappedVirtualObject hashMapWrappedVirtualObject) throws IfcModelInterfaceException {
IdEObject embeddedObject = ifcModel.create(hashMapWrappedVirtualObject.eClass());
((IdEObjectImpl)embeddedObject).setOid(-1);
((IdEObjectImpl)embeddedObject).setPid(revision.getProject().getId());
for (EAttribute eAttribute : hashMapWrappedVirtualObject.eClass().getEAllAttributes()) {
embeddedObject.eSet(eAttribute, hashMapWrappedVirtualObject.eGet(eAttribute));
}
return embeddedObject;
}
public int getProgress() {
return progress;
}
} |
package pt.davidafsilva.ghn.ui.main;
import com.jfoenix.controls.JFXListView;
import com.jfoenix.controls.JFXSpinner;
import com.jfoenix.controls.JFXToggleButton;
import org.controlsfx.glyphfont.FontAwesome;
import org.controlsfx.glyphfont.GlyphFont;
import org.controlsfx.glyphfont.GlyphFontRegistry;
import java.util.Comparator;
import java.util.Objects;
import java.util.TreeMap;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.MapChangeListener;
import javafx.collections.ObservableMap;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.control.Hyperlink;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Border;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.shape.Circle;
import pt.davidafsilva.ghn.model.mutable.Category;
/**
* @author david
*/
class LeftSideView extends BorderPane {
private static final int PHOTO_CIRCLE_RADIUS = 48;
private final NotificationsController controller;
private final ObservableMap<String, CategoryItem> categoriesMap = FXCollections
.observableMap(new TreeMap<String, CategoryItem>(Comparator.naturalOrder()));
private JFXListView<CategoryItem> categories;
private JFXToggleButton editButton;
LeftSideView(final NotificationsController controller) {
this.controller = controller;
getStyleClass().add("ghn-left-panel");
initialize();
}
private void initialize() {
final VBox panel = new VBox();
panel.setPadding(new Insets(15));
panel.setSpacing(20);
// photo and user panel
createPhotoUserPanel(panel);
createDivider(panel);
// categories
final Node categoriesPane = createCategories();
// app information
final Node appInfoPane = createAppInfoPanel();
// set the contents
setTop(panel);
setCenter(categoriesPane);
setBottom(appInfoPane);
}
private void createPhotoUserPanel(final VBox panel) {
// user & photo panel
final VBox photoUserPanel = new VBox();
// photo
photoUserPanel.setFillWidth(true);
photoUserPanel.setSpacing(10);
final ImageView photoImage = new ImageView(loadImage(getDefaultAvatar(), false));
photoImage.setClip(new Circle(PHOTO_CIRCLE_RADIUS, PHOTO_CIRCLE_RADIUS, PHOTO_CIRCLE_RADIUS));
final Label photo = new Label("", photoImage);
photo.setAlignment(Pos.CENTER);
photo.setMaxWidth(Double.MAX_VALUE);
photoUserPanel.getChildren().add(photo);
// lazily load the actual image from the network
controller.getUser().getAvatarUrl().ifPresent(url -> {
final Image img = loadImage(url, true);
img.progressProperty().addListener((ob, old, val) -> {
if (val.doubleValue() == 1d) {
photoImage.setImage(img);
}
});
});
// username
final Label username = new Label(controller.getUser().getUsername());
username.setAlignment(Pos.CENTER);
username.setMaxWidth(Double.MAX_VALUE);
username.getStyleClass().add("ghn-left-panel-username");
photoUserPanel.getChildren().add(username);
// add photo & username panel
panel.getChildren().add(photoUserPanel);
}
private VBox createAppInfoPanel() {
// container
final VBox appInfoPanel = new VBox();
appInfoPanel.getStyleClass().add("ghn-app-info");
// divider
createDivider(appInfoPanel);
// contents
final VBox contents = new VBox();
contents.setAlignment(Pos.CENTER);
final Label l1 = new Label("GitHub Notification Center");
final HBox madeByLabel = new HBox();
madeByLabel.setAlignment(Pos.CENTER);
madeByLabel.setPadding(new Insets(5));
madeByLabel.getChildren().add(new Label("Made with "));
final Label l2 = new Label("\u2665");
l2.getStyleClass().add("ghn-heart");
madeByLabel.getChildren().add(l2);
final Label personalLink = new Label(" by David Silva");
personalLink.setOnMouseClicked(e -> controller.openWebPage());
personalLink.setOnTouchReleased(e -> controller.openWebPage());
madeByLabel.getChildren().add(personalLink);
final GlyphFont fontAwesome = GlyphFontRegistry.font("FontAwesome");
final Hyperlink githubIcon = new Hyperlink("", fontAwesome.create(FontAwesome.Glyph.GITHUB)
.size(14));
githubIcon.setBorder(Border.EMPTY);
githubIcon.setOnAction(e -> controller.openGitHub());
contents.getChildren().addAll(l1, madeByLabel, githubIcon);
appInfoPanel.getChildren().add(contents);
return appInfoPanel;
}
private void createDivider(final VBox panel) {
final HBox divider = new HBox();
divider.getStyleClass().add("ghn-divider");
divider.prefWidthProperty().bind(panel.widthProperty().multiply(0.7));
panel.getChildren().add(divider);
}
private Image loadImage(final String path, final boolean inBackground) {
return new Image(path, PHOTO_CIRCLE_RADIUS * 2,
PHOTO_CIRCLE_RADIUS * 2, true, true, inBackground);
}
private String getDefaultAvatar() {
return getClass().getResource("/ghnc-96.png").toExternalForm();
}
private Node createCategories() {
final BorderPane container = new BorderPane();
container.getStyleClass().add("ghn-categories-pane");
// top label and edit button
final BorderPane topPane = new BorderPane();
// categories label
final Label label = new Label("CATEGORIES");
label.getStyleClass().add("ghn-categories-label");
topPane.setLeft(label);
// edit button
editButton = new JFXToggleButton();
editButton.setText("EDIT");
topPane.setRight(editButton);
topPane.setVisible(false);
container.setTop(topPane);
// categories
categories = new JFXListView<>();
categories.getStyleClass().add("ghn-categories-list");
categoriesMap.addListener((MapChangeListener<String, CategoryItem>) change -> {
if (change.getValueRemoved() != null) {
categories.getItems().remove(change.getValueRemoved());
}
if (change.getValueAdded() != null) {
categories.getItems().add(change.getValueAdded());
}
});
// loading
final VBox loadingCategories = new VBox();
loadingCategories.getStyleClass().add("ghn-categories-load");
loadingCategories.setAlignment(Pos.CENTER);
loadingCategories.setSpacing(20);
loadingCategories.getChildren().add(new JFXSpinner());
loadingCategories.getChildren().add(new Label("Loading categories..."));
container.setCenter(loadingCategories);
// create category
final HBox createCategory = new HBox();
createCategory.getStyleClass().add("ghn-create-category");
final GlyphFont fontAwesome = GlyphFontRegistry.font("FontAwesome");
final Node plusSign = fontAwesome.create(FontAwesome.Glyph.PLUS_CIRCLE).size(15);
final Label createLabel = new Label("Create Category");
createCategory.getChildren().addAll(plusSign, createLabel);
createCategory.visibleProperty().bind(editButton.selectedProperty());
createCategory.setOnMousePressed(e -> showCreateCategoryView());
createCategory.setOnTouchPressed(e -> showCreateCategoryView());
container.setBottom(createCategory);
return container;
}
private void showCreateCategoryView() {
// FIXME: implement
}
void updateCategory(final String name, final Category category) {
if (Objects.equals(name, category.getName())) {
// name not updated
Platform.runLater(() -> categoriesMap.computeIfPresent(name, (k, e) -> {
e.editablePropertyProperty().unbind();
final CategoryItem item = new CategoryItem(category);
item.editablePropertyProperty().bind(editButton.selectedProperty());
return item;
}));
} else {
// remove previous
removeCategory(name);
addCategory(category);
}
}
void addCategory(final Category category) {
if (categoriesMap.isEmpty()) {
// remove loading stuff
final BorderPane center = (BorderPane) getCenter();
Platform.runLater(() -> {
center.getTop().setVisible(true);
center.setCenter(categories);
});
}
final CategoryItem item = new CategoryItem(category);
item.editablePropertyProperty().bind(editButton.selectedProperty());
Platform.runLater(() -> categoriesMap.put(category.getName(), item));
}
void removeCategory(final Category category) {
removeCategory(category.getName());
}
private void removeCategory(final String name) {
Platform.runLater(() -> categoriesMap.remove(name));
}
} |
package com.dragonfruitstudios.brokenbonez;
import android.hardware.SensorEvent;
import android.util.Log;
import com.dragonfruitstudios.brokenbonez.Game.GameView;
import com.dragonfruitstudios.brokenbonez.Game.Scenes.Scene;
import java.util.HashMap;
/**
* This class implements a game scene manager, allowing using a single GameView object, to switch between
* different "scenes" (or screens). To use
* GameSceneManager gameSceneManager = new GameSceneManager(gameView, "SceneName", SceneObject);
*
* To add a new scene, use addScene(newSceneName, newGameObject, boolean setScene)
* The final parameter is optional and if set to true, it will also run setScene with the new scene.
* By default, it is false.
*
* To switch scene, use gameSceneManager.setScene("AwesomeScene")
*
* To get the current scene, you can use .getCurrentSceneObject() or .getCurrentSceneString()
*
* You can get a scene object from its name by using getGameSceneByName("SceneName)
*
* To update, use gameSceneManager.update(lastUpdate) (Should be handled by GameLoop)
* You can also pass in a string or object to draw that specific object
*
* To draw, use gameSceneManager.draw() (Should be handled by GameLoop)
* You can also pass in a string or object to draw that specific object
*
* To update current object size, use updateSize(width, length)
* For a different object by name, use updateSize(sceneName, width, length
*/
public class GameSceneManager {
protected GameView gameView;
private HashMap<String, Scene> gameScenes=new HashMap<String, Scene>();
private String currentScene = null;
public GameSceneManager(GameView gameView, String SceneName, Scene newGameObject){
this.gameView = gameView;
gameScenes.put(SceneName, newGameObject);
this.currentScene = SceneName;
}
public GameSceneManager(GameView gameView){
this.gameView = gameView;
}
public void addScene(String SceneName, Scene newGameObject){
//Adds new scene to the gameScenes hashmap
gameScenes.put(SceneName, newGameObject);
}
public void addScene(String SceneName, Scene newGameObject, boolean setScene){
//Adds new scene to the gameScenes hashmap and if setScene = true, will also set currentScene to that scene
gameScenes.put(SceneName, newGameObject);
if (setScene){
this.setScene(SceneName);
}
}
public void draw(){
// Draw the scene. Should only be called by GameLoop
this.getGameSceneByName(currentScene).draw(this.gameView);
}
public void draw(Scene GameScene){
// Draw the scene. Can be called from anywhere. Can pass in a custom GameScene object
GameScene.draw(this.gameView);
}
public void draw(String SceneName){
// Draw the scene. Can be called from anywhere. Can pass in a custom GameScene name
this.getGameSceneByName(SceneName).draw(this.gameView);
}
public void update(float lastUpdate){
// Update the scene. Should only be called by GameLoop
this.getGameSceneByName(this.currentScene).update(lastUpdate);
}
public void update(Scene GameScene, float lastUpdate){
// Update the scene. Can be called from anywhere. Can pass in a custom GameScene object
GameScene.update(lastUpdate);
}
public void update(String SceneName, float lastUpdate){
// Update the scene. Can be called from anywhere. Can pass in a custom GameScene name
this.getGameSceneByName(SceneName).update(lastUpdate);
}
public void setScene(String currentScene){
// Deactivate previous scene
if (this.currentScene != null) {
getCurrentSceneObject().deactivate();
}
// Set currentScene to the passed in name of another scene
this.currentScene = currentScene;
// After changing the scene call `updateSize` to let the scene know what the size of
// the GameView is -DP.
if (gameView.getWidth() != 0 && gameView.getHeight() != 0) {
updateSize(gameView.getWidth(), gameView.getHeight());
}
else {
Log.d("GameSceneManager", "Could not update size because GameView doesn't know it.");
}
// Run the activate method of the new scene
this.getCurrentSceneObject().activate();
}
public Scene getCurrentSceneObject(){
// Get current scene object being drawn/updated
return this.getGameSceneByName(this.currentScene);
}
public String getCurrentSceneString(){
// Get current scene name being drawn/updated
return this.currentScene;
}
public void updateSize(int width, int height){
// Update size of current scene
this.getGameSceneByName(this.currentScene).updateSize(width, height);
}
public void updateSize(String SceneName, int width, int height){
// Update size of a specified object by scene name
this.getGameSceneByName(SceneName).updateSize(width, height);
}
public Scene getGameSceneByName(String SceneName) {
// Get a scene object from passing in the string name of it
Scene gs;
if (this.gameScenes.containsKey(SceneName)) {
gs = this.gameScenes.get(SceneName);
} else {
gs = null;
Log.e("GameScenesLoader", "Unable to get gameScene with name " + SceneName);
throw new RuntimeException("Unable to select gameScene as gameScene does not exist with that name.");
}
return gs;
}
// Called when the user minimizes the game.
// or when the 'P' key is pressed (when debugging in an emulator).
public void pause() {
this.getCurrentSceneObject().pause();
}
// Called when the user resumes the game from the android menu.
public void resume() {
this.getCurrentSceneObject().resume();
}
public void onSensorChanged(SensorEvent event) {
this.getCurrentSceneObject().onSensorChanged(event);}
} |
package de.fu_berlin.cdv.chasingpictures.api;
import android.content.Context;
import android.support.annotation.StringRes;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;
import java.io.IOException;
import de.fu_berlin.cdv.chasingpictures.R;
import de.fu_berlin.cdv.chasingpictures.security.Access;
/**
* Abstract class for API requests.
*
* @author Simon Kalt
*/
public abstract class ApiRequest<ResponseType> {
protected final String apiUri;
protected final RestTemplate restTemplate;
protected final Context context;
protected HttpHeaders headers;
protected ApiRequest(Context context, int endpointResID) {
this.context = context;
this.apiUri = getURIforEndpoint(context, endpointResID);
this.restTemplate = buildJsonRestTemplate();
this.headers = new HttpHeaders();
}
/**
* Builds a basic JSON rest template for sending requests.
*
* @return A RestTemplate with a {@link org.springframework.http.converter.json.MappingJackson2HttpMessageConverter} attached.
*/
public static RestTemplate buildJsonRestTemplate() {
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
restTemplate.setErrorHandler(new DefaultAPIResponseErrorHandler());
return restTemplate;
}
/**
* Retrieves the API URI for the specified endpoint.
*
* @param context The current context
* @param endpointResID A resource id pointing to an R.strings.api_path_* value
* @return The URI to send your request to
*/
public static String getURIforEndpoint(Context context, @StringRes int endpointResID) {
return context.getString(R.string.api_url) + context.getString(endpointResID);
}
/**
* Sends this request to the API.
*
* @return A {@link ResponseEntity} with the result of the call.
*/
protected abstract ResponseEntity<ResponseType> send();
/**
* This is executed before executing a request.
* By default it loads the stored access info into the HTTP headers.
*/
protected void beforeSending() {
// Store access info in HTTP headers
Access.getAccess(context, headers);
}
/**
* This is executed after executing a request.
* By default it stores the received access info in the application.
*/
protected void afterSending(ResponseEntity<ResponseType> responseEntity) {
Access.setAccess(context, responseEntity);
}
/**
* Sends this request to the API.
*
* @return A {@link ResponseEntity} with the result of the call.
*/
public final ResponseEntity<ResponseType> sendRequest() {
beforeSending();
ResponseEntity<ResponseType> response = send();
afterSending(response);
return response;
}
/**
* This default error handler ignores the 403 error code,
* which is not always a fatal error.
*/
public static class DefaultAPIResponseErrorHandler extends DefaultResponseErrorHandler {
public void handleError(ClientHttpResponse response) throws IOException {
final HttpStatus statusCode = response.getStatusCode();
if (statusCode == HttpStatus.FORBIDDEN || statusCode == HttpStatus.UNAUTHORIZED) {
// Request was denied,
// do nothing and return.
return;
}
super.handleError(response);
}
}
} |
package seedu.ggist.logic.commands;
import java.util.Set;
/**
* Finds and lists all persons in address book whose name contains any of the argument keywords.
* Keyword matching is case sensitive.
*/
public class SearchCommand extends Command {
public static final String COMMAND_WORD = "find";
public static final String MESSAGE_USAGE = COMMAND_WORD + ": Finds all tasks whose names contain any of "
+ "the specified keywords (not case-sensitive) and displays them as a list with index numbers.\n"
+ "Parameters: KEYWORD [MORE_KEYWORDS]...\n"
+ "Example: " + COMMAND_WORD + " buy milk";
private final Set<String> keywords;
public SearchCommand(Set<String> keywords) {
this.keywords = keywords;
}
@Override
public CommandResult execute() {
model.updateFilteredTaskList(keywords);
return new CommandResult(getMessageForTaskListShownSummary(model.getFilteredTaskList().size()));
}
} |
package six42.fitnesse.jdbcslim;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import java.util.Set;
public class SheetCommandBase implements SheetCommandInterface {
protected String command = "";
protected SheetFixture myFixture;
protected String rawResult = null;
protected List<List<String>> resultSheet;
protected boolean success = true;
private PropertiesLoader loader = new PropertiesLoader();
public SheetCommandBase(String configurationOptions, String rawCommand, String outputFormatOptions) throws FileNotFoundException, IOException{
parseConfiguration(configurationOptions);
if (outputFormatOptions != null) {
parseConfigurationString(outputFormatOptions);
}
String commandToUse = getCommandIfMissing(configurationOptions, rawCommand);
setCommand(commandToUse);
myFixture = new SheetFixture(command, this);
}
public SheetCommandBase(String configurationOptions, String rawCommand) throws FileNotFoundException, IOException{
this(configurationOptions, rawCommand, null);
}
public SheetCommandBase(String configurationOptions) throws FileNotFoundException, IOException{
this(configurationOptions, null);
}
private String getCommandIfMissing(String propertiesFile, String rawCommand) {
if (rawCommand == null || rawCommand.isEmpty()){
rawCommand = loader.getProperty("cmd");
if (rawCommand == null){
throw new RuntimeException("Mandatory parameter 'cmd' not found in properties (" + propertiesFile + ")." );
}
}
return rawCommand;
}
private void parseConfiguration(String configurationOptions) throws FileNotFoundException, IOException {
loader.loadFromDefintionOrFile(configurationOptions );
}
private void parseConfigurationString(String configurationOptions) throws FileNotFoundException, IOException {
loader.loadFromString(configurationOptions );
}
public List<?> doTable(List<List<String>> ParameterTable) {
// Always do this
return myFixture.doTable(ParameterTable);
}
@Override
public void setCommand(String Command){
this.command = Command;
}
@Override
public void execute() {
// This is an implementation just for demonstration and testing purposes
resultSheet = loader.toTable();
success = true;
}
@Override
public void execute(String Command) {
setCommand(Command);
execute();
}
@Override
public void reset() {
// Nothing to be done
}
@Override
public void table(List<List<String>> table) {
// Nothing to be done
}
@Override
public void beginTable() {
// Nothing to be done
}
@Override
public void endTable() {
// Nothing to be done
}
@Override
public boolean success() {
return this.success;
}
@Override
public String rawResult() {
if (rawResult != null) return this.rawResult;
else return this.resultSheet.toString();
}
@Override
public String command() {
return this.command;
}
@Override
public List<List<String>> resultSheet() {
return this.resultSheet;
}
@Override
public PropertiesInterface Properties() {
return loader;
}
public String getCellValue(int row, int column){
return this.resultSheet.get(row)
.get(column);
}
public String getColumnValue( int column){
return this.resultSheet.get(1)
.get(column);
}
public String getColumnValueByName( String columnName){
List<String> Header = this.resultSheet.get(0);
List<String> Data = this.resultSheet.get(1);
for (int i =0; i< Header.size(); i++ ){
if (HeaderLine.isHeaderNameEqual(Header.get(i),columnName) ) return Data.get(i);
}
throw new RuntimeException("Column not found (" + columnName + ")." );
}
public void ResetConfiguration(String configurationOptions) throws FileNotFoundException, IOException {
loader = new PropertiesLoader();
loader.loadFromDefintionOrFile(configurationOptions );
}
public void ResetConfigurationFromString(String configurationOptions) throws FileNotFoundException, IOException {
loader = new PropertiesLoader();
loader.loadFromString(configurationOptions );
}
public List<?> compareSheet(List<List<String>> ParameterTable) {
// Always do this
return doTable(ParameterTable);
}
@Override
public void set(String columnName, String value) {
// TODO Auto-generated method stub
}
@Override
public String get(String columnName) {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean containsKey(String columnName) {
// TODO Auto-generated method stub
return false;
}
@Override
public Set<String> getUsedColumnNames() {
// TODO Auto-generated method stub
return null;
}
} |
package us.mikeandwan.photos.ui.categories;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import java.util.List;
import javax.inject.Inject;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import us.mikeandwan.photos.R;
import us.mikeandwan.photos.di.TaskComponent;
import us.mikeandwan.photos.models.Category;
import us.mikeandwan.photos.ui.BaseFragment;
// TODO: further genericize the adapters
public class CategoryListFragment extends BaseFragment {
private int _thumbSize;
private Unbinder _unbinder;
private ViewTreeObserver _viewTreeObserver;
private int _lastWidth = -1;
@BindView(R.id.category_recycler_view) RecyclerView _categoryRecyclerView;
@Inject Activity _activity;
@Inject SharedPreferences _sharedPrefs;
@Inject ListCategoryRecyclerAdapter _listAdapter;
@Inject ThumbnailCategoryRecyclerAdapter _gridAdapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_category_list, container, false);
_unbinder = ButterKnife.bind(this, view);
_thumbSize = (int)getResources().getDimension(R.dimen.category_grid_thumbnail_size);
_categoryRecyclerView.setHasFixedSize(true);
_viewTreeObserver = view.getViewTreeObserver();
_viewTreeObserver.addOnGlobalLayoutListener(() -> {
_categoryRecyclerView.post(() -> {
if(getView() == null || getView().getWidth() == _lastWidth) {
return;
}
int width = getView().getWidth();
if(width == _lastWidth) {
return;
}
_lastWidth = width;
if (_sharedPrefs.getBoolean("category_thumbnail_view", true)) {
int cols = Math.max(1, (width / _thumbSize));
GridLayoutManager glm = new GridLayoutManager(_activity, cols);
_categoryRecyclerView.setLayoutManager(glm);
}
});
});
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
this.getComponent(TaskComponent.class).inject(this);
}
@Override
public void onDestroy() {
super.onDestroy();
if(_listAdapter != null) {
_listAdapter.dispose();
}
if(_gridAdapter != null) {
_gridAdapter.dispose();
}
_unbinder.unbind();
}
public void setCategories(List<Category> categories) {
if (_sharedPrefs.getBoolean("category_thumbnail_view", true)) {
_gridAdapter.setCategoryList(categories);
_gridAdapter.getClicks().subscribe(c -> getCategoryActivity().selectCategory(c));
_categoryRecyclerView.setAdapter(_gridAdapter);
}
else {
_listAdapter.setCategoryList(categories);
_listAdapter.getClicks().subscribe(c -> getCategoryActivity().selectCategory(c));
LinearLayoutManager llm = new LinearLayoutManager(_activity);
llm.setOrientation(LinearLayoutManager.VERTICAL);
_categoryRecyclerView.setLayoutManager(llm);
DividerItemDecoration dec = new DividerItemDecoration(_categoryRecyclerView.getContext(), llm.getOrientation());
_categoryRecyclerView.addItemDecoration(dec);
_categoryRecyclerView.setAdapter(_listAdapter);
}
}
public void notifyCategoriesUpdated() {
if (_sharedPrefs.getBoolean("category_thumbnail_view", true)) {
_gridAdapter.notifyDataSetChanged();
}
else {
_listAdapter.notifyDataSetChanged();
}
}
private ICategoryListActivity getCategoryActivity() {
return (ICategoryListActivity) getActivity();
}
} |
package org.gluu.oxauth.ws.rs;
import static org.gluu.oxauth.model.register.RegisterRequestParam.APPLICATION_TYPE;
import static org.gluu.oxauth.model.register.RegisterRequestParam.CLAIMS_REDIRECT_URIS;
import static org.gluu.oxauth.model.register.RegisterRequestParam.CLIENT_NAME;
import static org.gluu.oxauth.model.register.RegisterRequestParam.CLIENT_URI;
import static org.gluu.oxauth.model.register.RegisterRequestParam.ID_TOKEN_SIGNED_RESPONSE_ALG;
import static org.gluu.oxauth.model.register.RegisterRequestParam.REDIRECT_URIS;
import static org.gluu.oxauth.model.register.RegisterRequestParam.SCOPE;
import static org.gluu.oxauth.model.register.RegisterResponseParam.CLIENT_ID_ISSUED_AT;
import static org.gluu.oxauth.model.register.RegisterResponseParam.CLIENT_SECRET;
import static org.gluu.oxauth.model.register.RegisterResponseParam.CLIENT_SECRET_EXPIRES_AT;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation.Builder;
import javax.ws.rs.core.Response;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.gluu.oxauth.BaseTest;
import org.gluu.oxauth.client.RegisterRequest;
import org.gluu.oxauth.client.RegisterResponse;
import org.gluu.oxauth.model.common.AuthenticationMethod;
import org.gluu.oxauth.model.common.SubjectType;
import org.gluu.oxauth.model.crypto.signature.SignatureAlgorithm;
import org.gluu.oxauth.model.register.ApplicationType;
import org.gluu.oxauth.model.register.RegisterResponseParam;
import org.gluu.oxauth.model.util.StringUtils;
import org.gluu.oxauth.ws.rs.ClientTestUtil;
import org.gluu.oxauth.util.ServerUtil;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import org.gluu.oxauth.model.uma.TestUtil;
/**
* Functional tests for Client Registration Web Services (embedded)
*
* @author Javier Rojas Blum
* @version November 29, 2017
*/
public class RegistrationRestWebServiceEmbeddedTest extends BaseTest {
@ArquillianResource
private URI url;
private static String registrationAccessToken1;
private static String registrationClientUri1;
@Parameters({"registerPath", "redirectUris"})
@Test
public void requestClientAssociate1(final String registerPath, final String redirectUris) throws Exception {
Builder request = ResteasyClientBuilder.newClient().target(url.toString() + registerPath).request();
String registerRequestContent = null;
try {
RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
StringUtils.spaceSeparatedToList(redirectUris));
registerRequest.setClaimsRedirectUris(StringUtils.spaceSeparatedToList(redirectUris));
registerRequestContent = ServerUtil.toPrettyJson(registerRequest.getJSONParameters());
} catch (JSONException e) {
e.printStackTrace();
fail(e.getMessage());
}
Response response = request.post(Entity.json(registerRequestContent));
String entity = response.readEntity(String.class);
showResponse("requestClientAssociate1", response, entity);
assertEquals(response.getStatus(), 200, "Unexpected response code. " + entity);
assertNotNull(entity, "Unexpected result: " + entity);
try {
final RegisterResponse registerResponse = RegisterResponse.valueOf(entity);
ClientTestUtil.assert_(registerResponse);
registrationAccessToken1 = registerResponse.getRegistrationAccessToken();
registrationClientUri1 = registerResponse.getRegistrationClientUri();
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage() + "\nResponse was: " + entity);
}
}
@Parameters({"registerPath", "redirectUris", "sectorIdentifierUri", "contactEmail1", "contactEmail2"})
@Test
public void requestClientAssociate2(final String registerPath, final String redirectUris,
final String sectorIdentifierUri, final String contactEmail1, final String contactEmail2) throws Exception {
Builder request = ResteasyClientBuilder.newClient().target(url.toString() + registerPath).request();
String registerRequestContent = null;
try {
List<String> contacts = Arrays.asList(contactEmail1, contactEmail2);
RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
StringUtils.spaceSeparatedToList(redirectUris));
registerRequest.setContacts(contacts);
registerRequest.setScope(Arrays.asList("openid", "clientinfo", "profile", "email", "invalid_scope"));
registerRequest.setLogoUri("http:
registerRequest.setClientUri("http:
registerRequest.setTokenEndpointAuthMethod(AuthenticationMethod.CLIENT_SECRET_JWT);
registerRequest.setPolicyUri("http:
registerRequest.setJwksUri("http:
registerRequest.setSectorIdentifierUri(sectorIdentifierUri);
registerRequest.setSubjectType(SubjectType.PAIRWISE);
registerRequest.setRequestObjectSigningAlg(SignatureAlgorithm.RS256);
registerRequestContent = ServerUtil.toPrettyJson(registerRequest.getJSONParameters());
} catch (JSONException e) {
e.printStackTrace();
fail(e.getMessage());
}
Response response = request.post(Entity.json(registerRequestContent));
String entity = response.readEntity(String.class);
showResponse("requestClientAssociate2", response, entity);
assertEquals(response.getStatus(), 200, "Unexpected response code. " + entity);
assertNotNull(entity, "Unexpected result: " + entity);
try {
final RegisterResponse registerResponse = RegisterResponse.valueOf(entity);
ClientTestUtil.assert_(registerResponse);
JSONObject jsonObj = new JSONObject(entity);
// Registered Metadata
assertTrue(jsonObj.has(CLIENT_URI.toString()));
assertTrue(jsonObj.has(SCOPE.toString()));
JSONArray scopesJsonArray = new JSONArray(StringUtils.spaceSeparatedToList(jsonObj.getString((SCOPE.toString()))));
List<String> scopes = new ArrayList<String>();
for (int i = 0; i < scopesJsonArray.length(); i++) {
scopes.add(scopesJsonArray.get(i).toString());
}
assertTrue(scopes.contains("openid"));
assertTrue(scopes.contains("email"));
assertTrue(scopes.contains("profile"));
assertTrue(scopes.contains("clientinfo"));
} catch (JSONException e) {
e.printStackTrace();
fail(e.getMessage() + "\nResponse was: " + entity);
}
}
@Parameters({"registerPath"})
@Test(dependsOnMethods = "requestClientAssociate1")
public void requestClientRead(final String registerPath) throws Exception {
Builder request = ResteasyClientBuilder.newClient().target(url.toString() + registerPath + "?"
+ registrationClientUri1.substring(registrationClientUri1.indexOf("?") + 1)).request();
request.header("Authorization", "Bearer " + registrationAccessToken1);
Response response = request.get();
String entity = response.readEntity(String.class);
showResponse("requestClientRead", response, entity);
readResponseAssert(response, entity);
}
public static void readResponseAssert(Response response, String entity) {
assertEquals(response.getStatus(), 200, "Unexpected response code. " + entity);
assertNotNull(entity, "Unexpected result: " + entity);
try {
JSONObject jsonObj = new JSONObject(entity);
assertTrue(jsonObj.has(RegisterResponseParam.CLIENT_ID.toString()));
assertTrue(jsonObj.has(CLIENT_SECRET.toString()));
assertTrue(jsonObj.has(CLIENT_ID_ISSUED_AT.toString()));
assertTrue(jsonObj.has(CLIENT_SECRET_EXPIRES_AT.toString()));
// Registered Metadata
assertTrue(jsonObj.has(REDIRECT_URIS.toString()));
assertTrue(jsonObj.has(CLAIMS_REDIRECT_URIS.toString()));
assertTrue(jsonObj.has(APPLICATION_TYPE.toString()));
assertTrue(jsonObj.has(CLIENT_NAME.toString()));
assertTrue(jsonObj.has(ID_TOKEN_SIGNED_RESPONSE_ALG.toString()));
assertTrue(jsonObj.has(SCOPE.toString()));
} catch (JSONException e) {
e.printStackTrace();
fail(e.getMessage() + "\nResponse was: " + entity);
}
}
@Parameters({"registerPath", "redirectUris", "contactEmail1", "contactEmail2"})
@Test(dependsOnMethods = "requestClientAssociate1")
public void requestClientUpdate(final String registerPath, final String redirectUris, final String contactEmail1,
final String contactEmail2) throws Exception {
final String contactEmailNewValue = contactEmail2;
final String logoUriNewValue = "http:
final String clientUriNewValue = "http:
Builder request = ResteasyClientBuilder.newClient().target(url.toString() + registerPath + "?"
+ registrationClientUri1.substring(registrationClientUri1.indexOf("?") + 1)).request();
String registerRequestContent = null;
try {
final RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
StringUtils.spaceSeparatedToList(redirectUris));
registerRequest.setContacts(Arrays.asList(contactEmail1, contactEmailNewValue));
registerRequest.setLogoUri(logoUriNewValue);
registerRequest.setClientUri(clientUriNewValue);
request.header("Authorization", "Bearer " + registrationAccessToken1);
registerRequestContent = ServerUtil.toPrettyJson(registerRequest.getJSONParameters());
} catch (Exception e) {
e.printStackTrace();
fail();
}
Response response = request.put(Entity.json(registerRequestContent));
String entity = response.readEntity(String.class);
showResponse("requestClientRead", response, entity);
readResponseAssert(response, entity);
try {
// check whether values are really updated
RegisterRequest r = RegisterRequest.fromJson(entity, true);
assertTrue(r.getContacts() != null && r.getContacts().contains(contactEmailNewValue));
assertTrue(r.getClientUri().equals(clientUriNewValue));
assertTrue(r.getLogoUri().equals(logoUriNewValue));
} catch (JSONException e) {
e.printStackTrace();
fail(e.getMessage() + "\nResponse was: " + entity);
}
}
@Parameters({"registerPath"})
@Test
public void requestClientRegistrationFail1(final String registerPath) throws Exception {
Builder request = ResteasyClientBuilder.newClient().target(url.toString() + registerPath).request();
String registerRequestContent = null;
try {
RegisterRequest registerRequest = new RegisterRequest(null, null, null);
registerRequestContent = ServerUtil.toPrettyJson(registerRequest.getJSONParameters());
} catch (JSONException e) {
e.printStackTrace();
fail(e.getMessage());
}
Response response = request.post(Entity.json(registerRequestContent));
String entity = response.readEntity(String.class);
showResponse("requestClientRegistrationFail 1", response, entity);
assertEquals(response.getStatus(), 400, "Unexpected response code. " + entity);
TestUtil.assertErrorResponse(entity);
}
@Parameters({"registerPath"})
@Test
public void requestClientRegistrationFail2(final String registerPath) throws Exception {
Builder request = ResteasyClientBuilder.newClient().target(url.toString() + registerPath).request();
String registerRequestContent = null;
try {
RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app", null); // Missing
// redirect
// URIs
registerRequestContent = ServerUtil.toPrettyJson(registerRequest.getJSONParameters());
} catch (JSONException e) {
e.printStackTrace();
fail(e.getMessage());
}
Response response = request.post(Entity.json(registerRequestContent));
String entity = response.readEntity(String.class);
showResponse("requestClientRegistrationFail 2", response, entity);
assertEquals(response.getStatus(), 400, "Unexpected response code. " + entity);
TestUtil.assertErrorResponse(entity);
}
@Parameters({"registerPath"})
@Test
public void requestClientRegistrationFail3(final String registerPath) throws Exception {
Builder request = ResteasyClientBuilder.newClient().target(url.toString() + registerPath).request();
String registerRequestContent = null;
try {
RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
Arrays.asList("https://client.example.com/cb#fail_fragment"));
registerRequestContent = ServerUtil.toPrettyJson(registerRequest.getJSONParameters());
} catch (JSONException e) {
e.printStackTrace();
fail(e.getMessage());
}
Response response = request.post(Entity.json(registerRequestContent));
String entity = response.readEntity(String.class);
showResponse("requestClientRegistrationFail3", response, entity);
assertEquals(response.getStatus(), 400, "Unexpected response code. " + entity);
TestUtil.assertErrorResponse(entity);
}
} |
package net.wayward_realms.waywardlocks;
import net.wayward_realms.waywardlib.character.Character;
import net.wayward_realms.waywardlocks.keyring.KeyringManager;
import org.bukkit.ChatColor;
import org.bukkit.Effect;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.BlockState;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.material.TrapDoor;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class PlayerInteractListener implements Listener {
private WaywardLocks plugin;
public PlayerInteractListener(WaywardLocks plugin) {
this.plugin = plugin;
}
@SuppressWarnings("deprecation")
@EventHandler
public void onPlayerInteract(PlayerInteractEvent event) {
if (event.hasBlock()) {
if (event.getClickedBlock().getType() == Material.CHEST || event.getClickedBlock().getType() == Material.WOODEN_DOOR) {
if (plugin.isClaiming(event.getPlayer())) {
Block block = null;
xLoop: for (int x = event.getClickedBlock().getX() - 1; x <= event.getClickedBlock().getX() + 1; x++) {
for (int y = event.getClickedBlock().getY() - 1; y <= event.getClickedBlock().getY() + 1; y++) {
for (int z = event.getClickedBlock().getZ() - 1; z <= event.getClickedBlock().getZ() + 1; z++) {
if (plugin.isLocked(event.getClickedBlock().getWorld().getBlockAt(x, y, z))) {
block = event.getClickedBlock().getWorld().getBlockAt(x, y, z);
break xLoop;
}
}
}
}
if (block == null) {
if (event.getPlayer().getItemInHand().getAmount() == 1) {
event.getPlayer().setItemInHand(null);
} else {
event.getPlayer().getItemInHand().setAmount(event.getPlayer().getItemInHand().getAmount() - 1);
}
for (ItemStack item : event.getPlayer().getInventory().addItem(plugin.lock(event.getClickedBlock())).values()) {
event.getPlayer().getWorld().dropItem(event.getPlayer().getLocation(), item);
}
event.getPlayer().updateInventory();
event.getPlayer().sendMessage(plugin.getPrefix() + ChatColor.GREEN + "Block successfully locked. You've been given the key, take good care of it.");
} else {
event.getPlayer().sendMessage(plugin.getPrefix() + ChatColor.RED + "That block is already locked!");
}
event.setCancelled(true);
} else if (plugin.isUnclaiming(event.getPlayer())) {
Block block = null;
xLoop: for (int x = event.getClickedBlock().getX() - 1; x <= event.getClickedBlock().getX() + 1; x++) {
for (int y = event.getClickedBlock().getY() - 1; y <= event.getClickedBlock().getY() + 1; y++) {
for (int z = event.getClickedBlock().getZ() - 1; z <= event.getClickedBlock().getZ() + 1; z++) {
if (plugin.isLocked(event.getClickedBlock().getWorld().getBlockAt(x, y, z))) {
block = event.getClickedBlock().getWorld().getBlockAt(x, y, z);
break xLoop;
}
}
}
}
if (block != null) {
if (event.getPlayer().getItemInHand() != null
&& event.getPlayer().getItemInHand().getType() == Material.IRON_INGOT
&& event.getPlayer().getItemInHand().hasItemMeta()
&& event.getPlayer().getItemInHand().getItemMeta().hasDisplayName()
&& event.getPlayer().getItemInHand().getItemMeta().hasLore()
&& event.getPlayer().getItemInHand().getItemMeta().getDisplayName().equals("Key")
&& event.getPlayer().getItemInHand().getItemMeta().getLore().contains(block.getWorld().getName() + "," + block.getLocation().getBlockX() + "," + block.getLocation().getBlockY() + "," + block.getLocation().getBlockZ())) {
plugin.unlock(block);
event.getPlayer().sendMessage(plugin.getPrefix() + ChatColor.GREEN + "The lock was successfully removed from the " + block.getType().toString().toLowerCase().replace('_', ' '));
event.getPlayer().setItemInHand(null);
ItemStack lockItem = new ItemStack(Material.IRON_INGOT);
ItemMeta lockMeta = lockItem.getItemMeta();
lockMeta.setDisplayName("Lock");
List<String> lore = new ArrayList<>();
lore.add("Used for locking chests");
lockMeta.setLore(lore);
lockItem.setItemMeta(lockMeta);
event.getPlayer().getInventory().addItem(lockItem);
event.getPlayer().updateInventory();
} else {
event.getPlayer().sendMessage(plugin.getPrefix() + ChatColor.RED + "You must be holding the key to a lock to remove the lock.");
}
} else {
event.getPlayer().sendMessage(plugin.getPrefix() + ChatColor.RED + "There are no locked blocks there.");
}
plugin.setUnclaiming(event.getPlayer(), false);
event.setCancelled(true);
} else if (plugin.isGettingKey(event.getPlayer())) {
Block block = null;
xLoop: for (int x = event.getClickedBlock().getX() - 1; x <= event.getClickedBlock().getX() + 1; x++) {
for (int y = event.getClickedBlock().getY() - 1; y <= event.getClickedBlock().getY() + 1; y++) {
for (int z = event.getClickedBlock().getZ() - 1; z <= event.getClickedBlock().getZ() + 1; z++) {
if (plugin.isLocked(event.getClickedBlock().getWorld().getBlockAt(x, y, z))) {
block = event.getClickedBlock().getWorld().getBlockAt(x, y, z);
break xLoop;
}
}
}
}
if (block == null) {
event.getPlayer().sendMessage(plugin.getPrefix() + ChatColor.RED + "That block is not locked.");
} else {
ItemStack key = new ItemStack(Material.IRON_INGOT, 1);
ItemMeta keyMeta = key.getItemMeta();
keyMeta.setDisplayName("Key");
List<String> keyLore = new ArrayList<>();
keyLore.add(block.getWorld().getName() + "," + block.getLocation().getBlockX() + "," + block.getLocation().getBlockY() + "," + block.getLocation().getBlockZ());
keyMeta.setLore(keyLore);
key.setItemMeta(keyMeta);
for (ItemStack item : event.getPlayer().getInventory().addItem(key).values()) {
event.getPlayer().getWorld().dropItem(event.getPlayer().getLocation(), item);
}
event.getPlayer().updateInventory();
event.getPlayer().sendMessage(plugin.getPrefix() + ChatColor.GREEN + "Here is the key.");
}
plugin.setGettingKey(event.getPlayer(), false);
event.setCancelled(true);
} else {
Block block = null;
xLoop: for (int x = event.getClickedBlock().getX() - 1; x <= event.getClickedBlock().getX() + 1; x++) {
for (int y = event.getClickedBlock().getY() - 1; y <= event.getClickedBlock().getY() + 1; y++) {
for (int z = event.getClickedBlock().getZ() - 1; z <= event.getClickedBlock().getZ() + 1; z++) {
if (plugin.isLocked(event.getClickedBlock().getWorld().getBlockAt(x, y, z))) {
block = event.getClickedBlock().getWorld().getBlockAt(x, y, z);
break xLoop;
}
}
}
}
if (block != null) {
if (event.getPlayer().getItemInHand() != null) {
if (event.getPlayer().getItemInHand().hasItemMeta()) {
if (event.getPlayer().getItemInHand().getItemMeta().hasDisplayName()) {
if (event.getPlayer().getItemInHand().getItemMeta().getDisplayName().equals("Lockpick")
&& event.getPlayer().getItemInHand().getItemMeta().hasLore()
&& event.getPlayer().getItemInHand().getItemMeta().getLore().contains("Used for breaking through locks")) {
if (event.getPlayer().getItemInHand().getAmount() > 1) {
event.getPlayer().getItemInHand().setAmount(event.getPlayer().getItemInHand().getAmount() - 1);
} else {
event.getPlayer().setItemInHand(null);
}
event.getPlayer().updateInventory();
Random random = new Random();
if (random.nextInt(100) > plugin.getLockpickEfficiency(event.getPlayer())) {
event.setCancelled(true);
switch (random.nextInt(5)) {
case 0: event.getPlayer().sendMessage(plugin.getPrefix() + ChatColor.RED + "Your lockpick bent inside the lock."); break;
case 1: event.getPlayer().sendMessage(plugin.getPrefix() + ChatColor.RED + "Your lockpick snapped as you tried to use it."); break;
case 2: event.getPlayer().sendMessage(plugin.getPrefix() + ChatColor.RED + "Your lockpick seems to have gotten stuck."); break;
case 3: event.getPlayer().sendMessage(plugin.getPrefix() + ChatColor.RED + "Your lockpick twists out of shape. It looks unusable."); break;
case 4: event.getPlayer().sendMessage(plugin.getPrefix() + ChatColor.RED + "Your lockpick makes a grating sound inside the lock, but nothing happens."); break;
}
} else {
event.getPlayer().sendMessage(plugin.getPrefix() + ChatColor.GREEN + "You hear a click and the lock opens, allowing you access to the " + block.getType().toString().toLowerCase().replace('_', ' '));
if (random.nextInt(100) < 50) {
plugin.setLockpickEfficiency(event.getPlayer(), plugin.getLockpickEfficiency(event.getPlayer()) + 1);
}
final Player player = event.getPlayer();
if (block.getType() == Material.CHEST) {
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
player.closeInventory();
player.sendMessage(ChatColor.RED + "The chest snaps shut again, the lock clicking shut.");
}
}, 60L);
} else if (block.getType() == Material.WOOD_DOOR || block.getType() == Material.WOODEN_DOOR) {
final Block finalBlock = block;
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
closeDoor(finalBlock);
player.sendMessage(ChatColor.RED + "The door slams behind you, the lock clicking shut.");
}
}, 60L);
}
}
return;
}
if (!event.getPlayer().getItemInHand().getItemMeta().getDisplayName().equals("Key")
|| !event.getPlayer().getItemInHand().getItemMeta().hasLore()
|| !event.getPlayer().getItemInHand().getItemMeta().getLore().contains(block.getWorld().getName() + "," + block.getLocation().getBlockX() + "," + block.getLocation().getBlockY() + "," + block.getLocation().getBlockZ())) {
event.setCancelled(true);
event.getPlayer().sendMessage(plugin.getPrefix() + ChatColor.RED + "The " + block.getType().toString().toLowerCase().replace('_', ' ') + " seems to be locked. You would need the key or a lockpick to get in.");
}
} else {
event.setCancelled(true);
event.getPlayer().sendMessage(plugin.getPrefix() + ChatColor.RED + "The " + block.getType().toString().toLowerCase().replace('_', ' ') + " seems to be locked. You would need the key or a lockpick to get in.");
}
} else {
event.setCancelled(true);
event.getPlayer().sendMessage(plugin.getPrefix() + ChatColor.RED + "The " + block.getType().toString().toLowerCase().replace('_', ' ') + " seems to be locked. You would need the key or a lockpick to get in.");
}
} else {
event.setCancelled(true);
event.getPlayer().sendMessage(plugin.getPrefix() + ChatColor.RED + "The " + block.getType().toString().toLowerCase().replace('_', ' ') + " seems to be locked. You would need the key or a lockpick to get in.");
}
}
}
}
}
}
public boolean hasKey(Character character, Block block) {
int blockX, blockY, blockZ;
String world = block.getLocation().getWorld().toString();
blockX = (int) block.getLocation().getX();
blockY = (int) block.getLocation().getY();
blockZ = (int) block.getLocation().getZ();
for (ItemStack key : plugin.getKeyringManager().getKeyring(character)) {
if (key.getItemMeta().getLore().contains(world + "," + blockX + "," + blockY + "," + blockZ))
return true;
}
return false;
}
public boolean isDoorClosed(Block block) {
if (block.getType() == Material.TRAP_DOOR) {
TrapDoor trapdoor = (TrapDoor)block.getState().getData();
return !trapdoor.isOpen();
} else {
byte data = block.getData();
if ((data & 0x8) == 0x8) {
block = block.getRelative(BlockFace.DOWN);
data = block.getData();
}
return ((data & 0x4) == 0);
}
}
public void openDoor(Block block) {
if (block.getType() == Material.TRAP_DOOR) {
BlockState state = block.getState();
TrapDoor trapdoor = (TrapDoor)state.getData();
trapdoor.setOpen(true);
state.update();
} else {
byte data = block.getData();
if ((data & 0x8) == 0x8) {
block = block.getRelative(BlockFace.DOWN);
data = block.getData();
}
if (isDoorClosed(block)) {
data = (byte) (data | 0x4);
block.setData(data, true);
block.getWorld().playEffect(block.getLocation(), Effect.DOOR_TOGGLE, 0);
}
}
}
public void closeDoor(Block block) {
if (block.getType() == Material.TRAP_DOOR) {
BlockState state = block.getState();
TrapDoor trapdoor = (TrapDoor)state.getData();
trapdoor.setOpen(false);
state.update();
} else {
byte data = block.getData();
if ((data & 0x8) == 0x8) {
block = block.getRelative(BlockFace.DOWN);
data = block.getData();
}
if (!isDoorClosed(block)) {
data = (byte) (data & 0xb);
block.setData(data, true);
block.getWorld().playEffect(block.getLocation(), Effect.DOOR_TOGGLE, 0);
}
}
}
} |
package im.actor.core;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.ContentObserver;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.hardware.display.DisplayManager;
import android.media.MediaMetadataRetriever;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.PowerManager;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.view.Display;
import android.webkit.MimeTypeMap;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Random;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import im.actor.core.entity.Contact;
import im.actor.core.entity.Dialog;
import im.actor.core.entity.Message;
import im.actor.core.entity.Peer;
import im.actor.core.entity.SearchEntity;
import im.actor.core.entity.content.FastThumb;
import im.actor.core.network.NetworkState;
import im.actor.core.utils.AppStateActor;
import im.actor.core.utils.IOUtils;
import im.actor.core.utils.ImageHelper;
import im.actor.core.viewmodel.Command;
import im.actor.core.viewmodel.CommandCallback;
import im.actor.runtime.actors.Actor;
import im.actor.runtime.actors.ActorCreator;
import im.actor.runtime.actors.ActorRef;
import im.actor.runtime.actors.Props;
import im.actor.runtime.android.AndroidContext;
import im.actor.runtime.eventbus.EventBus;
import im.actor.runtime.generic.mvvm.BindedDisplayList;
import im.actor.runtime.mvvm.Value;
import im.actor.runtime.mvvm.ValueChangedListener;
import me.leolin.shortcutbadger.ShortcutBadger;
import static im.actor.runtime.actors.ActorSystem.system;
public class AndroidMessenger extends im.actor.core.Messenger {
private final Executor fileDownloader = Executors.newSingleThreadExecutor();
private Context context;
private final Random random = new Random();
private ActorRef appStateActor;
private BindedDisplayList<Dialog> dialogList;
private HashMap<Peer, BindedDisplayList<Message>> messagesLists = new HashMap<Peer, BindedDisplayList<Message>>();
private HashMap<Peer, BindedDisplayList<Message>> docsLists = new HashMap<Peer, BindedDisplayList<Message>>();
public AndroidMessenger(Context context, im.actor.core.Configuration configuration) {
super(configuration);
this.context = context;
this.appStateActor = system().actorOf(Props.create(new ActorCreator() {
@Override
public AppStateActor create() {
return new AppStateActor(AndroidMessenger.this);
}
}), "actor/android/state");
// Catch all phone book changes
context.getContentResolver()
.registerContentObserver(ContactsContract.Contacts.CONTENT_URI, true,
new ContentObserver(null) {
@Override
public void onChange(boolean selfChange) {
onPhoneBookChanged();
}
});
// Catch network change
context.registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager cm =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
NetworkState state;
if (isConnected) {
switch (activeNetwork.getType()) {
case ConnectivityManager.TYPE_WIFI:
case ConnectivityManager.TYPE_WIMAX:
case ConnectivityManager.TYPE_ETHERNET:
state = NetworkState.WI_FI;
break;
case ConnectivityManager.TYPE_MOBILE:
state = NetworkState.MOBILE;
break;
default:
state = NetworkState.UNKNOWN;
}
} else {
state = NetworkState.NO_CONNECTION;
}
onNetworkChanged(state);
}
}, new IntentFilter(android.net.ConnectivityManager.CONNECTIVITY_ACTION));
// Screen change processor
IntentFilter screenFilter = new IntentFilter();
screenFilter.addAction(Intent.ACTION_SCREEN_OFF);
screenFilter.addAction(Intent.ACTION_SCREEN_ON);
context.registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
appStateActor.send(new AppStateActor.OnScreenOn());
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
appStateActor.send(new AppStateActor.OnScreenOff());
}
}
}, screenFilter);
if (isScreenOn()) {
appStateActor.send(new AppStateActor.OnScreenOn());
} else {
appStateActor.send(new AppStateActor.OnScreenOff());
}
modules.getAppStateModule().getAppStateVM().getGlobalCounter().subscribe(new ValueChangedListener<Integer>() {
@Override
public void onChanged(Integer val, Value<Integer> valueModel) {
ShortcutBadger.with(AndroidContext.getContext()).count(val);
}
});
// modules.getAppStateModule().getAppStateVM().getGlobalCounter().subscribe(new ValueChangedListener<Integer>() {
// @Override
// public void onChanged(Integer val, ValueModel<Integer> valueModel) {
// ShortcutBadger.with(AndroidContext.getContext()).count(val);
}
public Context getContext() {
return context;
}
@Override
public void changeGroupAvatar(int gid, String descriptor) {
try {
Bitmap bmp = ImageHelper.loadOptimizedHQ(descriptor);
if (bmp == null) {
return;
}
String resultFileName = getExternalTempFile("image", "jpg");
if (resultFileName == null) {
return;
}
ImageHelper.save(bmp, resultFileName);
super.changeGroupAvatar(gid, resultFileName);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void changeMyAvatar(String descriptor) {
try {
Bitmap bmp = ImageHelper.loadOptimizedHQ(descriptor);
if (bmp == null) {
return;
}
String resultFileName = getExternalTempFile("image", "jpg");
if (resultFileName == null) {
return;
}
ImageHelper.save(bmp, resultFileName);
super.changeMyAvatar(resultFileName);
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendDocument(Peer peer, String fullFilePath) {
sendDocument(peer, fullFilePath, new File(fullFilePath).getName());
}
public void sendDocument(Peer peer, String fullFilePath, String fileName) {
int dot = fileName.indexOf('.');
String mimeType = null;
if (dot >= 0) {
String ext = fileName.substring(dot + 1);
mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext);
}
if (mimeType == null) {
mimeType = "application/octet-stream";
}
Bitmap fastThumb = ImageHelper.loadOptimizedHQ(fullFilePath);
if (fastThumb != null) {
fastThumb = ImageHelper.scaleFit(fastThumb, 90, 90);
byte[] fastThumbData = ImageHelper.save(fastThumb);
sendDocument(peer, fileName, mimeType,
new FastThumb(fastThumb.getWidth(), fastThumb.getHeight(), fastThumbData),
fullFilePath);
} else {
sendDocument(peer, fileName, mimeType, fullFilePath);
}
}
public void sendPhoto(Peer peer, String fullFilePath) {
sendPhoto(peer, fullFilePath, new File(fullFilePath).getName());
}
public void sendPhoto(Peer peer, String fullFilePath, String fileName) {
try {
Bitmap bmp = ImageHelper.loadOptimizedHQ(fullFilePath);
if (bmp == null) {
return;
}
Bitmap fastThumb = ImageHelper.scaleFit(bmp, 90, 90);
String resultFileName = getExternalTempFile("image", "jpg");
if (resultFileName == null) {
return;
}
ImageHelper.save(bmp, resultFileName);
byte[] fastThumbData = ImageHelper.save(fastThumb);
sendPhoto(peer, fileName, bmp.getWidth(), bmp.getHeight(), new FastThumb(fastThumb.getWidth(), fastThumb.getHeight(),
fastThumbData), resultFileName);
} catch (Throwable t) {
t.printStackTrace();
}
}
public void sendVoice(Peer peer, int duration, String fullFilePath) {
File f = new File(fullFilePath);
sendAudio(peer, f.getName(), duration, fullFilePath);
}
public void sendVideo(Peer peer, String fullFilePath) {
sendVideo(peer, fullFilePath, new File(fullFilePath).getName());
}
public void sendVideo(Peer peer, String fullFilePath, String fileName) {
try {
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
retriever.setDataSource(fullFilePath);
int duration = (int) (Long.parseLong(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)) / 1000L);
Bitmap img = retriever.getFrameAtTime(0);
int width = img.getWidth();
int height = img.getHeight();
Bitmap smallThumb = ImageHelper.scaleFit(img, 90, 90);
byte[] smallThumbData = ImageHelper.save(smallThumb);
FastThumb thumb = new FastThumb(smallThumb.getWidth(), smallThumb.getHeight(), smallThumbData);
sendVideo(peer, fileName, width, height, duration, thumb, fullFilePath);
} catch (Throwable e) {
e.printStackTrace();
}
}
public Command<Boolean> sendUri(final Peer peer, final Uri uri) {
return new Command<Boolean>() {
@Override
public void start(final CommandCallback<Boolean> callback) {
fileDownloader.execute(new Runnable() {
@Override
public void run() {
String[] filePathColumn = {MediaStore.Images.Media.DATA, MediaStore.Video.Media.MIME_TYPE,
MediaStore.Video.Media.TITLE};
String picturePath;
String mimeType;
String fileName;
Cursor cursor = context.getContentResolver().query(uri, filePathColumn, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
picturePath = cursor.getString(cursor.getColumnIndex(filePathColumn[0]));
mimeType = cursor.getString(cursor.getColumnIndex(filePathColumn[1]));
fileName = cursor.getString(cursor.getColumnIndex(filePathColumn[2]));
if (mimeType == null) {
mimeType = "?/?";
}
cursor.close();
} else {
picturePath = uri.getPath();
fileName = new File(uri.getPath()).getName();
int index = fileName.lastIndexOf(".");
if (index > 0) {
mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileName.substring(index + 1));
} else {
mimeType = "?/?";
}
}
if (picturePath == null || !uri.getScheme().equals("file")) {
File externalFile = context.getExternalFilesDir(null);
if (externalFile == null) {
callback.onError(new NullPointerException());
return;
}
String externalPath = externalFile.getAbsolutePath();
File dest = new File(externalPath + "/Actor/");
dest.mkdirs();
File outputFile = new File(dest, "upload_" + random.nextLong() + ".jpg");
picturePath = outputFile.getAbsolutePath();
try {
IOUtils.copy(context.getContentResolver().openInputStream(uri), new File(picturePath));
} catch (IOException e) {
e.printStackTrace();
callback.onError(e);
return;
}
}
if (fileName == null) {
fileName = picturePath;
}
if (mimeType.startsWith("video/")) {
sendVideo(peer, picturePath, fileName);
// trackVideoSend(peer);
} else if (mimeType.startsWith("image/")) {
sendPhoto(peer, picturePath, new File(fileName).getName());
// trackPhotoSend(peer);
} else {
sendDocument(peer, picturePath, new File(fileName).getName());
// trackDocumentSend(peer);
}
callback.onResult(true);
}
});
}
};
}
public void onActivityOpen() {
appStateActor.send(new AppStateActor.OnActivityOpened());
}
public void onActivityClosed() {
appStateActor.send(new AppStateActor.OnActivityClosed());
}
public BindedDisplayList<SearchEntity> buildSearchDisplayList() {
return (BindedDisplayList<SearchEntity>) modules.getDisplayListsModule().buildSearchList(false);
}
public BindedDisplayList<Contact> buildContactsDisplayList() {
return (BindedDisplayList<Contact>) modules.getDisplayListsModule().buildContactList(false);
}
private boolean isScreenOn() {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
DisplayManager dm = (DisplayManager) context.getSystemService(Context.DISPLAY_SERVICE);
boolean screenOn = false;
for (Display display : dm.getDisplays()) {
if (display.getState() != Display.STATE_OFF) {
screenOn = true;
}
}
return screenOn;
} else {
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
//noinspection deprecation
return pm.isScreenOn();
}
}
public String getExternalTempFile(String prefix, String postfix) {
File externalFile = context.getExternalFilesDir(null);
if (externalFile == null) {
return null;
}
String externalPath = externalFile.getAbsolutePath();
File dest = new File(externalPath + "/actor/tmp/");
dest.mkdirs();
File outputFile = new File(dest, prefix + "_" + random.nextLong() + "." + postfix);
return outputFile.getAbsolutePath();
}
public String getInternalTempFile(String prefix, String postfix) {
File externalFile = context.getFilesDir();
if (externalFile == null) {
return null;
}
String externalPath = externalFile.getAbsolutePath();
File dest = new File(externalPath + "/actor/tmp/");
dest.mkdirs();
File outputFile = new File(dest, prefix + "_" + random.nextLong() + "." + postfix);
return outputFile.getAbsolutePath();
}
public BindedDisplayList<Dialog> getDialogsDisplayList() {
if (dialogList == null) {
dialogList = (BindedDisplayList<Dialog>) modules.getDisplayListsModule().getDialogsSharedList();
dialogList.setBindHook(new BindedDisplayList.BindHook<Dialog>() {
@Override
public void onScrolledToEnd() {
modules.getMessagesModule().loadMoreDialogs();
}
@Override
public void onItemTouched(Dialog item) {
}
});
}
return dialogList;
}
public BindedDisplayList<Message> getMessageDisplayList(final Peer peer) {
if (!messagesLists.containsKey(peer)) {
BindedDisplayList<Message> list = (BindedDisplayList<Message>) modules.getDisplayListsModule().getMessagesSharedList(peer);
list.setBindHook(new BindedDisplayList.BindHook<Message>() {
@Override
public void onScrolledToEnd() {
modules.getMessagesModule().loadMoreHistory(peer);
}
@Override
public void onItemTouched(Message item) {
}
});
messagesLists.put(peer, list);
}
return messagesLists.get(peer);
}
public BindedDisplayList<Message> getDocsDisplayList(final Peer peer) {
if (!docsLists.containsKey(peer)) {
BindedDisplayList<Message> list = (BindedDisplayList<Message>) modules.getDisplayListsModule().getDocsSharedList(peer);
docsLists.put(peer, list);
}
return docsLists.get(peer);
}
public EventBus getEvents() {
return modules.getEvents();
}
} |
package net.kyori.adventure.text.renderer;
import java.text.AttributedCharacterIterator;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import net.kyori.adventure.text.BlockNBTComponent;
import net.kyori.adventure.text.BuildableComponent;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.ComponentBuilder;
import net.kyori.adventure.text.EntityNBTComponent;
import net.kyori.adventure.text.KeybindComponent;
import net.kyori.adventure.text.NBTComponent;
import net.kyori.adventure.text.NBTComponentBuilder;
import net.kyori.adventure.text.ScoreComponent;
import net.kyori.adventure.text.SelectorComponent;
import net.kyori.adventure.text.StorageNBTComponent;
import net.kyori.adventure.text.TextComponent;
import net.kyori.adventure.text.TranslatableComponent;
import net.kyori.adventure.text.event.HoverEvent;
import net.kyori.adventure.text.format.Style;
import net.kyori.adventure.translation.TranslationRegistry;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* A component renderer that does server-side translation rendering.
*
* @param <C> the context type, usually {@link java.util.Locale}.
* @see #get()
* @since 4.0.0
*/
public abstract class TranslatableComponentRenderer<C> extends AbstractComponentRenderer<C> {
static final TranslatableComponentRenderer<Locale> INSTANCE = new TranslatableComponentRenderer<Locale>() {
@Override
public MessageFormat translate(final @NonNull String key, final @NonNull Locale locale) {
return TranslationRegistry.get().translate(key, locale);
}
};
private final Set<Style.Merge> MERGES = Style.Merge.of(Style.Merge.COLOR, Style.Merge.DECORATIONS, Style.Merge.INSERTION, Style.Merge.FONT);
/**
* Gets the default translatable component renderer.
*
* @return a translatable component renderer
* @see TranslationRegistry
* @since 4.0.0
*/
public static @NonNull TranslatableComponentRenderer<Locale> get() {
return INSTANCE;
}
/**
* Gets a message format from a key and context.
*
* @param key a translation key
* @param context a context
* @return a message format or {@code null} to skip translation
*/
protected abstract @Nullable MessageFormat translate(final @NonNull String key, final @NonNull C context);
@Override
protected @NonNull Component renderBlockNbt(final @NonNull BlockNBTComponent component, final @NonNull C context) {
final BlockNBTComponent.Builder builder = nbt(BlockNBTComponent.builder(), component)
.pos(component.pos());
return this.mergeStyleAndOptionallyDeepRender(component, builder, context);
}
@Override
protected @NonNull Component renderEntityNbt(final @NonNull EntityNBTComponent component, final @NonNull C context) {
final EntityNBTComponent.Builder builder = nbt(EntityNBTComponent.builder(), component)
.selector(component.selector());
return this.mergeStyleAndOptionallyDeepRender(component, builder, context);
}
@Override
protected @NonNull Component renderStorageNbt(final @NonNull StorageNBTComponent component, final @NonNull C context) {
final StorageNBTComponent.Builder builder = nbt(StorageNBTComponent.builder(), component)
.storage(component.storage());
return this.mergeStyleAndOptionallyDeepRender(component, builder, context);
}
protected static <C extends NBTComponent<C, B>, B extends NBTComponentBuilder<C, B>> B nbt(final B builder, final C oldComponent) {
return builder
.nbtPath(oldComponent.nbtPath())
.interpret(oldComponent.interpret());
}
@Override
protected @NonNull Component renderKeybind(final @NonNull KeybindComponent component, final @NonNull C context) {
final KeybindComponent.Builder builder = KeybindComponent.builder(component.keybind());
return this.mergeStyleAndOptionallyDeepRender(component, builder, context);
}
@Override
protected @NonNull Component renderScore(final @NonNull ScoreComponent component, final @NonNull C context) {
final ScoreComponent.Builder builder = ScoreComponent.builder()
.name(component.name())
.objective(component.objective())
.value(component.value());
return this.mergeStyleAndOptionallyDeepRender(component, builder, context);
}
@Override
protected @NonNull Component renderSelector(final @NonNull SelectorComponent component, final @NonNull C context) {
final SelectorComponent.Builder builder = SelectorComponent.builder(component.pattern());
return this.mergeStyleAndOptionallyDeepRender(component, builder, context);
}
@Override
protected @NonNull Component renderText(final @NonNull TextComponent component, final @NonNull C context) {
final TextComponent.Builder builder = TextComponent.builder(component.content());
return this.mergeStyleAndOptionallyDeepRender(component, builder, context);
}
@Override
protected @NonNull Component renderTranslatable(final @NonNull TranslatableComponent component, final @NonNull C context) {
final /* @Nullable */ MessageFormat format = this.translate(component.key(), context);
if(format == null) {
// we don't have a translation for this component, but the arguments or children
// of this component might need additional rendering
final TranslatableComponent.Builder builder = TranslatableComponent.builder()
.key(component.key());
if(!component.args().isEmpty()) {
final List<Component> args = new ArrayList<>(component.args());
for(int i = 0, size = args.size(); i < size; i++) {
args.set(i, this.render(args.get(i), context));
}
builder.args(args);
}
return this.mergeStyleAndOptionallyDeepRender(component, builder, context);
}
final List<Component> args = component.args();
final TextComponent.Builder builder = TextComponent.builder();
this.mergeStyle(component, builder, context);
// no arguments makes this render very simple
if(args.isEmpty()) {
return builder.content(format.format(null, new StringBuffer(), null).toString()).build();
}
final Object[] nulls = new Object[args.size()];
final StringBuffer sb = format.format(nulls, new StringBuffer(), null);
final AttributedCharacterIterator it = format.formatToCharacterIterator(nulls);
while(it.getIndex() < it.getEndIndex()) {
final int end = it.getRunLimit();
final Integer index = (Integer) it.getAttribute(MessageFormat.Field.ARGUMENT);
if(index != null) {
builder.append(this.render(args.get(index), context));
} else {
builder.append(TextComponent.of(sb.substring(it.getIndex(), end)));
}
it.setIndex(end);
}
return this.mergeStyleAndOptionallyDeepRender(component, builder, context);
}
protected <O extends BuildableComponent<O, B>, B extends ComponentBuilder<O, B>> O mergeStyleAndOptionallyDeepRender(final Component component, final B builder, final C context) {
this.mergeStyle(component, builder, context);
return this.optionallyRenderChildrenAppendAndBuild(component.children(), builder, context);
}
protected <O extends BuildableComponent<O, B>, B extends ComponentBuilder<O, B>> O optionallyRenderChildrenAppendAndBuild(final List<Component> children, final B builder, final C context) {
if(!children.isEmpty()) {
children.forEach(child -> builder.append(this.render(child, context)));
}
return builder.build();
}
protected <B extends ComponentBuilder<?, ?>> void mergeStyle(final Component component, final B builder, final C context) {
builder.mergeStyle(component, MERGES);
builder.clickEvent(component.clickEvent());
final /* @Nullable */ HoverEvent<?> hoverEvent = component.hoverEvent();
if(hoverEvent != null) {
builder.hoverEvent(hoverEvent.withRenderedValue(this, context));
}
}
} |
package com.github.mzule.androidweekly.api.parser;
import com.github.mzule.androidweekly.entity.Article;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class FresherArticlesParser implements ArticleParser {
@Override
public List<Object> parse(String issue) throws IOException {
Document doc = DocumentProvider.get(issue);
List<Object> articles = new ArrayList<>();
Elements tables = doc.getElementsByTag("table");
String currentSection = null;
for (Element e : tables) {
Elements h2 = e.getElementsByTag("h2");
Elements h5 = e.getElementsByTag("h5");// issue-226 SPONSORED h5
if (!h2.isEmpty() || !h5.isEmpty()) {
currentSection = h2.size() > 0 ? h2.get(0).text() : h5.get(0).text();
if (!articles.contains(currentSection)) {
articles.add(currentSection);
}
} else {
Elements tds = e.getElementsByTag("td");
Element td = tds.get(tds.size() - 2);
String imageUrl = null;
if (tds.size() == 4) {
imageUrl = tds.get(0).getElementsByTag("img").get(0).attr("src");
}
String title = td.getElementsByClass("article-headline").get(0).text();
String brief = td.getElementsByTag("p").get(0).text();
String link = td.getElementsByClass("article-headline").get(0).attr("href");
String domain = td.getElementsByTag("span").get(0).text().replace("(", "").replace(")", "");
if (issue == null) {
String number = doc.getElementsByClass("issue-header").get(0).getElementsByTag("span").get(0).text();
issue = "/issues/issue-" + number.replace("
}
Article article = new Article();
article.setTitle(title);
article.setBrief(brief);
article.setLink(link);
article.setDomain(domain);
article.setIssue(issue);
article.setImageUrl(imageUrl);
article.setSection(currentSection);
articles.add(article);
}
}
return articles;
}
} |
package com.sensirion.smartgadget.view.comfort_zone;
import android.app.Activity;
import android.graphics.Color;
import android.graphics.PointF;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.UiThread;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.TextView;
import com.sensirion.smartgadget.R;
import com.sensirion.smartgadget.peripheral.rht_sensor.RHTSensorFacade;
import com.sensirion.smartgadget.peripheral.rht_sensor.RHTSensorListener;
import com.sensirion.smartgadget.peripheral.rht_sensor.internal.RHTInternalSensorManager;
import com.sensirion.smartgadget.utils.Converter;
import com.sensirion.smartgadget.utils.DeviceModel;
import com.sensirion.smartgadget.utils.Settings;
import com.sensirion.smartgadget.utils.view.ParentFragment;
import com.sensirion.smartgadget.view.comfort_zone.graph.XyPlotView;
import com.sensirion.smartgadget.view.comfort_zone.graph.XyPoint;
import java.text.NumberFormat;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import butterknife.Bind;
import butterknife.BindColor;
import butterknife.BindInt;
import butterknife.BindString;
import butterknife.ButterKnife;
import static com.sensirion.smartgadget.utils.XmlFloatExtractor.getFloatValueFromId;
/**
* A fragment representing the ComfortZone view
*/
public class ComfortZoneFragment extends ParentFragment implements OnTouchListener, RHTSensorListener {
private static final String TAG = ComfortZoneFragment.class.getSimpleName();
@BindString(R.string.graph_label_relative_humidity)
String GRAPH_LABEL_RELATIVE_HUMIDITY;
@BindInt(R.integer.comfort_zone_min_y_axis_value)
int GRAPH_MIN_Y_VALUE;
@BindInt(R.integer.comfort_zone_max_y_axis_value)
int GRAPH_MAX_Y_VALUE;
@BindInt(R.integer.comfort_zone_y_axis_grid_size)
int GRAPH_Y_GRID_SIZE;
@BindInt(R.integer.comfort_zone_min_x_axis_value)
int GRAPH_MIN_X_VALUE;
@BindInt(R.integer.comfort_zone_max_x_axis_value)
int GRAPH_MAX_X_VALUE;
@BindInt(R.integer.comfort_zone_x_axis_grid_size_celsius)
int GRAPH_X_GRID_SIZE_CELSIUS;
@BindString(R.string.graph_label_temperature_celsius)
String GRAPH_X_LABEL_CELSIUS;
@BindString(R.string.graph_label_temperature_fahrenheit)
String GRAPH_X_LABEL_FAHRENHEIT;
@BindInt(R.integer.comfort_zone_plot_view_left_padding)
int GRAPH_LEFT_PADDING;
@BindInt(R.integer.comfort_zone_plot_view_right_padding)
int GRAPH_RIGHT_PADDING;
@BindInt(R.integer.comfort_zone_plot_view_bottom_padding)
int GRAPH_BOTTOM_PADDING;
@BindColor(R.color.sensirion_grey_dark)
int SENSIRION_GREY_DARK;
@Bind(R.id.plotview)
XyPlotView mPlotView;
@Bind(R.id.textview_left)
TextView mTextViewLeft;
@Bind(R.id.textview_top)
TextView mTextViewTop;
@Bind(R.id.textview_right)
TextView mTextViewRight;
@Bind(R.id.textview_bottom)
TextView mTextViewBottom;
@BindInt(R.integer.comfort_zone_temperature_humidity_value_text_size_graph)
int TEMPERATURE_HUMIDITY_TEXT_SIZE_GRAPH;
@BindInt(R.integer.comfort_zone_temperature_humidity_label_text_size)
int TEMPERATURE_HUMIDITY_TEXT_SIZE;
@BindInt(R.integer.comfort_zone_values_text_size)
int GRAPH_LABEL_TEXT_SIZE;
@Bind(R.id.tv_sensor_name)
TextView mSensorNameTextView;
@Bind(R.id.text_amb_temp)
TextView mSensorAmbientTemperatureTextView;
@Bind(R.id.text_rh)
TextView mSensorRelativeHumidity;
@BindString(R.string.text_sensor_name_default)
String DEFAULT_SENSOR_NAME;
@BindString(R.string.label_empty_t)
String EMPTY_TEMPERATURE_STRING;
@BindString(R.string.label_empty_rh)
String EMPTY_RELATIVE_HUMIDITY_STRING;
@Bind(R.id.parentframe)
ViewGroup mParentFrame;
@BindString(R.string.char_percent)
String PERCENTAGE_CHARACTER;
@BindInt(R.integer.comfort_zone_x_axis_grid_size_fahrenheit)
int GRAPH_X_GRID_SIZE_FAHRENHEIT;
@BindInt(R.integer.comfort_zone_plot_stroke_width)
int GRAPH_STROKE_WIDTH;
private Map<String, XyPoint> mActiveSensorViews;
private boolean mIsFahrenheit;
@Override
public View onCreateView(@NonNull final LayoutInflater inflater,
@Nullable final ViewGroup container,
@Nullable final Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_comfortzone, container, false);
ButterKnife.bind(this, view);
return view;
}
@Override
public void onViewCreated(@NonNull final View view, @Nullable final Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mActiveSensorViews = Collections.synchronizedMap(new LinkedHashMap<String, XyPoint>());
final Activity parent = getParent();
if (parent == null) {
Log.e(TAG, "onViewCreated -> Received null activity");
} else {
initXyPlotView();
}
}
private void initXyPlotView() {
mPlotView.setYAxisLabel(GRAPH_LABEL_RELATIVE_HUMIDITY);
mPlotView.setYAxisScale(GRAPH_MIN_Y_VALUE, GRAPH_MAX_Y_VALUE, GRAPH_Y_GRID_SIZE);
mPlotView.setXAxisScale(GRAPH_MIN_X_VALUE, GRAPH_MAX_X_VALUE, GRAPH_X_GRID_SIZE_CELSIUS);
mPlotView.setXAxisLabel(GRAPH_X_LABEL_CELSIUS);
mPlotView.setCustomLeftPaddingPx(GRAPH_LEFT_PADDING);
mPlotView.setCustomRightPaddingPx(GRAPH_RIGHT_PADDING);
mPlotView.setCustomBottomPaddingPx(GRAPH_BOTTOM_PADDING);
mPlotView.getBorderPaint().setShadowLayer(7, 3, 3, SENSIRION_GREY_DARK);
mPlotView.getBorderPaint().setColor(Color.DKGRAY);
mPlotView.getBorderPaint().setStrokeWidth(GRAPH_STROKE_WIDTH);
mPlotView.getGridPaint().setColor(Color.GRAY);
mPlotView.getAxisGridPaint().setColor(Color.DKGRAY);
mPlotView.getAxisLabelPaint().setColor(Color.WHITE);
mPlotView.getAxisLabelPaint().setShadowLayer(3, 1, 1, Color.DKGRAY);
mPlotView.getAxisValuePaint().setColor(Color.WHITE);
mPlotView.getAxisValuePaint().setShadowLayer(1, 1, 1, Color.DKGRAY);
mPlotView.setAxisLabelTextSize(TEMPERATURE_HUMIDITY_TEXT_SIZE_GRAPH);
mPlotView.getAxisValuePaint().setTextSize(TEMPERATURE_HUMIDITY_TEXT_SIZE);
mPlotView.setAxisValueTextSize(GRAPH_LABEL_TEXT_SIZE);
mPlotView.setBackgroundImage(R.drawable.img_background_overlay);
final float cornerRadius = getFloatValueFromId(getContext(), R.dimen.comfort_zone_grid_corner_radius);
mPlotView.setGridCornerRadius(getDipFor(cornerRadius));
mTextViewLeft.bringToFront();
mTextViewTop.bringToFront();
mTextViewRight.bringToFront();
mTextViewBottom.bringToFront();
}
@Override
public void onResume() {
super.onResume();
Log.i(TAG, "onResume()");
RHTSensorFacade.getInstance().registerListener(this);
updateSensorViews();
updateViewForSelectedSeason();
updateViewForSelectedTemperatureUnit();
updateTextViewName();
touchSelectedSensorView();
}
@Override
public void onPause() {
super.onPause();
Log.i(TAG, "onPause()");
RHTSensorFacade.getInstance().unregisterListener(this);
}
private void updateSensorViews() {
final Activity parent = getParent();
if (parent == null) {
Log.e(TAG, "updateViewForSelectedSeason -> obtained null activity when calling parent.");
return;
}
getParent().runOnUiThread(new Runnable() {
@Override
public void run() {
synchronized (mActiveSensorViews) {
for (final String key : mActiveSensorViews.keySet()) {
mParentFrame.removeView(mActiveSensorViews.get(key));
}
mActiveSensorViews.clear();
}
}
});
final Iterable<DeviceModel> connectedModels = RHTSensorFacade.getInstance().getConnectedSensors();
for (final DeviceModel model : connectedModels) {
createNewSensorViewFor(model);
}
}
private void createNewSensorViewFor(@NonNull final DeviceModel model) {
final Activity parent = getParent();
if (parent == null) {
Log.e(TAG, "updateViewForSelectedSeason -> obtained null activity when calling parent.");
return;
}
final String address = model.getAddress();
try {
Log.d(TAG, String.format("createNewSensorViewFor() -> TRY address %s", address));
final XyPoint sensorPoint = new XyPoint(getContext().getApplicationContext());
sensorPoint.setVisibility(View.INVISIBLE);
sensorPoint.setTag(address);
sensorPoint.setRadius(
getDipFor(
getFloatValueFromId(getContext(), R.dimen.comfort_zone_radius_sensor_point)
)
);
sensorPoint.setOutlineRadius(
getDipFor(
getFloatValueFromId(getContext(), R.dimen.comfort_zone_radius_sensor_point) +
getFloatValueFromId(getContext(), R.dimen.comfort_zone_outline_radius_offset)
)
);
sensorPoint.setInnerColor(model.getColor());
sensorPoint.setOnTouchListener(this);
synchronized (mActiveSensorViews) {
mActiveSensorViews.put(address, sensorPoint);
}
parent.runOnUiThread(new Runnable() {
@Override
public void run() {
mParentFrame.addView(sensorPoint);
}
});
} catch (final IllegalArgumentException e) {
Log.e(TAG, "createNewSensorViewFor -> The following exception was thrown: ", e);
}
}
private void updateViewForSelectedSeason() {
final Activity parent = getParent();
if (parent == null) {
Log.e(TAG, "updateViewForSelectedSeason -> obtained null activity when calling parent.");
return;
}
final boolean isSeasonWinter = Settings.getInstance().isSeasonWinter(getContext());
Log.i(TAG,
String.format(
"updateViewForSelectedSeason(): Season %s was selected.",
isSeasonWinter ? "Winter" : "Summer"
)
);
getParent().runOnUiThread(new Runnable() {
@Override
public void run() {
mPlotView.setComfortZoneWinter(isSeasonWinter);
}
});
}
@UiThread
private void updateViewForSelectedTemperatureUnit() {
final Activity parent = getParent();
if (parent == null) {
Log.e(TAG, "updateViewForSelectedTemperatureUnit -> obtained null activity when calling parent.");
return;
}
final String mAxisLabel;
final int gridSize;
float minXAxisValue = GRAPH_MIN_X_VALUE;
float maxXAxisValue = GRAPH_MAX_X_VALUE;
mIsFahrenheit = Settings.getInstance().isTemperatureUnitFahrenheit(getContext());
if (mIsFahrenheit) {
minXAxisValue = Converter.convertToF(minXAxisValue);
maxXAxisValue = Converter.convertToF(maxXAxisValue);
gridSize = GRAPH_X_GRID_SIZE_FAHRENHEIT;
mAxisLabel = GRAPH_X_LABEL_FAHRENHEIT;
Log.d(TAG, "updateViewForSelectedTemperatureUnit -> Updating temperature unit to Fahrenheit.");
} else {
gridSize = GRAPH_X_GRID_SIZE_CELSIUS;
mAxisLabel = GRAPH_X_LABEL_CELSIUS;
Log.d(TAG, "updateViewForSelectedTemperatureUnit -> Updating temperature unit to Celsius.");
}
mPlotView.setXAxisLabel(mAxisLabel);
mPlotView.setXAxisScale(minXAxisValue, maxXAxisValue, gridSize);
parent.runOnUiThread(new Runnable() {
@Override
public void run() {
mPlotView.invalidate();
}
});
}
private void touchSelectedSensorView() {
if (isAdded()) {
final String selectedAddress = Settings.getInstance().getSelectedAddress();
final XyPoint point = mActiveSensorViews.get(selectedAddress);
if (point == null) {
Log.e(TAG,
String.format(
"touchSelectedSensorView() -> could not find XyPoint for address: %s",
selectedAddress
)
);
} else {
selectSensor(selectedAddress);
final Activity parent = getParent();
if (parent == null) {
Log.e(TAG, "touchSelectedSensorView -> obtained null activity when calling parent.");
return;
}
getParent().runOnUiThread(new Runnable() {
@Override
public void run() {
point.animateTouch();
}
});
}
}
}
@Override
public boolean onTouch(@NonNull final View view, @NonNull final MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
if (view instanceof XyPoint) {
selectSensor(view.getTag().toString());
final Activity parent = getParent();
if (parent == null) {
Log.e(TAG, "onTouch -> obtained null activity when calling parent.");
return false;
}
getParent().runOnUiThread(new Runnable() {
@Override
public void run() {
((XyPoint) view).animateTouch();
}
});
}
}
return view.performClick();
}
private void selectSensor(final String selectedAddress) {
for (final XyPoint point : mActiveSensorViews.values()) {
point.setOutlineColor(Color.TRANSPARENT);
final Activity parent = getParent();
if (parent == null) {
Log.e(TAG, "updateTextViewName -> obtained null activity when calling parent.");
return;
}
parent.runOnUiThread(new Runnable() {
@Override
public void run() {
point.invalidate();
}
});
}
XyPoint selectedPoint = mActiveSensorViews.get(selectedAddress);
if (selectedPoint != null) {
Settings.getInstance().setSelectedAddress(selectedAddress);
selectedPoint.setOutlineColor(Color.WHITE);
selectedPoint.postInvalidate();
updateTextViewName();
} else {
Log.e(TAG, "selectSensor(): no selected address found: " + selectedAddress);
}
}
private void updateTextViewName() {
try {
final String selectedAddress = Settings.getInstance().getSelectedAddress();
final DeviceModel model;
if (selectedAddress == null) {
model = null;
} else {
model = RHTSensorFacade.getInstance().getDeviceModel(selectedAddress);
}
if (model == null) {
synchronized (mActiveSensorViews) {
mActiveSensorViews.remove(selectedAddress);
}
return;
}
final Activity parent = getParent();
if (parent == null) {
Log.e(TAG, "updateTextViewName -> obtained null activity when calling parent.");
return;
}
parent.runOnUiThread(new Runnable() {
@Override
public void run() {
XyPoint selectedPoint = mActiveSensorViews.get(selectedAddress);
if (selectedPoint != null) {
mSensorNameTextView.setTextColor(selectedPoint.getInnerColor());
} else {
Log.e(TAG,
String.format(
"updateTextViewName() -> mActiveSensorViews does not selected address: %s",
selectedAddress
)
);
mSensorNameTextView.setTextColor(model.getColor());
}
mSensorNameTextView.setText(model.getUserDeviceName());
}
});
} catch (final IllegalArgumentException e) {
Log.e(TAG, "updateTextViewName(): The following exception was produced -> ", e);
}
}
/**
* {@inheritDoc}
*/
@Override
public void onGadgetConnectionChanged(@NonNull final String deviceAddress,
final boolean deviceIsConnected) {
if (isAdded()) {
if (deviceIsConnected) {
Log.d(TAG,
String.format(
"onGadgetConnectionChanged() -> Device %s was connected.",
deviceAddress
)
);
} else {
Log.d(TAG,
String.format(
"onGadgetConnectionChanged() -> Device %s was disconnected. ",
deviceAddress
)
);
if (getView() == null) {
throw new NullPointerException(
String.format(
"%s: onGadgetConnectionChanged -> It was impossible to obtain the view.",
TAG
)
);
}
removeSensorView(deviceAddress);
if (RHTSensorFacade.getInstance().hasConnectedDevices()) {
touchSelectedSensorView();
} else {
final Activity parent = getParent();
if (parent == null) {
Log.e(TAG, "onGadgetConnectionChanged -> Received null activity.");
return;
}
parent.runOnUiThread(new Runnable() {
@Override
public void run() {
mSensorNameTextView.setText(DEFAULT_SENSOR_NAME);
mSensorAmbientTemperatureTextView.setText(EMPTY_TEMPERATURE_STRING);
mSensorRelativeHumidity.setText(EMPTY_RELATIVE_HUMIDITY_STRING);
}
});
}
}
}
}
/**
* {@inheritDoc}
*/
@Override
public void onNewRHTSensorData(final float temperature,
final float relativeHumidity,
@Nullable final String deviceAddress) {
if (deviceAddress == null) {
updateViewValues(
RHTInternalSensorManager.INTERNAL_SENSOR_ADDRESS,
temperature,
relativeHumidity
);
} else {
updateViewValues(deviceAddress, temperature, relativeHumidity);
}
}
private void removeSensorView(final String deviceAddress) {
synchronized (mActiveSensorViews) {
if (mActiveSensorViews.containsKey(deviceAddress)) {
if (getView() == null) {
throw new NullPointerException(
String.format(
"%s: removeSensorView -> It was impossible to obtain the view.",
TAG
)
);
}
Log.i(TAG,
String.format(
"removeSensorView() -> The view from address %s was removed.",
deviceAddress
)
);
final Activity parent = getParent();
if (parent == null) {
Log.e(TAG, "removeSensorView() -> Obtained null when calling the activity.");
return;
}
final XyPoint stalePoint = mActiveSensorViews.get(deviceAddress);
parent.runOnUiThread(new Runnable() {
@Override
public void run() {
mParentFrame.removeView(stalePoint);
}
});
mActiveSensorViews.remove(deviceAddress);
}
}
}
public void updateViewValues(@NonNull final String address,
final float temperature,
final float relativeHumidity) {
if (isAdded()) {
final Activity parent = getParent();
if (parent == null) {
Log.e(TAG, "updateViewValues() -> Obtained null when calling the activity.");
return;
}
parent.runOnUiThread(new Runnable() {
float newTemperature = temperature;
String unit;
@Override
public void run() {
Log.v(TAG,
String.format(
"updateViewValues(): address = %s | temperature = %f | relativeHumidity = %f",
address,
temperature,
relativeHumidity
)
);
if (mIsFahrenheit) {
newTemperature = Converter.convertToF(temperature);
unit = getString(R.string.unit_fahrenheit);
} else {
newTemperature = temperature;
unit = getString(R.string.unit_celsius);
}
updateTextViewRHT(address, newTemperature, relativeHumidity, unit);
final PointF newPos = new PointF(newTemperature, relativeHumidity);
boolean isClipped = false;
if (mPlotView.isOutsideComfortZone(newPos)) {
if (mPlotView.isOutsideGrid(newPos)) {
isClipped = true;
}
}
final XyPoint selectedPoint = mActiveSensorViews.get(address);
if (selectedPoint != null) {
updateViewPositionFor(selectedPoint, newPos, isClipped);
}
}
});
}
}
private void updateTextViewRHT(@NonNull final String address,
final float temperature,
final float humidity,
final String unit) {
if (address.equals(Settings.getInstance().getSelectedAddress())) {
if (getView() == null) {
throw new NullPointerException(
String.format("%s: updateTextViewRHT -> It was impossible to obtain the view.",
TAG
)
);
}
final NumberFormat nf = NumberFormat.getNumberInstance(Locale.ENGLISH);
nf.setMaximumFractionDigits(1);
nf.setMinimumFractionDigits(1);
mSensorAmbientTemperatureTextView.setText(nf.format(temperature) + unit);
mSensorRelativeHumidity.setText(String.format("%s%sRH", nf.format(humidity), PERCENTAGE_CHARACTER));
}
}
private void updateViewPositionFor(@NonNull final XyPoint selectedPoint,
@NonNull final PointF p,
final boolean isClipped) {
final PointF canvasPosition;
if (isClipped) {
final PointF clippedPoint = mPlotView.getClippedPoint();
if (clippedPoint == null) {
Log.e(TAG, "updateViewPositionFor -> Cannot obtain the clipped point");
return;
} else {
canvasPosition = mPlotView.mapCanvasCoordinatesFor(mPlotView.getClippedPoint());
}
} else {
canvasPosition = mPlotView.mapCanvasCoordinatesFor(p);
}
animateSensorViewPointTo(selectedPoint, canvasPosition.x, canvasPosition.y);
}
private void animateSensorViewPointTo(@NonNull final XyPoint selectedPoint, final float x, final float y) {
final Activity parent = getParent();
if (parent == null) {
Log.e(TAG, "animateSensorViewPointTo() -> Obtained null when calling the activity.");
return;
}
final float relativeX =
x - (getDipFor(getFloatValueFromId(parent, R.dimen.comfort_zone_radius_sensor_point) +
getFloatValueFromId(parent, R.dimen.comfort_zone_outline_radius_offset)));
final float relativeY =
y - (getDipFor(getFloatValueFromId(parent, R.dimen.comfort_zone_radius_sensor_point) +
getFloatValueFromId(parent, R.dimen.comfort_zone_outline_radius_offset)));
parent.runOnUiThread(new Runnable() {
@Override
@UiThread
public void run() {
selectedPoint.animateMove(relativeX, relativeY);
}
});
}
private float getDipFor(final float px) {
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, px, getResources().getDisplayMetrics());
}
} |
package com.appleframework.orm.mybatis.pagehelper;
import org.apache.ibatis.builder.StaticSqlSource;
import org.apache.ibatis.builder.annotation.ProviderSqlSource;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.apache.ibatis.scripting.defaults.RawSqlSource;
import org.apache.ibatis.scripting.xmltags.DynamicSqlSource;
import org.apache.ibatis.session.RowBounds;
import com.appleframework.orm.mybatis.pagehelper.parser.Parser;
import com.appleframework.orm.mybatis.pagehelper.parser.impl.AbstractParser;
import com.appleframework.orm.mybatis.pagehelper.sqlsource.PageDynamicSqlSource;
import com.appleframework.orm.mybatis.pagehelper.sqlsource.PageProviderSqlSource;
import com.appleframework.orm.mybatis.pagehelper.sqlsource.PageRawSqlSource;
import com.appleframework.orm.mybatis.pagehelper.sqlsource.PageSqlSource;
import com.appleframework.orm.mybatis.pagehelper.sqlsource.PageStaticSqlSource;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
@SuppressWarnings({"rawtypes"})
public class SqlUtil implements Constant {
private static final ThreadLocal<Page> LOCAL_PAGE = new ThreadLocal<Page>();
//params
private static Map<String, String> PARAMS = new HashMap<String, String>(5);
//request
private static Boolean hasRequest;
private static Class<?> requestClass;
private static Method getParameterMap;
static {
try {
requestClass = Class.forName("javax.servlet.ServletRequest");
getParameterMap = requestClass.getMethod("getParameterMap", new Class[]{});
hasRequest = true;
} catch (Throwable e) {
hasRequest = false;
}
}
//countms
private static final Map<String, MappedStatement> msCountMap = new ConcurrentHashMap<String, MappedStatement>();
//RowBoundsoffsetPageNum -
private boolean offsetAsPageNo = false;
//RowBoundscount -
private boolean rowBoundsWithCount = false;
//truepagesize0RowBoundslimit=0
private boolean pageSizeZero = false;
//parser
private Parser parser;
//false
private boolean supportMethodsArguments = false;
/**
*
*
* @param strDialect
*/
public SqlUtil(String strDialect) {
if (strDialect == null || "".equals(strDialect)) {
throw new IllegalArgumentException("Mybatisdialect!");
}
Exception exception = null;
try {
Dialect dialect = Dialect.of(strDialect);
parser = AbstractParser.newParser(dialect);
} catch (Exception e) {
exception = e;
try {
Class<?> parserClass = Class.forName(strDialect);
if (Parser.class.isAssignableFrom(parserClass)) {
parser = (Parser) parserClass.newInstance();
}
} catch (ClassNotFoundException ex) {
exception = ex;
} catch (InstantiationException ex) {
exception = ex;
} catch (IllegalAccessException ex) {
exception = ex;
}
}
if (parser == null) {
throw new RuntimeException(exception);
}
}
public static Boolean getCOUNT() {
Page page = getLocalPage();
if (page != null) {
return page.getCountSignal();
}
return null;
}
/**
* Page
*
* @return
*/
public static Page getLocalPage() {
return LOCAL_PAGE.get();
}
public static void setLocalPage(Page page) {
LOCAL_PAGE.set(page);
}
public static void clearLocalPage() {
LOCAL_PAGE.remove();
}
/**
*
*
* @param params
* @return
*/
public static Page getPageFromObject(Object params) {
long pageNo;
long pageSize;
MetaObject paramsObject = null;
if (params == null) {
throw new NullPointerException("!");
}
if (hasRequest && requestClass.isAssignableFrom(params.getClass())) {
try {
paramsObject = SystemMetaObject.forObject(getParameterMap.invoke(params, new Object[]{}));
} catch (Exception e) {
}
} else {
paramsObject = SystemMetaObject.forObject(params);
}
if (paramsObject == null) {
throw new NullPointerException("!");
}
Object orderBy = getParamValue(paramsObject, "orderBy", false);
boolean hasOrderBy = false;
if (orderBy != null && orderBy.toString().length() > 0) {
hasOrderBy = true;
}
try {
Object _pageNo = getParamValue(paramsObject, "pageNo", hasOrderBy ? false : true);
Object _pageSize = getParamValue(paramsObject, "pageSize", hasOrderBy ? false : true);
if (_pageNo == null || _pageSize == null) {
Page page = new Page();
page.setOrderBy(orderBy.toString());
page.setOrderByOnly(true);
return page;
}
pageNo = Long.parseLong(String.valueOf(_pageNo));
pageSize = Long.parseLong(String.valueOf(_pageSize));
} catch (NumberFormatException e) {
throw new IllegalArgumentException("!");
}
Page page = new Page(pageNo, pageSize);
//count
Object _count = getParamValue(paramsObject, "count", false);
if (_count != null) {
page.setCount(Boolean.valueOf(String.valueOf(_count)));
}
if (hasOrderBy) {
page.setOrderBy(orderBy.toString());
}
Object pageSizeZero = getParamValue(paramsObject, "pageSizeZero", false);
if (pageSizeZero != null) {
page.setPageSizeZero(Boolean.valueOf(String.valueOf(pageSizeZero)));
}
return page;
}
/**
*
*
* @param paramsObject
* @param paramName
* @param required
* @return
*/
public static Object getParamValue(MetaObject paramsObject, String paramName, boolean required) {
Object value = null;
if (paramsObject.hasGetter(PARAMS.get(paramName))) {
value = paramsObject.getValue(PARAMS.get(paramName));
}
if (value != null && value.getClass().isArray()) {
Object[] values = (Object[]) value;
if (values.length == 0) {
value = null;
} else {
value = values[0];
}
}
if (required && value == null) {
throw new RuntimeException(":" + PARAMS.get(paramName));
}
return value;
}
/**
*
*
* @param ms
* @return
*/
public boolean isPageSqlSource(MappedStatement ms) {
if (ms.getSqlSource() instanceof PageSqlSource) {
return true;
}
return false;
}
/**
* []countsql
*
* @param dialect
* @param originalSql sql
* @deprecated 5.x
*/
@Deprecated
public static void testSql(String dialect, String originalSql) {
testSql(Dialect.of(dialect), originalSql);
}
/**
* []countsql
*
* @param dialect
* @param originalSql sql
* @deprecated 5.x
*/
@Deprecated
public static void testSql(Dialect dialect, String originalSql) {
Parser parser = AbstractParser.newParser(dialect);
if (dialect == Dialect.sqlserver) {
setLocalPage(new Page(1, 10));
}
String countSql = parser.getCountSql(originalSql);
System.out.println(countSql);
String pageSql = parser.getPageSql(originalSql);
System.out.println(pageSql);
if (dialect == Dialect.sqlserver) {
clearLocalPage();
}
}
/**
* SqlSource
*
* @param ms
* @throws Throwable
*/
public void processMappedStatement(MappedStatement ms) throws Throwable {
SqlSource sqlSource = ms.getSqlSource();
MetaObject msObject = SystemMetaObject.forObject(ms);
SqlSource pageSqlSource;
if (sqlSource instanceof StaticSqlSource) {
pageSqlSource = new PageStaticSqlSource((StaticSqlSource) sqlSource);
} else if (sqlSource instanceof RawSqlSource) {
pageSqlSource = new PageRawSqlSource((RawSqlSource) sqlSource);
} else if (sqlSource instanceof ProviderSqlSource) {
pageSqlSource = new PageProviderSqlSource((ProviderSqlSource) sqlSource);
} else if (sqlSource instanceof DynamicSqlSource) {
pageSqlSource = new PageDynamicSqlSource((DynamicSqlSource) sqlSource);
} else {
throw new RuntimeException("[" + sqlSource.getClass() + "]SqlSource");
}
msObject.setValue("sqlSource", pageSqlSource);
//countCountMS
msCountMap.put(ms.getId(), MSUtils.newCountMappedStatement(ms));
}
/**
*
*
* @param args
* @return Page
*/
public Page getPage(Object[] args) {
Page page = getLocalPage();
if (page == null || page.isOrderByOnly()) {
Page oldPage = page;
//,page.isOrderByOnly()true
if ((args[2] == null || args[2] == RowBounds.DEFAULT) && page != null) {
return oldPage;
}
if (args[2] instanceof RowBounds && args[2] != RowBounds.DEFAULT) {
RowBounds rowBounds = (RowBounds) args[2];
if (offsetAsPageNo) {
page = new Page(rowBounds.getOffset(), rowBounds.getLimit(), rowBoundsWithCount);
} else {
page = new Page(new long[]{rowBounds.getOffset(), rowBounds.getLimit()}, rowBoundsWithCount);
//offsetAsPageNo=falsePageNumreasonablefalse
}
} else {
try {
page = getPageFromObject(args[1]);
} catch (Exception e) {
return null;
}
}
if (oldPage != null) {
page.setOrderBy(oldPage.getOrderBy());
}
setLocalPage(page);
}
//truepagesize0RowBoundslimit=0
if (page.getPageSizeZero() == null) {
page.setPageSizeZero(pageSizeZero);
}
return page;
}
/**
* MybatisThreadlocal
*
* @param invocation
* @return
* @throws Throwable
*/
public Object processPage(Invocation invocation) throws Throwable {
try {
Object result = _processPage(invocation);
return result;
} finally {
clearLocalPage();
}
}
/**
* Mybatis
*
* @param invocation
* @return
* @throws Throwable
*/
private Object _processPage(Invocation invocation) throws Throwable {
final Object[] args = invocation.getArgs();
Page page = null;
//Page
if (supportMethodsArguments) {
page = getPage(args);
}
RowBounds rowBounds = (RowBounds) args[2];
//page == null
if ((supportMethodsArguments && page == null)
//LocalPageRowBounds
|| (!supportMethodsArguments && SqlUtil.getLocalPage() == null && rowBounds == RowBounds.DEFAULT)) {
return invocation.proceed();
} else {
//page==null
if (!supportMethodsArguments && page == null) {
page = getPage(args);
}
return doProcessPage(invocation, page, args);
}
}
/**
*
*
* @param page
* @return
*/
private boolean isQueryOnly(Page page) {
return page.isOrderByOnly()
|| ((page.getPageSizeZero() != null && page.getPageSizeZero()) && page.getPageSize() == 0);
}
/**
*
*
* @param page
* @param invocation
* @return
* @throws Throwable
*/
private Page doQueryOnly(Page page, Invocation invocation) throws Throwable {
page.setCountSignal(null);
Object result = invocation.proceed();
page.setList((List) result);
page.setPageNo(1);
//pageSize=total
page.setPageSize(page.getPageSize());
//total
page.setTotalCount(page.getPageSize());
//Page -
return page;
}
/**
* Mybatis
*
* @param invocation
* @return
* @throws Throwable
*/
private Page doProcessPage(Invocation invocation, Page page, Object[] args) throws Throwable {
//RowBounds
RowBounds rowBounds = (RowBounds) args[2];
MappedStatement ms = (MappedStatement) args[0];
//PageSqlSource
if (!isPageSqlSource(ms)) {
processMappedStatement(ms);
}
//parsersetThreadLocal
((PageSqlSource)ms.getSqlSource()).setParser(parser);
try {
//RowBounds-Mybatis
args[2] = RowBounds.DEFAULT;
// pageSizeZero
if (isQueryOnly(page)) {
return doQueryOnly(page, invocation);
}
//totalcount
if (page.isCount()) {
page.setCountSignal(Boolean.TRUE);
args[0] = msCountMap.get(ms.getId());
Object result = invocation.proceed();
args[0] = ms;
page.setTotalCount(Long.parseLong(String.valueOf(((List) result).get(0))));
if (page.getTotalCount() == 0) {
return page;
}
} else {
page.setTotalCount(-1l);
}
//pageSize>0pageSize<=0count
if (page.getPageSize() > 0 &&
((rowBounds == RowBounds.DEFAULT && page.getPageNo() > 0)
|| rowBounds != RowBounds.DEFAULT)) {
//MappedStatementqs
page.setCountSignal(null);
BoundSql boundSql = ms.getBoundSql(args[1]);
args[1] = parser.setPageParameter(ms, args[1], boundSql, page);
page.setCountSignal(Boolean.FALSE);
Object result = invocation.proceed();
page.setList((List) result);
}
} finally {
((PageSqlSource)ms.getSqlSource()).removeParser();
}
return page;
}
public void setOffsetAsPageNo(boolean offsetAsPageNo) {
this.offsetAsPageNo = offsetAsPageNo;
}
public void setRowBoundsWithCount(boolean rowBoundsWithCount) {
this.rowBoundsWithCount = rowBoundsWithCount;
}
public void setPageSizeZero(boolean pageSizeZero) {
this.pageSizeZero = pageSizeZero;
}
public void setSupportMethodsArguments(boolean supportMethodsArguments) {
this.supportMethodsArguments = supportMethodsArguments;
}
public static void setParams(String params) {
PARAMS.put("pageNo", "pageNo");
PARAMS.put("pageSize", "pageSize");
PARAMS.put("count", "countSql");
PARAMS.put("orderBy", "orderBy");
PARAMS.put("reasonable", "reasonable");
PARAMS.put("pageSizeZero", "pageSizeZero");
if (StringUtil.isNotEmpty(params)) {
String[] ps = params.split("[;|,|&]");
for (String s : ps) {
String[] ss = s.split("[=|:]");
if (ss.length == 2) {
PARAMS.put(ss[0], ss[1]);
}
}
}
}
public void setProperties(Properties p) {
//offsetPageNum
String offsetAsPageNo = p.getProperty("offsetAsPageNo");
this.offsetAsPageNo = Boolean.parseBoolean(offsetAsPageNo);
//RowBoundscount
String rowBoundsWithCount = p.getProperty("rowBoundsWithCount");
this.rowBoundsWithCount = Boolean.parseBoolean(rowBoundsWithCount);
//truepagesize0RowBoundslimit=0
String pageSizeZero = p.getProperty("pageSizeZero");
this.pageSizeZero = Boolean.parseBoolean(pageSizeZero);
//truefalse
//false
String supportMethodsArguments = p.getProperty("supportMethodsArguments");
this.supportMethodsArguments = Boolean.parseBoolean(supportMethodsArguments);
//offsetAsPageNo=false
setParams(p.getProperty("params"));
}
public void setSqlUtilConfig(SqlUtilConfig config) {
this.offsetAsPageNo = config.isOffsetAsPageNo();
this.rowBoundsWithCount = config.isRowBoundsWithCount();
this.pageSizeZero = config.isPageSizeZero();
this.supportMethodsArguments = config.isSupportMethodsArguments();
setParams(config.getParams());
}
} |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.eas.client.forms.api.containers;
import com.eas.client.forms.api.Component;
import com.eas.client.forms.api.Container;
import com.eas.controls.wrappers.PlatypusCardLayout;
import com.eas.script.ScriptFunction;
import java.awt.CardLayout;
import javax.swing.JPanel;
/**
*
* @author mg
*/
public class CardPane extends Container<JPanel> {
public CardPane() {
this(0, 0);
}
public CardPane(int hgap) {
this(hgap, 0);
}
private static final String CONSTRUCTOR_JSDOC = "/**\n"
+ "* A container with Card Layout. It treats each component in the container as a card. Only one card is visible at a time, and the container acts as a stack of cards.\n"
+ "* @param hgap the horizontal gap (optional)."
+ "* @param vgap the vertical gap (optional)."
+ "*/";
@ScriptFunction(jsDoc = CONSTRUCTOR_JSDOC, params = {"hgap", "vgap"})
public CardPane(int hgap, int vgap) {
super();
setDelegate(new JPanel(new PlatypusCardLayout(hgap, vgap)));
}
protected CardPane(JPanel aDelegate) {
super();
assert aDelegate != null;
assert aDelegate.getLayout() instanceof CardLayout;
setDelegate(aDelegate);
}
private static final String ADD_JSDOC = "/**\n"
+ "* Appends the component to this container with the specified name.\n"
+ "* @param component the component to add.\n"
+ "* @param cardName the name of the card.\n"
+ "*/";
@ScriptFunction(jsDoc = ADD_JSDOC)
public void add(Component<?> aComp, String aCardName) {
if (aComp != null) {
delegate.add(unwrap(aComp), aCardName);
delegate.revalidate();
delegate.repaint();
}
}
private static final String CHILD_JSDOC = "/**\n"
+ "* Gets the component with the specified name from the container.\n"
+ "* @param cardName the card name\n"
+ "*/";
@ScriptFunction(jsDoc = CHILD_JSDOC, params = {"name"})
public Component<?> child(String aCardName) {
PlatypusCardLayout layout = (PlatypusCardLayout) delegate.getLayout();
return getComponentWrapper(layout.getComponent(aCardName));
}
private static final String SHOW_JSDOC = "/**\n"
+ "* Flips to the component that was added to this layout with the specified name.\n"
+ "* @param name the card name\n"
+ "*/";
@ScriptFunction(jsDoc = SHOW_JSDOC, params = {"name"})
public void show(String aCardName) {
PlatypusCardLayout layout = (PlatypusCardLayout) delegate.getLayout();
layout.show(delegate, aCardName);
}
} |
package br.ufsc.lehmann.survey;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import com.google.common.base.Stopwatch;
import com.google.gson.Gson;
import com.google.gson.JsonIOException;
import com.google.gson.JsonSyntaxException;
import br.ufsc.core.IMeasureDistance;
import br.ufsc.core.ITrainable;
import br.ufsc.core.trajectory.SemanticTrajectory;
import br.ufsc.ftsm.base.TrajectorySimilarityCalculator;
import br.ufsc.lehmann.msm.artigo.classifiers.validation.Validation;
import br.ufsc.lehmann.msm.artigo.clusterers.ClusteringResult;
import br.ufsc.lehmann.msm.artigo.clusterers.util.DistanceMatrix.Tuple;
import br.ufsc.lehmann.msm.artigo.problems.BasicSemantic;
import br.ufsc.lehmann.msm.artigo.problems.IDataReader;
import br.ufsc.lehmann.testexecution.Dataset;
import br.ufsc.lehmann.testexecution.Datasets;
import br.ufsc.lehmann.testexecution.ExecutionPOJO;
import br.ufsc.lehmann.testexecution.Groundtruth;
import br.ufsc.lehmann.testexecution.Measure;
import br.ufsc.lehmann.testexecution.Measures;
public abstract class AbstractPairClassClusteringEvaluation {
protected void executeDescriptor(String fileName) {
ExecutionPOJO execution;
try {
execution = new Gson().fromJson(new FileReader(fileName), ExecutionPOJO.class);
} catch (JsonSyntaxException | JsonIOException | FileNotFoundException e) {
throw new RuntimeException(e);
}
Dataset dataset = execution.getDataset();
Measure measure = execution.getMeasure();
Groundtruth groundtruth = execution.getGroundtruth();
List<TrajectorySimilarityCalculator<SemanticTrajectory>> similarityCalculator = Measures.createMeasures(measure);
BasicSemantic<Object> groundtruthSemantic = new BasicSemantic<>(groundtruth.getIndex().intValue());
IDataReader dataReader = Datasets.createDataset(dataset);
List<SemanticTrajectory> data = dataReader.read();
List<Tuple<Tuple<Object, Object>, List<SemanticTrajectory>>> pairedClasses = pairClasses(data, groundtruthSemantic);
for (TrajectorySimilarityCalculator<SemanticTrajectory> calculator : similarityCalculator) {
Validation validation = new Validation(groundtruthSemantic, (IMeasureDistance<SemanticTrajectory>) calculator);
Stopwatch w = Stopwatch.createStarted();
int errorCount = 0;
for (Tuple<Tuple<Object, Object>, List<SemanticTrajectory>> tuple : pairedClasses) {
List<SemanticTrajectory> pairData = tuple.getLast();
if(calculator instanceof ITrainable) {
((ITrainable) calculator).train(pairData);
}
double[][] distances = new double[pairData.size()][pairData.size()];
IMeasureDistance<SemanticTrajectory> measurer = (IMeasureDistance<SemanticTrajectory>) calculator;
for (int i = 0; i < pairData.size(); i++) {
distances[i][i] = 0;
final int finalI = i;
IntStream.iterate(0, j -> j + 1).limit(i).parallel().forEach((j) -> {
distances[finalI][j] = measurer.distance(pairData.get(finalI), pairData.get(j));
distances[j][finalI] = distances[finalI][j];
});
}
ClusteringResult result = validation.cluster(pairData.toArray(new SemanticTrajectory[pairData.size()]), distances, 2);
List<List<SemanticTrajectory>> clusteres = result.getClusteres();
for (List<SemanticTrajectory> cluster : clusteres) {
Stream<Object> classesInCluster = cluster.stream().map(t -> groundtruthSemantic.getData(t, 0)).distinct();
//se o cluster contiver mais de uma classe este cluster est errado
if(classesInCluster.count() != 1) {
errorCount++;
break;
}
}
}
System.out.printf("Elapsed time %d miliseconds\n", w.elapsed(TimeUnit.MILLISECONDS));
System.out.printf("Parameters: '%s'\n", calculator.parametrization());
System.out.printf("Total pair-clusters: '%s'\n", pairedClasses.size());
System.out.printf("Correct pair-clusters: '%s'\n", pairedClasses.size() - errorCount);
w = w.stop();
}
}
private List<Tuple<Tuple<Object, Object>, List<SemanticTrajectory>>> pairClasses(List<SemanticTrajectory> data, BasicSemantic<Object> semantic) {
List<Object> allDistinctClasses = data.stream().map(t -> semantic.getData(t, 0)).distinct().collect(Collectors.toList());
List<Tuple<Tuple<Object, Object>, List<SemanticTrajectory>>> ret = new ArrayList<>(allDistinctClasses.size() * 2);
for (int i = 0; i < allDistinctClasses.size(); i++) {
for (int j = i + 1; j < allDistinctClasses.size(); j++) {
Tuple<Object, Object> pair = new Tuple<>(allDistinctClasses.get(i), allDistinctClasses.get(j));
int finalI = i;
int finalJ = j;
List<SemanticTrajectory> stream = data.stream().filter(t -> Arrays.asList(allDistinctClasses.get(finalI), allDistinctClasses.get(finalJ)).contains(semantic.getData(t, 0))).collect(Collectors.toList());
ret.add(new Tuple<>(pair, stream));
}
}
return ret;
}
} |
package org.geomajas.internal.layer.vector;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.geomajas.configuration.LabelStyleInfo;
import org.geomajas.configuration.NamedStyleInfo;
import org.geomajas.geometry.CrsTransform;
import org.geomajas.global.GeomajasException;
import org.geomajas.internal.layer.feature.InternalFeatureImpl;
import org.geomajas.internal.layer.feature.LazyAttributeMap;
import org.geomajas.internal.rendering.StyleFilterImpl;
import org.geomajas.layer.VectorLayer;
import org.geomajas.layer.VectorLayerService;
import org.geomajas.layer.feature.Attribute;
import org.geomajas.layer.feature.FeatureModel;
import org.geomajas.layer.feature.InternalFeature;
import org.geomajas.layer.pipeline.GetFeaturesContainer;
import org.geomajas.rendering.StyleFilter;
import org.geomajas.security.SecurityContext;
import org.geomajas.service.GeoService;
import org.geomajas.service.pipeline.PipelineCode;
import org.geomajas.service.pipeline.PipelineContext;
import org.geomajas.service.pipeline.PipelineStep;
import org.opengis.filter.Filter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.vividsolutions.jts.geom.Envelope;
import com.vividsolutions.jts.geom.Geometry;
/**
* Get features from a vector layer.
*
* @author Joachim Van der Auwera
* @author Kristof Heirwegh
*/
public class GetFeaturesEachStep implements PipelineStep<GetFeaturesContainer> {
private final Logger log = LoggerFactory.getLogger(GetFeaturesEachStep.class);
private String id;
@Autowired
private SecurityContext securityContext;
@Autowired
private GeoService geoService;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@SuppressWarnings("unchecked")
public void execute(PipelineContext context, GetFeaturesContainer response) throws GeomajasException {
List<InternalFeature> features = response.getFeatures();
log.debug("Get features, was {}", features);
if (null == features) {
features = new ArrayList<InternalFeature>();
response.setFeatures(features);
VectorLayer layer = context.get(PipelineCode.LAYER_KEY, VectorLayer.class);
Filter filter = context.get(PipelineCode.FILTER_KEY, Filter.class);
int offset = context.get(PipelineCode.OFFSET_KEY, Integer.class);
int maxResultSize = context.get(PipelineCode.MAX_RESULT_SIZE_KEY, Integer.class);
int featureIncludes = context.get(PipelineCode.FEATURE_INCLUDES_KEY, Integer.class);
String layerId = context.get(PipelineCode.LAYER_ID_KEY, String.class);
NamedStyleInfo style = context.get(PipelineCode.STYLE_KEY, NamedStyleInfo.class);
CrsTransform transformation = context.getOptional(PipelineCode.CRS_TRANSFORM_KEY, CrsTransform.class);
List<StyleFilter> styleFilters = context.getOptional(GetFeaturesStyleStep.STYLE_FILTERS_KEY, List.class);
if (log.isDebugEnabled()) {
log.debug("getElements " + filter + ", offset = " + offset + ", maxResultSize= " + maxResultSize);
}
Envelope bounds = null;
Iterator<?> it = layer.getElements(filter, 0, 0); // do not limit result here, security needs to be applied
int count = 0;
while (it.hasNext()) {
Object featureObj = it.next();
Geometry geometry = layer.getFeatureModel().getGeometry(featureObj);
InternalFeature feature = convertFeature(featureObj, geometry, layerId, layer, transformation,
styleFilters, style.getLabelStyle(), featureIncludes);
log.debug("checking feature");
if (securityContext.isFeatureVisible(layerId, feature)) {
count++;
if (count > offset) {
feature.setEditable(securityContext.isFeatureUpdateAuthorized(layerId, feature));
feature.setDeletable(securityContext.isFeatureDeleteAuthorized(layerId, feature));
features.add(feature);
if (null != geometry) {
Envelope envelope = geometry.getEnvelopeInternal();
if (null == bounds) {
bounds = new Envelope();
}
bounds.expandToInclude(envelope);
}
if (features.size() == maxResultSize) {
break;
}
}
} else {
log.debug("feature not visible");
}
}
response.setBounds(bounds);
}
log.debug("getElements done, features {}, bounds {}", response.getFeatures(), response.getBounds());
}
/**
* Convert the generic feature object (as obtained from the layer model) into a {@link InternalFeature}, with
* requested data. Part may be lazy loaded.
*
* @param feature
* A feature object that comes directly from the {@link VectorLayer}
* @param geometry
* geometry of the feature, passed in as needed in surrounding code to calc bounding box
* @param layerId
* layer id
* @param layer
* vector layer for the feature
* @param transformation
* transformation to apply to the geometry
* @param styles
* style filters to apply
* @param labelStyle
* label style
* @param featureIncludes
* aspects to include in features
* @return actual feature
* @throws GeomajasException
* oops
*/
private InternalFeature convertFeature(Object feature, Geometry geometry, String layerId, VectorLayer layer,
CrsTransform transformation, List<StyleFilter> styles, LabelStyleInfo labelStyle, int featureIncludes)
throws GeomajasException {
FeatureModel featureModel = layer.getFeatureModel();
InternalFeatureImpl res = new InternalFeatureImpl();
res.setId(featureModel.getId(feature));
res.setLayer(layer);
// If allowed, add the label to the InternalFeature:
if ((featureIncludes & VectorLayerService.FEATURE_INCLUDE_LABEL) != 0) {
String labelAttr = labelStyle.getLabelAttributeName();
Attribute attribute = featureModel.getAttribute(feature, labelAttr);
if (null != attribute && null != attribute.getValue()) {
res.setLabel(attribute.getValue().toString());
}
}
// If allowed, add the geometry (transformed!) to the InternalFeature:
if ((featureIncludes & VectorLayerService.FEATURE_INCLUDE_GEOMETRY) != 0) {
Geometry transformed;
if (null != transformation) {
transformed = geoService.transform(geometry, transformation);
} else {
transformed = geometry;
}
res.setGeometry(transformed);
}
// If allowed, add the style definition to the InternalFeature:
if ((featureIncludes & VectorLayerService.FEATURE_INCLUDE_STYLE) != 0) {
res.setStyleDefinition(findStyleFilter(feature, styles).getStyleDefinition());
}
// If allowed, add the attributes to the InternalFeature:
if ((featureIncludes & VectorLayerService.FEATURE_INCLUDE_ATTRIBUTES) != 0) {
// create the lazy feature map
LazyAttributeMap attributes = new LazyAttributeMap(featureModel, layer.getLayerInfo().getFeatureInfo(),
feature);
res.setAttributes(attributes);
filterAttributes(attributes, layerId, res);
}
return res;
}
private void filterAttributes(LazyAttributeMap attributes, String layerId, InternalFeature feature) {
for (String name : attributes.keySet()) {
if (securityContext.isAttributeReadable(layerId, feature, name)) {
attributes.setAttributeEditable(name, securityContext.isAttributeWritable(layerId, feature, name));
} else {
attributes.removeAttribute(name);
}
}
}
/**
* Find the style filter that must be applied to this feature.
*
* @param feature
* feature to find the style for
* @param styles
* style filters to select from
* @return a style filter
*/
private StyleFilter findStyleFilter(Object feature, List<StyleFilter> styles) {
for (StyleFilter styleFilter : styles) {
if (styleFilter.getFilter().evaluate(feature)) {
return styleFilter;
}
}
return new StyleFilterImpl();
}
} |
package org.openspaces.dsl.internal;
import groovy.lang.Binding;
import groovy.lang.GroovyShell;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;
import java.util.logging.Level;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.codehaus.groovy.control.CompilationFailedException;
import org.codehaus.groovy.control.CompilerConfiguration;
import org.codehaus.groovy.control.customizers.ImportCustomizer;
import org.openspaces.admin.Admin;
import org.openspaces.core.cluster.ClusterInfo;
import org.openspaces.dsl.Application;
import org.openspaces.dsl.Service;
import org.openspaces.dsl.context.ServiceContext;
public class ServiceReader {
/*****
* Private Constructor to prevent instantiation.
*
*/
private ServiceReader() {
}
public static File getServiceFileFromDir(final File serviceDir) {
return getServiceFileFromDir(serviceDir, null);
}
public static File getServiceFileFromDir(final File serviceDir, final String serviceFileName) {
final File[] files = serviceDir.listFiles(new FilenameFilter() {
@Override
public boolean accept(final File dir, final String name) {
if (serviceFileName != null) {
return name.equals(serviceFileName);
} else {
return name.endsWith("-service.groovy");
}
}
});
if (serviceFileName == null) {
if (files.length > 1) {
throw new IllegalArgumentException("Found multiple service configuration files: "
+ Arrays.toString(files) + ". " +
"Only one may be supplied in the ext folder of the PU Jar file.");
}
if (files.length == 0) {
return null;
}
return files[0];
} else {
if (files.length > 1) {
// probably not possible, but better safe then sorry
throw new IllegalArgumentException("Found multiple service configuration files: "
+ Arrays.toString(files) + ", " +
"was expecting only one file - " + serviceFileName + ".");
}
if (files.length == 0) {
return null;
}
return files[0];
}
}
/****************
* Reads a service object from a groovy DSL file placed in the given directory. The file name
* must be of the format *-service.groovy, and there must be exactly one file in the directory
* with a name that matches this format.
*
* @param dir
* the directory to scan for the DSL file.
* @return the service
* @throws Exception
*/
public static Service getServiceFromFile(final File dir) {
final File[] files = dir.listFiles(new FilenameFilter() {
@Override
public boolean accept(final File dir, final String name) {
return name.endsWith("-service.groovy");
}
});
if (files.length > 1) {
throw new IllegalArgumentException("Found multiple service configuration files: "
+ Arrays.toString(files) + ". " +
"Only one may be supplied in the ext folder of the PU Jar file.");
}
if (files.length == 0) {
return null;
}
return ServiceReader.getServiceFromFile(files[0], dir);
}
public static Service getServiceFromFile(final File dslFile, final File workDir) {
return ServiceReader.getServiceFromFile(dslFile, workDir, null, null);
}
// TODO - consider adding a DSL exception
public static Service getServiceFromFile(final File dslFile, final File workDir, final Admin admin,
final ClusterInfo clusterInfo) {
final GroovyShell gs = ServiceReader.createGroovyShellForService();
Object result = null;
try {
result = gs.evaluate(dslFile);
} catch (final CompilationFailedException e) {
throw new IllegalArgumentException("The file " + dslFile +
" could not be compiled", e);
} catch (final IOException e) {
throw new IllegalStateException("The file " + dslFile + " could not be read",
e);
}
// final Object result = Eval.me(expr);
if (result == null) {
throw new IllegalStateException("The file " + dslFile + " evaluates to null, not to a service object");
}
if (!(result instanceof Service)) {
throw new IllegalStateException("The file: " + dslFile + " did not evaluate to the required object type");
}
final Service service = (Service) result;
final ServiceContext ctx = new ServiceContext(service, admin, workDir.getAbsolutePath(), clusterInfo);
gs.getContext().setProperty("context", ctx);
return service;
}
private static GroovyShell createGroovyShellForService() {
return ServiceReader.createGroovyShell(BaseServiceScript.class.getName());
}
private static GroovyShell createGroovyShellForApplication() {
return ServiceReader.createGroovyShell(BaseApplicationScript.class.getName());
}
private static GroovyShell createGroovyShell(final String baseClassName) {
final CompilerConfiguration cc = ServiceReader.createCompilerConfiguration(baseClassName);
final Binding binding = new Binding();
final GroovyShell gs = new GroovyShell(
ServiceReader.class.getClassLoader(), // this.getClass().getClassLoader(),
binding,
cc);
return gs;
}
private static CompilerConfiguration createCompilerConfiguration(final String baseClassName) {
final CompilerConfiguration cc = new CompilerConfiguration();
final ImportCustomizer ic = new ImportCustomizer();
ic.addStarImports("org.openspaces.dsl", "org.openspaces.dsl.ui", "org.openspaces.dsl.context");
ic.addImports("org.openspaces.dsl.ui.BarLineChart.Unit");
// ic.addStaticStars(USMUtils.class.getName());
// ic.addImports(Unit.class.getName());
cc.addCompilationCustomizers(ic);
cc.setScriptBaseClass(baseClassName);
return cc;
}
// TODO - Support Zip files in application
public static Application getApplicationFromFile(final File inputFile) throws IOException {
File actualApplicationDslFile = inputFile;
if (inputFile.isFile()) {
if (inputFile.getName().endsWith(".zip") || inputFile.getName().endsWith(".jar")) {
actualApplicationDslFile = ServiceReader.unzipApplicationFile(inputFile);
}
}
final File dslFile = ServiceReader.getApplicationDslFile(actualApplicationDslFile);
final Application app = ServiceReader.readApplicationFromFile(dslFile);
final File appDir = dslFile.getParentFile();
final List<String> serviceNames = app.getServiceNames();
final List<Service> services = new ArrayList<Service>(serviceNames.size());
for (final String serviceName : serviceNames) {
final Service service = ServiceReader.readApplicationService(app, serviceName, appDir);
services.add(service);
}
app.setServices(services);
return app;
}
private static java.util.logging.Logger logger =
java.util.logging.Logger.getLogger(ServiceReader.class.getName());
private static File unzipApplicationFile(final File inputFile) throws IOException {
ZipFile zipFile = null;
try {
final File baseDir = ServiceReader.createTempDir();
zipFile = new ZipFile(inputFile);
final Enumeration<? extends ZipEntry> entries = zipFile.entries();
while (entries.hasMoreElements()) {
final ZipEntry entry = entries.nextElement();
if (entry.isDirectory()) {
logger.info("Extracting directory: " + entry.getName());
final File dir = new File(baseDir, entry.getName());
dir.mkdir();
continue;
}
logger.info("Extracting file: " + entry.getName());
final File file = new File(baseDir, entry.getName());
file.getParentFile().mkdirs();
ServiceReader.copyInputStream(zipFile.getInputStream(entry),
new BufferedOutputStream(new FileOutputStream(file)));
}
return ServiceReader.getApplicationDSLFileFromDirectory(baseDir);
} finally {
if (zipFile != null) {
try {
zipFile.close();
} catch (final IOException e) {
logger.log(Level.SEVERE, "Failed to close zip file after unzipping zip contents", e);
}
}
}
}
public static final void copyInputStream(final InputStream in, final OutputStream out)
throws IOException {
final byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) >= 0) {
out.write(buffer, 0, len);
}
in.close();
out.close();
}
protected static File createTempDir() throws IOException {
final File tempFile = File.createTempFile("GS_tmp_dir", ".application");
final String path = tempFile.getAbsolutePath();
tempFile.delete();
tempFile.mkdirs();
final File baseDir = new File(path);
return baseDir;
}
private static File getApplicationDslFile(final File inputFile) throws FileNotFoundException {
if (!inputFile.exists()) {
throw new FileNotFoundException("Could not find file: " + inputFile);
}
if (inputFile.isFile()) {
if (inputFile.getName().endsWith("-application.groovy")) {
return inputFile;
}
if (inputFile.getName().endsWith(".zip") || inputFile.getName().endsWith(".jar")) {
return ServiceReader.getApplicationDslFileFromZip(inputFile);
}
}
if (inputFile.isDirectory()) {
return ServiceReader.getApplicationDSLFileFromDirectory(inputFile);
}
throw new IllegalStateException("Could not find File: " + inputFile);
}
protected static File getApplicationDSLFileFromDirectory(final File dir) {
final File[] files = dir.listFiles(new FilenameFilter() {
@Override
public boolean accept(final File dir, final String name) {
return (name.endsWith("-application.groovy"));
}
});
if (files.length != 1) {
throw new IllegalArgumentException("Expected to find one application file, found " + files.length);
}
return files[0];
}
/********
* Given an a
*
* @param inputFile
* @return
*/
private static File getApplicationDslFileFromZip(final File inputFile) {
// TODO Auto-generated method stub
return null;
}
private static Service readApplicationService(final Application app, final String serviceName, final File appDir)
throws FileNotFoundException {
final File serviceDir = new File(appDir, serviceName);
if (!serviceDir.exists()) {
throw new FileNotFoundException("Could not find directory " + serviceDir + " for service " + serviceName);
}
return ServiceReader.getServiceFromFile(serviceDir);
}
private static Application readApplicationFromFile(final File dslFile) throws IOException {
if (!dslFile.exists()) {
throw new FileNotFoundException(dslFile.getAbsolutePath());
}
final GroovyShell gs = ServiceReader.createGroovyShellForApplication();
Object result = null;
try {
result = gs.evaluate(dslFile);
} catch (final CompilationFailedException e) {
throw new IllegalArgumentException("The file " + dslFile +
" could not be compiled", e);
} catch (final IOException e) {
throw new IllegalStateException("The file " + dslFile + " could not be read",
e);
}
// final Object result = Eval.me(expr);
if (result == null) {
throw new IllegalStateException("The file: " + dslFile + " evaluates to null, not to an application object");
}
if (!(result instanceof Application)) {
throw new IllegalStateException("The file: " + dslFile + " did not evaluate to the required object type");
}
final Application application = (Application) result;
// final ServiceContext ctx = new ServiceContext(service, admin, workDir.getAbsolutePath(),
// clusterInfo);
// gs.getContext().setProperty("context", ctx);
return application;
}
} |
package org.ovirt.engine.core.bll;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.ovirt.engine.core.bll.command.utils.StorageDomainSpaceChecker;
import org.ovirt.engine.core.bll.utils.VmDeviceUtils;
import org.ovirt.engine.core.bll.validator.StorageDomainValidator;
import org.ovirt.engine.core.common.businessentities.Disk;
import org.ovirt.engine.core.common.businessentities.DiskImage;
import org.ovirt.engine.core.common.businessentities.DiskImageBase;
import org.ovirt.engine.core.common.businessentities.DiskImageDynamic;
import org.ovirt.engine.core.common.businessentities.ImageStatus;
import org.ovirt.engine.core.common.businessentities.StorageType;
import org.ovirt.engine.core.common.businessentities.VMStatus;
import org.ovirt.engine.core.common.businessentities.VmDeviceId;
import org.ovirt.engine.core.common.businessentities.VmDynamic;
import org.ovirt.engine.core.common.businessentities.VolumeFormat;
import org.ovirt.engine.core.common.businessentities.VolumeType;
import org.ovirt.engine.core.common.businessentities.image_storage_domain_map;
import org.ovirt.engine.core.common.businessentities.image_vm_map;
import org.ovirt.engine.core.common.businessentities.storage_domain_static;
import org.ovirt.engine.core.common.businessentities.storage_domains;
import org.ovirt.engine.core.common.errors.VdcBLLException;
import org.ovirt.engine.core.common.errors.VdcBllErrors;
import org.ovirt.engine.core.common.utils.VmDeviceType;
import org.ovirt.engine.core.common.vdscommands.GetImageInfoVDSCommandParameters;
import org.ovirt.engine.core.common.vdscommands.IrsBaseVDSCommandParameters;
import org.ovirt.engine.core.common.vdscommands.VDSCommandType;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.compat.RefObject;
import org.ovirt.engine.core.compat.StringHelper;
import org.ovirt.engine.core.compat.backendcompat.Path;
import org.ovirt.engine.core.dal.VdcBllMessages;
import org.ovirt.engine.core.dal.dbbroker.DbFacade;
import org.ovirt.engine.core.utils.log.Log;
import org.ovirt.engine.core.utils.log.LogFactory;
public final class ImagesHandler {
public static final Guid BlankImageTemplateId = new Guid("00000000-0000-0000-0000-000000000000");
public static final String DefaultDriveName = "1";
public static List<DiskImage> retrieveImagesByVm(Guid vmId) {
List<DiskImage> disks = DbFacade.getInstance().getDiskImageDAO().getAllForVm(vmId);
for (DiskImage disk : disks) {
List<Guid> domainsIds = DbFacade.getInstance()
.getStorageDomainDAO()
.getAllImageStorageDomainIdsForImage(disk.getId());
disk.setstorage_ids(new ArrayList<Guid>(domainsIds));
}
return disks;
}
/**
* Adds a disk image (Adds image, disk and relevant VmDevice entities)
*
* @param image
* DiskImage to add
* @param active
* true if the image should be added as active
* @param imageStorageDomainMap
* storage domain map entry to map between the image and its storage domain
*/
public static void addDiskImage(DiskImage image, boolean active, image_storage_domain_map imageStorageDomainMap) {
try {
addImage(image, active, imageStorageDomainMap);
addDiskToVmIfNotExists(image.getDisk(), image.getvm_guid());
} catch (RuntimeException ex) {
log.error("Failed adding new disk image and related entities to db", ex);
throw new VdcBLLException(VdcBllErrors.DB, ex);
}
}
/**
* Adds a disk image (Adds image with active flag according to the value in image, using the first storage domain in
* the storage id as entry to the storage domain map)
*
* @param image
* DiskImage to add
*/
public static void addDiskImage(DiskImage image) {
addDiskImage(image, image.getactive(), new image_storage_domain_map(image.getId(),
getStorageDomainId(image)));
}
/**
* Add image and related entities to DB (Adds image, disk image dynamic and image storage domain map)
*
* @param image
* the image to add
* @param active
* if true the image will be active
* @param imageStorageDomainMap
* entry of mapping between the storage domain and the image
*/
public static void addImage(DiskImage image, boolean active, image_storage_domain_map imageStorageDomainMap) {
DbFacade.getInstance().getDiskImageDAO().save(image);
DbFacade.getInstance().getImageVmMapDAO().save(
new image_vm_map(active, image.getId(), image.getvm_guid()));
DiskImageDynamic diskDynamic = new DiskImageDynamic();
diskDynamic.setId(image.getId());
diskDynamic.setactual_size(image.getactual_size());
DbFacade.getInstance().getDiskImageDynamicDAO().save(diskDynamic);
DbFacade.getInstance()
.getStorageDomainDAO()
.addImageStorageDomainMap(imageStorageDomainMap);
}
/**
* Add disk if it does not exist to a given vm
*
* @param disk
* the disk to add
* @param vmId
* the ID of the vm to add to if the disk does not exist for this VM
*/
public static void addDiskToVmIfNotExists(Disk disk, Guid vmId) {
if (!DbFacade.getInstance().getDiskDao().exists(disk.getId())) {
addDiskToVm(disk, vmId);
}
}
/**
* Adds disk to vm
*
* @param disk
* the disk to add
* @param vmId
* the ID of the VM to add to
*/
public static void addDiskToVm(Disk disk, Guid vmId) {
DbFacade.getInstance().getDiskDao().save(disk);
VmDeviceUtils.addManagedDevice(new VmDeviceId(disk.getId(), vmId),
VmDeviceType.DISK, VmDeviceType.DISK, "", true, false);
}
/**
* This function was developed especially for GUI needs. It returns a list of all the snapshots of current image of
* a specific VM. If there are two images mapped to same VM, it's assumed that this is a TryBackToImage case and the
* function returns a list of snapshots of inactive images. In this case the parent of the active image appears to
* be trybackfrom image
*
* @param imageId
* @param imageTemplateId
* @return
*/
public static ArrayList<DiskImage> getAllImageSnapshots(Guid imageId, Guid imageTemplateId) {
ArrayList<DiskImage> snapshots = new ArrayList<DiskImage>();
Guid curImage = imageId;
while (!imageTemplateId.equals(curImage) && !curImage.equals(Guid.Empty)) {
DiskImage curDiskImage = DbFacade.getInstance().getDiskImageDAO().getSnapshotById(curImage);
snapshots.add(curDiskImage);
curImage = curDiskImage.getParentId();
}
return snapshots;
}
public static int getImagesMappedToDrive(Guid vmId, String drive, RefObject<DiskImage> activeImage,
RefObject<DiskImage> inactiveImage) {
return getImagesMappedToDrive(DbFacade.getInstance().getDiskImageDAO().getAllForVm(vmId),
drive,
activeImage,
inactiveImage);
}
public static int getImagesMappedToDrive(
List<DiskImage> disks,
String drive,
RefObject<DiskImage> activeImage,
RefObject<DiskImage> inactiveImage) {
String currentDrive = StringHelper.isNullOrEmpty(drive) ? DefaultDriveName : drive;
activeImage.argvalue = null;
inactiveImage.argvalue = null;
int count = 0;
for (DiskImage disk : disks) {
if (StringHelper.EqOp(disk.getinternal_drive_mapping(), currentDrive)) {
if (disk.getactive() != null && disk.getactive().equals(true)) {
activeImage.argvalue = disk;
} else {
inactiveImage.argvalue = disk;
}
count++;
}
}
return count;
}
public static void setStorageDomainId(DiskImage diskImage, Guid storageDomainId) {
ArrayList<Guid> storageDomainIds = new ArrayList<Guid>();
storageDomainIds.add(storageDomainId);
diskImage.setstorage_ids(storageDomainIds);
}
public static Guid getStorageDomainId(DiskImage diskImage) {
return (diskImage.getstorage_ids() != null && !diskImage.getstorage_ids().isEmpty()) ? diskImage.getstorage_ids()
.get(0)
: null;
}
public static String cdPathWindowsToLinux(String windowsPath, Guid storagePoolId) {
if (StringHelper.isNullOrEmpty(windowsPath)) {
return windowsPath; // empty string is used for 'eject'.
}
String fileName = Path.GetFileName(windowsPath);
String isoPrefix = (String) Backend.getInstance().getResourceManager()
.RunVdsCommand(VDSCommandType.IsoPrefix, new IrsBaseVDSCommandParameters(storagePoolId))
.getReturnValue();
return String.format("%1$s/%2$s", isoPrefix, fileName);
}
public static boolean isImagesExists(Iterable<DiskImage> images, Guid storagePoolId, Guid storageDomainId) {
return isImagesExists(images, storagePoolId, storageDomainId, new RefObject<ArrayList<DiskImage>>());
}
private static boolean isImagesExists(Iterable<DiskImage> images, Guid storagePoolId, Guid domainId,
RefObject<java.util.ArrayList<DiskImage>> irsImages) {
irsImages.argvalue = new java.util.ArrayList<DiskImage>();
for (DiskImage image : images) {
DiskImage fromIrs;
try {
Guid storageDomainId =
image.getstorage_ids() != null && !image.getstorage_ids().isEmpty() ? image.getstorage_ids()
.get(0) : domainId;
Guid imageGroupId = image.getimage_group_id() != null ? image.getimage_group_id().getValue()
: Guid.Empty;
fromIrs = (DiskImage) Backend
.getInstance()
.getResourceManager()
.RunVdsCommand(
VDSCommandType.GetImageInfo,
new GetImageInfoVDSCommandParameters(storagePoolId, storageDomainId, imageGroupId,
image.getId())).getReturnValue();
} catch (java.lang.Exception e) {
return false;
}
if (fromIrs == null) {
return false;
}
irsImages.argvalue.add(fromIrs);
}
return true;
}
public static boolean isVmInPreview(List<DiskImage> images) {
java.util.ArrayList<String> drives = new java.util.ArrayList<String>();
for (DiskImage image : images) {
if (drives.contains(image.getinternal_drive_mapping())) {
return true;
}
drives.add(image.getinternal_drive_mapping());
}
return false;
}
public static boolean CheckImageConfiguration(storage_domain_static storageDomain,
DiskImageBase diskInfo, java.util.ArrayList<String> messages) {
boolean result = true;
if ((diskInfo.getvolume_type() == VolumeType.Preallocated && diskInfo.getvolume_format() == VolumeFormat.COW)
|| ((storageDomain.getstorage_type() == StorageType.FCP || storageDomain.getstorage_type() == StorageType.ISCSI) && (diskInfo
.getvolume_type() == VolumeType.Sparse && diskInfo.getvolume_format() == VolumeFormat.RAW))
|| (diskInfo.getvolume_format() == VolumeFormat.Unassigned || diskInfo.getvolume_type() == VolumeType.Unassigned)) {
// not supported
result = false;
messages.add(VdcBllMessages.ACTION_TYPE_FAILED_DISK_CONFIGURATION_NOT_SUPPORTED.toString());
}
return result;
}
public static boolean CheckImagesConfiguration(Guid storageDomainId,
Collection<? extends DiskImageBase> disksConfigList,
java.util.ArrayList<String> messages) {
boolean result = true;
storage_domain_static storageDomain = DbFacade.getInstance().getStorageDomainStaticDAO().get(storageDomainId);
for (DiskImageBase diskInfo : disksConfigList) {
result = CheckImageConfiguration(storageDomain, diskInfo, messages);
if (!result)
break;
}
return result;
}
public static boolean PerformImagesChecks(Guid vmGuid,
java.util.ArrayList<String> messages,
Guid storagePoolId,
Guid storageDomainId,
boolean diskSpaceCheck,
boolean checkImagesLocked,
boolean checkImagesIllegal,
boolean checkImagesExist,
boolean checkVmInPreview,
boolean checkVmIsDown,
boolean checkStorageDomain) {
return PerformImagesChecks(vmGuid, messages, storagePoolId, storageDomainId, diskSpaceCheck,
checkImagesLocked, checkImagesIllegal, checkImagesExist, checkVmInPreview,
checkVmIsDown, checkStorageDomain, true);
}
public static boolean PerformImagesChecks(Guid vmGuid,
ArrayList<String> messages,
Guid storagePoolId,
Guid storageDomainId,
boolean diskSpaceCheck,
boolean checkImagesLocked,
boolean checkImagesIllegal,
boolean checkImagesExist,
boolean checkVmInPreview,
boolean checkVmIsDown,
boolean checkStorageDomain,
boolean checkIsValid) {
return PerformImagesChecks(vmGuid, messages, storagePoolId, storageDomainId, diskSpaceCheck,
checkImagesLocked, checkImagesIllegal, checkImagesExist, checkVmInPreview,
checkVmIsDown, checkStorageDomain, checkIsValid, null);
}
public static boolean PerformImagesChecks(Guid vmGuid,
java.util.ArrayList<String> messages,
Guid storagePoolId,
Guid storageDomainId,
boolean diskSpaceCheck,
boolean checkImagesLocked,
boolean checkImagesIllegal,
boolean checkImagesExist,
boolean checkVmInPreview,
boolean checkVmIsDown,
boolean checkStorageDomain,
boolean checkIsValid, List<DiskImage> diskImageList) {
boolean returnValue = true;
boolean isValid = checkIsValid
&& ((Boolean) Backend.getInstance().getResourceManager()
.RunVdsCommand(VDSCommandType.IsValid, new IrsBaseVDSCommandParameters(storagePoolId))
.getReturnValue()).booleanValue();
if (checkIsValid && !isValid) {
returnValue = false;
if (messages != null) {
messages.add(VdcBllMessages.ACTION_TYPE_FAILED_IMAGE_REPOSITORY_NOT_FOUND.toString());
}
} else if (checkStorageDomain) {
StorageDomainValidator storageDomainValidator =
new StorageDomainValidator(DbFacade.getInstance().getStorageDomainDAO().getForStoragePool(
storageDomainId, storagePoolId));
returnValue = storageDomainValidator.isDomainExistAndActive(messages);
}
VmDynamic vm = DbFacade.getInstance().getVmDynamicDAO().get(vmGuid);
if (returnValue && checkImagesLocked && vm.getstatus() == VMStatus.ImageLocked) {
returnValue = false;
if (messages != null) {
messages.add(VdcBllMessages.ACTION_TYPE_FAILED_VM_IMAGE_IS_LOCKED.toString());
}
} else if (returnValue && checkVmIsDown && vm.getstatus() != VMStatus.Down) {
returnValue = false;
if (messages != null) {
messages.add(VdcBllMessages.ACTION_TYPE_FAILED_VM_IS_NOT_DOWN.toString());
}
} else if (returnValue && isValid) {
List<DiskImage> images;
if (diskImageList == null) {
images = DbFacade.getInstance().getDiskImageDAO().getAllForVm(vmGuid);
} else {
images = diskImageList;
}
if (images.size() > 0) {
ArrayList<DiskImage> irsImages = null;
Guid domainId = !Guid.Empty.equals(storageDomainId) ? storageDomainId : images.get(0)
.getstorage_ids().get(0);
if (checkImagesExist) {
RefObject<ArrayList<DiskImage>> tempRefObject =
new RefObject<ArrayList<DiskImage>>();
boolean isImagesExist = isImagesExists(images, storagePoolId, domainId, tempRefObject);
irsImages = tempRefObject.argvalue;
if (!isImagesExist) {
returnValue = false;
if (messages != null) {
messages.add(VdcBllMessages.ACTION_TYPE_FAILED_VM_IMAGE_DOES_NOT_EXIST.toString());
}
}
}
if (returnValue && checkImagesIllegal) {
returnValue = CheckImagesLegality(messages, images, vm, irsImages);
}
if (returnValue && checkVmInPreview && isVmInPreview(images)) {
returnValue = false;
if (messages != null) {
messages.add(VdcBllMessages.ACTION_TYPE_FAILED_VM_IN_PREVIEW.toString());
}
}
if (returnValue && diskSpaceCheck) {
storage_domains domain = DbFacade.getInstance().getStorageDomainDAO().get(domainId);
if (!StorageDomainSpaceChecker.isBelowThresholds(domain)) {
returnValue = false;
if (messages != null) {
messages.add(VdcBllMessages.ACTION_TYPE_FAILED_DISK_SPACE_LOW.toString());
}
}
}
} else if (checkImagesExist) {
returnValue = false;
if (messages != null) {
messages.add(VdcBllMessages.ACTION_TYPE_FAILED_VM_HAS_NO_DISKS.toString());
}
}
}
return returnValue;
}
private static boolean CheckImagesLegality(List<String> messages,
List<DiskImage> images, VmDynamic vm, List<DiskImage> irsImages) {
boolean returnValue = true;
if (vm.getstatus() == VMStatus.ImageIllegal) {
returnValue = false;
if (messages != null) {
messages.add(VdcBllMessages.ACTION_TYPE_FAILED_VM_IMAGE_IS_ILLEGAL.toString());
}
} else {
int i = 0;
for (DiskImage diskImage : images) {
if (diskImage != null) {
DiskImage image = irsImages.get(i++);
if (image.getimageStatus() != ImageStatus.OK) {
diskImage.setimageStatus(image.getimageStatus());
DbFacade.getInstance().getDiskImageDAO().update(diskImage);
returnValue = false;
if (messages != null) {
messages.add(VdcBllMessages.ACTION_TYPE_FAILED_VM_IMAGE_IS_ILLEGAL.toString());
}
break;
}
}
}
}
return returnValue;
}
protected static Log log = LogFactory.getLog(ImagesHandler.class);
} |
package be.iminds.iot.dianne.command;
import be.iminds.iot.dianne.api.dataset.Dataset;
import be.iminds.iot.dianne.api.dataset.DatasetRangeAdapter;
import be.iminds.iot.dianne.api.nn.module.Input;
import be.iminds.iot.dianne.api.nn.module.Output;
import be.iminds.iot.dianne.api.nn.train.Evaluation;
import be.iminds.iot.dianne.nn.train.eval.ArgMaxEvaluator;
// helper class to separate training related commands
// that can be turned off when training bundle not deployed
// ugly, but works
public class DianneTrainCommands {
final DianneCommands commands;
public DianneTrainCommands(DianneCommands c) throws NoClassDefFoundError {
this.commands = c;
// to test whether this class is available, will throw exception otherwise
ArgMaxEvaluator test = new ArgMaxEvaluator(c.factory);
}
public void eval(String nnId, String dataset, int start, int end){
Dataset d = commands.datasets.get(dataset);
if(d==null){
System.out.println("Dataset "+dataset+" not available");
return;
}
Input input = commands.getInput(nnId);
if(input==null){
System.out.println("No Input module found for neural network "+nnId);
return;
}
Output output = commands.getOutput(nnId);
if(output==null){
System.out.println("No Output module found for neural network "+nnId);
return;
}
try {
ArgMaxEvaluator evaluator = new ArgMaxEvaluator(commands.factory);
DatasetRangeAdapter range = new DatasetRangeAdapter(d, start, end);
Evaluation eval = evaluator.evaluate(input, output, range);
System.out.println("Overall accuracy: "+eval.accuracy());
} catch(Throwable t){
t.printStackTrace();
}
}
} |
package net.acomputerdog.OBFUtil.parse.types;
import net.acomputerdog.OBFUtil.parse.FileFormatException;
import net.acomputerdog.OBFUtil.parse.FileParser;
import net.acomputerdog.OBFUtil.table.OBFTable;
import net.acomputerdog.OBFUtil.util.TargetType;
import net.acomputerdog.core.file.TextFileReader;
import java.io.*;
import java.util.regex.Pattern;
/**
* Reads and writes obfuscation data to an MCP .srg file.
*/
public class SRGFileParser implements FileParser {
private final String side;
/**
* Creates a new SRGFileParser
*
* @param side The side to read. Should be "C" or "S" (client/server). Unsided entries are always read, but will be saved as as this.
*/
public SRGFileParser(String side) {
this.side = side;
}
/**
* Loads all entries located in a File into an OBFTable.
*
* @param file The file to load from. Must exist.
* @param table The table to write to.
* @param overwrite If true overwrite existing mappings.
*/
@Override
public void loadEntries(File file, OBFTable table, boolean overwrite) throws IOException {
TextFileReader reader = null;
try {
reader = new TextFileReader(file);
int line = 0;
for (String str : reader.readAllLines()) {
line++;
String[] sections = str.split(Pattern.quote(" "));
if (sections.length < 3) {
throw new FileFormatException("Not enough sections on line " + line + ": \"" + str + "\"");
}
TargetType type = TargetType.getType(sections[0].replaceAll(Pattern.quote(":"), ""));
if (type == null) {
throw new FileFormatException("Illegal target type on line " + line + ": \"" + sections[0] + "\"");
}
if (type == TargetType.METHOD) {
if (sections.length < 5) {
throw new FileFormatException("Not enough sections on line " + line + ": \"" + str + "\"");
}
String obf = sections[1].replaceAll(Pattern.quote("/"), ".").concat(" ").concat(sections[2].replaceAll(Pattern.quote("/"), "."));
String deobf = sections[3].replaceAll(Pattern.quote("/"), ".").concat(" ").concat(sections[4].replaceAll(Pattern.quote("/"), "."));
String side = (sections.length >= 6) ? sections[5].replaceAll(Pattern.quote("
if ((overwrite || !table.hasType(type, obf)) && (side.isEmpty() || side.equals(this.side))) {
table.addType(type, obf, deobf);
}
} else {
String obf = sections[1].replaceAll(Pattern.quote("/"), ".");
String deobf = sections[2].replaceAll(Pattern.quote("/"), ".");
String side = (sections.length >= 4) ? sections[3].replaceAll(Pattern.quote("
if ((overwrite || !table.hasType(type, obf)) && (side.isEmpty() || side.equals(this.side))) {
table.addType(type, obf, deobf);
}
}
}
} finally {
if (reader != null) {
reader.close();
}
}
}
/**
* Saves all entries located in an OBFTable into a file.
*
* @param file The file to write to. Must exist.
* @param table The table to read from
* @throws java.io.IOException
*/
@Override
public void storeEntries(File file, OBFTable table) throws IOException {
Writer out = null;
try {
out = new BufferedWriter(new FileWriter(file));
for (TargetType type : TargetType.values()) {
for (String obf : table.getAllType(type)) {
String deobf = table.getType(type, obf);
out.write(getPrefix(type));
out.write(": ");
out.write(obf);
out.write(" ");
out.write(deobf);
out.write("
out.write(side);
out.write("\n");
}
}
} finally {
if (out != null) {
out.close();
}
}
}
private String getPrefix(TargetType type) {
switch (type) {
case PACKAGE:
return "PK";
case CLASS:
return "CL";
case METHOD:
return "MD";
case FIELD:
return "FD";
default:
throw new IllegalArgumentException("Invalid TargetType: " + type.name());
}
}
} |
/*
* AlleleDepthBuilder
*/
package net.maizegenetics.dna.snp.depth;
import java.util.ArrayList;
import java.util.List;
import net.maizegenetics.dna.snp.NucleotideAlignmentConstants;
import net.maizegenetics.util.SuperByteMatrix;
import net.maizegenetics.util.SuperByteMatrixBuilder;
/**
* Builder to store information on DNA read depths.
*
* @author Terry Casstevens
*/
public class AlleleDepthBuilder {
private List<SuperByteMatrix> myDepths = null;
private final boolean myIsHDF5;
private final int myMaxNumAlleles;
private final int myNumSites;
private int myNumTaxa = 0;
private AlleleDepthBuilder(boolean hdf5, int numSites, int maxNumAlleles) {
myIsHDF5 = hdf5;
myMaxNumAlleles = maxNumAlleles;
myNumSites = numSites;
if (myIsHDF5) {
} else {
myDepths = new ArrayList<>();
}
}
private AlleleDepthBuilder(boolean hdf5, int numTaxa, int numSites, int maxNumAlleles) {
myIsHDF5 = hdf5;
myMaxNumAlleles = maxNumAlleles;
myNumSites = numSites;
myNumTaxa = numTaxa;
if (myIsHDF5) {
} else {
myDepths = new ArrayList<>();
for (int i = 0; i < myNumTaxa; i++) {
myDepths.add(SuperByteMatrixBuilder.getInstance(myNumSites, myMaxNumAlleles));
}
}
}
public static AlleleDepthBuilder getInstance(int numTaxa, int numSites, int maxNumAlleles) {
return new AlleleDepthBuilder(false, numTaxa, numSites, maxNumAlleles);
}
public static AlleleDepthBuilder getNucleotideInstance(int numTaxa, int numSites) {
return new AlleleDepthBuilder(false, numTaxa, numSites, NucleotideAlignmentConstants.NUMBER_NUCLEOTIDE_ALLELES);
}
public static AlleleDepthBuilder getHDF5NucleotideInstance(int numSites) {
return new AlleleDepthBuilder(true, numSites, NucleotideAlignmentConstants.NUMBER_NUCLEOTIDE_ALLELES);
}
/**
* Set allele value for taxon, site, and allele. Value will be translated
* using AlleleDepthUtil.
*
* @param taxon taxon
* @param site site
* @param allele allele
* @param value value
*
* @return builder
*/
public AlleleDepthBuilder setDepth(int taxon, int site, byte allele, int value) {
if (myIsHDF5) {
throw new IllegalStateException("AlleleDepthBuilder: setDepth: use addTaxon for HDF5 files.");
}
myDepths.get(taxon).set(site, allele, AlleleDepthUtil.depthIntToByte(value));
return this;
}
/**
* Set allele for the all sites and alleles for a taxon simultaneously.
* Value will be translated using AlleleDepthUtil.
*
* @param taxon Index of taxon
* @param value array[sites][allele] of all values
*
* @return builder
*/
public AlleleDepthBuilder setDepth(int taxon, int[][] value) {
if (myIsHDF5) {
throw new IllegalStateException("AlleleDepthBuilder: setDepth: use addTaxon for HDF5 files.");
}
int numSites = value.length;
if (numSites != myNumSites) {
throw new IllegalArgumentException("AlleleDepthBuilder: setDepth: value number of sites: " + numSites + " should have: " + myNumSites);
}
int numAlleles = value[0].length;
if (numAlleles != myMaxNumAlleles) {
throw new IllegalArgumentException("AlleleDepthBuilder: setDepth: value number of alleles: " + numAlleles + " should have: " + myMaxNumAlleles);
}
for (int s = 0; s < myNumSites; s++) {
for (int a = 0; a < myMaxNumAlleles; a++) {
setDepth(taxon, s, (byte) a, value[s][a]);
}
}
return this;
}
/**
* Set allele value for taxon, site, and allele. Value should have already
* been translated using AlleleDepthUtil.
*
* @param taxon taxon
* @param site site
* @param allele allele
* @param value value
*
* @return builder
*/
public AlleleDepthBuilder setDepth(int taxon, int site, byte allele, byte value) {
if (myIsHDF5) {
throw new IllegalStateException("AlleleDepthBuilder: setDepth: use addTaxon for HDF5 files.");
}
myDepths.get(taxon).set(site, allele, value);
return this;
}
/**
* Set allele for the all sites and alleles for a taxon simultaneously.
* Values should have already been translated using AlleleDepthUtil.
*
* @param taxon Index of taxon
* @param value array[sites][allele] of all values
*
* @return builder
*/
public AlleleDepthBuilder setDepth(int taxon, byte[][] value) {
if (myIsHDF5) {
throw new IllegalStateException("AlleleDepthBuilder: setDepth: use addTaxon for HDF5 files.");
}
int numSites = value.length;
if (numSites != myNumSites) {
throw new IllegalArgumentException("AlleleDepthBuilder: setDepth: value number of sites: " + numSites + " should have: " + myNumSites);
}
int numAlleles = value[0].length;
if (numAlleles != myMaxNumAlleles) {
throw new IllegalArgumentException("AlleleDepthBuilder: setDepth: value number of alleles: " + numAlleles + " should have: " + myMaxNumAlleles);
}
for (int s = 0; s < myNumSites; s++) {
for (int a = 0; a < myMaxNumAlleles; a++) {
setDepth(taxon, s, (byte) a, value[s][a]);
}
}
return this;
}
/**
* Add taxon and set values for all sites and alleles for that taxon.
*
* @param taxon taxon
* @param values depth values
*
* @return builder
*/
public AlleleDepthBuilder addTaxon(int taxon, byte[][] values) {
if (myIsHDF5) {
} else {
myDepths.add(SuperByteMatrixBuilder.getInstance(myNumSites, myMaxNumAlleles));
setDepth(taxon, values);
}
return this;
}
/**
* Add taxon and set values for all sites and alleles for that taxon.
*
* @param taxon taxon
* @param values depth values
*
* @return builder
*/
public AlleleDepthBuilder addTaxon(int taxon, int[][] values) {
if (myIsHDF5) {
} else {
myDepths.add(SuperByteMatrixBuilder.getInstance(myNumSites, myMaxNumAlleles));
setDepth(taxon, values);
}
return this;
}
public AlleleDepth build() {
if (myIsHDF5) {
return null;
} else {
SuperByteMatrix[] temp = new SuperByteMatrix[myDepths.size()];
temp = myDepths.toArray(temp);
myDepths = null;
return new MemoryAlleleDepth(temp);
}
}
} |
package org.ensembl.healthcheck;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Handler;
import java.util.logging.Level;
import org.ensembl.healthcheck.util.ConnectionPool;
import org.ensembl.healthcheck.util.LogFormatter;
import org.ensembl.healthcheck.util.MyStreamHandler;
import org.ensembl.healthcheck.util.Utils;
/**
* Submit multiple NodeDatabaseTestRunners in parallel.
*/
public class ParallelDatabaseTestRunner extends TestRunner {
protected boolean debug = false;
/**
* Main run method.
*
* @param args
* Command-line arguments.
*/
protected void run(String[] args) {
parseCommandLine(args);
setupLogging();
Utils.readPropertiesFileIntoSystem(PROPERTIES_FILE);
parseProperties();
ReportManager.connectToOutputDatabase();
ReportManager.createDatabaseSession();
List databasesAndGroups = getDatabasesAndGroups();
submitJobs(databasesAndGroups, ReportManager.getSessionID());
ConnectionPool.closeAll();
} // run
/**
* Command-line entry point.
*
* @param args
* Command line args.
*/
public static void main(String[] args) {
new ParallelDatabaseTestRunner().run(args);
} // main
private void parseCommandLine(String[] args) {
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-h")) {
printUsage();
System.exit(0);
} else if (args[i].equals("-debug")) {
debug = true;
logger.finest("Running in debug mode");
}
}
} // parseCommandLine
private void printUsage() {
System.out.println("\nUsage: ParallelDatabaseTestRunner {options} \n");
System.out.println("Options:");
System.out.println(" -h This message.");
System.out.println(" -debug Print debugging info");
System.out.println();
System.out.println("All configuration information is read from the file database.properties. ");
System.out.println("See the comments in that file for information on which options to set.");
}
protected void setupLogging() {
// stop parent logger getting the message
logger.setUseParentHandlers(false);
Handler myHandler = new MyStreamHandler(System.out, new LogFormatter());
logger.addHandler(myHandler);
logger.setLevel(Level.WARNING);
if (debug) {
logger.setLevel(Level.FINEST);
}
} // setupLogging
private void parseProperties() {
if (System.getProperty("output.databases") == null) {
System.err.println("No databases specified in " + PROPERTIES_FILE);
System.exit(1);
}
if (System.getProperty("output.release") == null) {
System.err.println("No release specified in " + PROPERTIES_FILE + " - please add an output.release property");
System.exit(1);
}
}
/**
* Create a list; of database regexps and test case groups Parsed from the
* output.databases property, which should be of the form
* regexp1:group1,regexp2:group2 etc
*/
private List getDatabasesAndGroups() {
return Arrays.asList(System.getProperty("output.databases").split(","));
}
private void submitJobs(List databasesAndGroups, long sessionID) {
String dir = System.getProperty("user.dir");
Iterator it = databasesAndGroups.iterator();
while (it.hasNext()) {
String[] databaseAndGroup = ((String) it.next()).split(":");
String database = databaseAndGroup[0];
String group = databaseAndGroup[1];
String[] cmd = { "bsub", "-q", "normal", "-o", "healthcheck_%J.out", "-e", "healthcheck_%J.err",
dir + File.separator + "run-healthcheck-node.sh", "-d", database, "-group", group, "-session", "" + sessionID };
try {
Process p = Runtime.getRuntime().exec(cmd);
System.out.println("Submitted job with database regexp " + database + " and group " + group + ", session ID " + sessionID);
int returnCode = p.exitValue();
if (returnCode > 0) {
System.err.println("Error: bsub returned code " + returnCode + " for " + database + ":" + group);
}
} catch (IOException ioe) {
System.err.println("Error in head job " + ioe.getMessage());
}
}
}
} // ParallelDatabaseTestRunner |
package org.game_host.hebo.nullpomino.game.play;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Random;
import org.apache.log4j.Logger;
import org.game_host.hebo.nullpomino.game.component.BGMStatus;
import org.game_host.hebo.nullpomino.game.component.Block;
import org.game_host.hebo.nullpomino.game.component.Controller;
import org.game_host.hebo.nullpomino.game.component.Field;
import org.game_host.hebo.nullpomino.game.component.Piece;
import org.game_host.hebo.nullpomino.game.component.ReplayData;
import org.game_host.hebo.nullpomino.game.component.RuleOptions;
import org.game_host.hebo.nullpomino.game.component.SpeedParam;
import org.game_host.hebo.nullpomino.game.component.Statistics;
import org.game_host.hebo.nullpomino.game.component.WallkickResult;
import org.game_host.hebo.nullpomino.game.subsystem.ai.AIPlayer;
import net.omegaboshi.nullpomino.game.subsystem.randomizer.MemorylessRandomizer;
import net.omegaboshi.nullpomino.game.subsystem.randomizer.Randomizer;
import org.game_host.hebo.nullpomino.game.subsystem.wallkick.Wallkick;
public class GameEngine {
static Logger log = Logger.getLogger(GameEngine.class);
public static final int STAT_NOTHING = -1,
STAT_SETTING = 0,
STAT_READY = 1,
STAT_MOVE = 2,
STAT_LOCKFLASH = 3,
STAT_LINECLEAR = 4,
STAT_ARE = 5,
STAT_ENDINGSTART = 6,
STAT_CUSTOM = 7,
STAT_EXCELLENT = 8,
STAT_GAMEOVER = 9,
STAT_RESULT = 10,
STAT_FIELDEDIT = 11,
STAT_INTERRUPTITEM = 12;
public static final int MAX_STATC = 10;
public static final int LASTMOVE_NONE = 0,
LASTMOVE_FALL_AUTO = 1,
LASTMOVE_FALL_SELF = 2,
LASTMOVE_SLIDE_AIR = 3,
LASTMOVE_SLIDE_GROUND = 4,
LASTMOVE_ROTATE_AIR = 5,
LASTMOVE_ROTATE_GROUND = 6;
public static final int BLOCK_OUTLINE_NONE = 0, BLOCK_OUTLINE_NORMAL = 1, BLOCK_OUTLINE_CONNECT = 2, BLOCK_OUTLINE_SAMECOLOR = 3;
public static final int READY_START = 0, READY_END = 49, GO_START = 50, GO_END = 100;
public static final int FRAME_COLOR_BLUE = 0, FRAME_COLOR_GREEN = 1, FRAME_COLOR_RED = 2, FRAME_COLOR_GRAY = 3, FRAME_COLOR_YELLOW = 4,
FRAME_COLOR_CYAN = 5, FRAME_COLOR_PINK = 6, FRAME_COLOR_PURPLE = 7;
public static final int METER_COLOR_RED = 0, METER_COLOR_ORANGE = 1, METER_COLOR_YELLOW = 2, METER_COLOR_GREEN = 3;
/** T-Spin Mini */
public static final int TSPINMINI_TYPE_ROTATECHECK = 0, TSPINMINI_TYPE_WALLKICKFLAG = 1;
/** Spin detection type */
public static final int SPINTYPE_4POINT = 1,
SPINTYPE_IMMOBILE = 2;
public static final int COMBO_TYPE_DISABLE = 0, COMBO_TYPE_NORMAL = 1, COMBO_TYPE_DOUBLE = 2;
public static final int INTERRUPTITEM_NONE = 0,
INTERRUPTITEM_MIRROR = 1;
/** Line gravity types */
public static final int LINE_GRAVITY_NATIVE = 0, LINE_GRAVITY_CASCADE = 1;
/** Clear mode settings */
public static final int CLEAR_LINE = 0, CLEAR_COLOR = 1, CLEAR_LINE_COLOR = 2;
public static final int[] ITEM_COLOR_BRIGHT_TABLE =
{
10, 10, 9, 9, 8, 8, 8, 7, 7, 7,
6, 6, 6, 5, 5, 5, 4, 4, 4, 4,
3, 3, 3, 3, 2, 2, 2, 2, 1, 1,
1, 1, 0, 0, 0, 0, 0, 0, 0, 0
};
/** Default list of block colors to use for random block colors. */
public static final int[] BLOCK_COLORS_DEFAULT = {
Block.BLOCK_COLOR_RED,
Block.BLOCK_COLOR_ORANGE,
Block.BLOCK_COLOR_YELLOW,
Block.BLOCK_COLOR_GREEN,
Block.BLOCK_COLOR_CYAN,
Block.BLOCK_COLOR_BLUE,
Block.BLOCK_COLOR_PURPLE
};;
/** GameOwner */
public GameManager owner;
public int playerID;
public RuleOptions ruleopt;
public Wallkick wallkick;
public Randomizer randomizer;
public Field field;
public Controller ctrl;
public Statistics statistics;
public SpeedParam speed;
/** speed.denominator1 */
public int gcount;
public long randSeed;
public Random random;
public ReplayData replayData;
public AIPlayer ai;
public int aiMoveDelay;
public int aiThinkDelay;
public boolean aiUseThread;
public int stat;
public int[] statc;
/** true */
public boolean gameActive;
/** true */
public boolean timerActive;
public int replayTimer;
public long startTime;
public long endTime;
public float versionMajor;
public int versionMinor;
public float versionMinorOld;
public boolean quitflag;
public Piece nowPieceObject;
public int nowPieceX;
public int nowPieceY;
public int nowPieceBottomY;
public int nowPieceColorOverride;
public boolean[] nextPieceEnable;
/** NEXT1400 */
public int nextPieceArraySize;
/** NEXTID */
public int[] nextPieceArrayID;
/** NEXT */
public Piece[] nextPieceArrayObject;
/** NEXT */
public int nextPieceCount;
/** null: */
public Piece holdPieceObject;
/** true */
public boolean holdDisable;
public int holdUsedCount;
public int lineClearing;
/** Line gravity type (Native, Cascade, etc) */
public int lineGravityType;
/** Current number of chains */
public int chain;
/** Number of lines cleared for this chains */
public int lineGravityTotalLines;
public int lockDelayNow;
public int dasCount;
public int dasDirection;
public int dasSpeedCount;
/** Repeat statMove() for instant DAS */
public boolean dasRepeat;
/** In the middle of an instant DAS loop */
public boolean dasInstant;
/** Disallow shift while locking key is pressed */
public int shiftLock;
public int initialRotateDirection;
public int initialRotateLastDirection;
public boolean initialRotateContinuousUse;
public boolean initialHoldFlag;
public boolean initialHoldContinuousUse;
public int nowPieceMoveCount;
public int nowPieceRotateCount;
public int extendedMoveCount;
public int extendedRotateCount;
public int nowWallkickCount;
public int nowUpwardWallkickCount;
public int softdropFall;
public int harddropFall;
public boolean softdropContinuousUse;
public boolean harddropContinuousUse;
/** true */
public boolean manualLock;
public int lastmove;
/** T-Spintrue */
public boolean tspin;
/** T-Spin Minitrue */
public boolean tspinmini;
/** EZ T-spin */
public boolean tspinez;
/** B2Btrue */
public boolean b2b;
/** B2B */
public int b2bcount;
public int combo;
/** T-Spin */
public boolean tspinEnable;
/** EZ-T toggle */
public boolean tspinEnableEZ;
/** T-Spin */
public boolean tspinAllowKick;
/** T-Spin Mini */
public int tspinminiType;
/** Spin detection type */
public int spinCheckType;
public boolean useAllSpinBonus;
/** B2B */
public boolean b2bEnable;
public int comboType;
public int blockHidden;
public boolean blockHiddenAnim;
public int blockOutlineType;
public boolean blockShowOutlineOnly;
/** HIDDEN */
public boolean heboHiddenEnable;
/** HIDDEN */
public int heboHiddenTimerNow;
/** HIDDEN */
public int heboHiddenTimerMax;
/** HIDDEN */
public int heboHiddenYNow;
/** HIDDEN */
public int heboHiddenYLimit;
/** Set when ARE or line delay is canceled */
public boolean delayCancel;
/** Piece must move left after canceled delay */
public boolean delayCancelMoveLeft;
/** Piece must move right after canceled delay */
public boolean delayCancelMoveRight;
public boolean bone;
public boolean big;
public boolean bigmove;
public boolean bighalf;
/** true */
public boolean kickused;
public int fieldWidth, fieldHeight, fieldHiddenHeight;
public int ending;
public boolean staffrollEnable;
public boolean staffrollNoDeath;
public boolean staffrollEnableStatistics;
public int framecolor;
public int readyStart, readyEnd, goStart, goEnd;
/** 2READYGOtrue */
public boolean readyDone;
public int lives;
public boolean ghost;
public int meterValue;
public int meterColor;
/** ARE */
public boolean lagARE;
public boolean lagStop;
public boolean minidisplay;
public boolean enableSE;
public boolean gameoverAll;
public boolean isVisible;
/** NEXT */
public boolean isNextVisible;
public boolean isHoldVisible;
public int fldeditX, fldeditY;
public int fldeditColor;
public int fldeditPreviousStat;
public int fldeditFrames;
/** ReadyGoNEXT1 */
public boolean holdButtonNextSkip;
/** EventReceiver */
public boolean allowTextRenderByReceiver;
public boolean itemRollRollEnable;
public int itemRollRollInterval;
/** X-RAY */
public boolean itemXRayEnable;
/** X-RAY */
public int itemXRayCount;
public boolean itemColorEnable;
public int itemColorCount;
public int interruptItemNumber;
public int interruptItemPreviousStat;
public Field interruptItemMirrorField;
/** A -1= 0= 1= */
public int owRotateButtonDefaultRight;
/** -1= 0= */
public int owSkin;
/** / -1= 0= */
public int owMinDAS, owMaxDAS;
/** -1= 0= */
public int owDasDelay;
/** Clear mode selection */
public int clearMode;
/** Size needed for a color-group clear */
public int colorClearSize;
/** If true, color clears will also clear adjacent garbage blocks. */
public boolean garbageColorClear;
/** If true, each individual block is a random color. */
public boolean randomBlockColor;
/** If true, block in pieces are connected. */
public boolean connectBlocks;
/** List of block colors to use for random block colors. */
public int[] blockColors;
/** Number of colors in blockColors to use. */
public int numColors;
/** If true, line color clears can be diagonal. */
public boolean lineColorDiagonals;
/** If true, gems count as the same color as their respectively-colored normal blocks */
public boolean gemSameColor;
/** Delay for each step in cascade animations */
public int cascadeDelay;
/** Delay between landing and checking for clears in cascade */
public int cascadeClearDelay;
/**
*
* @param owner GameOwner
* @param playerID
*/
public GameEngine(GameManager owner, int playerID) {
this.owner = owner;
this.playerID = playerID;
this.ruleopt = new RuleOptions();
this.wallkick = null;
this.randomizer = null;
owRotateButtonDefaultRight = -1;
owSkin = -1;
owMinDAS = -1;
owMaxDAS = -1;
owDasDelay = -1;
}
/**
*
* @param owner GameOwner
* @param playerID
* @param ruleopt
* @param wallkick
* @param randomizer
*/
public GameEngine(GameManager owner, int playerID, RuleOptions ruleopt, Wallkick wallkick, Randomizer randomizer) {
this(owner,playerID);
this.ruleopt = ruleopt;
this.wallkick = wallkick;
this.randomizer = randomizer;
}
/**
* READY
*/
public void init() {
//log.debug("GameEngine init() playerID:" + playerID);
field = null;
ctrl = new Controller();
statistics = new Statistics();
speed = new SpeedParam();
gcount = 0;
replayData = new ReplayData();
if(owner.replayMode == false) {
versionMajor = GameManager.getVersionMajor();
versionMinor = GameManager.getVersionMinor();
versionMinorOld = GameManager.getVersionMinorOld();
Random tempRand = new Random();
randSeed = tempRand.nextLong();
random = new Random(randSeed);
} else {
versionMajor = owner.replayProp.getProperty("version.core.major", 0f);
versionMinor = owner.replayProp.getProperty("version.core.minor", 0);
versionMinorOld = owner.replayProp.getProperty("version.core.minor", 0f);
replayData.readProperty(owner.replayProp, playerID);
String tempRand = owner.replayProp.getProperty(playerID + ".replay.randSeed", "0");
randSeed = Long.parseLong(tempRand, 16);
random = new Random(randSeed);
owRotateButtonDefaultRight = owner.replayProp.getProperty(playerID + ".tuning.owRotateButtonDefaultRight", -1);
owSkin = owner.replayProp.getProperty(playerID + ".tuning.owSkin", -1);
owMinDAS = owner.replayProp.getProperty(playerID + ".tuning.owMinDAS", -1);
owMaxDAS = owner.replayProp.getProperty(playerID + ".tuning.owMaxDAS", -1);
owDasDelay = owner.replayProp.getProperty(playerID + ".tuning.owDasDelay", -1);
// Fixing old replays to accomodate for new DAS notation
if (versionMajor < 7.3) {
if (owDasDelay >= 0) {
owDasDelay++;
} else {
owDasDelay = owner.replayProp.getProperty(playerID + ".ruleopt.dasDelay", 0) + 1;
}
}
}
quitflag = false;
stat = STAT_SETTING;
statc = new int[MAX_STATC];
gameActive = false;
timerActive = false;
replayTimer = 0;
nowPieceObject = null;
nowPieceX = 0;
nowPieceY = 0;
nowPieceBottomY = 0;
nowPieceColorOverride = -1;
nextPieceArraySize = 1400;
nextPieceEnable = new boolean[Piece.PIECE_COUNT];
for(int i = 0; i < Piece.PIECE_STANDARD_COUNT; i++) nextPieceEnable[i] = true;
nextPieceArrayID = null;
nextPieceArrayObject = null;
nextPieceCount = 0;
holdPieceObject = null;
holdDisable = false;
holdUsedCount = 0;
lineClearing = 0;
lineGravityType = LINE_GRAVITY_NATIVE;
chain = 0;
lineGravityTotalLines = 0;
lockDelayNow = 0;
dasCount = 0;
dasDirection = 0;
dasSpeedCount = getDASDelay();
dasRepeat = false;
dasInstant = false;
shiftLock = 0;
initialRotateDirection = 0;
initialRotateLastDirection = 0;
initialHoldFlag = false;
initialRotateContinuousUse = false;
initialHoldContinuousUse = false;
nowPieceMoveCount = 0;
nowPieceRotateCount = 0;
extendedMoveCount = 0;
extendedRotateCount = 0;
nowWallkickCount = 0;
nowUpwardWallkickCount = 0;
softdropFall = 0;
harddropFall = 0;
softdropContinuousUse = false;
harddropContinuousUse = false;
manualLock = false;
lastmove = LASTMOVE_NONE;
tspin = false;
tspinmini = false;
tspinez = false;
b2b = false;
b2bcount = 0;
combo = 0;
tspinEnable = false;
tspinEnableEZ = false;
tspinAllowKick = true;
tspinminiType = TSPINMINI_TYPE_ROTATECHECK;
spinCheckType = SPINTYPE_4POINT;
useAllSpinBonus = false;
b2bEnable = false;
comboType = COMBO_TYPE_DISABLE;
blockHidden = -1;
blockHiddenAnim = true;
blockOutlineType = BLOCK_OUTLINE_NORMAL;
blockShowOutlineOnly = false;
heboHiddenEnable = false;
heboHiddenTimerNow = 0;
heboHiddenTimerMax = 0;
heboHiddenYNow = 0;
heboHiddenYLimit = 0;
delayCancel = false;
delayCancelMoveLeft = false;
delayCancelMoveRight = false;
bone = false;
big = false;
bigmove = true;
bighalf = true;
kickused = false;
fieldWidth = -1;
fieldHeight = -1;
fieldHiddenHeight = -1;
ending = 0;
staffrollEnable = false;
staffrollNoDeath = false;
staffrollEnableStatistics = false;
framecolor = FRAME_COLOR_BLUE;
readyStart = READY_START;
readyEnd = READY_END;
goStart = GO_START;
goEnd = GO_END;
readyDone = false;
lives = 0;
ghost = true;
meterValue = 0;
meterColor = METER_COLOR_RED;
lagARE = false;
lagStop = false;
minidisplay = (playerID >= 2);
enableSE = true;
gameoverAll = true;
isNextVisible = true;
isHoldVisible = true;
isVisible = true;
holdButtonNextSkip = false;
allowTextRenderByReceiver = true;
itemRollRollEnable = false;
itemRollRollInterval = 30;
itemXRayEnable = false;
itemXRayCount = 0;
itemColorEnable = false;
itemColorCount = 0;
interruptItemNumber = INTERRUPTITEM_NONE;
clearMode = CLEAR_LINE;
colorClearSize = -1;
garbageColorClear = false;
connectBlocks = true;
lineColorDiagonals = false;
blockColors = BLOCK_COLORS_DEFAULT;
cascadeDelay = 0;
cascadeClearDelay = 0;
if(owner.mode != null) {
owner.mode.playerInit(this, playerID);
if(owner.replayMode) owner.mode.loadReplay(this, playerID, owner.replayProp);
}
owner.receiver.playerInit(this, playerID);
if(ai != null) {
ai.shutdown(this, playerID);
ai.init(this, playerID);
}
}
public void shutdown() {
//log.debug("GameEngine shutdown() playerID:" + playerID);
if(ai != null) ai.shutdown(this, playerID);
owner = null;
ruleopt = null;
wallkick = null;
randomizer = null;
field = null;
ctrl = null;
statistics = null;
speed = null;
random = null;
replayData = null;
}
public void resetStatc() {
for(int i = 0; i < statc.length; i++) statc[i] = 0;
}
/**
* enableSEtrue
* @param name
*/
public void playSE(String name) {
if(enableSE) owner.receiver.playSE(name);
}
/**
* NEXTID
* @param c NEXT
* @return NEXTID
*/
public int getNextID(int c) {
if(nextPieceArrayID == null) return Piece.PIECE_NONE;
int c2 = c;
while(c2 >= nextPieceArrayID.length) c2 = c2 - nextPieceArrayID.length;
return nextPieceArrayID[c2];
}
/**
* NEXT
* @param c NEXT
* @return NEXT
*/
public Piece getNextObject(int c) {
if(nextPieceArrayObject == null) return null;
int c2 = c;
while(c2 >= nextPieceArrayObject.length) c2 = c2 - nextPieceArrayObject.length;
return nextPieceArrayObject[c2];
}
/**
* NEXT
* @param c NEXT
* @return NEXT
*/
public Piece getNextObjectCopy(int c) {
Piece p = getNextObject(c);
Piece r = null;
if(p != null) r = new Piece(p);
return r;
}
/**
* ARE
* @return ARE
*/
public int getARE() {
if((speed.are < ruleopt.minARE) && (ruleopt.minARE >= 0)) return ruleopt.minARE;
if((speed.are > ruleopt.maxARE) && (ruleopt.maxARE >= 0)) return ruleopt.maxARE;
return speed.are;
}
/**
* ARE
* @return ARE
*/
public int getARELine() {
if((speed.areLine < ruleopt.minARELine) && (ruleopt.minARELine >= 0)) return ruleopt.minARELine;
if((speed.areLine > ruleopt.maxARELine) && (ruleopt.maxARELine >= 0)) return ruleopt.maxARELine;
return speed.areLine;
}
/**
*
* @return
*/
public int getLineDelay() {
if((speed.lineDelay < ruleopt.minLineDelay) && (ruleopt.minLineDelay >= 0)) return ruleopt.minLineDelay;
if((speed.lineDelay > ruleopt.maxLineDelay) && (ruleopt.maxLineDelay >= 0)) return ruleopt.maxLineDelay;
return speed.lineDelay;
}
/**
*
* @return
*/
public int getLockDelay() {
if((speed.lockDelay < ruleopt.minLockDelay) && (ruleopt.minLockDelay >= 0)) return ruleopt.minLockDelay;
if((speed.lockDelay > ruleopt.maxLockDelay) && (ruleopt.maxLockDelay >= 0)) return ruleopt.maxLockDelay;
return speed.lockDelay;
}
/**
* DAS
* @return DAS
*/
public int getDAS() {
if((speed.das < owMinDAS) && (owMinDAS >= 0)) return owMinDAS;
if((speed.das > owMaxDAS) && (owMaxDAS >= 0)) return owMaxDAS;
if((speed.das < ruleopt.minDAS) && (ruleopt.minDAS >= 0)) return ruleopt.minDAS;
if((speed.das > ruleopt.maxDAS) && (ruleopt.maxDAS >= 0)) return ruleopt.maxDAS;
return speed.das;
}
/**
*
* @return
*/
public int getDASDelay() {
if((ruleopt == null) || (owDasDelay >= 0)) {
return owDasDelay;
}
return ruleopt.dasDelay;
}
/**
*
* @return
*/
public int getSkin() {
if((ruleopt == null) || (owSkin >= 0)) {
return owSkin;
}
return ruleopt.skin;
}
/**
* @return Afalsetrue
*/
public boolean isRotateButtonDefaultRight() {
if((ruleopt == null) || (owRotateButtonDefaultRight >= 0)) {
if(owRotateButtonDefaultRight == 0) return false;
else return true;
}
return ruleopt.rotateButtonDefaultRight;
}
public void resetFieldVisible() {
if(field != null) {
for(int x = 0; x < field.getWidth(); x++) {
for(int y = 0; y < field.getHeight(); y++) {
Block blk = field.getBlock(x, y);
if((blk != null) && (blk.color > Block.BLOCK_COLOR_NONE)) {
blk.alpha = 1f;
blk.darkness = 0f;
blk.setAttribute(Block.BLOCK_ATTRIBUTE_VISIBLE, true);
blk.setAttribute(Block.BLOCK_ATTRIBUTE_OUTLINE, true);
}
}
}
}
}
public void checkDropContinuousUse() {
if(gameActive) {
if((!ctrl.isPress(Controller.BUTTON_DOWN)) || (!ruleopt.softdropLimit))
softdropContinuousUse = false;
if((!ctrl.isPress(Controller.BUTTON_UP)) || (!ruleopt.harddropLimit))
harddropContinuousUse = false;
if((!ctrl.isPress(Controller.BUTTON_D)) || (!ruleopt.holdInitialLimit))
initialHoldContinuousUse = false;
if(!ruleopt.rotateInitialLimit)
initialRotateContinuousUse = false;
if(initialRotateContinuousUse) {
int dir = 0;
if(ctrl.isPress(Controller.BUTTON_A) || ctrl.isPress(Controller.BUTTON_C)) dir = -1;
else if(ctrl.isPress(Controller.BUTTON_B)) dir = 1;
else if(ctrl.isPress(Controller.BUTTON_E)) dir = 2;
if((initialRotateLastDirection != dir) || (dir == 0))
initialRotateContinuousUse = false;
}
}
}
/**
*
* @return -1: 0: 1:
*/
public int getMoveDirection() {
if(ctrl.isPress(Controller.BUTTON_LEFT) && ctrl.isPress(Controller.BUTTON_RIGHT)) {
if(ruleopt.moveLeftAndRightAllow) {
if(ctrl.buttonTime[Controller.BUTTON_LEFT] > ctrl.buttonTime[Controller.BUTTON_RIGHT])
return ruleopt.moveLeftAndRightUsePreviousInput ? -1 : 1;
else if(ctrl.buttonTime[Controller.BUTTON_LEFT] < ctrl.buttonTime[Controller.BUTTON_RIGHT])
return ruleopt.moveLeftAndRightUsePreviousInput ? 1 : -1;
}
} else if(ctrl.isPress(Controller.BUTTON_LEFT)) {
return -1;
} else if(ctrl.isPress(Controller.BUTTON_RIGHT)) {
return 1;
}
return 0;
}
public void padRepeat() {
int moveDirection = getMoveDirection();
if(moveDirection != 0) {
dasCount++;
} else if(!ruleopt.dasStoreChargeOnNeutral) {
dasCount = 0;
}
dasDirection = moveDirection;
}
/**
* Called if delay doesn't allow charging but dasRedirectInDelay == true
* Updates dasDirection so player can change direction without dropping charge on entry.
*/
public void dasRedirect() {
dasDirection = getMoveDirection();
}
/**
*
* @return true
*/
public boolean isMoveCountExceed() {
if(ruleopt.lockresetLimitShareCount == true) {
if((extendedMoveCount + extendedRotateCount >= ruleopt.lockresetLimitMove) && (ruleopt.lockresetLimitMove >= 0))
return true;
} else {
if((extendedMoveCount >= ruleopt.lockresetLimitMove) && (ruleopt.lockresetLimitMove >= 0))
return true;
}
return false;
}
/**
*
* @return true
*/
public boolean isRotateCountExceed() {
if(ruleopt.lockresetLimitShareCount == true) {
if((extendedMoveCount + extendedRotateCount >= ruleopt.lockresetLimitMove) && (ruleopt.lockresetLimitMove >= 0))
return true;
} else {
if((extendedRotateCount >= ruleopt.lockresetLimitRotate) && (ruleopt.lockresetLimitRotate >= 0))
return true;
}
return false;
}
/**
* T-Spin
* @param x X
* @param y Y
* @param piece
* @param fld
* @return T-Spintrue
*/
public void setTSpin(int x, int y, Piece piece, Field fld) {
if((piece == null) || (piece.id != Piece.PIECE_T)) {
tspin = false;
return;
}
if(!tspinAllowKick && kickused) {
tspin = false;
return;
}
if(spinCheckType == SPINTYPE_4POINT) {
if(tspinminiType == TSPINMINI_TYPE_ROTATECHECK) {
if(nowPieceObject.checkCollision(nowPieceX, nowPieceY, getRotateDirection(-1), field) &&
nowPieceObject.checkCollision(nowPieceX, nowPieceY, getRotateDirection( 1), field))
tspinmini = true;
} else if(tspinminiType == TSPINMINI_TYPE_WALLKICKFLAG) {
tspinmini = kickused;
}
int[] tx = new int[4];
int[] ty = new int[4];
if(piece.big == true) {
tx[0] = 1;
ty[0] = 1;
tx[1] = 4;
ty[1] = 1;
tx[2] = 1;
ty[2] = 4;
tx[3] = 4;
ty[3] = 4;
} else {
tx[0] = 0;
ty[0] = 0;
tx[1] = 2;
ty[1] = 0;
tx[2] = 0;
ty[2] = 2;
tx[3] = 2;
ty[3] = 2;
}
for(int i = 0; i < tx.length; i++) {
if(piece.big) {
tx[i] += ruleopt.pieceOffsetX[piece.id][piece.direction] * 2;
ty[i] += ruleopt.pieceOffsetY[piece.id][piece.direction] * 2;
} else {
tx[i] += ruleopt.pieceOffsetX[piece.id][piece.direction];
ty[i] += ruleopt.pieceOffsetY[piece.id][piece.direction];
}
}
int count = 0;
for(int i = 0; i < tx.length; i++) {
if(fld.getBlockColor(x + tx[i], y + ty[i]) != Block.BLOCK_COLOR_NONE) count++;
}
if(count >= 3) tspin = true;
} else if(spinCheckType == SPINTYPE_IMMOBILE) {
if( piece.checkCollision(x, y - 1, fld) &&
piece.checkCollision(x + 1, y, fld) &&
piece.checkCollision(x - 1, y, fld) ) {
tspin = true;
Field copyField = new Field(fld);
piece.placeToField(x, y, copyField);
if((copyField.checkLineNoFlag() == 1) && (kickused == true)) tspinmini = true;
} else if((tspinEnableEZ) && (kickused == true)) {
tspin = true;
tspinez = true;
}
}
}
/**
* Spin()
* @param x X
* @param y Y
* @param piece
* @param fld
*/
public void setAllSpin(int x, int y, Piece piece, Field fld) {
tspin = false;
tspinmini = false;
tspinez = false;
if(piece == null) return;
if(!tspinAllowKick && kickused) return;
if(piece.big) return;
if(spinCheckType == SPINTYPE_4POINT) {
int offsetX = ruleopt.pieceOffsetX[piece.id][piece.direction];
int offsetY = ruleopt.pieceOffsetY[piece.id][piece.direction];
for(int i = 0; i < Piece.SPINBONUSDATA_HIGH_X[piece.id][piece.direction].length / 2; i++) {
boolean isHighSpot1 = false;
boolean isHighSpot2 = false;
boolean isLowSpot1 = false;
boolean isLowSpot2 = false;
if(!fld.getBlockEmptyF(
x + Piece.SPINBONUSDATA_HIGH_X[piece.id][piece.direction][i * 2 + 0] + offsetX,
y + Piece.SPINBONUSDATA_HIGH_Y[piece.id][piece.direction][i * 2 + 0] + offsetY))
{
isHighSpot1 = true;
}
if(!fld.getBlockEmptyF(
x + Piece.SPINBONUSDATA_HIGH_X[piece.id][piece.direction][i * 2 + 1] + offsetX,
y + Piece.SPINBONUSDATA_HIGH_Y[piece.id][piece.direction][i * 2 + 1] + offsetY))
{
isHighSpot2 = true;
}
if(!fld.getBlockEmptyF(
x + Piece.SPINBONUSDATA_LOW_X[piece.id][piece.direction][i * 2 + 0] + offsetX,
y + Piece.SPINBONUSDATA_LOW_Y[piece.id][piece.direction][i * 2 + 0] + offsetY))
{
isLowSpot1 = true;
}
if(!fld.getBlockEmptyF(
x + Piece.SPINBONUSDATA_LOW_X[piece.id][piece.direction][i * 2 + 1] + offsetX,
y + Piece.SPINBONUSDATA_LOW_Y[piece.id][piece.direction][i * 2 + 1] + offsetY))
{
isLowSpot2 = true;
}
//log.debug(isHighSpot1 + "," + isHighSpot2 + "," + isLowSpot1 + "," + isLowSpot2);
if(isHighSpot1 && isHighSpot2 && (isLowSpot1 || isLowSpot2)) {
tspin = true;
} else if(!tspin && isLowSpot1 && isLowSpot2 && (isHighSpot1 || isHighSpot2)) {
tspin = true;
tspinmini = true;
}
}
} else if(spinCheckType == SPINTYPE_IMMOBILE) {
int y2 = y - 1;
log.debug(x + "," + y2 + ":" + piece.checkCollision(x, y2, fld));
if( piece.checkCollision(x, y - 1, fld) &&
piece.checkCollision(x + 1, y, fld) &&
piece.checkCollision(x - 1, y, fld) ) {
tspin = true;
Field copyField = new Field(fld);
piece.placeToField(x, y, copyField);
if((copyField.checkLineNoFlag() == 1) && (kickused == true)) tspinmini = true;
} else if((tspinEnableEZ) && (kickused == true)) {
tspin = true;
tspinez = true;
}
}
}
/**
*
* @return true
*/
public boolean isHoldOK() {
if( (!ruleopt.holdEnable) || (holdDisable) || ((holdUsedCount >= ruleopt.holdLimit) && (ruleopt.holdLimit >= 0)) || (initialHoldContinuousUse) )
return false;
return true;
}
/**
* X
* @param fld
* @param piece
* @return X
*/
public int getSpawnPosX(Field fld, Piece piece) {
int x = -1 + (fld.getWidth() - piece.getWidth() + 1) / 2;
if((big == true) && (bigmove == true) && (x % 2 != 0))
x++;
if(big == true) {
x += ruleopt.pieceSpawnXBig[piece.id][piece.direction];
} else {
x += ruleopt.pieceSpawnX[piece.id][piece.direction];
}
return x;
}
/**
* Y
* @param piece
* @return Y
*/
public int getSpawnPosY(Piece piece) {
int y = 0;
if((ruleopt.pieceEnterAboveField == true) && (ruleopt.fieldCeiling == false)) {
y = -1 - piece.getMaximumBlockY();
if(big == true) y
} else {
y = -piece.getMinimumBlockY();
}
if(big == true) {
y += ruleopt.pieceSpawnYBig[piece.id][piece.direction];
} else {
y += ruleopt.pieceSpawnY[piece.id][piece.direction];
}
return y;
}
/**
*
* @param move -1: 1: 2:180
* @return
*/
public int getRotateDirection(int move) {
int rt = 0 + move;
if(nowPieceObject != null) rt = nowPieceObject.direction + move;
if(move == 2) {
if(rt > 3) rt -= 4;
if(rt < 0) rt += 4;
} else {
if(rt > 3) rt = 0;
if(rt < 0) rt = 3;
}
return rt;
}
public void initialRotate() {
initialRotateDirection = 0;
initialHoldFlag = false;
if((ruleopt.rotateInitial == true) && (initialRotateContinuousUse == false)) {
int dir = 0;
if(ctrl.isPress(Controller.BUTTON_A) || ctrl.isPress(Controller.BUTTON_C)) dir = -1;
else if(ctrl.isPress(Controller.BUTTON_B)) dir = 1;
else if(ctrl.isPress(Controller.BUTTON_E)) dir = 2;
initialRotateDirection = dir;
}
if((ctrl.isPress(Controller.BUTTON_D)) && (ruleopt.holdInitial == true) && isHoldOK()) {
initialHoldFlag = true;
initialHoldContinuousUse = true;
playSE("initialhold");
}
}
public void fieldUpdate() {
if(field != null) {
for(int i = 0; i < field.getWidth(); i++) {
for(int j = (field.getHiddenHeight() * -1); j < field.getHeight(); j++) {
Block blk = field.getBlock(i, j);
if((blk != null) && (blk.color >= Block.BLOCK_COLOR_GRAY)) {
if(blk.elapsedFrames < 0) {
if(!blk.getAttribute(Block.BLOCK_ATTRIBUTE_GARBAGE))
blk.darkness = 0f;
} else if(blk.elapsedFrames < ruleopt.lockflash) {
blk.darkness = -0.8f;
if(blockShowOutlineOnly) {
blk.setAttribute(Block.BLOCK_ATTRIBUTE_OUTLINE, true);
blk.setAttribute(Block.BLOCK_ATTRIBUTE_VISIBLE, false);
blk.setAttribute(Block.BLOCK_ATTRIBUTE_BONE, false);
}
} else {
blk.darkness = 0f;
blk.setAttribute(Block.BLOCK_ATTRIBUTE_OUTLINE, true);
if(blockShowOutlineOnly) {
blk.setAttribute(Block.BLOCK_ATTRIBUTE_VISIBLE, false);
blk.setAttribute(Block.BLOCK_ATTRIBUTE_BONE, false);
}
}
if((blockHidden != -1) && (blk.elapsedFrames >= blockHidden - 10) && (gameActive == true)) {
if(blockHiddenAnim == true) {
blk.alpha -= 0.1f;
if(blk.alpha < 0.0f) blk.alpha = 0.0f;
}
if(blk.elapsedFrames >= blockHidden) {
blk.alpha = 0.0f;
blk.setAttribute(Block.BLOCK_ATTRIBUTE_OUTLINE, false);
blk.setAttribute(Block.BLOCK_ATTRIBUTE_VISIBLE, false);
}
}
if(blk.elapsedFrames >= 0) blk.elapsedFrames++;
}
}
}
}
// X-RAY
if((field != null) && (gameActive) && (itemXRayEnable)) {
for(int i = 0; i < field.getWidth(); i++) {
for(int j = (field.getHiddenHeight() * -1); j < field.getHeight(); j++) {
Block blk = field.getBlock(i, j);
if((blk != null) && (blk.color >= Block.BLOCK_COLOR_GRAY)) {
blk.setAttribute(Block.BLOCK_ATTRIBUTE_VISIBLE, (itemXRayCount % 36 == i));
blk.setAttribute(Block.BLOCK_ATTRIBUTE_OUTLINE, (itemXRayCount % 36 == i));
}
}
}
itemXRayCount++;
} else {
itemXRayCount = 0;
}
// COLOR
if((field != null) && (gameActive) && (itemColorEnable)) {
for(int i = 0; i < field.getWidth(); i++) {
for(int j = (field.getHiddenHeight() * -1); j < field.getHeight(); j++) {
int bright = j;
if(bright >= 5) bright = 9 - bright;
bright = 40 - ( (((20 - i) + bright) * 4 + itemColorCount) % 40 );
if((bright >= 0) && (bright < ITEM_COLOR_BRIGHT_TABLE.length)) {
bright = 10 - ITEM_COLOR_BRIGHT_TABLE[bright];
}
if(bright > 10) bright = 10;
Block blk = field.getBlock(i, j);
if(blk != null) {
blk.alpha = bright * 0.1f;
blk.setAttribute(Block.BLOCK_ATTRIBUTE_OUTLINE, false);
blk.setAttribute(Block.BLOCK_ATTRIBUTE_VISIBLE, true);
}
}
}
itemColorCount++;
} else {
itemColorCount = 0;
}
// HIDDEN
if(heboHiddenEnable && gameActive) {
heboHiddenTimerNow++;
if(heboHiddenTimerNow > heboHiddenTimerMax) {
heboHiddenTimerNow = 0;
heboHiddenYNow++;
if(heboHiddenYNow > heboHiddenYLimit)
heboHiddenYNow = heboHiddenYLimit;
}
}
}
public void saveReplay() {
if((owner.replayMode == true) && (owner.replayRerecord == false)) return;
owner.replayProp.setProperty("version.core", versionMajor + "." + versionMinor);
owner.replayProp.setProperty("version.core.major", versionMajor);
owner.replayProp.setProperty("version.core.minor", versionMinor);
owner.replayProp.setProperty(playerID + ".replay.randSeed", Long.toString(randSeed, 16));
replayData.writeProperty(owner.replayProp, playerID, replayTimer);
statistics.writeProperty(owner.replayProp, playerID);
ruleopt.writeProperty(owner.replayProp, playerID);
if(playerID == 0) {
if(owner.mode != null) owner.replayProp.setProperty("name.mode", owner.mode.getName());
if(ruleopt.strRuleName != null) owner.replayProp.setProperty("name.rule", ruleopt.strRuleName);
GregorianCalendar currentTime = new GregorianCalendar();
int month = currentTime.get(Calendar.MONTH) + 1;
String strDate = String.format("%04d/%02d/%02d", currentTime.get(Calendar.YEAR), month, currentTime.get(Calendar.DATE));
String strTime = String.format("%02d:%02d:%02d",
currentTime.get(Calendar.HOUR_OF_DAY), currentTime.get(Calendar.MINUTE), currentTime.get(Calendar.SECOND));
owner.replayProp.setProperty("timestamp.date", strDate);
owner.replayProp.setProperty("timestamp.time", strTime);
}
owner.replayProp.setProperty(playerID + ".tuning.owRotateButtonDefaultRight", owRotateButtonDefaultRight);
owner.replayProp.setProperty(playerID + ".tuning.owSkin", owSkin);
owner.replayProp.setProperty(playerID + ".tuning.owMinDAS", owMinDAS);
owner.replayProp.setProperty(playerID + ".tuning.owMaxDAS", owMaxDAS);
owner.replayProp.setProperty(playerID + ".tuning.owDasDelay", owDasDelay);
if(owner.mode != null) owner.mode.saveReplay(this, playerID, owner.replayProp);
}
public void enterFieldEdit() {
fldeditPreviousStat = stat;
stat = STAT_FIELDEDIT;
fldeditX = 0;
fldeditY = 0;
fldeditColor = Block.BLOCK_COLOR_GRAY;
fldeditFrames = 0;
owner.menuOnly = false;
createFieldIfNeeded();
}
public void createFieldIfNeeded() {
if(fieldWidth < 0) fieldWidth = ruleopt.fieldWidth;
if(fieldHeight < 0) fieldHeight = ruleopt.fieldHeight;
if(fieldHiddenHeight < 0) fieldHiddenHeight = ruleopt.fieldHiddenHeight;
if(field == null) field = new Field(fieldWidth, fieldHeight, fieldHiddenHeight, ruleopt.fieldCeiling);
}
public void update() {
if(gameActive) {
if(!owner.replayMode || owner.replayRerecord) {
if(ai != null) ai.setControl(this, playerID, ctrl);
replayData.setInputData(ctrl.getButtonBit(), replayTimer);
} else {
ctrl.setButtonBit(replayData.getInputData(replayTimer));
}
replayTimer++;
}
ctrl.updateButtonTime();
if(owner.mode != null) owner.mode.onFirst(this, playerID);
owner.receiver.onFirst(this, playerID);
if((ai != null) && (!owner.replayMode || owner.replayRerecord)) ai.onFirst(this, playerID);
if(!lagStop) {
switch(stat) {
case STAT_NOTHING:
break;
case STAT_SETTING:
statSetting();
break;
case STAT_READY:
statReady();
break;
case STAT_MOVE:
dasRepeat = true;
dasInstant = false;
while(dasRepeat){
statMove();
}
break;
case STAT_LOCKFLASH:
statLockFlash();
break;
case STAT_LINECLEAR:
statLineClear();
break;
case STAT_ARE:
statARE();
break;
case STAT_ENDINGSTART:
statEndingStart();
break;
case STAT_CUSTOM:
statCustom();
break;
case STAT_EXCELLENT:
statExcellent();
break;
case STAT_GAMEOVER:
statGameOver();
break;
case STAT_RESULT:
statResult();
break;
case STAT_FIELDEDIT:
statFieldEdit();
break;
case STAT_INTERRUPTITEM:
statInterruptItem();
break;
}
}
fieldUpdate();
if((ending == 0) || (staffrollEnableStatistics)) statistics.update();
if(owner.mode != null) owner.mode.onLast(this, playerID);
owner.receiver.onLast(this, playerID);
if((ai != null) && (!owner.replayMode || owner.replayRerecord)) ai.onLast(this, playerID);
if(gameActive && timerActive) {
statistics.time++;
}
}
/**
*
* GameEngine
*/
public void render() {
if(owner.mode != null) owner.mode.renderFirst(this, playerID);
owner.receiver.renderFirst(this, playerID);
switch(stat) {
case STAT_NOTHING:
break;
case STAT_SETTING:
if(owner.mode != null) owner.mode.renderSetting(this, playerID);
owner.receiver.renderSetting(this, playerID);
break;
case STAT_READY:
if(owner.mode != null) owner.mode.renderReady(this, playerID);
owner.receiver.renderReady(this, playerID);
break;
case STAT_MOVE:
if(owner.mode != null) owner.mode.renderMove(this, playerID);
owner.receiver.renderMove(this, playerID);
break;
case STAT_LOCKFLASH:
if(owner.mode != null) owner.mode.renderLockFlash(this, playerID);
owner.receiver.renderLockFlash(this, playerID);
break;
case STAT_LINECLEAR:
if(owner.mode != null) owner.mode.renderLineClear(this, playerID);
owner.receiver.renderLineClear(this, playerID);
break;
case STAT_ARE:
if(owner.mode != null) owner.mode.renderARE(this, playerID);
owner.receiver.renderARE(this, playerID);
break;
case STAT_ENDINGSTART:
if(owner.mode != null) owner.mode.renderEndingStart(this, playerID);
owner.receiver.renderEndingStart(this, playerID);
break;
case STAT_CUSTOM:
if(owner.mode != null) owner.mode.renderCustom(this, playerID);
owner.receiver.renderCustom(this, playerID);
break;
case STAT_EXCELLENT:
if(owner.mode != null) owner.mode.renderExcellent(this, playerID);
owner.receiver.renderExcellent(this, playerID);
break;
case STAT_GAMEOVER:
if(owner.mode != null) owner.mode.renderGameOver(this, playerID);
owner.receiver.renderGameOver(this, playerID);
break;
case STAT_RESULT:
if(owner.mode != null) owner.mode.renderResult(this, playerID);
owner.receiver.renderResult(this, playerID);
break;
case STAT_FIELDEDIT:
if(owner.mode != null) owner.mode.renderFieldEdit(this, playerID);
owner.receiver.renderFieldEdit(this, playerID);
break;
case STAT_INTERRUPTITEM:
break;
}
if(owner.mode != null) owner.mode.renderLast(this, playerID);
owner.receiver.renderLast(this, playerID);
}
public void statSetting() {
if(owner.mode != null) {
if(owner.mode.onSetting(this, playerID) == true) return;
}
owner.receiver.onSetting(this, playerID);
// Ready
stat = STAT_READY;
resetStatc();
}
public void statReady() {
if(owner.mode != null) {
if(owner.mode.onReady(this, playerID) == true) return;
}
owner.receiver.onReady(this, playerID);
if(ruleopt.dasInReady && gameActive) padRepeat();
else if(ruleopt.dasRedirectInDelay) { dasRedirect(); }
if(statc[0] == 0) {
createFieldIfNeeded();
// NEXT
if(nextPieceArrayID == null) {
boolean allDisable = true;
for(int i = 0; i < nextPieceEnable.length; i++) {
if(nextPieceEnable[i] == true) {
allDisable = false;
break;
}
}
if(allDisable == true) {
for(int i = 0; i < nextPieceEnable.length; i++) nextPieceEnable[i] = true;
}
// NEXT
if(randomizer == null) {
randomizer = new MemorylessRandomizer(nextPieceEnable, randSeed);
} else {
randomizer.setState(nextPieceEnable, randSeed);
}
nextPieceArrayID = new int[nextPieceArraySize];
for (int i = 0; i < nextPieceArraySize; i++) {
nextPieceArrayID[i] = randomizer.next();
}
}
// NEXT
if(nextPieceArrayObject == null) {
nextPieceArrayObject = new Piece[nextPieceArrayID.length];
for(int i = 0; i < nextPieceArrayObject.length; i++) {
nextPieceArrayObject[i] = new Piece(nextPieceArrayID[i]);
nextPieceArrayObject[i].direction = ruleopt.pieceDefaultDirection[nextPieceArrayObject[i].id];
if(nextPieceArrayObject[i].direction >= Piece.DIRECTION_COUNT) {
nextPieceArrayObject[i].direction = random.nextInt(Piece.DIRECTION_COUNT);
}
nextPieceArrayObject[i].setColor(ruleopt.pieceColor[nextPieceArrayObject[i].id]);
nextPieceArrayObject[i].setSkin(getSkin());
nextPieceArrayObject[i].updateConnectData();
nextPieceArrayObject[i].setAttribute(Block.BLOCK_ATTRIBUTE_VISIBLE, true);
nextPieceArrayObject[i].setAttribute(Block.BLOCK_ATTRIBUTE_BONE, bone);
nextPieceArrayObject[i].connectBlocks = this.connectBlocks;
}
if (randomBlockColor)
{
if (blockColors.length < numColors || numColors < 1)
numColors = blockColors.length;
for(int i = 0; i < nextPieceArrayObject.length; i++) {
int size = nextPieceArrayObject[i].getMaxBlock();
int[] colors = new int[size];
for (int j = 0; j < size; j++)
colors[j] = blockColors[random.nextInt(numColors)];
nextPieceArrayObject[i].setColor(colors);
}
}
}
if(!readyDone) {
ctrl.reset();
gameActive = true;
}
}
// READY
if(statc[0] == readyStart) playSE("ready");
if(statc[0] == goStart) playSE("go");
// NEXT
if((statc[0] > 0) && (statc[0] < goEnd) && (holdButtonNextSkip) && (isHoldOK()) && (ctrl.isPush(Controller.BUTTON_D))) {
playSE("initialhold");
holdPieceObject = getNextObjectCopy(nextPieceCount);
holdPieceObject.applyOffsetArray(ruleopt.pieceOffsetX[holdPieceObject.id], ruleopt.pieceOffsetY[holdPieceObject.id]);
nextPieceCount++;
if(nextPieceCount < 0) nextPieceCount = 0;
}
if(statc[0] >= goEnd) {
if(!readyDone) owner.bgmStatus.bgm = 0;
if(owner.mode != null) owner.mode.startGame(this, playerID);
owner.receiver.startGame(this, playerID);
initialRotate();
stat = STAT_MOVE;
resetStatc();
if(!readyDone) {
startTime = System.currentTimeMillis();
}
readyDone = true;
return;
}
statc[0]++;
}
public void statMove() {
dasRepeat = false;
if(owner.mode != null) {
if(owner.mode.onMove(this, playerID) == true) return;
}
owner.receiver.onMove(this, playerID);
int moveDirection = getMoveDirection();
if((statc[0] > 0) || (ruleopt.dasInMoveFirstFrame)) {
if(dasDirection != moveDirection) {
dasDirection = moveDirection;
if(!(dasDirection == 0 && ruleopt.dasStoreChargeOnNeutral)){
dasCount = 0;
}
}
}
if(statc[0] == 0) {
if((statc[1] == 0) && (initialHoldFlag == false)) {
nowPieceObject = getNextObjectCopy(nextPieceCount);
nextPieceCount++;
if(nextPieceCount < 0) nextPieceCount = 0;
holdDisable = false;
} else {
if(initialHoldFlag) {
if(holdPieceObject == null) {
holdPieceObject = getNextObjectCopy(nextPieceCount);
holdPieceObject.applyOffsetArray(ruleopt.pieceOffsetX[holdPieceObject.id], ruleopt.pieceOffsetY[holdPieceObject.id]);
nextPieceCount++;
if(nextPieceCount < 0) nextPieceCount = 0;
if(bone == true) getNextObject(nextPieceCount + ruleopt.nextDisplay - 1).setAttribute(Block.BLOCK_ATTRIBUTE_BONE, true);
nowPieceObject = getNextObjectCopy(nextPieceCount);
nextPieceCount++;
if(nextPieceCount < 0) nextPieceCount = 0;
} else {
Piece pieceTemp = holdPieceObject;
holdPieceObject = getNextObjectCopy(nextPieceCount);
holdPieceObject.applyOffsetArray(ruleopt.pieceOffsetX[holdPieceObject.id], ruleopt.pieceOffsetY[holdPieceObject.id]);
nowPieceObject = pieceTemp;
nextPieceCount++;
if(nextPieceCount < 0) nextPieceCount = 0;
}
} else {
if(holdPieceObject == null) {
nowPieceObject.big = false;
holdPieceObject = nowPieceObject;
nowPieceObject = getNextObjectCopy(nextPieceCount);
nextPieceCount++;
if(nextPieceCount < 0) nextPieceCount = 0;
} else {
nowPieceObject.big = false;
Piece pieceTemp = holdPieceObject;
holdPieceObject = nowPieceObject;
nowPieceObject = pieceTemp;
}
}
if((ruleopt.holdResetDirection) && (ruleopt.pieceDefaultDirection[holdPieceObject.id] < Piece.DIRECTION_COUNT)) {
holdPieceObject.direction = ruleopt.pieceDefaultDirection[holdPieceObject.id];
holdPieceObject.updateConnectData();
}
holdUsedCount++;
statistics.totalHoldUsed++;
initialHoldFlag = false;
holdDisable = true;
}
playSE("piece" + getNextObject(nextPieceCount).id);
if(nowPieceObject.offsetApplied == false)
nowPieceObject.applyOffsetArray(ruleopt.pieceOffsetX[nowPieceObject.id], ruleopt.pieceOffsetY[nowPieceObject.id]);
nowPieceObject.big = big;
nowPieceX = getSpawnPosX(field, nowPieceObject);
nowPieceY = getSpawnPosY(nowPieceObject);
nowPieceBottomY = nowPieceObject.getBottom(nowPieceX, nowPieceY, field);
nowPieceColorOverride = -1;
if(itemRollRollEnable) nowPieceColorOverride = Block.BLOCK_COLOR_GRAY;
initialRotate();
//if( (getARE() != 0) && ((getARELine() != 0) || (version < 6.3f)) ) initialRotate();
if((speed.gravity > speed.denominator) && (speed.denominator > 0))
gcount = speed.gravity % speed.denominator;
else
gcount = 0;
lockDelayNow = 0;
dasSpeedCount = getDASDelay();
dasRepeat = false;
dasInstant = false;
extendedMoveCount = 0;
extendedRotateCount = 0;
softdropFall = 0;
harddropFall = 0;
manualLock = false;
nowPieceMoveCount = 0;
nowPieceRotateCount = 0;
nowWallkickCount = 0;
nowUpwardWallkickCount = 0;
lineClearing = 0;
lastmove = LASTMOVE_NONE;
kickused = false;
tspin = false;
tspinmini = false;
tspinez = false;
getNextObject(nextPieceCount + ruleopt.nextDisplay - 1).setAttribute(Block.BLOCK_ATTRIBUTE_BONE, bone);
if(ending == 0) timerActive = true;
if((ai != null) && (!owner.replayMode || owner.replayRerecord)) ai.newPiece(this, playerID);
}
checkDropContinuousUse();
boolean softdropUsed = false; // true
int softdropFallNow = 0;
boolean updown = false;
if(ctrl.isPress(Controller.BUTTON_UP) && ctrl.isPress(Controller.BUTTON_DOWN)) updown = true;
if(!dasInstant) {
if(ctrl.isPush(Controller.BUTTON_D) || initialHoldFlag) {
if(isHoldOK()) {
statc[0] = 0;
statc[1] = 1;
if(!initialHoldFlag) playSE("hold");
initialHoldContinuousUse = true;
initialHoldFlag = false;
holdDisable = true;
initialRotate();
statMove();
return;
} else if((statc[0] > 0) && (!initialHoldFlag)) {
playSE("holdfail");
}
}
boolean onGroundBeforeRotate = nowPieceObject.checkCollision(nowPieceX, nowPieceY + 1, field);
int move = 0;
boolean rotated = false;
if(initialRotateDirection != 0) {
move = initialRotateDirection;
initialRotateLastDirection = initialRotateDirection;
initialRotateContinuousUse = true;
playSE("initialrotate");
} else if((statc[0] > 0) || (ruleopt.moveFirstFrame == true)) {
if((itemRollRollEnable) && (replayTimer % itemRollRollInterval == 0)) move = 1;
if(ctrl.isPush(Controller.BUTTON_A) || ctrl.isPush(Controller.BUTTON_C)) move = -1;
else if(ctrl.isPush(Controller.BUTTON_B)) move = 1;
else if(ctrl.isPush(Controller.BUTTON_E)) move = 2;
if(move != 0) {
initialRotateLastDirection = move;
initialRotateContinuousUse = true;
}
}
if((ruleopt.rotateButtonAllowDouble == false) && (move == 2)) move = -1;
if((ruleopt.rotateButtonAllowReverse == false) && (move == 1)) move = -1;
if(isRotateButtonDefaultRight() && (move != 2)) move = move * -1;
if(move != 0) {
int rt = getRotateDirection(move);
if(nowPieceObject.checkCollision(nowPieceX, nowPieceY, rt, field) == false)
{
rotated = true;
kickused = false;
nowPieceObject.direction = rt;
nowPieceObject.updateConnectData();
} else if( (ruleopt.rotateWallkick == true) &&
(wallkick != null) &&
((initialRotateDirection == 0) || (ruleopt.rotateInitialWallkick == true)) &&
((ruleopt.lockresetLimitOver != RuleOptions.LOCKRESET_LIMIT_OVER_NOWALLKICK) || (isRotateCountExceed() == false)) )
{
boolean allowUpward = (ruleopt.rotateMaxUpwardWallkick < 0) || (nowUpwardWallkickCount < ruleopt.rotateMaxUpwardWallkick);
WallkickResult kick = wallkick.executeWallkick(nowPieceX, nowPieceY, move, nowPieceObject.direction, rt,
allowUpward, nowPieceObject, field, ctrl);
if(kick != null) {
rotated = true;
kickused = true;
nowWallkickCount++;
if(kick.isUpward()) nowUpwardWallkickCount++;
nowPieceObject.direction = kick.direction;
nowPieceObject.updateConnectData();
nowPieceX += kick.offsetX;
nowPieceY += kick.offsetY;
}
}
if(rotated == true) {
nowPieceBottomY = nowPieceObject.getBottom(nowPieceX, nowPieceY, field);
if((ruleopt.lockresetRotate == true) && (isRotateCountExceed() == false)) {
lockDelayNow = 0;
nowPieceObject.setDarkness(0f);
}
if(onGroundBeforeRotate) {
extendedRotateCount++;
lastmove = LASTMOVE_ROTATE_GROUND;
} else {
lastmove = LASTMOVE_ROTATE_AIR;
}
if(initialRotateDirection == 0) {
playSE("rotate");
}
nowPieceRotateCount++;
if((ending == 0) || (staffrollEnableStatistics)) statistics.totalPieceRotate++;
} else {
playSE("rotfail");
}
}
initialRotateDirection = 0;
if((statc[0] == 0) && (nowPieceObject.checkCollision(nowPieceX, nowPieceY, field) == true)) {
for(int i = 0; i < ruleopt.pieceEnterMaxDistanceY; i++) {
if(nowPieceObject.big) nowPieceY -= 2;
else nowPieceY
if(nowPieceObject.checkCollision(nowPieceX, nowPieceY, field) == false) {
nowPieceBottomY = nowPieceObject.getBottom(nowPieceX, nowPieceY, field);
break;
}
}
if(nowPieceObject.checkCollision(nowPieceX, nowPieceY, field) == true) {
nowPieceObject.placeToField(nowPieceX, nowPieceY, field);
nowPieceObject = null;
stat = STAT_GAMEOVER;
if((ending == 2) && (staffrollNoDeath)) stat = STAT_NOTHING;
resetStatc();
return;
}
}
}
int move = 0;
boolean sidemoveflag = false; // true
if((statc[0] > 0) || (ruleopt.moveFirstFrame == true)) {
boolean onGroundBeforeMove = nowPieceObject.checkCollision(nowPieceX, nowPieceY + 1, field);
move = moveDirection;
if (statc[0] == 0 && delayCancel) {
if (delayCancelMoveLeft) move = -1;
if (delayCancelMoveRight) move = 1;
dasCount = 0;
// delayCancel = false;
delayCancelMoveLeft = false;
delayCancelMoveRight = false;
} else if (statc[0] == 1 && delayCancel && (dasCount < getDAS())) {
move = 0;
delayCancel = false;
}
if(move != 0) sidemoveflag = true;
if(big && bigmove) move *= 2;
if((move != 0) && (dasCount == 0)) shiftLock = 0;
if( (move != 0) && ((dasCount == 0) || (dasCount >= getDAS())) ) {
shiftLock &= ctrl.getButtonBit();
if(shiftLock == 0) {
if( (dasSpeedCount >= getDASDelay()) || (dasCount == 0) ) {
if(dasCount > 0) dasSpeedCount = 1;
if(nowPieceObject.checkCollision(nowPieceX + move, nowPieceY, field) == false) {
nowPieceX += move;
if((getDASDelay() == 0) && (dasCount > 0) && (nowPieceObject.checkCollision(nowPieceX + move, nowPieceY, field) == false)) {
dasRepeat = true;
dasInstant = true;
}
//log.debug("Successful movement: move="+move);
if((ruleopt.lockresetMove == true) && (isMoveCountExceed() == false)) {
lockDelayNow = 0;
nowPieceObject.setDarkness(0f);
}
nowPieceMoveCount++;
if((ending == 0) || (staffrollEnableStatistics)) statistics.totalPieceMove++;
nowPieceBottomY = nowPieceObject.getBottom(nowPieceX, nowPieceY, field);
if(onGroundBeforeMove) {
extendedMoveCount++;
lastmove = LASTMOVE_SLIDE_GROUND;
} else {
lastmove = LASTMOVE_SLIDE_AIR;
}
playSE("move");
} else if (ruleopt.dasChargeOnBlockedMove) {
dasCount = getDAS();
dasSpeedCount = getDASDelay();
}
} else {
dasSpeedCount++;
}
}
}
if( (ctrl.isPress(Controller.BUTTON_UP) == true) &&
(harddropContinuousUse == false) &&
(ruleopt.harddropEnable == true) &&
((ruleopt.moveDiagonal == true) || (sidemoveflag == false)) &&
((ruleopt.moveUpAndDown == true) || (updown == false)) &&
(nowPieceY < nowPieceBottomY) )
{
harddropFall += nowPieceBottomY - nowPieceY;
if(nowPieceY != nowPieceBottomY) {
nowPieceY = nowPieceBottomY;
playSE("harddrop");
}
if(owner.mode != null) owner.mode.afterHardDropFall(this, playerID, harddropFall);
owner.receiver.afterHardDropFall(this, playerID, harddropFall);
lastmove = LASTMOVE_FALL_SELF;
if(ruleopt.lockresetFall == true) {
lockDelayNow = 0;
nowPieceObject.setDarkness(0f);
extendedMoveCount = 0;
extendedRotateCount = 0;
}
}
if( (ctrl.isPress(Controller.BUTTON_DOWN) == true) &&
(softdropContinuousUse == false) &&
(ruleopt.softdropEnable == true) &&
((ruleopt.moveDiagonal == true) || (sidemoveflag == false)) &&
((ruleopt.moveUpAndDown == true) || (updown == false)) )
{
if((ruleopt.softdropMultiplyNativeSpeed == true) || (speed.denominator <= 0))
gcount += (int)(speed.gravity * ruleopt.softdropSpeed);
else
gcount += (int)(speed.denominator * ruleopt.softdropSpeed);
softdropUsed = true;
}
if((ending == 0) || (staffrollEnableStatistics)) statistics.totalPieceActiveTime++;
}
gcount += speed.gravity;
while((gcount >= speed.denominator) || (speed.gravity < 0)) {
if(nowPieceObject.checkCollision(nowPieceX, nowPieceY + 1, field) == false) {
if(speed.gravity >= 0) gcount -= speed.denominator;
nowPieceY++;
if(ruleopt.lockresetFall == true) {
lockDelayNow = 0;
nowPieceObject.setDarkness(0f);
}
if((lastmove != LASTMOVE_ROTATE_GROUND) && (lastmove != LASTMOVE_SLIDE_GROUND) && (lastmove != LASTMOVE_FALL_SELF)) {
extendedMoveCount = 0;
extendedRotateCount = 0;
}
if(softdropUsed == true) {
lastmove = LASTMOVE_FALL_SELF;
softdropFall++;
softdropFallNow++;
playSE("softdrop");
} else {
lastmove = LASTMOVE_FALL_AUTO;
}
} else {
break;
}
}
if(softdropFallNow > 0) {
if(owner.mode != null) owner.mode.afterSoftDropFall(this, playerID, softdropFallNow);
owner.receiver.afterSoftDropFall(this, playerID, softdropFallNow);
}
if( (nowPieceObject.checkCollision(nowPieceX, nowPieceY + 1, field) == true) &&
((statc[0] > 0) || (ruleopt.moveFirstFrame == true)) )
{
if((lockDelayNow == 0) && (getLockDelay() > 0))
playSE("step");
if(lockDelayNow < getLockDelay())
lockDelayNow++;
if((getLockDelay() >= 99) && (lockDelayNow > 98))
lockDelayNow = 98;
if(lockDelayNow < getLockDelay()) {
if(lockDelayNow >= getLockDelay() - 1)
nowPieceObject.setDarkness(0.5f);
else
nowPieceObject.setDarkness((lockDelayNow * 7 / getLockDelay()) * 0.05f);
}
if(getLockDelay() != 0)
gcount = speed.gravity;
// true
boolean instantlock = false;
if( (ctrl.isPress(Controller.BUTTON_UP) == true) &&
(harddropContinuousUse == false) &&
(ruleopt.harddropEnable == true) &&
((ruleopt.moveDiagonal == true) || (sidemoveflag == false)) &&
((ruleopt.moveUpAndDown == true) || (updown == false)) &&
(ruleopt.harddropLock == true) )
{
harddropContinuousUse = true;
manualLock = true;
instantlock = true;
}
if( (ctrl.isPress(Controller.BUTTON_DOWN) == true) &&
(softdropContinuousUse == false) &&
(ruleopt.softdropEnable == true) &&
((ruleopt.moveDiagonal == true) || (sidemoveflag == false)) &&
((ruleopt.moveUpAndDown == true) || (updown == false)) &&
(ruleopt.softdropLock == true) )
{
softdropContinuousUse = true;
manualLock = true;
instantlock = true;
}
if( (ctrl.isPush(Controller.BUTTON_DOWN) == true) &&
(ruleopt.softdropEnable == true) &&
((ruleopt.moveDiagonal == true) || (sidemoveflag == false)) &&
((ruleopt.moveUpAndDown == true) || (updown == false)) &&
(ruleopt.softdropSurfaceLock == true) )
{
softdropContinuousUse = true;
manualLock = true;
instantlock = true;
}
if((manualLock == true) && (ruleopt.shiftLockEnable)) {
// bit 1 and 2 are button_up and button_down currently
shiftLock = ctrl.getButtonBit() & 3;
}
if( (ruleopt.lockresetLimitOver == RuleOptions.LOCKRESET_LIMIT_OVER_INSTANT) && (isMoveCountExceed() || isRotateCountExceed()) ) {
instantlock = true;
}
if( (getLockDelay() == 0) && ((gcount >= speed.denominator) || (speed.gravity < 0)) ) {
instantlock = true;
}
if( ((lockDelayNow >= getLockDelay()) && (getLockDelay() > 0)) || (instantlock == true) ) {
if(ruleopt.lockflash > 0) nowPieceObject.setDarkness(-0.8f);
/*if((lastmove == LASTMOVE_ROTATE_GROUND) && (tspinEnable == true)) {
tspinmini = false;
// T-Spin Mini
if(!useAllSpinBonus) {
if(spinCheckType == SPINTYPE_4POINT) {
if(tspinminiType == TSPINMINI_TYPE_ROTATECHECK) {
if(nowPieceObject.checkCollision(nowPieceX, nowPieceY, getRotateDirection(-1), field) &&
nowPieceObject.checkCollision(nowPieceX, nowPieceY, getRotateDirection( 1), field))
tspinmini = true;
} else if(tspinminiType == TSPINMINI_TYPE_WALLKICKFLAG) {
tspinmini = kickused;
}
} else if(spinCheckType == SPINTYPE_IMMOBILE) {
Field copyField = new Field(field);
nowPieceObject.placeToField(nowPieceX, nowPieceY, copyField);
if((copyField.checkLineNoFlag() == 1) && (kickused == true)) tspinmini = true;
}
}
}*/
// T-Spin
if((lastmove == LASTMOVE_ROTATE_GROUND) && (tspinEnable == true)) {
if(useAllSpinBonus)
setAllSpin(nowPieceX, nowPieceY, nowPieceObject, field);
else
setTSpin(nowPieceX, nowPieceY, nowPieceObject, field);
}
nowPieceObject.setAttribute(Block.BLOCK_ATTRIBUTE_SELFPLACED, true);
boolean partialLockOut = nowPieceObject.isPartialLockOut(nowPieceX, nowPieceY, field);
boolean put = nowPieceObject.placeToField(nowPieceX, nowPieceY, field);
playSE("lock");
holdDisable = false;
if((ending == 0) || (staffrollEnableStatistics)) statistics.totalPieceLocked++;
if (clearMode == CLEAR_LINE)
lineClearing = field.checkLineNoFlag();
else if (clearMode == CLEAR_COLOR)
lineClearing = field.checkColor(colorClearSize, false, garbageColorClear, gemSameColor);
else if (clearMode == CLEAR_LINE_COLOR)
lineClearing = field.checkLineColor(colorClearSize, false, lineColorDiagonals, gemSameColor);
chain = 0;
lineGravityTotalLines = 0;
if(lineClearing == 0) {
combo = 0;
if(tspin) {
playSE("tspin0");
if((ending == 0) || (staffrollEnableStatistics)) {
if(tspinmini) statistics.totalTSpinZeroMini++;
else statistics.totalTSpinZero++;
}
}
if(owner.mode != null) owner.mode.calcScore(this, playerID, lineClearing);
owner.receiver.calcScore(this, playerID, lineClearing);
}
if(owner.mode != null) owner.mode.pieceLocked(this, playerID, lineClearing);
owner.receiver.pieceLocked(this, playerID, lineClearing);
dasRepeat = false;
dasInstant = false;
if((stat == STAT_MOVE) || (versionMajor <= 6.3f)) {
resetStatc();
if((ending == 1) && (versionMajor >= 6.6f) && (versionMinorOld >= 0.1f)) {
stat = STAT_ENDINGSTART;
} else if( (!put && ruleopt.fieldLockoutDeath) || (partialLockOut && ruleopt.fieldPartialLockoutDeath) ) {
stat = STAT_GAMEOVER;
if((ending == 2) && (staffrollNoDeath)) stat = STAT_NOTHING;
} else if (lineGravityType == LINE_GRAVITY_CASCADE && !connectBlocks) {
stat = STAT_LINECLEAR;
statc[0] = getLineDelay();
statLineClear();
} else if( (lineClearing > 0) && ((ruleopt.lockflash <= 0) || (!ruleopt.lockflashBeforeLineClear)) ) {
stat = STAT_LINECLEAR;
statLineClear();
} else if( ((getARE() > 0) || (lagARE) || (ruleopt.lockflashBeforeLineClear)) &&
(ruleopt.lockflash > 0) && (ruleopt.lockflashOnlyFrame) )
{
// ARE
stat = STAT_LOCKFLASH;
} else if((getARE() > 0) || (lagARE)) {
// ARE
statc[1] = getARE();
stat = STAT_ARE;
} else if(interruptItemNumber != INTERRUPTITEM_NONE) {
nowPieceObject = null;
interruptItemPreviousStat = STAT_MOVE;
stat = STAT_INTERRUPTITEM;
} else {
// ARE
stat = STAT_MOVE;
if(ruleopt.moveFirstFrame == false) statMove();
}
}
return;
}
}
if((statc[0] > 0) || (ruleopt.dasInMoveFirstFrame)) {
if( (moveDirection != 0) && (moveDirection == dasDirection) && ((dasCount < getDAS()) || (getDAS() <= 0)) ) {
dasCount++;
}
}
statc[0]++;
}
public void statLockFlash() {
if(owner.mode != null) {
if(owner.mode.onLockFlash(this, playerID) == true) return;
}
owner.receiver.onLockFlash(this, playerID);
statc[0]++;
checkDropContinuousUse();
if(ruleopt.dasInLockFlash) padRepeat();
else if(ruleopt.dasRedirectInDelay) { dasRedirect(); }
if(statc[0] >= ruleopt.lockflash) {
resetStatc();
if(lineClearing > 0) {
stat = STAT_LINECLEAR;
statLineClear();
} else {
// ARE
statc[1] = getARE();
stat = STAT_ARE;
}
return;
}
}
public void statLineClear() {
if(owner.mode != null) {
if(owner.mode.onLineClear(this, playerID) == true) return;
}
owner.receiver.onLineClear(this, playerID);
checkDropContinuousUse();
if(ruleopt.dasInLineClear) padRepeat();
else if(ruleopt.dasRedirectInDelay) { dasRedirect(); }
if(statc[0] == 0) {
if (clearMode == CLEAR_LINE)
lineClearing = field.checkLine();
// Set color clear flags
else if (clearMode == CLEAR_COLOR)
lineClearing = field.checkColor(colorClearSize, true, garbageColorClear, gemSameColor);
// Set line color clear flags
else if (clearMode == CLEAR_LINE_COLOR)
lineClearing = field.checkLineColor(colorClearSize, true, lineColorDiagonals, gemSameColor);
int li = lineClearing;
if(big && bighalf)
li >>= 1;
//if(li > 4) li = 4;
if(tspin) {
playSE("tspin" + li);
if((ending == 0) || (staffrollEnableStatistics)) {
if((li == 1) && (tspinmini)) statistics.totalTSpinSingleMini++;
if((li == 1) && (!tspinmini)) statistics.totalTSpinSingle++;
if((li == 2) && (tspinmini)) statistics.totalTSpinDoubleMini++;
if((li == 2) && (!tspinmini)) statistics.totalTSpinDouble++;
if(li == 3) statistics.totalTSpinTriple++;
}
} else {
if (clearMode == CLEAR_LINE)
playSE("erase" + li);
if((ending == 0) || (staffrollEnableStatistics)) {
if(li == 1) statistics.totalSingle++;
if(li == 2) statistics.totalDouble++;
if(li == 3) statistics.totalTriple++;
if(li == 4) statistics.totalFour++;
}
}
// B2B
if(b2bEnable) {
if((tspin) || (li >= 4)) {
b2bcount++;
if(b2bcount == 1) {
playSE("b2b_start");
} else {
b2b = true;
playSE("b2b_continue");
if((ending == 0) || (staffrollEnableStatistics)) {
if(li == 4) statistics.totalB2BFour++;
else statistics.totalB2BTSpin++;
}
}
} else if(b2bcount != 0) {
b2b = false;
b2bcount = 0;
playSE("b2b_end");
}
}
if((comboType != COMBO_TYPE_DISABLE) && (chain == 0)) {
if( (comboType == COMBO_TYPE_NORMAL) || ((comboType == COMBO_TYPE_DOUBLE) && (li >= 2)) )
combo++;
if(combo >= 2) {
int cmbse = combo - 1;
if(cmbse > 20) cmbse = 20;
playSE("combo" + cmbse);
}
if((ending == 0) || (staffrollEnableStatistics)) {
if(combo > statistics.maxCombo) statistics.maxCombo = combo;
}
}
lineGravityTotalLines += lineClearing;
if((ending == 0) || (staffrollEnableStatistics)) statistics.lines += li;
if(field.getHowManyGemClears() > 0) playSE("gem");
if(owner.mode != null) owner.mode.calcScore(this, playerID, li);
owner.receiver.calcScore(this, playerID, li);
if (clearMode == CLEAR_LINE) {
for(int i = 0; i < field.getHeight(); i++) {
if(field.getLineFlag(i)) {
for(int j = 0; j < field.getWidth(); j++) {
Block blk = field.getBlock(j, i);
if(blk != null) {
if(owner.mode != null) owner.mode.blockBreak(this, playerID, j, i, blk);
owner.receiver.blockBreak(this, playerID, j, i, blk);
}
}
}
}
} else if (clearMode == CLEAR_LINE_COLOR || clearMode == CLEAR_COLOR)
for(int i = 0; i < field.getHeight(); i++) {
for(int j = 0; j < field.getWidth(); j++) {
Block blk = field.getBlock(j, i);
if (blk == null)
continue;
if(blk.getAttribute(Block.BLOCK_ATTRIBUTE_ERASE)) {
if(owner.mode != null) owner.mode.blockBreak(this, playerID, j, i, blk);
owner.receiver.blockBreak(this, playerID, j, i, blk);
}
}
}
if (clearMode == CLEAR_LINE)
field.clearLine();
else if (clearMode == CLEAR_COLOR)
field.clearColor(colorClearSize, garbageColorClear, gemSameColor);
else if (clearMode == CLEAR_LINE_COLOR)
field.clearLineColor(colorClearSize, lineColorDiagonals, gemSameColor);
}
if((lineGravityType == LINE_GRAVITY_NATIVE) &&
(getLineDelay() >= (lineClearing - 1)) && (statc[0] >= getLineDelay() - (lineClearing - 1)) && (ruleopt.lineFallAnim))
{
field.downFloatingBlocksSingleLine();
}
// Line delay cancel check
delayCancelMoveLeft = ctrl.isPush(Controller.BUTTON_LEFT);
delayCancelMoveRight = ctrl.isPush(Controller.BUTTON_RIGHT);
boolean moveCancel = ruleopt.lineCancelMove && (ctrl.isPush(Controller.BUTTON_UP) ||
ctrl.isPush(Controller.BUTTON_DOWN) || delayCancelMoveLeft || delayCancelMoveRight);
boolean rotateCancel = ruleopt.lineCancelRotate && (ctrl.isPush(Controller.BUTTON_A) ||
ctrl.isPush(Controller.BUTTON_B) || ctrl.isPush(Controller.BUTTON_C) ||
ctrl.isPush(Controller.BUTTON_E));
boolean holdCancel = ruleopt.lineCancelHold && ctrl.isPush(Controller.BUTTON_D);
delayCancel = moveCancel || rotateCancel || holdCancel;
if( (statc[0] < getLineDelay()) && delayCancel ) {
statc[0] = getLineDelay();
}
if(statc[0] >= getLineDelay()) {
// Cascade
if(lineGravityType == LINE_GRAVITY_CASCADE) {
if (statc[6] < getCascadeDelay()) {
statc[6]++;
return;
} else if(field.doCascadeGravity()) {
statc[6] = 0;
return;
} else if (statc[6] < getCascadeClearDelay()) {
statc[6]++;
return;
} else if(((clearMode == CLEAR_LINE) && field.checkLineNoFlag() > 0) ||
((clearMode == CLEAR_COLOR) && field.checkColor(colorClearSize, false, garbageColorClear, gemSameColor) > 0) ||
((clearMode == CLEAR_LINE_COLOR) && field.checkLineColor(colorClearSize, false, lineColorDiagonals, gemSameColor) > 0)) {
tspin = false;
tspinmini = false;
chain++;
if(chain > statistics.maxChain) statistics.maxChain = chain;
statc[0] = 0;
statc[6] = 0;
return;
}
}
boolean skip = false;
if(owner.mode != null) skip = owner.mode.lineClearEnd(this, playerID);
owner.receiver.lineClearEnd(this, playerID);
if(!skip) {
if(lineGravityType == LINE_GRAVITY_NATIVE) field.downFloatingBlocks();
playSE("linefall");
field.lineColorsCleared = null;
if((stat == STAT_LINECLEAR) || (versionMajor <= 6.3f)) {
resetStatc();
if(ending == 1) {
stat = STAT_ENDINGSTART;
} else if((getARELine() > 0) || (lagARE)) {
// ARE
statc[0] = 0;
statc[1] = getARELine();
statc[2] = 1;
stat = STAT_ARE;
} else if(interruptItemNumber != INTERRUPTITEM_NONE) {
nowPieceObject = null;
interruptItemPreviousStat = STAT_MOVE;
stat = STAT_INTERRUPTITEM;
} else {
// ARE
nowPieceObject = null;
initialRotate();
stat = STAT_MOVE;
}
}
}
return;
}
statc[0]++;
}
public int getCascadeDelay() {
return cascadeDelay;
}
public int getCascadeClearDelay() {
return cascadeClearDelay;
}
/**
* ARE
*/
public void statARE() {
if(owner.mode != null) {
if(owner.mode.onARE(this, playerID) == true) return;
}
owner.receiver.onARE(this, playerID);
statc[0]++;
checkDropContinuousUse();
// ARE cancel check
delayCancelMoveLeft = ctrl.isPush(Controller.BUTTON_LEFT);
delayCancelMoveRight = ctrl.isPush(Controller.BUTTON_RIGHT);
boolean moveCancel = ruleopt.areCancelMove && (ctrl.isPush(Controller.BUTTON_UP) ||
ctrl.isPush(Controller.BUTTON_DOWN) || delayCancelMoveLeft || delayCancelMoveRight);
boolean rotateCancel = ruleopt.areCancelRotate && (ctrl.isPush(Controller.BUTTON_A) ||
ctrl.isPush(Controller.BUTTON_B) || ctrl.isPush(Controller.BUTTON_C) ||
ctrl.isPush(Controller.BUTTON_E));
boolean holdCancel = ruleopt.areCancelHold && ctrl.isPush(Controller.BUTTON_D);
delayCancel = moveCancel || rotateCancel || holdCancel;
if( (statc[0] < statc[1]) && delayCancel ) {
statc[0] = statc[1];
}
if( (ruleopt.dasInARE) && ((statc[0] < statc[1] - 1) || (ruleopt.dasInARELastFrame)) )
padRepeat();
else if(ruleopt.dasRedirectInDelay) { dasRedirect(); }
if((statc[0] >= statc[1]) && (!lagARE)) {
nowPieceObject = null;
resetStatc();
if(interruptItemNumber != INTERRUPTITEM_NONE) {
interruptItemPreviousStat = STAT_MOVE;
stat = STAT_INTERRUPTITEM;
} else {
initialRotate();
stat = STAT_MOVE;
}
}
}
public void statEndingStart() {
if(owner.mode != null) {
if(owner.mode.onEndingStart(this, playerID) == true) return;
}
owner.receiver.onEndingStart(this, playerID);
checkDropContinuousUse();
if(ruleopt.dasInEndingStart) padRepeat();
else if(ruleopt.dasRedirectInDelay) { dasRedirect(); }
if(statc[2] == 0) {
timerActive = false;
owner.bgmStatus.bgm = BGMStatus.BGM_NOTHING;
playSE("endingstart");
statc[2] = 1;
}
if(statc[0] < getLineDelay()) {
statc[0]++;
} else if(statc[1] < field.getHeight() * 6) {
if(statc[1] % 6 == 0) {
int y = field.getHeight() - (statc[1] / 6);
field.setLineFlag(y, true);
for(int i = 0; i < field.getWidth(); i++) {
Block blk = field.getBlock(i, y);
if((blk != null) && (blk.color != Block.BLOCK_COLOR_NONE)) {
if(owner.mode != null) owner.mode.blockBreak(this, playerID, i, y, blk);
owner.receiver.blockBreak(this, playerID, i, y, blk);
field.setBlockColor(i, y, Block.BLOCK_COLOR_NONE);
}
}
}
statc[1]++;
} else if(statc[0] < getLineDelay() + 2) {
statc[0]++;
} else {
ending = 2;
field.reset();
resetStatc();
if(staffrollEnable) {
nowPieceObject = null;
stat = STAT_MOVE;
} else {
stat = STAT_EXCELLENT;
}
}
}
public void statCustom() {
if(owner.mode != null) {
if(owner.mode.onCustom(this, playerID) == true) return;
}
owner.receiver.onCustom(this, playerID);
}
public void statExcellent() {
if(owner.mode != null) {
if(owner.mode.onExcellent(this, playerID) == true) return;
}
owner.receiver.onExcellent(this, playerID);
if(statc[0] == 0) {
gameActive = false;
timerActive = false;
owner.bgmStatus.fadesw = true;
if(ai != null) ai.shutdown(this, playerID);
resetFieldVisible();
playSE("excellent");
}
if((statc[0] >= 120) && (ctrl.isPush(Controller.BUTTON_A))) {
statc[0] = 600;
}
if((statc[0] >= 600) && (statc[1] == 0)) {
resetStatc();
stat = STAT_GAMEOVER;
} else {
statc[0]++;
}
}
public void statGameOver() {
if(owner.mode != null) {
if(owner.mode.onGameOver(this, playerID) == true) return;
}
owner.receiver.onGameOver(this, playerID);
if(lives <= 0) {
if(statc[0] == 0) {
endTime = System.currentTimeMillis();
statistics.gamerate = (float)(replayTimer / (.06*(endTime - startTime)));
gameActive = false;
timerActive = false;
blockShowOutlineOnly = false;
if(owner.getPlayers() < 2) owner.bgmStatus.bgm = BGMStatus.BGM_NOTHING;
if(ai != null) ai.shutdown(this, playerID);
if(field.isEmpty()) {
statc[0] = field.getHeight() + 1;
} else {
resetFieldVisible();
}
}
if(statc[0] < field.getHeight() + 1) {
for(int i = 0; i < field.getWidth(); i++) {
if(field.getBlockColor(i, field.getHeight() - statc[0]) != Block.BLOCK_COLOR_NONE) {
Block blk = field.getBlock(i, field.getHeight() - statc[0]);
if(blk != null) {
if(!blk.getAttribute(Block.BLOCK_ATTRIBUTE_GARBAGE)) {
blk.color = Block.BLOCK_COLOR_GRAY;
blk.setAttribute(Block.BLOCK_ATTRIBUTE_GARBAGE, true);
}
blk.darkness = 0.3f;
blk.elapsedFrames = -1;
}
}
}
statc[0]++;
} else if(statc[0] == field.getHeight() + 1) {
playSE("gameover");
statc[0]++;
} else if(statc[0] < field.getHeight() + 1 + 180) {
if((statc[0] >= field.getHeight() + 1 + 60) && (ctrl.isPush(Controller.BUTTON_A))) {
statc[0] = field.getHeight() + 1 + 180;
}
statc[0]++;
} else {
if(!owner.replayMode || owner.replayRerecord) owner.saveReplay();
for(int i = 0; i < owner.getPlayers(); i++) {
if((i == playerID) || (gameoverAll)) {
if(owner.engine[i].field != null) {
owner.engine[i].field.reset();
}
owner.engine[i].resetStatc();
owner.engine[i].stat = STAT_RESULT;
}
}
}
} else {
if(statc[0] == 0) {
blockShowOutlineOnly = false;
playSE("died");
resetFieldVisible();
for(int i = (field.getHiddenHeight() * -1); i < field.getHeight(); i++) {
for(int j = 0; j < field.getWidth(); j++) {
if(field.getBlockColor(j, i) != Block.BLOCK_COLOR_NONE) {
field.setBlockColor(j, i, Block.BLOCK_COLOR_GRAY);
}
}
}
statc[0] = 1;
}
if(!field.isEmpty()) {
field.pushDown();
} else if(statc[1] < getARE()) {
statc[1]++;
} else {
lives
resetStatc();
stat = STAT_MOVE;
}
}
}
public void statResult() {
if(owner.mode != null) {
if(owner.mode.onResult(this, playerID) == true) return;
}
owner.receiver.onResult(this, playerID);
if(ctrl.isMenuRepeatKey(Controller.BUTTON_LEFT) || ctrl.isMenuRepeatKey(Controller.BUTTON_RIGHT)) {
if(statc[0] == 0) statc[0] = 1;
else statc[0] = 0;
playSE("cursor");
}
if(ctrl.isPush(Controller.BUTTON_A)) {
playSE("decide");
if(statc[0] == 0) {
owner.reset();
} else {
quitflag = true;
}
}
}
public void statFieldEdit() {
if(owner.mode != null) {
if(owner.mode.onFieldEdit(this, playerID) == true) return;
}
owner.receiver.onFieldEdit(this, playerID);
fldeditFrames++;
if(ctrl.isMenuRepeatKey(Controller.BUTTON_LEFT, false) && !ctrl.isPress(Controller.BUTTON_C)) {
playSE("move");
fldeditX
if(fldeditX < 0) fldeditX = fieldWidth - 1;
}
if(ctrl.isMenuRepeatKey(Controller.BUTTON_RIGHT, false) && !ctrl.isPress(Controller.BUTTON_C)) {
playSE("move");
fldeditX++;
if(fldeditX > fieldWidth - 1) fldeditX = 0;
}
if(ctrl.isMenuRepeatKey(Controller.BUTTON_UP, false)) {
playSE("move");
fldeditY
if(fldeditY < 0) fldeditY = fieldHeight - 1;
}
if(ctrl.isMenuRepeatKey(Controller.BUTTON_DOWN, false)) {
playSE("move");
fldeditY++;
if(fldeditY > fieldHeight - 1) fldeditY = 0;
}
if(ctrl.isMenuRepeatKey(Controller.BUTTON_LEFT, false) && ctrl.isPress(Controller.BUTTON_C)) {
playSE("cursor");
fldeditColor
if(fldeditColor < Block.BLOCK_COLOR_GRAY) fldeditColor = Block.BLOCK_COLOR_GEM_PURPLE;
}
if(ctrl.isMenuRepeatKey(Controller.BUTTON_RIGHT, false) && ctrl.isPress(Controller.BUTTON_C)) {
playSE("cursor");
fldeditColor++;
if(fldeditColor > Block.BLOCK_COLOR_GEM_PURPLE) fldeditColor = Block.BLOCK_COLOR_GRAY;
}
if(ctrl.isPress(Controller.BUTTON_A) && (fldeditFrames > 10)) {
try {
if(field.getBlockColorE(fldeditX, fldeditY) != fldeditColor) {
Block blk = new Block(fldeditColor, getSkin(), Block.BLOCK_ATTRIBUTE_VISIBLE | Block.BLOCK_ATTRIBUTE_OUTLINE);
field.setBlockE(fldeditX, fldeditY, blk);
playSE("change");
}
} catch (Exception e) {}
}
if(ctrl.isPress(Controller.BUTTON_D) && (fldeditFrames > 10)) {
try {
if(!field.getBlockEmptyE(fldeditX, fldeditY)) {
field.setBlockColorE(fldeditX, fldeditY, Block.BLOCK_COLOR_NONE);
playSE("change");
}
} catch (Exception e) {}
}
if(ctrl.isPush(Controller.BUTTON_B) && (fldeditFrames > 10)) {
stat = fldeditPreviousStat;
if(owner.mode != null) owner.mode.fieldEditExit(this, playerID);
owner.receiver.fieldEditExit(this, playerID);
}
}
public void statInterruptItem() {
boolean contFlag = false;
switch(interruptItemNumber) {
case INTERRUPTITEM_MIRROR:
contFlag = interruptItemMirrorProc();
break;
}
if(!contFlag) {
interruptItemNumber = INTERRUPTITEM_NONE;
resetStatc();
stat = interruptItemPreviousStat;
}
}
/**
*
* @return true
*/
public boolean interruptItemMirrorProc() {
if(statc[0] == 0) {
interruptItemMirrorField = new Field(field);
field.reset();
} else if((statc[0] >= 21) && (statc[0] < 21 + (field.getWidth() * 2)) && (statc[0] % 2 == 0)) {
int x = ((statc[0] - 20) / 2) - 1;
for(int y = (field.getHiddenHeight() * -1); y < field.getHeight(); y++) {
field.setBlock(field.getWidth() - x - 1, y, interruptItemMirrorField.getBlock(x, y));
}
} else if(statc[0] < 21 + (field.getWidth() * 2) + 5) {
} else {
statc[0] = 0;
interruptItemMirrorField = null;
return false;
}
statc[0]++;
return true;
}
} |
package org.netmelody.cii.witness.teamcity;
import static com.google.common.collect.Collections2.filter;
import static com.google.common.collect.Collections2.transform;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.netmelody.cii.domain.Feature;
import org.netmelody.cii.domain.Sponsor;
import org.netmelody.cii.domain.Status;
import org.netmelody.cii.domain.Target;
import org.netmelody.cii.domain.TargetGroup;
import org.netmelody.cii.persistence.Detective;
import org.netmelody.cii.witness.Witness;
import org.netmelody.cii.witness.protocol.RestRequester;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public final class TeamCityWitness implements Witness {
private final Gson json = new GsonBuilder().create();
private final RestRequester restRequester = new RestRequester();
private final String endpoint;
public TeamCityWitness(String endpoint) {
this.endpoint = endpoint;
}
public static void main(String[] args) {
final Feature feature = new Feature("HIP - Trunk", "http://teamcity-server:8111");
final TeamCityWitness witness = new TeamCityWitness(feature.endpoint());
witness.statusOf(feature);
}
@Override
public TargetGroup statusOf(final Feature feature) {
restRequester.makeRequest(endpoint + "/guestAuth/");
if (!endpoint.equals(feature.endpoint())) {
return new TargetGroup();
}
final Project project = filter(projects(), new Predicate<Project>() {
@Override public boolean apply(Project project) {
return project.name.startsWith(feature.name());
}
}).iterator().next();
final Collection<Target> targets = transform(buildTypesFor(project), new Function<BuildType, Target>() {
@Override public Target apply(BuildType buildType) {
return targetFrom(buildType);
}
});
return new TargetGroup(targets);
}
@Override
public long millisecondsUntilNextUpdate() {
return 0L;
}
private Collection<Project> projects() {
return makeTeamCityRestCall(endpoint + "/app/rest/projects", TeamCityProjects.class).project;
}
private Collection<BuildType> buildTypesFor(Project projectDigest) {
return makeTeamCityRestCall(endpoint + projectDigest.href, ProjectDetail.class).buildTypes.buildType;
}
private Target targetFrom(BuildType buildType) {
final BuildTypeDetail buildTypeDetail = makeTeamCityRestCall(endpoint + buildType.href, BuildTypeDetail.class);
if (buildTypeDetail.paused) {
return new Target(buildType.id, buildType.name, Status.DISABLED);
}
final Builds builds = makeTeamCityRestCall(endpoint + buildTypeDetail.builds.href, Builds.class);
if (builds.build == null || builds.build.isEmpty()) {
return new Target(buildType.id, buildType.name, Status.GREEN);
}
final Build lastBuild = builds.build.iterator().next();
final BuildDetail lastBuildDetail = makeTeamCityRestCall(endpoint + lastBuild.href, BuildDetail.class);
final List<Sponsor> sponsors = sponsorsOf(lastBuildDetail);
return new Target(buildType.id, buildType.name, lastBuildDetail.status(), sponsors);
}
private List<Sponsor> sponsorsOf(BuildDetail build) {
return new Detective().sponsorsOf(analyseChanges(build));
}
private String analyseChanges(BuildDetail build) {
if (build.changes == null) {
return "";
}
final List<Change> changes = new ArrayList<Change>();
if (build.changes.count == 1) {
changes.add(makeTeamCityRestCall(endpoint + build.changes.href, ChangesOne.class).change);
}
else {
changes.addAll(makeTeamCityRestCall(endpoint + build.changes.href, ChangesMany.class).change);
}
final StringBuilder result = new StringBuilder();
for (Change change : changes) {
final ChangeDetail changeDetail = makeTeamCityRestCall(endpoint + change.href, ChangeDetail.class);
result.append(changeDetail.comment);
result.append(changeDetail.username);
}
return result.toString();
}
private <T> T makeTeamCityRestCall(String url, Class<T> type) {
return json.fromJson(restRequester.makeRequest(url).replace("\"@", "\""), type);
}
static class TeamCityProjects {
List<Project> project;
}
static class Project {
String name;
String id;
String href;
}
static class ProjectDetail extends Project {
String webUrl;
String description;
boolean archived;
BuildTypes buildTypes;
}
static class BuildTypes {
List<BuildType> buildType;
}
static class BuildType {
String id;
String name;
String href;
String projectName;
String projectId;
String webUrl;
}
static class BuildTypeDetail extends BuildType {
String description;
boolean paused;
Project project;
BuildsHref builds;
//vcs-root
//parameters
//runParameters
}
static class BuildsHref {
String href;
}
static class Builds {
int count;
List<Build> build;
}
static class Build {
long id;
String number;
String status;
String buildTypeId;
String href;
String webUrl;
}
static class BuildDetail {
long id;
String number;
String status;
String href;
String webUrl;
boolean personal;
boolean history;
boolean pinned;
String statusText;
//buildType
//startDate
//finishDate
//agent
//tags
//properties
//revisions
ChangesHref changes;
//relatedIssues
public Status status() {
if (status == null || "SUCCESS".equals(status)) {
return Status.GREEN;
}
return Status.BROKEN;
}
}
static class ChangesHref {
String href;
int count;
}
static class ChangesOne {
//String @count
Change change;
}
static class ChangesMany {
//String @count
List<Change> change;
}
static class Change {
//@SerializedName("@version")
String version;
//@SerializedName("@id")
String id;
//@SerializedName("@href")
String href;
}
static class ChangeDetail {
String username;
//date
String version;
long id;
String href;
String comment;
//files
}
} |
package org.pentaho.di.job.entries.ssh2put;
import static org.pentaho.di.job.entry.validator.AndValidator.putValidators;
import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.andValidator;
import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.fileExistsValidator;
import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.integerValidator;
import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.notBlankValidator;
import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.notNullValidator;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.vfs.FileObject;
import org.apache.commons.vfs.FileType;
import org.pentaho.di.cluster.SlaveServer;
import org.pentaho.di.core.CheckResultInterface;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.Result;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.exception.KettleDatabaseException;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleXMLException;
import org.pentaho.di.core.logging.LogWriter;
import org.pentaho.di.core.vfs.KettleVFS;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.di.job.Job;
import org.pentaho.di.job.JobEntryType;
import org.pentaho.di.job.JobMeta;
import org.pentaho.di.job.entries.ssh2get.FTPUtils;
import org.pentaho.di.job.entry.JobEntryBase;
import org.pentaho.di.job.entry.JobEntryInterface;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.resource.ResourceEntry;
import org.pentaho.di.resource.ResourceReference;
import org.pentaho.di.resource.ResourceEntry.ResourceType;
import org.w3c.dom.Node;
import com.trilead.ssh2.Connection;
import com.trilead.ssh2.HTTPProxyData;
import com.trilead.ssh2.KnownHosts;
import com.trilead.ssh2.SFTPv3Client;
import com.trilead.ssh2.SFTPv3FileAttributes;
import com.trilead.ssh2.SFTPv3FileHandle;
/**
* This defines a SSH2 Put job entry.
*
* @author Samatar
* @since 17-12-2007
*
*/
public class JobEntrySSH2PUT extends JobEntryBase implements Cloneable, JobEntryInterface
{
LogWriter log = LogWriter.getInstance();
private String serverName;
private String userName;
private String password;
private String serverPort;
private String ftpDirectory;
private String localDirectory;
private String wildcard;
private boolean onlyGettingNewFiles; /* Don't overwrite files */
private boolean usehttpproxy;
private String httpproxyhost;
private String httpproxyport;
private String httpproxyusername;
private String httpProxyPassword;
private boolean publicpublickey;
private String keyFilename;
private String keyFilePass;
private boolean useBasicAuthentication;
private boolean createRemoteFolder;
private String afterFtpPut;
private String destinationfolder;
private boolean createDestinationFolder;
private boolean cachehostkey;
private int timeout;
static KnownHosts database = new KnownHosts();
public JobEntrySSH2PUT(String n)
{
super(n, "");
serverName=null;
publicpublickey=false;
keyFilename=null;
keyFilePass=null;
usehttpproxy=false;
httpproxyhost=null;
httpproxyport=null;
httpproxyusername=null;
httpProxyPassword=null;
serverPort="22";
useBasicAuthentication=false;
createRemoteFolder=false;
afterFtpPut="do_nothing";
destinationfolder=null;
createDestinationFolder=false;
cachehostkey=false;
timeout=0;
setID(-1L);
setJobEntryType(JobEntryType.SSH2_PUT);
}
public JobEntrySSH2PUT()
{
this("");
}
public JobEntrySSH2PUT(JobEntryBase jeb)
{
super(jeb);
}
public Object clone()
{
JobEntrySSH2PUT je = (JobEntrySSH2PUT) super.clone();
return je;
}
public String getXML()
{
StringBuffer retval = new StringBuffer(128);
retval.append(super.getXML());
retval.append(" ").append(XMLHandler.addTagValue("servername", serverName));
retval.append(" ").append(XMLHandler.addTagValue("username", userName));
retval.append(" ").append(XMLHandler.addTagValue("password", password));
retval.append(" ").append(XMLHandler.addTagValue("serverport", serverPort));
retval.append(" ").append(XMLHandler.addTagValue("ftpdirectory", ftpDirectory));
retval.append(" ").append(XMLHandler.addTagValue("localdirectory", localDirectory));
retval.append(" ").append(XMLHandler.addTagValue("wildcard", wildcard));
retval.append(" ").append(XMLHandler.addTagValue("only_new", onlyGettingNewFiles));
retval.append(" ").append(XMLHandler.addTagValue("usehttpproxy", usehttpproxy));
retval.append(" ").append(XMLHandler.addTagValue("httpproxyhost", httpproxyhost));
retval.append(" ").append(XMLHandler.addTagValue("httpproxyport", httpproxyport));
retval.append(" ").append(XMLHandler.addTagValue("httpproxyusername", httpproxyusername));
retval.append(" ").append(XMLHandler.addTagValue("httpproxypassword", httpProxyPassword));
retval.append(" ").append(XMLHandler.addTagValue("publicpublickey", publicpublickey));
retval.append(" ").append(XMLHandler.addTagValue("keyfilename", keyFilename));
retval.append(" ").append(XMLHandler.addTagValue("keyfilepass", keyFilePass));
retval.append(" ").append(XMLHandler.addTagValue("usebasicauthentication", useBasicAuthentication));
retval.append(" ").append(XMLHandler.addTagValue("createremotefolder", createRemoteFolder));
retval.append(" ").append(XMLHandler.addTagValue("afterftpput", afterFtpPut));
retval.append(" ").append(XMLHandler.addTagValue("destinationfolder", destinationfolder));
retval.append(" ").append(XMLHandler.addTagValue("createdestinationfolder", createDestinationFolder));
retval.append(" ").append(XMLHandler.addTagValue("cachehostkey", cachehostkey));
retval.append(" ").append(XMLHandler.addTagValue("timeout", timeout));
return retval.toString();
}
public void loadXML(Node entrynode, List<DatabaseMeta> databases, List<SlaveServer> slaveServers, Repository rep) throws KettleXMLException
{
try
{
super.loadXML(entrynode, databases, slaveServers);
serverName = XMLHandler.getTagValue(entrynode, "servername");
userName = XMLHandler.getTagValue(entrynode, "username");
password = XMLHandler.getTagValue(entrynode, "password");
serverPort = XMLHandler.getTagValue(entrynode, "serverport");
ftpDirectory = XMLHandler.getTagValue(entrynode, "ftpdirectory");
localDirectory = XMLHandler.getTagValue(entrynode, "localdirectory");
wildcard = XMLHandler.getTagValue(entrynode, "wildcard");
onlyGettingNewFiles = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "only_new") );
usehttpproxy = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "usehttpproxy") );
httpproxyhost = XMLHandler.getTagValue(entrynode, "httpproxyhost");
httpproxyport = XMLHandler.getTagValue(entrynode, "httpproxyport");
httpproxyusername = XMLHandler.getTagValue(entrynode, "httpproxyusername");
httpProxyPassword = XMLHandler.getTagValue(entrynode, "httpproxypassword");
publicpublickey = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "publicpublickey") );
keyFilename = XMLHandler.getTagValue(entrynode, "keyfilename");
keyFilePass = XMLHandler.getTagValue(entrynode, "keyfilepass");
useBasicAuthentication = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "usebasicauthentication") );
createRemoteFolder = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "createremotefolder") );
afterFtpPut = XMLHandler.getTagValue(entrynode, "afterftpput");
destinationfolder = XMLHandler.getTagValue(entrynode, "destinationfolder");
createDestinationFolder = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "createdestinationfolder") );
cachehostkey = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "cachehostkey") );
timeout = Const.toInt(XMLHandler.getTagValue(entrynode, "timeout"), 0);
}
catch(KettleXMLException xe)
{
throw new KettleXMLException(Messages.getString("JobSSH2PUT.Log.UnableLoadXML", xe.getMessage()));
}
}
public void loadRep(Repository rep, long id_jobentry, List<DatabaseMeta> databases, List<SlaveServer> slaveServers)
throws KettleException
{
try
{
super.loadRep(rep, id_jobentry, databases, slaveServers);
serverName = rep.getJobEntryAttributeString(id_jobentry, "servername");
userName = rep.getJobEntryAttributeString(id_jobentry, "username");
password = rep.getJobEntryAttributeString(id_jobentry, "password");
serverPort =rep.getJobEntryAttributeString(id_jobentry, "serverport");
ftpDirectory = rep.getJobEntryAttributeString(id_jobentry, "ftpdirectory");
localDirectory = rep.getJobEntryAttributeString(id_jobentry, "localdirectory");
wildcard = rep.getJobEntryAttributeString(id_jobentry, "wildcard");
onlyGettingNewFiles = rep.getJobEntryAttributeBoolean(id_jobentry, "only_new");
usehttpproxy = rep.getJobEntryAttributeBoolean(id_jobentry, "usehttpproxy");
httpproxyhost = rep.getJobEntryAttributeString(id_jobentry, "httpproxyhost");
httpproxyusername = rep.getJobEntryAttributeString(id_jobentry, "httpproxyusername");
httpProxyPassword = rep.getJobEntryAttributeString(id_jobentry, "httpproxypassword");
publicpublickey = rep.getJobEntryAttributeBoolean(id_jobentry, "publicpublickey");
keyFilename = rep.getJobEntryAttributeString(id_jobentry, "keyfilename");
keyFilePass = rep.getJobEntryAttributeString(id_jobentry, "keyfilepass");
useBasicAuthentication = rep.getJobEntryAttributeBoolean(id_jobentry, "usebasicauthentication");
createRemoteFolder = rep.getJobEntryAttributeBoolean(id_jobentry, "createremotefolder");
afterFtpPut = rep.getJobEntryAttributeString(id_jobentry, "afterftpput");
destinationfolder = rep.getJobEntryAttributeString(id_jobentry, "destinationfolder");
createDestinationFolder = rep.getJobEntryAttributeBoolean(id_jobentry, "createdestinationfolder");
cachehostkey = rep.getJobEntryAttributeBoolean(id_jobentry, "cachehostkey");
timeout = (int)rep.getJobEntryAttributeInteger(id_jobentry, "timeout");
}
catch(KettleException dbe)
{
throw new KettleException(Messages.getString("JobSSH2PUT.Log.UnableLoadRep",""+id_jobentry,dbe.getMessage()));
}
}
public void saveRep(Repository rep, long id_job)
throws KettleException
{
try
{
super.saveRep(rep, id_job);
rep.saveJobEntryAttribute(id_job, getID(), "servername", serverName);
rep.saveJobEntryAttribute(id_job, getID(), "username", userName);
rep.saveJobEntryAttribute(id_job, getID(), "password", password);
rep.saveJobEntryAttribute(id_job, getID(), "serverport", serverPort);
rep.saveJobEntryAttribute(id_job, getID(), "ftpdirectory", ftpDirectory);
rep.saveJobEntryAttribute(id_job, getID(), "localdirectory", localDirectory);
rep.saveJobEntryAttribute(id_job, getID(), "wildcard", wildcard);
rep.saveJobEntryAttribute(id_job, getID(), "only_new", onlyGettingNewFiles);
rep.saveJobEntryAttribute(id_job, getID(), "usehttpproxy", usehttpproxy);
rep.saveJobEntryAttribute(id_job, getID(), "httpproxyhost", httpproxyhost);
rep.saveJobEntryAttribute(id_job, getID(), "httpproxyport", httpproxyport);
rep.saveJobEntryAttribute(id_job, getID(), "httpproxyusername", httpproxyusername);
rep.saveJobEntryAttribute(id_job, getID(), "httpproxypassword", httpProxyPassword);
rep.saveJobEntryAttribute(id_job, getID(), "publicpublickey", publicpublickey);
rep.saveJobEntryAttribute(id_job, getID(), "keyfilename", keyFilename);
rep.saveJobEntryAttribute(id_job, getID(), "keyfilepass", keyFilePass);
rep.saveJobEntryAttribute(id_job, getID(), "usebasicauthentication", useBasicAuthentication);
rep.saveJobEntryAttribute(id_job, getID(), "createremotefolder", createRemoteFolder);
rep.saveJobEntryAttribute(id_job, getID(), "afterftpput", afterFtpPut);
rep.saveJobEntryAttribute(id_job, getID(), "destinationfolder", destinationfolder);
rep.saveJobEntryAttribute(id_job, getID(), "createdestinationfolder", createDestinationFolder);
rep.saveJobEntryAttribute(id_job, getID(), "cachehostkey", cachehostkey);
rep.saveJobEntryAttribute(id_job, getID(), "timeout", timeout);
}
catch(KettleDatabaseException dbe)
{
throw new KettleException(Messages.getString("JobSSH2PUT.Log.UnableSaveRep",""+id_job,dbe.getMessage()));
}
}
/**
* @return Returns the directory.
*/
public String getFtpDirectory()
{
return ftpDirectory;
}
/**
* @param directory The directory to set.
*/
public void setFtpDirectory(String directory)
{
this.ftpDirectory = directory;
}
/**
* @return Returns the password.
*/
public String getPassword()
{
return password;
}
/**
* @param password The password to set.
*/
public void setPassword(String password)
{
this.password = password;
}
/**
* @return Returns The action to do after transfer
*/
public String getAfterFTPPut()
{
return afterFtpPut;
}
/**
* @param afterFtpPut The action to do after transfer
*/
public void setAfterFTPPut(String afterFtpPut)
{
this.afterFtpPut = afterFtpPut;
}
/**
* @param httpProxyPassword The HTTP proxy password to set.
*/
public void setHTTPProxyPassword(String httpProxyPassword)
{
this.httpProxyPassword = httpProxyPassword;
}
/**
* @return Returns the password.
*/
public String getHTTPProxyPassword()
{
return httpProxyPassword;
}
/**
* @param keyFilePass The key file pass to set.
*/
public void setKeyFilepass(String keyFilePass)
{
this.keyFilePass = keyFilePass;
}
/**
* @return Returns the key file pass.
*/
public String getKeyFilepass()
{
return keyFilePass;
}
/**
* @return Returns the serverName.
*/
public String getServerName()
{
return serverName;
}
/**
* @param serverName The serverName to set.
*/
public void setServerName(String serverName)
{
this.serverName = serverName;
}
/**
* @param proxyhost The httpproxyhost to set.
*/
public void setHTTPProxyHost(String proxyhost)
{
this.httpproxyhost = proxyhost;
}
/**
* @return Returns the httpproxyhost.
*/
public String getHTTPProxyHost()
{
return httpproxyhost;
}
/**
* @param keyFilename The key filename to set.
*/
public void setKeyFilename(String keyFilename)
{
this.keyFilename = keyFilename;
}
/**
* @return Returns the key filename.
*/
public String getKeyFilename()
{
return keyFilename;
}
/**
* @return Returns the userName.
*/
public String getUserName()
{
return userName;
}
/**
* @param userName The userName to set.
*/
public void setUserName(String userName)
{
this.userName = userName;
}
/**
* @param proxyusername The httpproxyusername to set.
*/
public void setHTTPProxyUsername(String proxyusername)
{
this.httpproxyusername = proxyusername;
}
/**
* @return Returns the userName.
*/
public String getHTTPProxyUsername()
{
return httpproxyusername;
}
/**
* @return Returns the wildcard.
*/
public String getWildcard()
{
return wildcard;
}
/**
* @param wildcard The wildcard to set.
*/
public void setWildcard(String wildcard)
{
this.wildcard = wildcard;
}
/**
* @return Returns the localDirectory.
*/
public String getlocalDirectory()
{
return localDirectory;
}
/**
* @param localDirectory The localDirectory to set.
*/
public void setlocalDirectory(String localDirectory)
{
this.localDirectory = localDirectory;
}
/**
* @return Returns the onlyGettingNewFiles.
*/
public boolean isOnlyGettingNewFiles()
{
return onlyGettingNewFiles;
}
/**
* @param onlyGettingNewFiles The onlyGettingNewFiles to set.
*/
public void setOnlyGettingNewFiles(boolean onlyGettingNewFiles)
{
this.onlyGettingNewFiles = onlyGettingNewFiles;
}
/**
* @param cachehostkeyin The cachehostkey to set.
*/
public void setCacheHostKey(boolean cachehostkeyin)
{
this.cachehostkey = cachehostkeyin;
}
/**
* @return Returns the cachehostkey.
*/
public boolean isCacheHostKey()
{
return cachehostkey;
}
/**
* @param httpproxy The usehttpproxy to set.
*/
public void setUseHTTPProxy(boolean httpproxy)
{
this.usehttpproxy = httpproxy;
}
/**
* @return Returns the usehttpproxy.
*/
public boolean isUseHTTPProxy()
{
return usehttpproxy;
}
/**
* @return Returns the usebasicauthentication.
*/
public boolean isUseBasicAuthentication()
{
return useBasicAuthentication;
}
/**
* @param useBasicAuthenticationin The use basic authentication flag to set.
*/
public void setUseBasicAuthentication(boolean useBasicAuthenticationin)
{
this.useBasicAuthentication = useBasicAuthenticationin;
}
/**
* @param createRemoteFolder The create remote folder flag to set.
*/
public void setCreateRemoteFolder(boolean createRemoteFolder)
{
this.createRemoteFolder = createRemoteFolder;
}
/**
* @return Returns the create remote folder flag.
*/
public boolean isCreateRemoteFolder()
{
return createRemoteFolder;
}
/**
* @param createDestinationFolder The create destination folder flag to set.
*/
public void setCreateDestinationFolder(boolean createDestinationFolder)
{
this.createDestinationFolder = createDestinationFolder;
}
/**
* @return Returns the create destination folder flag
*/
public boolean isCreateDestinationFolder()
{
return createDestinationFolder;
}
/**
* @param publickey The publicpublickey to set.
*/
public void setUsePublicKey(boolean publickey)
{
this.publicpublickey = publickey;
}
/**
* @return Returns the usehttpproxy.
*/
public boolean isUsePublicKey()
{
return publicpublickey;
}
public String getServerPort() {
return serverPort;
}
public void setServerPort(String serverPort) {
this.serverPort = serverPort;
}
public void setHTTPProxyPort(String proxyport) {
this.httpproxyport = proxyport;
}
public String getHTTPProxyPort() {
return httpproxyport;
}
public void setDestinationFolder(String destinationfolderin) {
this.destinationfolder = destinationfolderin;
}
public String getDestinationFolder() {
return destinationfolder;
}
/**
* @param timeout The timeout to set.
*/
public void setTimeout(int timeout)
{
this.timeout = timeout;
}
/**
* @return Returns the timeout.
*/
public int getTimeout()
{
return timeout;
}
public Result execute(Result previousResult, int nr, Repository rep, Job parentJob)
{
LogWriter log = LogWriter.getInstance();
Result result = previousResult;
result.setResult( false );
try {
// Get real variable value
String realServerName=environmentSubstitute(serverName);
int realServerPort=Const.toInt(environmentSubstitute(serverPort),22);
String realUserName=environmentSubstitute(userName);
String realServerPassword=environmentSubstitute(password);
// Proxy Host
String realProxyHost=environmentSubstitute(httpproxyhost);
int realProxyPort=Const.toInt(environmentSubstitute(httpproxyport),22);
String realproxyUserName=environmentSubstitute(httpproxyusername);
String realProxyPassword=environmentSubstitute(httpProxyPassword);
// Key file
String realKeyFilename=environmentSubstitute(keyFilename);
String relKeyFilepass=environmentSubstitute(keyFilePass);
// Source files
String realLocalDirectory=environmentSubstitute(localDirectory);
String realwildcard=environmentSubstitute(wildcard);
// Remote destination
String realftpDirectory=environmentSubstitute(ftpDirectory);
// Destination folder (Move to)
String realDestinationFolder=environmentSubstitute(destinationfolder);
try{
// Remote source
realftpDirectory=FTPUtils.normalizePath(realftpDirectory);
// Destination folder (Move to)
realDestinationFolder=FTPUtils.normalizePath(realDestinationFolder);
}catch(Exception e){
log.logError(toString(),Messages.getString("JobSSH2PUT.Log.CanNotNormalizePath",e.getMessage()));
result.setNrErrors(1);
return result;
}
// Check for mandatory fields
boolean mandatoryok=true;
if(Const.isEmpty(realServerName))
{
mandatoryok=false;
log.logError(toString(),Messages.getString("JobSSH2PUT.Log.ServernameMissing"));
}
if(usehttpproxy)
{
if(Const.isEmpty(realProxyHost))
{
mandatoryok=false;
log.logError(toString(),Messages.getString("JobSSH2PUT.Log.HttpProxyhostMissing"));
}
}
if(publicpublickey)
{
if(Const.isEmpty(realKeyFilename))
{
mandatoryok=false;
log.logError(toString(),Messages.getString("JobSSH2PUT.Log.KeyFileMissing"));
}else
{
// Let's check if folder exists...
if(!KettleVFS.fileExists(realKeyFilename))
{
mandatoryok=false;
log.logError(toString(),Messages.getString("JobSSH2PUT.Log.KeyFileNotExist"));
}
}
}
if(Const.isEmpty(realLocalDirectory))
{
mandatoryok=false;
log.logError(toString(),Messages.getString("JobSSH2PUT.Log.LocalFolderMissing"));
}
if(afterFtpPut.equals("move_file"))
{
if(Const.isEmpty(realDestinationFolder))
{
mandatoryok=false;
log.logError(toString(),Messages.getString("JobSSH2PUT.Log.DestinatFolderMissing"));
}else{
// Let's check if folder exists...
if(!KettleVFS.fileExists(realDestinationFolder))
{
mandatoryok=false;
log.logError(toString(),Messages.getString("JobSSH2PUT.Log.DestinatFolderNotExist",realDestinationFolder));
}
}
}
if(mandatoryok)
{
Connection conn = null;
SFTPv3Client client = null;
boolean good=true;
int nbfilestoput=0;
int nbput=0;
int nbrerror=0;
try
{
// Create a connection instance
conn = getConnection(realServerName,realServerPort,realProxyHost,realProxyPort,realproxyUserName,realProxyPassword);
if(timeout>0){
// Use timeout
// Cache Host Key
if(cachehostkey) conn.connect(new SimpleVerifier(database),0,timeout*1000);
else conn.connect(null,0,timeout*1000);
}else{
// Cache Host Key
if(cachehostkey) conn.connect(new SimpleVerifier(database));
else conn.connect();
}
// Authenticate
boolean isAuthenticated = false;
if(publicpublickey){
String keyContent = KettleVFS.getTextFileContent(realKeyFilename, Const.XML_ENCODING);
isAuthenticated=conn.authenticateWithPublicKey(realUserName, keyContent.toCharArray(), relKeyFilepass);
}else{
isAuthenticated=conn.authenticateWithPassword(realUserName, realServerPassword);
}
// LET'S CHECK AUTHENTICATION ...
if (isAuthenticated == false)
log.logError(toString(),Messages.getString("JobSSH2PUT.Log.AuthenticationFailed"));
else
{
if(log.isBasic()) log.logBasic(toString(),Messages.getString("JobSSH2PUT.Log.Connected",serverName,userName));
client = new SFTPv3Client(conn);
if(log.isDetailed()) log.logDetailed(toString(), Messages.getString("JobSSH2PUT.Log.ProtocolVersion",""+client.getProtocolVersion()));
// Check if remote directory exists
if(!Const.isEmpty(realftpDirectory))
{
if (!sshDirectoryExists(client, realftpDirectory))
{
good=false;
if(createRemoteFolder)
{
good=CreateRemoteFolder(client,realftpDirectory);
if(good) log.logBasic(toString(),Messages.getString("JobSSH2PUT.Log.RemoteDirectoryCreated"));
}
else
log.logError(toString(),Messages.getString("JobSSH2PUT.Log.RemoteDirectoryNotExist",realftpDirectory));
}
else
if(log.isDetailed()) log.logDetailed(toString(),Messages.getString("JobSSH2PUT.Log.RemoteDirectoryExist",realftpDirectory));
}
if (good)
{
// Get files list from local folder (source)
List<FileObject> myFileList = getFiles(realLocalDirectory);
// Prepare Pattern for wildcard
Pattern pattern = null;
if (!Const.isEmpty(realwildcard)) pattern = Pattern.compile(realwildcard);
// Let's put files now ...
// Get the files in the list
for (int i=0;i<myFileList.size() && !parentJob.isStopped();i++)
{
FileObject myFile = myFileList.get(i);
String localFilename = myFile.toString();
String remoteFilename = myFile.getName().getBaseName();
// do we have a target directory?
if(!Const.isEmpty(realftpDirectory)) remoteFilename=realftpDirectory + FTPUtils.FILE_SEPARATOR +remoteFilename;
boolean getIt = true;
// First see if the file matches the regular expression!
if (pattern!=null){
Matcher matcher = pattern.matcher(remoteFilename);
getIt = matcher.matches();
}
if(getIt)
{
nbfilestoput++;
boolean putok=true;
if ( (onlyGettingNewFiles == false) ||
(onlyGettingNewFiles == true) && !sshFileExists(client, remoteFilename))
{
putok=putFile(myFile, remoteFilename, client,log);
if(!putok) {
nbrerror++;
log.logError(toString(),Messages.getString("JobSSH2PUT.Log.Error.CanNotPutFile",localFilename));
}else{
nbput++;
}
}
if(putok && !afterFtpPut.equals("do_nothing")){
deleteOrMoveFiles(myFile,realDestinationFolder);
}
}
}
if(log.isDetailed())
{
log.logDetailed(toString(), Messages.getString("JobSSH2PUT.Log.Result.JobEntryEnd1"));
log.logDetailed(toString(), Messages.getString("JobSSH2PUT.Log.Result.TotalFiles",""+nbfilestoput));
log.logDetailed(toString(), Messages.getString("JobSSH2PUT.Log.Result.TotalFilesPut",""+nbput));
log.logDetailed(toString(), Messages.getString("JobSSH2PUT.Log.Result.TotalFilesError",""+nbrerror));
log.logDetailed(toString(), Messages.getString("JobSSH2PUT.Log.Result.JobEntryEnd2"));
}
if(nbrerror==0) result.setResult(true);
}
}
}
catch (Exception e)
{
result.setNrErrors(nbrerror);
log.logError(toString(), Messages.getString("JobSSH2PUT.Log.Error.ErrorFTP",e.getMessage()));
}
finally
{
if (conn!=null) conn.close();
if(client!=null) client.close();
}
}
}
catch(Exception e) {
result.setResult(false);
result.setNrErrors(1L);
log.logError(toString(), Messages.getString("JobSSH2PUT.Log.Error.UnexpectedError"), e);
}
return result;
}
private Connection getConnection(String servername,int serverpassword,
String proxyhost,int proxyport,String proxyusername,String proxypassword)
{
/* Create a connection instance */
Connection connnect = new Connection(servername,serverpassword);
/* We want to connect through a HTTP proxy */
if(usehttpproxy)
{
connnect.setProxyData(new HTTPProxyData(proxyhost, proxyport));
/* Now connect */
// if the proxy requires basic authentication:
if(useBasicAuthentication)
{
connnect.setProxyData(new HTTPProxyData(proxyhost, proxyport, proxyusername, proxypassword));
}
}
return connnect;
}
private boolean putFile(FileObject localFile, String remotefilename, SFTPv3Client sftpClient,LogWriter log)
{
long filesize=-1;
InputStream in = null;
BufferedInputStream inBuf = null;
SFTPv3FileHandle sftpFileHandle=null;
boolean retval=false;
try
{
// Put file in the folder
sftpFileHandle=sftpClient.createFileTruncate(remotefilename);
// Associate a file input stream for the current local file
in = KettleVFS.getInputStream(localFile);
inBuf = new BufferedInputStream(in);
byte[] buf = new byte[2048];
long offset = 0;
long length = localFile.getContent().getSize();
if(log.isDetailed()) log.logDetailed(toString(),Messages.getString("JobSSH2PUT.Log.SendingFile",localFile.toString()
,""+length,remotefilename));
// Write to remote file
while(true){
int len = in.read(buf, 0, buf.length);
if(len <= 0) break;
sftpClient.write(sftpFileHandle, offset, buf, 0, len);
offset += len;
}
// Get File size
filesize=getFileSize(sftpClient, remotefilename) ;
if(log.isDetailed()) log.logDetailed(toString(),Messages.getString("JobSSH2PUT.Log.FileOnRemoteHost",
remotefilename,""+filesize));
retval= true;
} catch(Exception e)
{
// We failed to put files
log.logError(toString(),Messages.getString("JobSSH2PUT.Log.ErrorCopyingFile",localFile.toString())+":"+e.getMessage());
}
finally
{
if (in != null)
{
try
{
in.close();
in = null;
}
catch (Exception ex) {}
}
if(inBuf!=null)
{
try
{
inBuf.close();
inBuf = null;
}
catch (Exception ex) {}
}
if(sftpFileHandle!=null)
{
try
{
sftpClient.closeFile(sftpFileHandle);
sftpFileHandle=null;
} catch (Exception ex) {}
}
}
return retval;
}
/**
* Check existence of a file
*
* @param sftpClient
* @param filename
* @return true, if file exists
* @throws Exception
*/
public boolean sshFileExists(SFTPv3Client sftpClient, String filename) {
try {
SFTPv3FileAttributes attributes = sftpClient.stat(filename);
if (attributes != null) {
return (attributes.isRegularFile());
} else {
return false;
}
} catch (Exception e) {
return false;
}
}
/**
* Checks if a directory exists
*
* @param sftpClient
* @param directory
* @return true, if directory exists
*/
public boolean sshDirectoryExists(SFTPv3Client sftpClient, String directory) {
try {
SFTPv3FileAttributes attributes = sftpClient.stat(directory);
if (attributes != null) {
return (attributes.isDirectory());
} else {
return false;
}
} catch (Exception e) {
return false;
}
}
/**
* Create remote folder
*
* @param sftpClient
* @param foldername
* @return true, if foldername is created
*/
private boolean CreateRemoteFolder(SFTPv3Client sftpClient, String foldername)
{
LogWriter log = LogWriter.getInstance();
boolean retval=false;
if(!sshDirectoryExists(sftpClient, foldername))
{
try
{
sftpClient.mkdir(foldername, 0700);
retval=true;
}catch (Exception e)
{
log.logError(toString(), Messages.getString("JobSSH2PUT.Log.Error.CreatingRemoteFolder",foldername));
}
}
return retval;
}
/**
* Returns the file size of a file
*
* @param sftpClient
* @param filename
* @return the size of the file
* @throws Exception
*/
public long getFileSize(SFTPv3Client sftpClient, String filename) throws Exception
{
return sftpClient.stat(filename).size.longValue();
}
private List<FileObject> getFiles(String localfolder) throws IOException
{
List<FileObject> myFileList = new ArrayList<FileObject>();
// Get all the files in the local directory...
FileObject localFiles = KettleVFS.getFileObject(localfolder);
FileObject[] children = localFiles.getChildren();
if (children!=null)
{
for (int i=0; i<children.length; i++)
{
// Get filename of file or directory
if (children[i].getType().equals(FileType.FILE))
{
myFileList.add(children[i]);
}
} // end for
}
return myFileList;
}
private boolean deleteOrMoveFiles(FileObject file, String destinationFolder) throws KettleException
{
try {
boolean retval=false;
// Delete the file if this is needed!
if (afterFtpPut.equals("delete_file"))
{
file.delete();
retval=true;
if (log.isDetailed()) log.logDetailed(toString(), Messages.getString("JobSSH2PUT.Log.DeletedFile",file.toString()));
}
else if (afterFtpPut.equals("move_file"))
{
// Move File
FileObject destination=null;
FileObject source=null;
try
{
destination = KettleVFS.getFileObject(destinationFolder + Const.FILE_SEPARATOR + file.getName().getBaseName());
file.moveTo(destination);
retval=true;
}
catch (Exception e)
{
log.logError(toString(), Messages.getString("JobSSH2PUT.Cant_Move_File.Label",file.toString(),destinationFolder,e.getMessage()));
}
finally
{
if ( destination != null )
{try {destination.close();}catch (Exception ex ) {};}
if ( source != null )
{try {source.close();}
catch (Exception ex ) {};
}
}
if (log.isDetailed()) log.logDetailed(toString(), Messages.getString("JobSSH2PUT.Log.MovedFile",file.toString(),ftpDirectory));
}
return retval;
}
catch(Exception e) {
throw new KettleException(e);
}
}
public boolean evaluates()
{
return true;
}
public List<ResourceReference> getResourceDependencies(JobMeta jobMeta) {
List<ResourceReference> references = super.getResourceDependencies(jobMeta);
if (!Const.isEmpty(serverName)) {
String realServerName = jobMeta.environmentSubstitute(serverName);
ResourceReference reference = new ResourceReference(this);
reference.getEntries().add( new ResourceEntry(realServerName, ResourceType.SERVER));
references.add(reference);
}
return references;
}
@Override
public void check(List<CheckResultInterface> remarks, JobMeta jobMeta)
{
andValidator().validate(this, "serverName", remarks, putValidators(notBlankValidator())); //$NON-NLS-1$
andValidator()
.validate(this, "localDirectory", remarks, putValidators(notBlankValidator(), fileExistsValidator())); //$NON-NLS-1$
andValidator().validate(this, "userName", remarks, putValidators(notBlankValidator())); //$NON-NLS-1$
andValidator().validate(this, "password", remarks, putValidators(notNullValidator())); //$NON-NLS-1$
andValidator().validate(this, "serverPort", remarks, putValidators(integerValidator())); //$NON-NLS-1$
}
} |
// 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 the future.
package org.usfirst.frc5933.StevenDave.commands;
import edu.wpi.first.wpilibj.command.CommandGroup;
import org.usfirst.frc5933.StevenDave.RobotMap;
import org.usfirst.frc5933.StevenDave.subsystems.*;
public class Pos1LowBar extends CommandGroup {
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=PARAMETERS
public Pos1LowBar() {
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=PARAMETERS
// Add Commands here:
// e.g. addSequential(new Command1());
// addSequential(new Command2());
// these will run in order.
// To run multiple commands at the same time,
// use addParallel()
// e.g. addParallel(new Command1());
// addSequential(new Command2());
// Command1 and Command2 will run in parallel.
// A command group will require all of the subsystems that each member
// would require.
// e.g. if Command1 requires chassis, and Command2 requires arm,
// a CommandGroup containing them would require both the chassis and the
// arm.
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=COMMAND_DECLARATIONS
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=COMMAND_DECLARATIONS
addParallel(new LiftingArmDown(1));
RobotMap.helmsman.resetGyro();
addSequential(new EncoderDriveStraight(65);
addSequential(new EncoderTurnDegrees(173));
RobotMap.helmsman.resetEncoder();
addSequential(new EncoderDriveStraight(65));
addSequential(new EncoderTurnDegrees(174));
RobotMap.helmsman.resetEncoder();
addSequential(new EncoderDriveStraight(63));
}
} |
package gov.nih.nci.cabig.caaers.resolver;
import edu.duke.cabig.c3pr.esb.Metadata;
import edu.duke.cabig.c3pr.esb.OperationNameEnum;
import edu.duke.cabig.c3pr.esb.ServiceTypeEnum;
import gov.nih.nci.cabig.caaers.CaaersSystemException;
import gov.nih.nci.cabig.caaers.esb.client.MessageBroadcastService;
import gov.nih.nci.cabig.caaers.tools.configuration.Configuration;
import gov.nih.nci.cabig.caaers.utils.XMLUtil;
import gov.nih.nci.coppa.po.Bl;
import gov.nih.nci.coppa.po.CorrelationNode;
import gov.nih.nci.coppa.po.IdentifiedOrganization;
import gov.nih.nci.coppa.po.IdentifiedPerson;
import gov.nih.nci.coppa.po.Organization;
import gov.nih.nci.coppa.po.Person;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.iso._21090.DSETII;
import org.iso._21090.II;
public abstract class BaseResolver {
private MessageBroadcastService messageBroadcastService;
private static Log log = LogFactory.getLog(BaseResolver.class);
private static final String CTEP_PERSON = "Cancer Therapy Evaluation Program Person Identifier";
public static final String PERSON_ROOT = "2.16.840.1.113883.3.26.4.1";
private static final String CTEP_ID = "CTEP ID";
/**
*
* @param organizationNciIdentifier
* @param role
* @return
*/
protected List<Object> searchRoleBasedOnOrganization(String organizationNciIdentifier,gov.nih.nci.coppa.po.Correlation role){
//Get IdentifiedOrganization by ctepId
IdentifiedOrganization identifiedOrganizationSearchCriteria = CoppaObjectFactory.getCoppaIdentfiedOrganizationSearchCriteriaOnCTEPId(organizationNciIdentifier);
String payload = CoppaObjectFactory.getCoppaIdentfiedOrganization(identifiedOrganizationSearchCriteria);
String results = null;
try {
results = broadcastIdentifiedOrganizationSearch(payload);
} catch (Exception e) {
log.error(e.getMessage());
}
//Assuming here that the ctepCode search yields exactly one organization
List<String> resultObjects = XMLUtil.getObjectsFromCoppaResponse(results);
if(resultObjects.size() == 0){
return new ArrayList<Object>();
}
if(resultObjects.size() > 1){
log.error("searchRoleBasedOnOrganization: The ctep code matches more than one organization. The current implementation uses only the first match as it" +
"assumes the ctep code search to always yield one exact match.");
}
IdentifiedOrganization coppaIdOrganization = CoppaObjectFactory.getCoppaIdentfiedOrganization(resultObjects.get(0));
II organizationIdentifier = coppaIdOrganization.getPlayerIdentifier();
gov.nih.nci.coppa.po.Organization organization = CoppaObjectFactory.getCoppaOrganizationFromII(organizationIdentifier);
String correlationNodeXmlPayload = CoppaObjectFactory.getCorrelationNodePayload(role, null, organization);
List<CorrelationNode> correlationNodeList = getCorrelationNodesFromPayloadXml(correlationNodeXmlPayload);
List<Person> listOfAllPersons = new ArrayList<Person>();
Person person = null;
for(CorrelationNode cNode: correlationNodeList){
person = getCoppaPersonFromCorrelationNode(cNode);
if(person != null){
listOfAllPersons.add(person);
}
}
//Use the list of all persons to build a map of identified persons using the getByPlayerIds operation.
Map<String, List<IdentifiedPerson>> personIdToIdentifiedPersonMap =
getIdentifiedPersonsForPersonList(listOfAllPersons);
List<Object> remoteRoleList = new ArrayList<Object>();
Object populatedRole = null;
Person coppaPerson = null;
String assignedIdentifier;
for(CorrelationNode cNode: correlationNodeList){
assignedIdentifier = null;
coppaPerson = getCoppaPersonFromCorrelationNode(cNode);
assignedIdentifier = getAssignedIdentifierFromCorrelationNode(coppaPerson, personIdToIdentifiedPersonMap);
if(assignedIdentifier == null){
assignedIdentifier = coppaPerson.getIdentifier().getExtension();
}
populatedRole = populateRole(coppaPerson, assignedIdentifier, coppaIdOrganization);
if(populatedRole != null){
remoteRoleList.add(populatedRole);
}
}
return remoteRoleList;
}
/**
*
* @param nciIdentifier
* @param role
* @return
*/
protected List<Object> searchRoleBasedOnNciId(String nciIdentifier,gov.nih.nci.coppa.po.Correlation role) {
List<Object> remoteRoleList = new ArrayList<Object>();
List<IdentifiedPerson> identifiedPersonsList = new ArrayList<IdentifiedPerson>();
if (nciIdentifier != null) {
//get Identified Organization using the Identifier provided
IdentifiedPerson identifiedPersonToSearch = CoppaObjectFactory.getCoppaIdentfiedPersonSearchCriteriaOnCTEPId(nciIdentifier);
IdentifiedPerson exactMatchIdentifiedPersonResult = getIdentifiedPerson(identifiedPersonToSearch,nciIdentifier);
if (exactMatchIdentifiedPersonResult == null) {
return remoteRoleList;
} else {
identifiedPersonsList.add(exactMatchIdentifiedPersonResult);
}
}
String personIiExtension = null;
Person person = null;
String correlationNodeXmlPayload = null;
List<CorrelationNode> correlationNodeList = null;
//Get the Role corresponding to every Identified Person fetched. Because the identifiedPerson search by CTEP code is a
//like match not exact match and can return more than one result.
for(int i=0; i<identifiedPersonsList.size(); i++ ){
personIiExtension = identifiedPersonsList.get(i).getPlayerIdentifier().getExtension();
if(personIiExtension == null){
return remoteRoleList;
}
person = CoppaObjectFactory.getCoppaPersonForExtension(personIiExtension);
correlationNodeXmlPayload = CoppaObjectFactory.getCorrelationNodePayload(role, person, null);
correlationNodeList = getCorrelationNodesFromPayloadXml(correlationNodeXmlPayload);
remoteRoleList.addAll(getRemoteRolesFromCorrelationNodesList(correlationNodeList));
}
return remoteRoleList;
}
/**
*
* @param firstName
* @param middleName
* @param lastName
* @param role (instance of HealthCareProvide or ClinicalResearchStaff)
* @return
*/
protected List<Object> searchRoleBasedOnName(String firstName,String middleName, String lastName, gov.nih.nci.coppa.po.Correlation role) {
Person person = CoppaObjectFactory.getCoppaPerson(firstName, middleName, lastName);
String correlationNodeXmlPayload = CoppaObjectFactory.getCorrelationNodePayload(role, person, null);
List<CorrelationNode> correlationNodeList = getCorrelationNodesFromPayloadXml(correlationNodeXmlPayload);
List<Object> remoteRoleList = getRemoteRolesFromCorrelationNodesList(correlationNodeList);
return remoteRoleList;
}
/**
* Gets the remote investigators/rs from correlation nodes list.
*
* @param correlationNodeList the correlation node list
* @return the remote investigators/rs from correlation nodes list
*/
protected List<Object> getRemoteRolesFromCorrelationNodesList(
List<CorrelationNode> correlationNodeList) {
List<Object> remoteRoleList = new ArrayList<Object>();
HashMap<String, List<gov.nih.nci.coppa.po.Organization>> personIdToCoppaOrganizationsHashMap = new HashMap<String, List<gov.nih.nci.coppa.po.Organization>>();
List<gov.nih.nci.coppa.po.Organization> listOfAllOrganizations = new ArrayList<gov.nih.nci.coppa.po.Organization>();
List<Person> listOfAllPersons = new ArrayList<Person>();
Person tempPerson = null;
//gov.nih.nci.coppa.po.Organization tempOrganization = null;
for(CorrelationNode cNode: correlationNodeList){
tempPerson = getCoppaPersonFromCorrelationNode(cNode);
List<gov.nih.nci.coppa.po.Organization> orgsFromCorrelation = getCoppaOrganizationFromCorrelationNode(cNode);
//building a list of all organizations
for (gov.nih.nci.coppa.po.Organization tempOrganization:orgsFromCorrelation) {
listOfAllOrganizations.add(tempOrganization);
}
List<gov.nih.nci.coppa.po.Organization> organizationList = null;
if(personIdToCoppaOrganizationsHashMap.containsKey(tempPerson.getIdentifier().getExtension())){
organizationList = personIdToCoppaOrganizationsHashMap.get(tempPerson.getIdentifier().getExtension());
for (gov.nih.nci.coppa.po.Organization tempOrganization:orgsFromCorrelation) {
organizationList.add(tempOrganization);
}
} else {
organizationList = new ArrayList<gov.nih.nci.coppa.po.Organization>();
for (gov.nih.nci.coppa.po.Organization tempOrganization:orgsFromCorrelation) {
organizationList.add(tempOrganization);
}
personIdToCoppaOrganizationsHashMap.put(tempPerson.getIdentifier().getExtension(), organizationList);
//building a list of all persons. This is in the else loop because different correlationNodes can have the same person.
//So we only add when the personIdToCoppaOrganizationsHashMap does not contain the personId as the key.
listOfAllPersons.add(tempPerson);
}
}
Map<String, IdentifiedOrganization> organizationIdToIdentifiedOrganizationsMap =
getIdentifiedOrganizationsForOrganizationsList(listOfAllOrganizations);
Map<String, List<IdentifiedPerson>> personIdToIdentifiedPersonMap =
getIdentifiedPersonsForPersonList(listOfAllPersons);
Object populatedRole = null;
for(CorrelationNode cNode: correlationNodeList){
Person coppaPerson = getCoppaPersonFromCorrelationNode(cNode);
String assignedIdentifier = getAssignedIdentifierFromCorrelationNode(coppaPerson, personIdToIdentifiedPersonMap);
if(assignedIdentifier == null){
assignedIdentifier = coppaPerson.getIdentifier().getExtension();
}
populatedRole = populateRole(coppaPerson, assignedIdentifier,
personIdToCoppaOrganizationsHashMap.get(coppaPerson.getIdentifier().getExtension()), organizationIdToIdentifiedOrganizationsMap);
if(populatedRole != null){
remoteRoleList.add(populatedRole);
}
}
return remoteRoleList;
}
/**
*
* @param coppaPerson
* @param staffAssignedIdentifier
* @param coppaOrganizationList
* @param organizationIdToIdentifiedOrganizationsMap
* @return
*/
public abstract Object populateRole(Person coppaPerson, String staffAssignedIdentifier, List<gov.nih.nci.coppa.po.Organization> coppaOrganizationList,
Map<String, IdentifiedOrganization> organizationIdToIdentifiedOrganizationsMap);
/**
*
* @param coppaPerson
* @param staffAssignedIdentifier
* @param identifiedOrganization
* @return
*/
public abstract Object populateRole(Person coppaPerson, String staffAssignedIdentifier, IdentifiedOrganization identifiedOrganization);
/**
*
* @param correlationNodeXml
* @param player
* @param scoper
* @return
*/
protected String broadcastSearchCorrelationsWithEntities(String correlationNodeXml, boolean player, boolean scoper) {
Metadata mData = new Metadata("searchCorrelationsWithEntities", "externalId", "PO_BUSINESS");
List<String> cctsDomainObjectXMLList = new ArrayList<String>();
cctsDomainObjectXMLList.add(correlationNodeXml);
Bl playerBoolean = new Bl();
playerBoolean.setValue(player);
Bl scoperBoolean = new Bl();
scoperBoolean.setValue(scoper);
String playerBooleanXml = CoppaObjectFactory.getBooleanPayload(playerBoolean);
String scoperBooleanXml = CoppaObjectFactory.getBooleanPayload(scoperBoolean);
cctsDomainObjectXMLList.add(playerBooleanXml);
cctsDomainObjectXMLList.add(scoperBooleanXml);
Integer configuredPOLimit = Configuration.LAST_LOADED_CONFIGURATION.get(Configuration.PO_SEARCH_LIMIT);
String poLimitOffset = CoppaPAObjectFactory.getLimitOffsetXML((configuredPOLimit != null) ? configuredPOLimit : 50 , 0);
cctsDomainObjectXMLList.add(poLimitOffset);
return broadcastCOPPA(cctsDomainObjectXMLList, mData);
}
/**
* Gets the correlation nodes from payload xml.
*
* @param correlationNodeXmlPayload the correlation node xml payload
* @return the correlation nodes from payload xml
*/
public List<CorrelationNode> getCorrelationNodesFromPayloadXml(String correlationNodeXmlPayload) {
String correlationNodeArrayXml = "";
try{
correlationNodeArrayXml = broadcastSearchCorrelationsWithEntities(correlationNodeXmlPayload, true, true);
//System.out.println(correlationNodeArrayXml);
} catch(Exception e){
log.error(e.getStackTrace());
}
List<String> correlationNodes = XMLUtil.getObjectsFromCoppaResponse(correlationNodeArrayXml);
List<CorrelationNode> correlationNodeList = new ArrayList<CorrelationNode>();
//creating a list of correlationNodes
for(String correlationNode: correlationNodes){
correlationNodeList.add(CoppaObjectFactory.getCorrelationNodeObjectFromXml(correlationNode));
}
return correlationNodeList;
}
/**
* Gets the coppa person from correlation node.
*
* @param cNode the correlation node
* @return the coppa person from correlation node
*/
public Person getCoppaPersonFromCorrelationNode(CorrelationNode cNode) {
Person person = null;
for(int i = 0; i < cNode.getPlayer().getContent().size(); i++){
Object object = cNode.getPlayer().getContent().get(i);
if(object instanceof Person){
person = (Person) object;
break;
}
}
return person;
}
/**
* Gets the coppa organization associated to investigator from correlation node.
*
* @param cNode the correlation node
* @return the coppa organization associated to investigator from correlation node
*/
public List<Organization> getCoppaOrganizationFromCorrelationNode(CorrelationNode cNode) {
Organization coppaOrganization = null;
List<Organization> orgList = new ArrayList<Organization>();
for(int i = 0; i < cNode.getScoper().getContent().size(); i++){
Object object = cNode.getScoper().getContent().get(i);
if(object instanceof Organization){
coppaOrganization = (Organization)object;
orgList.add(coppaOrganization);
}
}
return orgList;
}
/**
* Gets the assigned identifier from correlation node.
*
* @param coppaPerson the coppa person
* @param personIdToIdentifiedPersonMap the person id to identified person map
* @return the assigned identifier from correlation node
*/
public String getAssignedIdentifierFromCorrelationNode(Person coppaPerson, Map<String, List<IdentifiedPerson>> personIdToIdentifiedPersonMap) {
String assignedIdentifier = null;
if(personIdToIdentifiedPersonMap.containsKey(coppaPerson.getIdentifier().getExtension())){
List<IdentifiedPerson> identifiedPersonList = personIdToIdentifiedPersonMap.get(coppaPerson.getIdentifier().getExtension());
for(IdentifiedPerson identifiedPerson: identifiedPersonList){
if(identifiedPerson != null && identifiedPerson.getAssignedId().getRoot().equalsIgnoreCase(CTEP_PERSON)){
assignedIdentifier = identifiedPerson.getAssignedId().getExtension();
}
}
}
return assignedIdentifier;
}
/**
* Gets the identifier organizations for organizations list.
*
* @param coppaOrganizationsList the coppa organizations list
*
* @return the identifier organizations for organizations list
*/
public Map<String, IdentifiedOrganization> getIdentifiedOrganizationsForOrganizationsList(List<gov.nih.nci.coppa.po.Organization> coppaOrganizationsList) {
Map<String, IdentifiedOrganization> identifiedOrganizationsMap = new HashMap<String, IdentifiedOrganization>();
try {
//Build a list of orgId Xml
List<String> organizationIdXmlList = new ArrayList<String>();
DSETII dsetii = null;
for(gov.nih.nci.coppa.po.Organization coppaOrganization : coppaOrganizationsList){
dsetii = CoppaObjectFactory.getDSETIISearchCriteria(coppaOrganization.getIdentifier().getExtension());
organizationIdXmlList.add(CoppaObjectFactory.getCoppaIIXml(dsetii));
}
if(organizationIdXmlList.size() > 0){
//Coppa-call for Identifier Organizations getByIds
String identifiedOrganizationsXml = broadcastIdentifiedOrganizationGetByPlayerIds(organizationIdXmlList);
List<String> identifiedOrganizations = XMLUtil.getObjectsFromCoppaResponse(identifiedOrganizationsXml);
//Build a map with orgId as key and identifiedOrganization as value. Only get IdOrgs that have CTEP ID
if(identifiedOrganizations != null && identifiedOrganizations.size() > 0){
IdentifiedOrganization identifiedOrganization = null;
for(String identifiedOrganizationString : identifiedOrganizations){
identifiedOrganization = CoppaObjectFactory.getCoppaIdentfiedOrganization(identifiedOrganizationString);
if(identifiedOrganization != null && identifiedOrganization.getAssignedId().getIdentifierName().equals(CTEP_ID)){
identifiedOrganizationsMap.put(identifiedOrganization.getPlayerIdentifier().getExtension(), identifiedOrganization);
}
}
}
}
} catch(Exception e){
log.error(e.getMessage());
}
return identifiedOrganizationsMap;
}
/**
* Gets the nci ids for person list.
* Returns a map with personID as key and associated NciId as value.
*
* @param coppaPersonsList the coppa persons list
*
* @return the nci ids for person list
*/
public Map<String, List<IdentifiedPerson>> getIdentifiedPersonsForPersonList(List<Person> coppaPersonsList){
Map<String, List<IdentifiedPerson>> identifiedPersonMap = new HashMap<String, List<IdentifiedPerson>>();
try {
//Build a list of personId Xml
List<String> personIdXmlList = new ArrayList<String>();
for(Person coppaPerson:coppaPersonsList){
personIdXmlList.add(CoppaObjectFactory.getCoppaPersonIdXML(coppaPerson.getIdentifier().getExtension()));
}
//Coppa-call for Identifier Persons getByIds
if(personIdXmlList.size() > 0){
String identifiedPersonsXml = broadcastIdentifiedPersonGetByPlayerIds(personIdXmlList);
List<String> identifiedPersons = XMLUtil.getObjectsFromCoppaResponse(identifiedPersonsXml);
//Build a map with personId as key and sRole as value
if(identifiedPersons != null && identifiedPersons.size() > 0){
IdentifiedPerson identifiedPerson = null;
for(String identifiedPersonString : identifiedPersons){
identifiedPerson = CoppaObjectFactory.getCoppaIdentfiedPerson(identifiedPersonString);
if(identifiedPerson != null){
//identifiedPersonMap.put(identifiedPerson.getPlayerIdentifier().getExtension(), identifiedPerson);
List<IdentifiedPerson> ipList = null;
if(identifiedPersonMap.containsKey(identifiedPerson.getPlayerIdentifier().getExtension())){
ipList = identifiedPersonMap.get(identifiedPerson.getPlayerIdentifier().getExtension());
ipList.add(identifiedPerson);
} else {
ipList = new ArrayList<IdentifiedPerson>();
ipList.add(identifiedPerson);
identifiedPersonMap.put(identifiedPerson.getPlayerIdentifier().getExtension(), ipList);
}
}
}
}
}
} catch(Exception e){
log.error(e.getMessage());
}
return identifiedPersonMap;
}
/**
*
* @param personIdXmlList
* @return
* @throws Exception
*/
private String broadcastIdentifiedPersonGetByPlayerIds(List<String> personIdXmlList) throws Exception{
//build metadata with operation name and the external Id and pass it to the broadcast method.
//log.debug("Broadcasting : Operation --> "+ OperationNameEnum.getByPlayerIds.getName() + " Service -->" +ServiceTypeEnum.IDENTIFIED_PERSON.getName());
Metadata mData = new Metadata(OperationNameEnum.getByPlayerIds.getName(), "externalId", ServiceTypeEnum.IDENTIFIED_PERSON.getName());
return broadcastCOPPA(personIdXmlList, mData);
}
/**
*
* @param organizationIdXmlList
* @return
* @throws Exception
*/
private String broadcastIdentifiedOrganizationGetByPlayerIds(List<String> organizationIdXmlList) throws Exception {
//build metadata with operation name and the external Id and pass it to the broadcast method.
//log.debug("Broadcasting : Operation --> "+ OperationNameEnum.getByPlayerIds.getName() + " Service -->" +ServiceTypeEnum.IDENTIFIED_ORGANIZATION.getName());
Metadata mData = new Metadata(OperationNameEnum.getByPlayerIds.getName(), "externalId", ServiceTypeEnum.IDENTIFIED_ORGANIZATION.getName());
return broadcastCOPPA(organizationIdXmlList, mData);
}
/**
* Gets the identified person.
* Returns a list of IdentifiedPersons.
*
* @param ip the ip
*
* @return the identified person
*/
public IdentifiedPerson getIdentifiedPerson(IdentifiedPerson ip,String nciIdentifier) {
//List<IdentifiedPerson> identifiedPersonsList = new ArrayList<IdentifiedPerson>();
String ipPayload = CoppaObjectFactory.getCoppaIdentfiedPersonXml(ip);
String result = "";
try {
result = broadcastIdentifiedPersonSearch(ipPayload);
} catch (Exception e) {
log.error(e.getMessage());
}
List<String> identifiedPersons = XMLUtil.getObjectsFromCoppaResponse(result);
IdentifiedPerson identifiedPerson = null;
for(String identifiedPersonXml: identifiedPersons){
identifiedPerson = CoppaObjectFactory.getCoppaIdentfiedPerson(identifiedPersonXml);
if (identifiedPerson.getAssignedId().getExtension().equals(nciIdentifier)) {
return identifiedPerson;
}
//identifiedPersonsList.add(identifiedPerson);
}
return null;
}
/**
*
* @param ipXml
* @return
* @throws Exception
*/
private String broadcastIdentifiedPersonSearch(String ipXml) throws Exception{
//build metadata with operation name and the external Id and pass it to the broadcast method.
//log.debug("Broadcasting : Operation --> "+ OperationNameEnum.search.getName() + " Service -->" +ServiceTypeEnum.IDENTIFIED_PERSON.getName());
Metadata mData = new Metadata(OperationNameEnum.search.getName(), "externalId", ServiceTypeEnum.IDENTIFIED_PERSON.getName());
return broadcastCOPPA(ipXml, mData);
}
/**
* Gets the coppa person from correlation node.
*
* @param cNode the correlation node
* @return the coppa person from correlation node
*/
public Person getCoppaPersonFromPlayerInCorrelationNode(CorrelationNode cNode) {
Person person = null;
for(int i = 0; i < cNode.getPlayer().getContent().size(); i++){
Object object = cNode.getPlayer().getContent().get(i);
if(object instanceof Person){
person = (Person) object;
break;
}
}
return person;
}
public String broadcastIdentifiedOrganizationSearch(String healthcareSiteXml) throws CaaersSystemException {
Metadata mData = new Metadata(OperationNameEnum.search.getName(), "externalId", ServiceTypeEnum.IDENTIFIED_ORGANIZATION.getName());
return broadcastCOPPA(healthcareSiteXml, mData);
}
/**
*
* @param message
* @param metaData
* @return
* @throws gov.nih.nci.cabig.caaers.esb.client.BroadcastException
*/
public String broadcastCOPPA(String message,Metadata metaData) throws gov.nih.nci.cabig.caaers.esb.client.BroadcastException {
return broadcastCOPPA(Arrays.asList(message), metaData);
}
/**
*
* @param messages
* @param metaData
* @return
*/
public String broadcastCOPPA(List<String> messages,Metadata metaData) {
log.info("COPPA CALL :: SERVICETYPE-->" + metaData.getServiceType() + " :: OPERATION-->" + metaData.getOperationName());
//System.out.println("COPPA CALL :: SERVICETYPE-->" + metaData.getServiceType() + " :: OPERATION-->" + metaData.getOperationName());
String result = null;
try {
result = messageBroadcastService.broadcastCOPPA(messages, metaData);
} catch (Exception e) {
log.error("ERROR with COPPA BroadCast " + e.getMessage());
e.printStackTrace();
}
return result;
}
public MessageBroadcastService getMessageBroadcastService() {
return messageBroadcastService;
}
public void setMessageBroadcastService(MessageBroadcastService messageBroadcastService) {
this.messageBroadcastService = messageBroadcastService;
}
} |
package gov.nih.nci.cabig.caaers.web.ae;
import gov.nih.nci.cabig.caaers.CaaersSystemException;
import gov.nih.nci.cabig.caaers.domain.ExpeditedAdverseEventReport;
import gov.nih.nci.cabig.caaers.domain.report.Report;
import gov.nih.nci.cabig.caaers.domain.report.ReportVersion;
import gov.nih.nci.cabig.caaers.service.ReportSubmissionService;
import gov.nih.nci.cabig.caaers.web.fields.DefaultInputFieldGroup;
import gov.nih.nci.cabig.caaers.web.fields.InputField;
import gov.nih.nci.cabig.caaers.web.fields.InputFieldAttributes;
import gov.nih.nci.cabig.caaers.web.fields.InputFieldFactory;
import gov.nih.nci.cabig.caaers.web.fields.InputFieldGroup;
import gov.nih.nci.cabig.caaers.web.fields.InputFieldGroupMap;
import gov.nih.nci.cabig.caaers.web.fields.TabWithFields;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.validator.EmailValidator;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.validation.Errors;
/**
* @author Krikor Krumlian
*/
public class SubmitReportTab extends TabWithFields<ExpeditedAdverseEventInputCommand> {
protected final Log log = LogFactory.getLog(getClass());
protected ReportSubmissionService reportSubmissionService;
public SubmitReportTab() {
super("Submission", "Recipients", "ae/submitReport");
}
@Override
@SuppressWarnings("unchecked")
public InputFieldGroupMap createFieldGroups(ExpeditedAdverseEventInputCommand command) {
String reportIndex = ((SubmitExpeditedAdverseEventCommand) command).getReportIndex();
if (reportIndex == null) {
throw new CaaersSystemException("Report Index Not Defined");
}
InputFieldGroupMap map = new InputFieldGroupMap();
InputFieldGroup ccReport = new DefaultInputFieldGroup("ccReport");
InputField cc = InputFieldFactory.createTextArea("aeReport.reports[" + reportIndex
+ "].lastVersion.ccEmails", "Cc");
InputFieldAttributes.setColumns(cc, 50);
ccReport.getFields().add(cc);
map.addInputFieldGroup(ccReport);
return map;
}
@Override
protected void validate(ExpeditedAdverseEventInputCommand command, BeanWrapper commandBean,
Map<String, InputFieldGroup> fieldGroups, Errors errors) {
String reportIndex = ((SubmitExpeditedAdverseEventCommand) command).getReportIndex();
Report report = command.getAeReport().getReports().get(Integer.parseInt(reportIndex));
if(!report.isActive()){
errors.reject("SAE_032", new Object[]{report.getStatus().getDisplayName()},
"Cannot submit this report, as it is already submitted/withdrawn/amended/replaced");
}
ReportVersion lastVersion = report.getLastVersion();
String emailString =lastVersion.getCcEmails();
if (emailString != null) {
String[] emails = emailString.split(",");
for (String email : emails) {
if (!isEmailValid(email)) {
InputField field = fieldGroups.get("ccReport").getFields().get(0);
errors.rejectValue(field.getPropertyName(), "SAE_007", new Object[]{field.getDisplayName()},"Not Valid "
+ field.getDisplayName());
break;
}
}
}
}
public boolean isEmailValid(String email) {
String trimmedEmail = (email != null) ? email.trim() : email;
return EmailValidator.getInstance().isValid(trimmedEmail);
}
@Override
public void postProcess(HttpServletRequest request, ExpeditedAdverseEventInputCommand cmd, Errors errors) {
if(cmd.getNextPage() < 2) return; //only process if we are moving forward.
log.debug("In postProcess");
SubmitExpeditedAdverseEventCommand command = (SubmitExpeditedAdverseEventCommand) cmd;
Integer reportIndex = Integer.valueOf(command.getReportIndex());
log.debug("Report Index :" + reportIndex.intValue());
ExpeditedAdverseEventReport aeReport = command.getAeReport();
Report report = aeReport.getReports().get(((int) reportIndex));
if(report.isActive() && (!command.getReportSubmitted()) ){
reportSubmissionService.submitReport(report);
}
}
public ReportSubmissionService getReportSubmissionService() {
return reportSubmissionService;
}
@Required
public void setReportSubmissionService(ReportSubmissionService reportSubmissionService) {
this.reportSubmissionService = reportSubmissionService;
}
} |
package edu.duke.cabig.catrip.gui.util;
import java.awt.Color;
import java.awt.Image;
import java.io.File;
import javax.swing.Icon;
import org.openide.util.Utilities;
/**
* Holds all Constants defined for GUI. Should read the constants from a config file.
*
* @author Sanjeev Agarwal
*/
public class GUIConstants {
public static final Image WINDOW_ICON = Utilities.loadImage ("edu/duke/cabig/catrip/gui/resources/WindowIcon.gif");
/** Icons for the JTree nodes. */
public static final Icon TREE_CLOSE_ICON = new javax.swing.ImageIcon (Utilities.loadImage ("edu/duke/cabig/catrip/gui/resources/tree/icon_close.png"));
public static final Icon TREE_OPEN_ICON = new javax.swing.ImageIcon (Utilities.loadImage ("edu/duke/cabig/catrip/gui/resources/tree/icon_open.png"));
public static final Icon ATTRIBUTES_ICON = new javax.swing.ImageIcon (Utilities.loadImage ("edu/duke/cabig/catrip/gui/resources/tree/icon_attributes.png"));
public static final Icon ASSOCIATIONS_ICON = new javax.swing.ImageIcon (Utilities.loadImage ("edu/duke/cabig/catrip/gui/resources/tree/icon_associations.png"));
public static final Icon ASSOCIATION_LEAF_ICON = new javax.swing.ImageIcon (Utilities.loadImage ("edu/duke/cabig/catrip/gui/resources/tree/icon_association.png"));
public static final Icon CLASS_ICON = new javax.swing.ImageIcon (Utilities.loadImage ("edu/duke/cabig/catrip/gui/resources/tree/icon_class_.png"));
public static final Icon SERVICE_ICON = new javax.swing.ImageIcon (Utilities.loadImage ("edu/duke/cabig/catrip/gui/resources/tree/icon_service.png"));
public static final String DEFAULT_INDEX_SERVICE_URL = "http://localhost:8080/wsrf/services/DefaultIndexService";
// caTrip home is not final so that It can be changed if catrip.home.dir argument is passed.
public static String CATRIP_HOME = System.getProperty("user.home") + File.separator + ".caTRIP"; // default home.
public static String CATRIP_CONFIG_FILE_LOCATION = CATRIP_HOME + File.separator + "catrip-config.xml";
public static final String CATRIP_SERVICES_CONFIG_FILE_NAME = "services-config.xml";
public static String caTRIPVersion = "1_beta";
public static final Color[] COLOR_SET = {Color.BLACK, Color.RED, Color.GREEN, Color.BLUE};
public static final String[] HTML_COLOR_SET = {"#000000", "#FF0033", "#006600", "#3333CC"}; // Black, Red, Green, Blue
public static final Image LARGE_TEXT_ICON = Utilities.loadImage ("edu/duke/cabig/catrip/gui/resources/btn_icons/view.png");
public static final int LARGE_TEXT_LIMIT = 20; // Limit of the number of chars in the result table after which it will be considered as a Long text and will be displayed in a popup.
// runtime properties..
public static boolean simpleGui = true;
public static boolean resultAvailable = false;
} |
package org.chromium.chrome.browser.init;
import android.content.Context;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.StrictMode;
import android.preference.PreferenceManager;
import android.util.Log;
import org.chromium.base.BaseSwitches;
import org.chromium.base.CommandLine;
import org.chromium.base.ContentUriUtils;
import org.chromium.base.ResourceExtractor;
import org.chromium.base.ThreadUtils;
import org.chromium.base.TraceEvent;
import org.chromium.base.library_loader.ProcessInitException;
import org.chromium.chrome.browser.ChromeApplication;
import org.chromium.chrome.browser.ChromeSwitches;
import org.chromium.chrome.browser.ChromeVersionInfo;
import org.chromium.chrome.browser.FileProviderHelper;
import org.chromium.chrome.browser.device.DeviceClassManager;
import org.chromium.content.app.ContentApplication;
import org.chromium.content.browser.BrowserStartupController;
import org.chromium.content.browser.DeviceUtils;
import org.chromium.content.browser.SpeechRecognition;
import org.chromium.net.NetworkChangeNotifier;
import java.util.LinkedList;
/**
* Application level delegate that handles start up tasks.
* {@link AsyncInitializationActivity} classes should override the {@link BrowserParts}
* interface for any additional initialization tasks for the initialization to work as intended.
*/
public class ChromeBrowserInitializer {
private static final String TAG = "ChromeBrowserInitializer";
private static ChromeBrowserInitializer sChromeBrowserInitiliazer;
private final Handler mHandler;
private final ChromeApplication mApplication;
private boolean mPreInflationStartupComplete;
private boolean mPostInflationStartupComplete;
private boolean mNativeInitializationComplete;
/**
* A callback to be executed when there is a new version available in Play Store.
*/
public interface OnNewVersionAvailableCallback extends Runnable {
/**
* Set the update url to get the new version available.
* @param updateUrl The url to be used.
*/
void setUpdateUrl(String updateUrl);
}
/**
* This class is an application specific object that orchestrates the app initialization.
* @param context The context to get the application context from.
* @return The singleton instance of {@link ChromeBrowserInitializer}.
*/
public static ChromeBrowserInitializer getInstance(Context context) {
if (sChromeBrowserInitiliazer == null) {
sChromeBrowserInitiliazer = new ChromeBrowserInitializer(context);
}
return sChromeBrowserInitiliazer;
}
private ChromeBrowserInitializer(Context context) {
mApplication = (ChromeApplication) context.getApplicationContext();
mHandler = new Handler(Looper.getMainLooper());
}
/**
* Execute startup tasks that can be done without native libraries. See {@link BrowserParts} for
* a list of calls to be implemented.
* @param parts The delegate for the {@link ChromeBrowserInitializer} to communicate
* initialization tasks.
*/
public void handlePreNativeStartup(final BrowserParts parts) {
preInflationStartup();
parts.preInflationStartup();
preInflationStartupDone();
parts.setContentViewAndLoadLibrary();
postInflationStartup();
parts.postInflationStartup();
}
/**
* This is needed for device class manager which depends on commandline args that are
* initialized in preInflationStartup()
*/
private void preInflationStartupDone() {
// Domain reliability uses significant enough memory that we should disable it on low memory
// devices for now.
// TODO(zbowling): remove this after domain reliability is refactored. (crbug.com/495342)
if (DeviceClassManager.disableDomainReliability()) {
CommandLine.getInstance().appendSwitch(ChromeSwitches.DISABLE_DOMAIN_RELIABILITY);
}
}
private void preInflationStartup() {
ThreadUtils.assertOnUiThread();
if (mPreInflationStartupComplete) return;
// Ensure critical files are available, so they aren't blocked on the file-system
// behind long-running accesses in next phase.
// Don't do any large file access here!
ContentApplication.initCommandLine(mApplication);
waitForDebuggerIfNeeded();
configureStrictMode();
// Warm up the shared prefs stored.
PreferenceManager.getDefaultSharedPreferences(mApplication);
DeviceUtils.addDeviceSpecificUserAgentSwitch(mApplication);
mPreInflationStartupComplete = true;
}
private void postInflationStartup() {
ThreadUtils.assertOnUiThread();
if (mPostInflationStartupComplete) return;
// Check to see if we need to extract any new resources from the APK. This could
// be on first run when we need to extract all the .pak files we need, or after
// the user has switched locale, in which case we want new locale resources.
ResourceExtractor.get(mApplication).startExtractingResources();
mPostInflationStartupComplete = true;
}
/**
* Execute startup tasks that require native libraries to be loaded. See {@link BrowserParts}
* for a list of calls to be implemented.
* @param parts The delegate for the {@link ChromeBrowserInitializer} to communicate
* initialization tasks.
*/
public void handlePostNativeStartup(final BrowserParts delegate) {
final LinkedList<Runnable> initQueue = new LinkedList<Runnable>();
abstract class NativeInitTask implements Runnable {
@Override
public final void run() {
// Run the current task then put a request for the next one onto the
// back of the UI message queue. This lets Chrome handle input events
// between tasks.
initFunction();
if (!initQueue.isEmpty()) {
mHandler.post(initQueue.pop());
}
}
public abstract void initFunction();
}
initQueue.add(new NativeInitTask() {
@Override
public void initFunction() {
mApplication.initializeProcess();
}
});
initQueue.add(new NativeInitTask() {
@Override
public void initFunction() {
initNetworkChangeNotifier(mApplication.getApplicationContext());
}
});
initQueue.add(new NativeInitTask() {
@Override
public void initFunction() {
// This is not broken down as a separate task, since this:
// 1. Should happen as early as possible
// 2. Only submits asynchronous work
// 3. Is thus very cheap (profiled at 0.18ms on a Nexus 5 with Lollipop)
// It should also be in a separate task (and after) initNetworkChangeNotifier, as
// this posts a task to the UI thread that would interfere with preconneciton
// otherwise. By preconnecting afterwards, we make sure that this task has run.
delegate.maybePreconnect();
onStartNativeInitialization();
}
});
initQueue.add(new NativeInitTask() {
@Override
public void initFunction() {
if (delegate.isActivityDestroyed()) return;
delegate.initializeCompositor();
}
});
initQueue.add(new NativeInitTask() {
@Override
public void initFunction() {
if (delegate.isActivityDestroyed()) return;
delegate.initializeState();
}
});
initQueue.add(new NativeInitTask() {
@Override
public void initFunction() {
onFinishNativeInitialization();
}
});
initQueue.add(new NativeInitTask() {
@Override
public void initFunction() {
if (delegate.isActivityDestroyed()) return;
delegate.finishNativeInitialization();
}
});
// We want to start this queue once the C++ startup tasks have run; allow the
// C++ startup to run asynchonously, and set it up to start the Java queue once
// it has finished.
startChromeBrowserProcesses(delegate, new BrowserStartupController.StartupCallback() {
@Override
public void onFailure() {
delegate.onStartupFailure();
}
@Override
public void onSuccess(boolean arg0) {
mHandler.post(initQueue.pop());
}
});
}
private void startChromeBrowserProcesses(BrowserParts parts,
BrowserStartupController.StartupCallback callback) {
try {
TraceEvent.begin("ChromeBrowserInitializer.startChromeBrowserProcesses");
mApplication.startChromeBrowserProcessesAsync(callback);
} catch (ProcessInitException e) {
parts.onStartupFailure();
} finally {
TraceEvent.end("ChromeBrowserInitializer.startChromeBrowserProcesses");
}
}
public static void initNetworkChangeNotifier(Context context) {
ThreadUtils.assertOnUiThread();
TraceEvent.begin("NetworkChangeNotifier.init");
// Enable auto-detection of network connectivity state changes.
NetworkChangeNotifier.init(context);
NetworkChangeNotifier.setAutoDetectConnectivityState(true);
TraceEvent.end("NetworkChangeNotifier.init");
}
private void onStartNativeInitialization() {
ThreadUtils.assertOnUiThread();
if (mNativeInitializationComplete) return;
SpeechRecognition.initialize(mApplication);
}
private void onFinishNativeInitialization() {
if (mNativeInitializationComplete) return;
mNativeInitializationComplete = true;
ContentUriUtils.setFileProviderUtil(new FileProviderHelper());
}
private static void configureStrictMode() {
CommandLine commandLine = CommandLine.getInstance();
if ("eng".equals(Build.TYPE)
|| ("userdebug".equals(Build.TYPE) && !ChromeVersionInfo.isStableBuild())
|| commandLine.hasSwitch(ChromeSwitches.STRICT_MODE)) {
StrictMode.enableDefaults();
StrictMode.ThreadPolicy.Builder threadPolicy =
new StrictMode.ThreadPolicy.Builder(StrictMode.getThreadPolicy());
threadPolicy = threadPolicy.detectAll()
.penaltyFlashScreen()
.penaltyDeathOnNetwork();
StrictMode.VmPolicy.Builder vmPolicy = new StrictMode.VmPolicy.Builder();
vmPolicy = vmPolicy.detectActivityLeaks()
.detectLeakedClosableObjects()
.detectLeakedRegistrationObjects()
.detectLeakedSqlLiteObjects()
.penaltyLog();
if ("death".equals(commandLine.getSwitchValue(ChromeSwitches.STRICT_MODE))) {
threadPolicy = threadPolicy.penaltyDeath();
vmPolicy = vmPolicy.penaltyDeath();
}
StrictMode.setThreadPolicy(threadPolicy.build());
StrictMode.setVmPolicy(vmPolicy.build());
}
}
private void waitForDebuggerIfNeeded() {
if (CommandLine.getInstance().hasSwitch(BaseSwitches.WAIT_FOR_JAVA_DEBUGGER)) {
Log.e(TAG, "Waiting for Java debugger to connect...");
android.os.Debug.waitForDebugger();
Log.e(TAG, "Java debugger connected. Resuming execution.");
}
}
} |
package ikube.action.index.handler.filesystem;
import ikube.IConstants;
import ikube.action.index.IndexManager;
import ikube.action.index.handler.ResourceHandler;
import ikube.action.index.parse.IParser;
import ikube.action.index.parse.ParserProvider;
import ikube.model.IndexContext;
import ikube.model.IndexableFileSystem;
import ikube.toolkit.FileUtilities;
import ikube.toolkit.HashUtilities;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field.Index;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.document.Field.TermVector;
import org.xml.sax.SAXParseException;
import de.schlichtherle.truezip.file.TFile;
import de.schlichtherle.truezip.file.TFileInputStream;
/**
* This resource handler will handle files from the file system handler. Getting the correct parser for the type and extracting the data, eventually adding the
* data to the specified fields in the Lucene index.
*
* @author Michael Couck
* @since 25.03.13
* @version 01.00
*/
public class FileResourceHandler extends ResourceHandler<IndexableFileSystem> {
/**
* {@inheritDoc}
*/
@Override
public Document handleResource(final IndexContext<?> indexContext, final IndexableFileSystem indexableFileSystem, final Document document,
final Object resource) throws Exception {
File file = (File) resource;
try {
if (logger.isDebugEnabled()) {
logger.debug("Processing file : " + file);
}
handleResource(indexContext, indexableFileSystem, document, file, file.getName());
} catch (Exception e) {
if (SAXParseException.class.isAssignableFrom(e.getClass())) {
// If this is an xml exception then try the html parser it is more lenient
handleResource(indexContext, indexableFileSystem, document, file, "text/html");
}
}
return document;
}
private Document handleResource(final IndexContext<?> indexContext, final IndexableFileSystem indexableFileSystem, final Document document,
final File file, final String mimeType) throws Exception {
InputStream inputStream = null;
ByteArrayInputStream byteInputStream = null;
ByteArrayOutputStream byteOutputStream = null;
try {
int length = file.length() > 0 && file.length() < indexableFileSystem.getMaxReadLength() ? (int) file.length() : (int) indexableFileSystem
.getMaxReadLength();
byte[] byteBuffer = new byte[length];
if (TFile.class.isAssignableFrom(file.getClass())) {
inputStream = new TFileInputStream(file);
} else {
inputStream = new FileInputStream(file);
}
int read = inputStream.read(byteBuffer, 0, byteBuffer.length);
byteInputStream = new ByteArrayInputStream(byteBuffer, 0, read);
byteOutputStream = new ByteArrayOutputStream();
IParser parser = ParserProvider.getParser(file.getName(), byteBuffer);
String parsedContent = parser.parse(byteInputStream, byteOutputStream).toString();
Store store = indexableFileSystem.isStored() ? Store.YES : Store.NO;
Index analyzed = indexableFileSystem.isAnalyzed() ? Index.ANALYZED : Index.NOT_ANALYZED;
TermVector termVector = indexableFileSystem.isVectored() ? TermVector.YES : TermVector.NO;
// This is the unique id of the resource to be able to delete it
String fileId = HashUtilities.hash(file.getAbsolutePath()).toString();
String pathFieldName = indexableFileSystem.getPathFieldName();
String nameFieldName = indexableFileSystem.getNameFieldName();
String modifiedFieldName = indexableFileSystem.getLastModifiedFieldName();
String lengthFieldName = indexableFileSystem.getLengthFieldName();
String contentFieldName = indexableFileSystem.getContentFieldName();
// NOTE to self: To be able to delete using the index writer the identifier field must be non analyzed and non tokenized/vectored!
IndexManager.addStringField(IConstants.FILE_ID, fileId, document, Store.YES, Index.NOT_ANALYZED, TermVector.NO);
IndexManager.addStringField(pathFieldName, file.getAbsolutePath(), document, Store.YES, analyzed, termVector);
IndexManager.addStringField(nameFieldName, file.getName(), document, Store.YES, analyzed, termVector);
IndexManager.addNumericField(modifiedFieldName, Long.toString(file.lastModified()), document, Store.YES);
IndexManager.addStringField(lengthFieldName, Long.toString(file.length()), document, Store.YES, analyzed, termVector);
IndexManager.addStringField(contentFieldName, parsedContent, document, store, analyzed, termVector);
addDocument(indexContext, indexableFileSystem, document);
indexableFileSystem.setContent(parsedContent);
} finally {
FileUtilities.close(inputStream);
FileUtilities.close(byteInputStream);
FileUtilities.close(byteOutputStream);
}
return document;
}
} |
package com.archimatetool.model.util;
import java.io.File;
import java.util.HashMap;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceFactoryImpl;
import org.eclipse.emf.ecore.resource.impl.ResourceImpl;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.util.ExtendedMetaData;
import org.eclipse.emf.ecore.xmi.XMLResource;
/**
* <!-- begin-user-doc -->
* The <b>Resource Factory</b> associated with the package.
* <!-- end-user-doc -->
* @see com.archimatetool.model.util.ArchimateResource
* @generated
*/
public class ArchimateResourceFactory extends ResourceFactoryImpl {
/**
* Creates an instance of the resource factory.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ArchimateResourceFactory() {
super();
}
/**
* @return a Resource that allows saving and loading files with any type of file extension
* as registered in plugin.xml
*/
public static Resource createNewResource(File file) {
return createNewResource(URI.createFileURI(file.getAbsolutePath()));
}
/**
* @return a Resource that allows saving and loading files with any type of file extension
* as registered in plugin.xml
*/
public static Resource createNewResource(URI uri) {
// This will return an ArchimateResource as registered in plugin.xml
ResourceSet resourceSet = createResourceSet();
return resourceSet.createResource(uri);
}
/**
* @return a ResourceSet that allows saving and loading files with any type of extension
*/
public static ResourceSet createResourceSet() {
ResourceSet resourceSet = new ResourceSetImpl();
/*
* Register the * extension on the ResourceSet to over-ride the ECore global one
* This is needed to create an ArchimateModel object from any file (thus pattern "*") without relying on its extension.
* Without this code it is impossible to load a model from file without extension (error "Class 'model' is not found or is abstract").
*/
resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("*", new ArchimateResourceFactory()); //$NON-NLS-1$
return resourceSet;
}
/**
* Creates an instance of the resource.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated NOT
*/
@Override
public Resource createResource(URI uri) {
XMLResource result = new ArchimateResource(uri);
// Ensure we have ExtendedMetaData for both Saving and Loading
ExtendedMetaData ext = new ConverterExtendedMetadata();
result.getDefaultLoadOptions().put(XMLResource.OPTION_EXTENDED_META_DATA, ext);
result.getDefaultSaveOptions().put(XMLResource.OPTION_EXTENDED_META_DATA, ext);
result.getDefaultSaveOptions().put(XMLResource.OPTION_ENCODING, "UTF-8"); //$NON-NLS-1$
result.getDefaultLoadOptions().put(XMLResource.OPTION_ENCODING, "UTF-8"); //$NON-NLS-1$
result.getDefaultLoadOptions().put(XMLResource.OPTION_DEFER_IDREF_RESOLUTION, Boolean.TRUE);
((ResourceImpl)result).setIntrinsicIDToEObjectMap(new HashMap<String, EObject>());
// Not sure about this
// result.getDefaultSaveOptions().put(XMLResource.OPTION_SCHEMA_LOCATION, Boolean.TRUE);
// Don't set this as it prefixes a hash # to ID references
// result.getDefaultLoadOptions().put(XMLResource.OPTION_USE_ENCODED_ATTRIBUTE_STYLE, Boolean.TRUE);
// result.getDefaultSaveOptions().put(XMLResource.OPTION_USE_ENCODED_ATTRIBUTE_STYLE, Boolean.TRUE);
// Not sure about this
// result.getDefaultLoadOptions().put(XMLResource.OPTION_USE_LEXICAL_HANDLER, Boolean.TRUE);
return result;
}
} //ArchimateResourceFactory |
package com.python.pydev.analysis;
import static com.python.pydev.analysis.IAnalysisPreferences.TYPE_DUPLICATED_SIGNATURE;
import static com.python.pydev.analysis.IAnalysisPreferences.TYPE_UNDEFINED_VARIABLE;
import static com.python.pydev.analysis.IAnalysisPreferences.TYPE_UNUSED_IMPORT;
import static com.python.pydev.analysis.IAnalysisPreferences.TYPE_UNUSED_VARIABLE;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashSet;
import org.eclipse.core.resources.IMarker;
import org.eclipse.jface.text.Document;
import org.python.pydev.core.REF;
import org.python.pydev.core.TestDependent;
import org.python.pydev.editor.codecompletion.revisited.modules.AbstractModule;
import org.python.pydev.editor.codecompletion.revisited.modules.SourceModule;
import com.python.pydev.analysis.messages.IMessage;
public class OccurrencesAnalyzerTest extends AnalysisTestsBase {
public static void main(String[] args) {
try {
OccurrencesAnalyzerTest analyzer2 = new OccurrencesAnalyzerTest();
analyzer2.setUp();
analyzer2.testUnusedVariable2();
analyzer2.testNoUnusedVariable();
analyzer2.tearDown();
System.out.println("finished");
junit.textui.TestRunner.run(OccurrencesAnalyzerTest.class);
System.out.println("finished all");
} catch (Throwable e) {
e.printStackTrace();
}
System.exit(0);
}
public void testUnusedImports(){
prefs.severityForUnusedImport = IMarker.SEVERITY_ERROR;
prefs.severityForUnusedWildImport = IMarker.SEVERITY_ERROR;
doc = new Document("import testlib\n");
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
assertEquals(1, msgs.length);
assertEquals("Unused import: testlib", msgs[0].getMessage());
assertEquals(IMarker.SEVERITY_ERROR, msgs[0].getSeverity());
assertEquals(TYPE_UNUSED_IMPORT, msgs[0].getType());
doc = new Document("import testlib\nprint testlib");
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
assertEquals(0, msgs.length);
sDoc = "from testlib.unittest import *";
doc = new Document(sDoc);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs, 1);
assertEquals(IMarker.SEVERITY_ERROR, msgs[0].getSeverity());
assertEquals(6, msgs[0].getStartCol(doc));
assertEquals(31, msgs[0].getEndCol(doc));
assertEquals("Unused in wild import: anothertest, guitestcase, main, TestCase, AnotherTest, t, TestCaseAlias, GUITest, testcase", msgs[0].getMessage());
prefs.severityForUnusedImport = IMarker.SEVERITY_WARNING;
prefs.severityForUnusedWildImport = IMarker.SEVERITY_WARNING;
sDoc = "from testlib.unittest import *\nprint TestCase";
doc = new Document(sDoc);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
assertEquals(1, msgs.length);
assertEquals(IMarker.SEVERITY_WARNING, msgs[0].getSeverity());
assertEquals("Unused in wild import: anothertest, guitestcase, main, AnotherTest, t, TestCaseAlias, GUITest, testcase", msgs[0].getMessage());
assertEquals("TestCase", msgs[0].getAdditionalInfo().get(0));
prefs.severityForUnusedImport = IMarker.SEVERITY_INFO;
prefs.severityForUnusedWildImport = IMarker.SEVERITY_INFO;
sDoc = "from testlib.unittest import *\nprint TestCase\nprint testcase";
doc = new Document(sDoc);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
//even in ignore mode, we get the message
assertEquals(1, msgs.length);
assertEquals("Unused in wild import: anothertest, guitestcase, main, AnotherTest, t, TestCaseAlias, GUITest", msgs[0].getMessage());
assertEquals("TestCase", msgs[0].getAdditionalInfo().get(0));
assertEquals("testcase", msgs[0].getAdditionalInfo().get(1));
}
public void testMetaclass(){
doc = new Document(
"class MyMetaclass(type):\n"+
" def __init__(cls, name, bases, dict): #@UnusedVariable\n"+
" pass\n"+
"\n"
);
checkNoError();
}
public void testOsPath(){
doc = new Document(
"from os.path import *#@UnusedWildImport\n"+
"print exists\n"
);
checkNoError();
}
public void testFalseUnused(){
doc = new Document(
"def m1():\n"+
" name = ''\n"+
" getattr(1, name).text().latin1\n"
);
checkNoError();
}
public void testDelete(){
doc = new Document(
"def m1():\n"+
" del foo\n"
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs,1);
}
public void testAugAssign(){
doc = new Document(
"def m1():\n"+
" foo|=1\n"
);
checkAug(1);
doc = new Document(
"def m1():\n"+
" foo+=1\n"
);
checkAug(1);
doc = new Document(
"def m1():\n"+
" foo*=1\n"
);
checkAug(1);
doc = new Document(
"def m1():\n"+
" print foo|1\n"
);
checkAug(1);
doc = new Document(
"def m1():\n"+
" foo = 10\n" +
" foo += 20"
);
checkAug(0);
}
private void checkAug(int errors){
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs,errors);
}
public void testFromFutureImport(){
doc = new Document(
"from __future__ import generators\n"
);
checkNoError();
}
public void testMetaclassImport(){
doc = new Document(
"from psyco.classes import __metaclass__ #@UnresolvedImport\n"
);
checkNoError();
}
public void testFromFutureImport2(){
doc = new Document(
"from __future__ import generators\n"
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc("foo", null, doc, nature, 0), prefs, doc);
printMessages(msgs,0);
}
public void testClassVar(){
doc = new Document(
"class Foo:\n"+
" x = 1\n"+
" def m1(self):\n"+
" print x\n"+ //should access with self.x or Foo.x
" print Foo.x\n"+
" print self.x\n"
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs,1);
assertEquals("Undefined variable: x", msgs[0].getMessage());
}
public void testImportWithTryExcept(){
doc = new Document(
"try:\n"+
" import foo\n"+
"except ImportError:\n"+
" foo = None\n"
);
checkNoError();
}
public void testImportWithTryExcept2(){
doc = new Document(
"try:\n"+
" import foo\n"+
"except:\n"+
" foo = None\n"
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs,1);
assertEquals("Unresolved import: foo", msgs[0].getMessage());
}
public void testClsInNew(){
doc = new Document(
"class C2:\n"+
" def __new__(cls):\n"+
" print cls\n"+
""
);
checkNoError();
}
public void testMsgInNew(){
doc = new Document(
"class C2:\n"+
" def __new__(foo):\n"+
" print foo\n"+
""
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs,1);
assertEquals("Method '__new__' should have self or cls as first parameter", msgs[0].getMessage());
}
public void testClsInsteadOfSelf(){
doc = new Document(
"class C2:\n" +
" @str\n"+
" def foo(cls):\n"+
" print cls\n"+
""
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs,1);
assertContainsMsg("Method 'foo' should have self as first parameter", msgs);
assertEquals(9, msgs[0].getStartCol(doc));
assertEquals(3, msgs[0].getStartLine(doc));
}
public void testConsiderAsGlobals(){
doc = new Document(
"print considerGlobal"
);
checkNoError();
}
public void testUnusedImports2(){
doc = new Document(
"from simpleimport import *\n" +
"print xml"
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs,1);
assertContainsMsg("Unused in wild import: xml.dom.domreg, xml.dom", msgs);
assertEquals("xml", msgs[0].getAdditionalInfo().get(0)); //this is the used import
}
public void testUnusedImports2a(){
doc = new Document(
"import os.path"
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs,2);
IMessage message = assertContainsMsg("Unused import: os", msgs);
assertEquals(8, message.getStartCol(doc));
assertEquals(10, message.getEndCol(doc));
message = assertContainsMsg("Unused import: os.path", msgs);
assertEquals(8, message.getStartCol(doc));
assertEquals(15, message.getEndCol(doc));
}
public void testUnusedImports2b(){
doc = new Document(
"\n\nfrom testlib.unittest import *"
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs,1);
assertEquals(6, msgs[0].getStartCol(doc));
assertEquals(31, msgs[0].getEndCol(doc));
}
public void testUnusedImports3(){
doc = new Document(
"import os.path as otherthing\n" +
""
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
assertEquals(1, msgs.length);
assertContainsMsg("Unused import: otherthing", msgs);
assertEquals(8, msgs[0].getStartCol(doc));
assertEquals(29, msgs[0].getEndCol(doc));
}
public void testUnusedImports3a(){
doc = new Document(
"import os.path as otherthing, unittest\n" +
""
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs, 2);
IMessage message = assertContainsMsg("Unused import: otherthing", msgs);
assertEquals(8, message.getStartCol(doc));
assertEquals(29, message.getEndCol(doc));
message = assertContainsMsg("Unused import: unittest", msgs);
assertEquals(31, message.getStartCol(doc));
assertEquals(39, message.getEndCol(doc));
}
public void testUnusedImports3b(){
doc = new Document(
"from testlib import unittest, __init__\n" +
""
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs, 2);
IMessage message = assertContainsMsg("Unused import: unittest", msgs);
assertEquals(21, message.getStartCol(doc));
assertEquals(29, message.getEndCol(doc));
message = assertContainsMsg("Unused import: __init__", msgs);
assertEquals(31, message.getStartCol(doc));
assertEquals(39, message.getEndCol(doc));
}
public void testUnusedImports4(){
doc = new Document(
"def m():\n" +
" import os.path as otherthing\n" +
""
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
assertEquals(1, msgs.length);
assertContainsMsg("Unused import: otherthing", msgs);
assertEquals(12, msgs[0].getStartCol(doc));
assertEquals(33, msgs[0].getEndCol(doc));
}
public void testUnusedImports5(){
doc = new Document(
"from definitions import methoddef\n" +
"@methoddef.decorator1\n" +
"def m1():pass\n" +
"\n" +
""
);
checkNoError();
}
public void testGlu(){
if(TestDependent.HAS_GLU_INSTALLED){
doc = new Document(
"from OpenGL.GL import glPushMatrix\n" +
"print glPushMatrix\n" +
""
);
checkNoError();
}
}
public void testGlu2(){
if(TestDependent.HAS_GLU_INSTALLED){
doc = new Document(
"from OpenGL.GL import * #@UnusedWildImport\n" +
"print glPushMatrix\n" +
""
);
checkNoError();
}
}
public void testGlu3(){
if(TestDependent.HAS_GLU_INSTALLED){
doc = new Document(
"from OpenGL.GL import glRotatef\n" +
"print glRotatef\n" +
""
);
checkNoError();
}
}
public void testGlu4(){
if(TestDependent.HAS_GLU_INSTALLED){
doc = new Document(
"from OpenGL.GLU import gluLookAt\n" +
"print gluLookAt" +
""
);
checkNoError();
}
}
public void testCompiledUnusedImports5(){
if(TestDependent.HAS_WXPYTHON_INSTALLED){
doc = new Document(
"from wxPython.wx import wxButton\n" +
""
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs, 1);
assertContainsMsg("Unused import: wxButton", msgs);
}
}
public void testCompiledWx(){
if(TestDependent.HAS_WXPYTHON_INSTALLED){
// CompiledModule.TRACE_COMPILED_MODULES = true;
doc = new Document(
"from wx import glcanvas\n" +
"print glcanvas.GLCanvas\n" +
""
);
checkNoError();
}
}
public void testImportNotFound(){
doc = new Document(
"def m():\n" +
" import invalidImport\n" +
""
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
assertEquals(2, msgs.length);
assertContainsMsg("Unresolved import: invalidImport", msgs);
assertContainsMsg("Unused import: invalidImport", msgs);
}
public void testImportNotFound2(){
doc = new Document(
"import invalidImport\n" +
""
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
assertEquals(2, msgs.length);
assertContainsMsg("Unresolved import: invalidImport", msgs);
assertContainsMsg("Unused import: invalidImport", msgs);
}
public void testImportNotFound3(){
doc = new Document(
"import os.notDefined\n" +
""
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs,3);
assertContainsMsg("Unused import: os.notDefined", msgs);
assertContainsMsg("Unused import: os", msgs);
assertContainsMsg("Unresolved import: os.notDefined", msgs);
}
public void testImportNotFound9(){
doc = new Document(
"from os import path, notDefined\n" +
""
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs,3);
assertContainsMsg("Unresolved import: notDefined", msgs);
assertContainsMsg("Unused import: notDefined", msgs);
assertContainsMsg("Unused import: path", msgs);
}
public void testMultilineImport(){
doc = new Document(
"from os import (pathNotDef1,\n" +
" notDefined)\n" +
""
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
IMessage message;
printMessages(msgs,4);
message = assertContainsMsg("Unresolved import: pathNotDef1", msgs);
assertEquals(1, message.getStartLine(doc));
message = assertContainsMsg("Unresolved import: notDefined", msgs);
assertEquals(2, message.getStartLine(doc));
assertEquals(2, message.getEndLine(doc));
assertEquals(17, message.getStartCol(doc));
assertEquals(27, message.getEndCol(doc));
assertContainsMsg("Unused import: notDefined", msgs);
assertContainsMsg("Unused import: pathNotDef1", msgs);
}
public void testImportNotFound4(){
doc = new Document(
"import os as otherThing\n" +
""
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs,1);
assertContainsMsg("Unused import: otherThing", msgs);
}
public void testImportNotFound6(){
doc = new Document(
"import os\n" +
""
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs,1);
IMessage msg = assertContainsMsg("Unused import: os", msgs);
assertEquals(1, msg.getStartLine(doc));
}
public void testImportNotFound7(){
doc = new Document(
"import encodings.latin_1\n" +
"print encodings.latin_1\n" +
""
);
checkNoError();
}
public void testRelImport() throws FileNotFoundException{
analyzer = new OccurrencesAnalyzer();
File file = new File(TestDependent.TEST_PYSRC_LOC+"relative/__init__.py");
Document doc = new Document(REF.getFileContents(file));
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModule("relative.__init__", file, nature, 0), prefs, doc);
//no unused import message is generated
printMessages(msgs, 0);
}
public void testImportNotFound8() throws FileNotFoundException{
analyzer = new OccurrencesAnalyzer();
File file = new File(TestDependent.TEST_PYSRC_LOC+"testenc/encimport.py");
Document doc = new Document(REF.getFileContents(file));
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModule("testenc.encimport", file, nature, 0), prefs, doc);
printMessages(msgs, 0);
}
public void testUnusedWildRelativeImport() throws FileNotFoundException{
analyzer = new OccurrencesAnalyzer();
File file = new File(TestDependent.TEST_PYSRC_LOC+"testOtherImports/f1.py");
Document doc = new Document(REF.getFileContents(file));
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModule("testOtherImports.f1", file, nature, 0), prefs, doc);
printMessages(msgs, 1);
assertContainsMsg("Unused in wild import: SomeOtherTest, Test", msgs);
}
public void testImportNotFound5(){
doc = new Document(
"from os import path as otherThing\n" +
""
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs,1);
assertContainsMsg("Unused import: otherThing", msgs);
}
public void testImportFound1(){
doc = new Document(
"from os import path\n" +
""
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs,1);
assertContainsMsg("Unused import: path", msgs);
}
public void testReimport4(){
doc = new Document(
"from testlib.unittest.relative import toimport\n" +
"from testlib.unittest.relative import toimport\n" +
""
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs, 3);
assertContainsMsg("Unused import: toimport", msgs, 1);
assertContainsMsg("Unused import: toimport", msgs, 2);
assertContainsMsg("Import redefinition: toimport", msgs);
HashSet set = new HashSet();
for (IMessage m : msgs) {
set.add(m);
}
assertEquals(2, set.size()); //that's because we actually only have those 2 messages (but one appears 2 times)
}
public void testRelativeNotUndefined() throws FileNotFoundException{
analyzer = new OccurrencesAnalyzer();
File file = new File(TestDependent.TEST_PYSRC_LOC+"testlib/unittest/relative/testrelative.py");
Document doc = new Document(REF.getFileContents(file));
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModule("testlib.unittest.relative.testrelative", file, nature, 0), prefs, doc);
printMessages(msgs, 0);
}
public void testRelativeNotUndefined2() throws FileNotFoundException{
analyzer = new OccurrencesAnalyzer();
File file = new File(TestDependent.TEST_PYSRC_LOC+"relative/mod2.py");
Document doc = new Document(REF.getFileContents(file));
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModule("relative.mod2", file, nature, 0), prefs, doc);
printMessages(msgs, 1);
assertEquals("Unused import: mod1", msgs[0].getMessage());
}
public void testLambda(){
doc = new Document(
"a = lambda b: callit(b)\n"+
""
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs, 1);
assertContainsMsg("Undefined variable: callit", msgs);
}
public void testLambda2(){
doc = new Document(
"a = lambda c,*b: callit(c, *b)\n"+
"\n"+
""
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs, 1);
assertContainsMsg("Undefined variable: callit", msgs);
}
public void testReimport(){
doc = new Document(
"import os \n"+
"import os \n"+
"print os \n"+
""
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs, 2);
IMessage message = assertContainsMsg("Import redefinition: os", msgs, 2);
assertContainsMsg("Unused import: os", msgs, 1);
assertEquals(8, message.getStartCol(doc));
assertEquals(10, message.getEndCol(doc));
assertEquals(2, message.getStartLine(doc));
}
public void testReimport2(){
doc = new Document(
"import os \n"+
"import os \n"+
""
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs, 3);
assertContainsMsg("Import redefinition: os", msgs);
assertContainsMsg("Unused import: os", msgs, 1);
assertContainsMsg("Unused import: os", msgs, 2);
HashSet set = new HashSet();
for (IMessage m : msgs) {
set.add(m);
}
assertEquals(2, set.size()); //that's because we actually only have those 2 messages (but one appears 2 times)
}
public void testReimport5(){
doc = new Document(
"import os \n" +
"print os \n"+
"import os \n"+
""
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs, 2);
assertContainsMsg("Import redefinition: os", msgs, 3);
assertContainsMsg("Unused import: os", msgs, 3);
}
public void testReimport3(){
doc = new Document(
"import os \n"+
"def m1(): \n"+
" import os \n"+
" print os \n"+
"\n"+
""
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs, 2);
assertEquals(2, msgs.length);
assertContainsMsg("Import redefinition: os", msgs, 3);
assertContainsMsg("Unused import: os", msgs, 1);
}
public void testUnusedVariable2() {
//ignore the self
doc = new Document(
"class Class1: \n" +
" def met1(self, a):\n" +
" pass"
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs, 1);
assertEquals("Unused parameter: a", msgs[0].getMessage());
}
public void testNoUnusedVariable() {
doc = new Document(
"class Class1: \n" +
" @classmethod\n" +
" def met1(cls):\n" +
" pass"
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs, 0);
}
public void testUnusedVariable() {
doc = new Document(
"def m1(): \n" +
" a = 1 ");
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
assertEquals(1, msgs.length);
assertEquals(TYPE_UNUSED_VARIABLE, msgs[0].getType());
assertEquals("Unused variable: a", msgs[0].getMessage());
doc = new Document("a = 1;print a");
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
assertEquals(0, msgs.length);
}
public void test2UnusedVariables() {
doc = new Document(
"def m1(): \n"+
" result = 10 \n"+
" \n"+
" if False: \n"+
" result = 20\n"+
" \n"
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
assertEquals(2, msgs.length);
}
public void test3UnusedVariables() {
doc = new Document(
"def m1(): \n"+
" dummyResult = 10 \n"+
" \n"+
" if False: \n"+
" dummy2 = 20 \n"+
" \n"
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
assertEquals(0, msgs.length);
}
public void test4UnusedVariables() {
doc = new Document(
"notdefined.aa().bb.cc\n"
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs, 1);
assertEquals(1, msgs[0].getStartCol(doc));
}
public void test5UnusedVariables() {
doc = new Document(
"notdefined.aa[10].bb.cc\n"
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs, 1);
assertEquals(1, msgs[0].getStartCol(doc));
}
public void testNotUnusedVariable() {
doc = new Document(
"def m1(): \n"+
" result = 10 \n"+
" \n"+
" if False: \n"+
" result = 20\n"+
" \n"+
" print result \n"
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs);
assertEquals(0, msgs.length);
}
public void testNotUnusedVariable4() {
doc = new Document(
"def m1(): \n"+
" result = 10 \n"+
" \n"+
" while result > 0: \n"+
" result = 0 \n"+
" \n"+
""
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs);
assertEquals(0, msgs.length);
}
public void testNotUnusedVariable5() {
doc = new Document(
"def m(): \n"+
" try: \n"+
" c = 'a' \n"+
" except: \n"+
" c = 'b' \n"+
" print c \n"+
""
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs);
assertEquals(0, msgs.length);
}
public void testNotUnusedVariable6() {
doc = new Document(
"def m(): \n"+
" try: \n"+
" c = 'a' \n"+
" finally: \n"+
" c = 'b' \n"+
" print c \n"+
""
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs);
assertEquals(0, msgs.length);
}
public void testNotUnusedVariable7() {
doc = new Document(
"def m(a, b): \n"+
" raise RuntimeError('err')\n"+
""
);
checkNoError();
assertEquals(0, msgs.length);
}
public void testNotUnusedVariable8() {
doc = new Document(
"def m(a, b): \n"+
" '''test''' \n"+
" raise RuntimeError('err')\n"+
""
);
checkNoError();
assertEquals(0, msgs.length);
}
public void testUnusedVariable8() {
doc = new Document(
"def outer(show=True): \n"+
" def inner(show): \n"+
" print show \n"+
""
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs, 1);
assertEquals(1, msgs.length);
assertContainsMsg("Unused parameter: show", msgs, 1);
}
public void testUnusedVariable9() {
doc = new Document(
"def outer(show=True): \n"+
" def inner(show=show): \n"+
" pass \n"+
""
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs, 1);
assertEquals(1, msgs.length);
assertContainsMsg("Unused parameter: show", msgs, 2);
}
public void testUnusedVariable10() {
doc = new Document(
"def outer(show): \n"+
" def inner(show): \n"+
" pass \n"+
""
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs, 2);
assertEquals(2, msgs.length);
assertContainsMsg("Unused parameter: show", msgs, 1);
assertContainsMsg("Unused parameter: show", msgs, 2);
}
public void testUnusedVariable6() {
doc = new Document(
"def m(): \n"+
" try: \n"+
" c = 'a' \n"+
" finally: \n"+
" c = 'b' \n"+
""
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs,2 );
assertEquals(2, msgs.length);
}
public void testUnusedVariable7() {
doc = new Document(
"def m( a, b ): \n"+
" def m1( a, b ): \n"+
" print a, b \n"+
" if a: \n"+
" print 'ok' \n"+
""
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs,1 );
assertEquals(1, msgs.length);
assertContainsMsg("Unused parameter: b", msgs, 1);
}
public void testNotUnusedVariable2() {
doc = new Document(
"def GetValue( option ): \n"+
" return int( option ).Value()\n"+
""
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs);
assertEquals(0, msgs.length);
}
public void testNotUnusedVariable3() {
doc = new Document(
"def val(i): \n"+
" i = i + 1 \n"+
" print i \n"+
""
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs);
assertEquals(0, msgs.length);
}
public void testUndefinedVar() {
doc = new Document(
"def GetValue(): \n"+
" return int( option ).Value()\n"+
""
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs,1);
assertEquals(1, msgs.length);
assertContainsMsg("Undefined variable: option", msgs);
}
public void testScopes() {
//2 messages with token with same name
doc = new Document(
"def m1(): \n"+
" def m2(): \n"+
" print a \n"+
" a = 10 "
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs);
assertEquals(0, msgs.length);
}
public void testScopes2() {
doc = new Document(
"class Class1: \n"+
" c = 1 \n"+
""
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs);
assertEquals(0, msgs.length);
}
public void testScopes3() {
doc = new Document(
"class Class1: \n"+
" def __init__( self ): \n"+
" print Class1 \n"+
""
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs);
assertEquals(0, msgs.length);
}
public void testScopes4() {
doc = new Document(
"def rec(): \n"+
" def rec2(): \n"+
" return rec2 \n"+
""
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs);
assertEquals(0, msgs.length);
}
public void testScopes5() {
doc = new Document(
"class C: \n"+
" class I: \n"+
" print I\n"+
""
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs);
assertEquals(0, msgs.length);
}
public void testScopes6() {
doc = new Document(
"def ok(): \n"+
" print col \n"+
"def rowNotEmpty(): \n"+
" col = 1 \n"+
""
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs, 2);
assertContainsMsg("Undefined variable: col", msgs, 2);
assertContainsMsg("Unused variable: col", msgs, 4);
}
public void testScopes7() {
doc = new Document(
"def ok(): \n"+
" def call(): \n"+
" call2() \n"+
" \n"+
" def call2(): \n"+
" pass\n"+
""
);
checkNoError();
}
public void testScopes8() {
doc = new Document(
"def m1(): \n"+
" print (str(undef)).lower() \n"+
" \n"+
""
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs, 1);
assertContainsMsg("Undefined variable: undef", msgs, 2);
}
public void testScopes9() {
doc = new Document(
"def m1(): \n"+
" undef = 10 \n"+
" print (str(undef)).lower() \n"+
" \n"+
""
);
checkNoError();
}
public void testScopes10() {
doc = new Document(
"class C:\n"+
" def m1(self):\n"+
" print m2\n"+ //should give error, as we are inside the method (and not in the class scope)
" def m2(self):\n"+
" print m1\n"+ //should give error, as we are inside the method (and not in the class scope)
"\n"+
"\n"+
"\n"+
"\n"+
""
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs, 2);
}
public void testSameName() {
//2 messages with token with same name
doc = new Document(
"def m1():\n"+
" a = 1\n"+
" a = 2" );
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
assertEquals(2, msgs.length);
}
public void testVarArgs() {
doc = new Document(
"def m1(*args): \n"+
" print args "
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
assertEquals(0, msgs.length);
}
public void testVarArgsNotUsed() {
doc = new Document(
"\n" +
"def m1(*args): \n"+
" pass "
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
assertEquals(1, msgs.length);
assertContainsMsg("Unused parameter: args", msgs, 2);
assertEquals(9, msgs[0].getStartCol(doc));
assertEquals(13, msgs[0].getEndCol(doc));
}
public void testKwArgs() {
doc = new Document(
"def m1(**kwargs): \n"+
" print kwargs "
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs);
assertEquals(0, msgs.length);
}
public void testKwArgs2() {
doc = new Document(
"def m3(): \n" +
" def m1(**kwargs): \n"+
" pass "
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs,1);
assertEquals(1, msgs.length);
assertContainsMsg("Unused parameter: kwargs", msgs, 2);
assertEquals(14, msgs[0].getStartCol(doc));
assertEquals(20, msgs[0].getEndCol(doc));
}
public void testOtherScopes() {
//2 messages with token with same name
doc = new Document(
"def m1( aeee ): \n"+
" pass \n"+
"def m2( afff ): \n"+
" pass " );
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
assertEquals(2, msgs.length);
}
public void testUndefinedVariable() {
//2 messages with token with same name
doc = new Document(
"print a"
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
assertEquals(1, msgs.length);
assertEquals(TYPE_UNDEFINED_VARIABLE, msgs[0].getType());
assertEquals("Undefined variable: a", msgs[0].getMessage());
}
public void testUndefinedVariable2() {
doc = new Document(
"a = 10 \n"+ //global scope - does not give msg
"def m1(): \n"+
" a = 20 \n"+
" print a \n"+
"\n"
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs);
assertEquals(0, msgs.length);
}
public void testDecoratorUndefined() {
doc = new Document(
"@notdefined \n"+
"def m1(): \n"+
" pass \n"+
"\n"
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs,1);
IMessage msg = msgs[0];
assertEquals("Undefined variable: notdefined", msg.getMessage());
assertEquals(2, msg.getStartCol(doc));
assertEquals(1, msg.getStartLine(doc));
}
public void testUndefinedVariable3() {
doc = new Document(
"a = 10 \n"+ //global scope - does not give msg
"def m1(): \n"+
" a = 20 \n"+
"\n"
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs,1);
assertEquals(1, msgs.length);
assertEquals(TYPE_UNUSED_VARIABLE, msgs[0].getType());
assertEquals("Unused variable: a", msgs[0].getMessage());
assertEquals(3, msgs[0].getStartLine(doc));
}
public void testOk() {
//all ok...
doc = new Document(
"import os \n" +
" \n" +
"def m1(): \n" +
" print os\n" +
" \n" +
"print m1 \n"
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs);
assertEquals(0, msgs.length);
}
public void testImportAfter() {
doc = new Document(
"def met(): \n" +
" print os.path \n" +
"import os.path \n" +
""
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs);
assertEquals(0, msgs.length);
}
public void testImportAfter2() {
doc = new Document(
"def met(): \n" +
" print os.path \n" +
"import os \n" +
""
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs);
assertEquals(0, msgs.length);
}
public void testImportPartial() {
doc = new Document(
"import os.path \n" +
"print os \n" +
""
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
assertEquals(1, msgs.length);
assertContainsMsg("Unused import: os.path", msgs);
}
public void testImportAs() {
doc = new Document(
"import os.path as bla \n" +
"print bla \n" +
""
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs);
assertEquals(0, msgs.length);
}
public void testImportAs2() {
doc = new Document(
"import os.path as bla \n" +
"print os.path \n" +
""
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs,2);
assertEquals(2, msgs.length);
assertContainsMsg("Undefined variable: os", msgs);
assertContainsMsg("Unused import: bla", msgs);
}
public void testImportAs3() {
doc = new Document(
"import os.path as bla \n" +
"print os \n" +
""
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
assertEquals(2, msgs.length);
assertContainsMsg("Undefined variable: os", msgs);
assertContainsMsg("Unused import: bla", msgs);
}
public void testAttributeImport() {
//all ok...
doc = new Document(
"import os.path \n" +
"print os.path \n" +
""
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs);
assertEquals(0, msgs.length);
}
public void testGlobal() {
//no need to warn if global variable is unused (and it should be defined at the global definition)
doc = new Document(
"def m(): \n" +
" global __progress \n" +
" __progress = __progress + 1 \n" +
""
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs);
assertEquals(0, msgs.length);
}
public void testGlobal2() {
//no need to warn if global variable is unused (and it should be defined at the global definition)
doc = new Document(
"def m(): \n" +
" global __progress \n" +
" __progress = 1 \n" +
""
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs);
assertEquals(0, msgs.length);
}
public void testAttributeImportAccess() {
//all ok...
doc = new Document(
"import os \n" +
"print os.path \n" +
""
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs);
assertEquals(0, msgs.length);
}
public void testAttributeAccessMsg() {
//all ok...
doc = new Document(
"s.a = 10 \n" +
""
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
assertEquals(1, msgs.length);
assertEquals("Undefined variable: s", msgs[0].getMessage());
}
public void testAttributeAccess() {
//all ok...
doc = new Document(
"def m1(): \n" +
" class Stub():pass \n" +
" s = Stub() \n" +
" s.a = 10 \n" +
" s.b = s.a \n" +
""
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs);
assertEquals(0, msgs.length);
}
public void testAttributeAccess2() {
//all ok...
doc = new Document(
"class TestCase: \n" +
" def test(self): \n" +
" db = 10 \n" +
" comp = db.select(1) \n" +
" aa.bbb.cccc[comp.id].hasSimulate = True \n" +
" \n" +
""
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs, 1);
//comp should be used
//aa undefined (check pos)
assertNotContainsMsg("Unused variable: comp", msgs);
assertContainsMsg("Undefined variable: aa", msgs, 5);
assertEquals(1, msgs.length);
assertEquals(9, msgs[0].getStartCol(doc));
}
public void testAttributeErrorPos() {
//all ok...
doc = new Document(
"print message().bla\n" +
""
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs, 1);
assertEquals(1, msgs.length);
assertEquals("Undefined variable: message", msgs[0].getMessage());
assertEquals(7, msgs[0].getStartCol(doc));
assertEquals(14, msgs[0].getEndCol(doc));
}
public void testAttributeErrorPos2() {
//all ok...
doc = new Document(
"lambda x: os.rmdir( x )\n" +
""
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs, 1);
assertEquals(1, msgs.length);
assertEquals("Undefined variable: os", msgs[0].getMessage());
assertEquals(11, msgs[0].getStartCol(doc));
assertEquals(13, msgs[0].getEndCol(doc));
}
public void testAttributeErrorPos3() {
//all ok...
doc = new Document(
"os.rmdir( '' )\n" +
""
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs, 1);
assertEquals(1, msgs.length);
assertEquals("Undefined variable: os", msgs[0].getMessage());
assertEquals(1, msgs[0].getStartCol(doc));
assertEquals(3, msgs[0].getEndCol(doc));
}
public void testImportAttr() {
//all ok...
doc = new Document(
"import os.path \n" +
"if os.path.isfile( '' ):pass \n" +
""
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs);
assertEquals(0, msgs.length);
}
public void testSelf() {
//all ok...
doc = new Document(
"class C: \n" +
" def m1(self): \n" +
" print self \n" +
""
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs);
assertEquals(0, msgs.length);
}
public void testDefinitionLater() {
doc = new Document(
"def m1(): \n" +
" print m2()\n" +
" \n" +
"def m2(): \n" +
" pass \n"
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs);
assertEquals(0, msgs.length);
}
public void testDefinitionLater2() {
doc = new Document(
"def m(): \n" +
" AroundContext().m1()\n" +
" \n" +
"class AroundContext: \n" +
" def m1(self): \n" +
" pass \n"
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs);
assertEquals(0, msgs.length);
}
public void testNotDefinedLater() {
doc = new Document(
"def m1(): \n" +
" print m2()\n" +
" \n"
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
assertEquals(1, msgs.length);
}
public void testNotDefinedLater2() {
doc = new Document(
"def m1(): \n" +
" print c \n" +
" c = 10 \n" +
" \n"
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
assertEquals(2, msgs.length);
}
public void testUndefinedVariableBuiltin() {
doc = new Document(
"print False"
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
assertEquals(0, msgs.length);
}
public void testUndefinedVariableBuiltin2() {
doc = new Document(
"print __file__" //source folder always has the builtin __file__
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs);
assertEquals(0, msgs.length);
}
public void testUndefinedVariableBuiltin3() {
doc = new Document(
"print [].__str__" //[] is a builtin
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs);
assertEquals(0, msgs.length);
}
public void testSelfAttribute() {
doc = new Document(
"class C: \n" +
" def m2(self): \n" +
" self.m1 = '' \n" +
" print self.m1.join('a').join('b') \n"
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs);
assertEquals(0, msgs.length);
}
public void testBuiltinAcess() {
doc = new Document(
"print file.read"
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
assertEquals(0, msgs.length);
}
public void testDictAcess() {
doc = new Document(
"def m1():\n" +
" k = {} \n" +
" print k[0].append(10) "
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs);
assertEquals(0, msgs.length);
}
public void testAttribute1() {
doc = new Document(
"def m1():\n" +
" file( 10, 'r' ).read()"
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
assertEquals(0, msgs.length);
}
public void testAttributeFloat() {
doc = new Document(
"def m1():\n" +
" v = 1.0.__class__\n" +
" print v "
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs);
assertEquals(0, msgs.length);
}
public void testAttributeString() {
doc = new Document(
"def m1():\n" +
" v = 'r'.join('a')\n" +
" print v "
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs);
assertEquals(0, msgs.length);
}
public void testAttributeString2() {
doc = new Document(
"def m1():\n" +
" v = 'r.a.s.b'.join('a')\n" +
" print v "
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs);
assertEquals(0, msgs.length);
}
public void testUnusedInFor() {
doc = new Document(
"def test():\n" +
" for a in range(10):\n" + //a is unused
" pass"
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs, 1);
}
public void testUnusedInFor2() {
doc = new Document(
"def problemFunct():\n" +
" msg='initialised'\n" +
" for i in []:\n" +
" msg='success at %s' % i\n" +
" return msg\n"
);
checkNoError();
}
public void testTupleVar() {
doc = new Document(
"def m1():\n" +
" print (0,0).__class__"
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs);
assertEquals(0, msgs.length);
}
public void testStaticNoSelf() {
doc = new Document(
"class C:\n" +
" @staticmethod\n" +
" def m():\n" +
" pass\n" +
"\n" +
"\n" +
""
);
checkNoError();
}
public void testClassMethodCls() {
doc = new Document(
"class C:\n" +
" @classmethod\n" +
" def m(cls):\n" +
" print cls\n" +
"\n" +
"\n" +
""
);
checkNoError();
}
public void testClassMethodCls2() {
doc = new Document(
"class C:\n" +
" def m(cls):\n" +
" print cls\n" +
" m = classmethod(m)" +
"\n" +
"\n" +
""
);
checkNoError();
}
public void testClassMethodCls3() {
doc = new Document(
"class C:\n" +
" def m():\n" +
" pass\n" +
" m = classmethod(m)" +
"\n" +
"\n" +
""
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs, 1);
assertEquals("Method 'm' should have cls as first parameter", msgs[0].toString());
}
public void testStaticNoSelf2() {
doc = new Document(
"class C:\n" +
" def m():\n" +
" pass\n" +
" m = staticmethod(m)\n" +
"\n" +
""
);
checkNoError();
}
public void testNoSelf() {
doc = new Document(
"class C:\n" +
" def m():\n" +
" pass\n" +
"\n" +
"\n" +
""
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs, 1);
assertEquals("Method 'm' should have self as first parameter", msgs[0].getMessage());
}
public void testTupleVar2() {
doc = new Document(
"def m1():\n" +
" print (10 / 10).__class__"
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs);
assertEquals(0, msgs.length);
}
public void testDuplicatedSignature() {
//2 messages with token with same name
doc = new Document(
"class C: \n" +
" def m1(self):pass\n" +
" def m1(self):pass\n"
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
assertEquals(1, msgs.length);
assertEquals(TYPE_DUPLICATED_SIGNATURE, msgs[0].getType());
assertEquals("Duplicated signature: m1", msgs[0].getMessage());
assertEquals(9, msgs[0].getStartCol(doc));
//ignore
prefs.severityForDuplicatedSignature = IMarker.SEVERITY_INFO;
doc = new Document(
"class C: \n" +
" def m1(self):pass\n" +
" def m1(self):pass\n"
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
assertEquals(1, msgs.length); //it is created, but in ignore mode
assertEquals(IMarker.SEVERITY_INFO, msgs[0].getSeverity());
}
public void testUndefinedWithTab() {
doc = new Document(
"def m():\n" +
"\tprint a\n" +
"\n" +
""
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs, 1);
assertEquals("Undefined variable: a", msgs[0].getMessage());
assertEquals(8, msgs[0].getStartCol(doc));
}
public void testUnusedVar() {
doc = new Document(
"def test(data):\n"+
" return str(data)[0].strip()\n"+
"\n"
);
checkNoError();
}
public void testUndefinedVar1() {
doc = new Document(
"return (data)[0].strip()"
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs, 1);
assertEquals("Undefined variable: data", msgs[0].getMessage());
}
public void testUnusedParameter() {
doc = new Document(
"def a(x):pass"
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs, 1);
assertEquals("Unused parameter: x", msgs[0].getMessage());
}
public void testUnusedParameter2() {
doc = new Document(
"def a(*x):pass"
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs, 1);
assertEquals("Unused parameter: x", msgs[0].getMessage());
}
public void testUnusedParameter3() {
doc = new Document(
"def a(**x):pass"
);
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs, 1);
assertEquals("Unused parameter: x", msgs[0].getMessage());
}
public void testEmptyDict() {
doc = new Document(
"for k,v in {}.iteritmes(): print k,v"
);
checkNoError();
}
public void testDirectDictAccess() {
doc = new Document(
"def Load(self):\n"+
" #Is giving Unused variable: i\n"+
" for i in xrange(10): \n"+
" coerce(dict[i].text.strip())\n"
);
checkNoError();
}
public void testDefinedInClassAndInLocal() {
doc = new Document(
"class MyClass(object):\n"+
" foo = 10\n"+
" \n"+
" def mystery(self):\n"+
" for foo in range(12):\n"+
" print foo\n"+
"\n"
);
checkNoError();
}
public void testDefinedInClassAndInLocal2() {
doc = new Document(
"class MyClass(object):\n"+
" options = [i for i in range(10)]\n"+
" \n"+
" def mystery(self):\n"+
" for i in range(12):\n"+
" print i #should not be undefined!\n"+
"\n"
);
checkNoError();
}
public void testColError() {
doc = new Document("print function()[0].strip()");
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs, 1);
assertEquals("Undefined variable: function", msgs[0].getMessage());
assertEquals(7, msgs[0].getStartCol(doc));
}
public void testColError2() {
doc = new Document("" +
"class Foo(object):\n" +
" def m1(self):\n" +
" pass\n" +
" def m1(self):\n" +
" pass\n" +
"");
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs, 1);
assertEquals("Duplicated signature: m1", msgs[0].getMessage());
assertEquals(10, msgs[0].getStartCol(doc));
}
public void testColError3() {
doc = new Document("" +
"class Foo(object):\n" +
" pass\n" +
"class Foo(object):\n" +
" pass\n" +
"");
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs, 1);
assertEquals("Duplicated signature: Foo", msgs[0].getMessage());
assertEquals(8, msgs[0].getStartCol(doc));
}
public void testDupl2() {
doc = new Document("" +
"if True:\n" +
" def f(self):\n" +
" pass\n" +
"else:\n" +
" def f(self):\n" +
" pass\n" +
"\n" +
"");
checkNoError();
}
public void testNoEffect() {
doc = new Document("" +
"2 == 1\n" + //has no effect
"if 2 == 1: pass\n" + //has effect
"");
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs, 1);
assertEquals("Statement apppears to have no effect", msgs[0].getMessage());
}
public void testNoEffect2() {
doc = new Document("" +
"a = 5\n" +
"a == 1\n" + //has no effect
"if a == 1: pass\n" + //has effect
"");
analyzer = new OccurrencesAnalyzer();
msgs = analyzer.analyzeDocument(nature, (SourceModule) AbstractModule.createModuleFromDoc(null, null, doc, nature, 0), prefs, doc);
printMessages(msgs, 1);
assertEquals("Statement apppears to have no effect", msgs[0].getMessage());
}
} |
.
.
// Global variables
private int rawYCoordinate;
private int yCoordinate;
private int maxHeight;
private int nFactor;
.
.
// Helper method to get maxHeight
private void getWindowData (Context context) {
private WindowManager windowManager;
windowManager = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
maxHeight = windowManager.getDefaultDisplay().getHeight();
}
// Heart and soul of this implementation
OnTouchListener gestureListener = new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch(event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
// Nothing here
break;
case MotionEvent.ACTION_UP:
// To suppress warnings
v.performClick();
break;
case MotionEvent.ACTION_MOVE:
rawYCoordinate = (int) event.getY();
yCoordinate = 255 - (rawYCoordinate / nFactor);
android.provider.Settings.System.putInt(mContext.getContentResolver(),
android.provider.Settings.System.SCREEN_BRIGHTNESS, yCoordinate);
break;
}
return true;
}
};
.
. |
package com.ctrip.platform.dal.dao.sqlbuilder;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import com.ctrip.platform.dal.common.enums.DatabaseCategory;
import com.ctrip.platform.dal.dao.StatementParameter;
import com.ctrip.platform.dal.dao.StatementParameters;
public abstract class AbstractSqlBuilder implements TableSqlBuilder {
protected DatabaseCategory dbCategory = DatabaseCategory.MySql;
protected StatementParameters parameters = new StatementParameters();
protected int index = 1;
protected List<FieldEntry> selectOrUpdataFieldEntrys = new ArrayList<FieldEntry>();
private LinkedList<WhereClauseEntry> whereClauseEntries = new LinkedList<>();
private List<FieldEntry> whereFieldEntrys = new ArrayList<FieldEntry>();
private String tableName;
private boolean compatible = false;
public boolean isCompatible() {
return compatible;
}
public void setCompatible(boolean compatible) {
this.compatible = compatible;
}
public AbstractSqlBuilder from(String tableName) throws SQLException {
if(tableName ==null || tableName.isEmpty())
throw new SQLException("table name is illegal.");
this.tableName = tableName;
return this;
}
public AbstractSqlBuilder setDatabaseCategory(DatabaseCategory dbCategory) throws SQLException {
Objects.requireNonNull(dbCategory, "DatabaseCategory can't be null.");
this.dbCategory = dbCategory;
return this;
}
public String getTableName() {
return tableName;
}
public String getTableName(String shardStr) {
return tableName + shardStr;
}
/**
* StatementParameters
* @return
*/
public StatementParameters buildParameters(){
parameters = new StatementParameters();
index = 1;
for(FieldEntry entry : selectOrUpdataFieldEntrys) {
parameters.add(new StatementParameter(index++, entry.getSqlType(), entry.getParamValue()).setSensitive(entry.isSensitive()).setName(entry.getFieldName()).setInParam(entry.isInParam()));
}
for(FieldEntry entry : whereFieldEntrys){
parameters.add(new StatementParameter(index++, entry.getSqlType(), entry.getParamValue()).setSensitive(entry.isSensitive()).setName(entry.getFieldName()).setInParam(entry.isInParam()));
}
return this.parameters;
}
/**
* StatementParametersindexsql1
* @return
*/
public int getStatementParameterIndex(){
return this.index;
}
/**
* MySQL `SqlServer[]
* @param fieldName
* @return
*/
public String wrapField(String fieldName){
return wrapField(dbCategory, fieldName);
}
/**
* MySQL `SqlServer[]
* @param fieldName
* @return
*/
public static String wrapField(DatabaseCategory dbCategory, String fieldName){
if("*".equalsIgnoreCase(fieldName) || fieldName.contains("ROW_NUMBER") || fieldName.contains(",")){
return fieldName;
}
return dbCategory.quote(fieldName);
}
/**
* build sql.
* @return
*/
public abstract String build();
private static final String EMPTY = "";
/**
* build where expression
* @return
*/
public String getWhereExp(){
// return whereExp.toString().trim().isEmpty()? "": "WHERE"+ whereExp.toString();
if(whereClauseEntries.size() == 0)
return EMPTY;
LinkedList<WhereClauseEntry> filtered = new LinkedList<>();
for(WhereClauseEntry entry: whereClauseEntries) {
if(entry.isClause() && entry.isNull()){
meltDownNullValue(filtered);
continue;
}
if(entry.isBracket() && !((BracketClauseEntry)entry).isLeft()){
if(meltDownRightBracket(filtered))
continue;
}
// AND/OR
if(entry.isOperator() && !entry.isClause()) {
if(meltDownAndOrOperator(filtered))
continue;
}
filtered.add(entry);
}
StringBuilder sb = new StringBuilder();
for(WhereClauseEntry entry: filtered) {
sb.append(entry.getClause(dbCategory)).append(" ");
}
String whereClause = sb.toString().trim();
if(whereClause.isEmpty())
return "";
return whereClause;
}
private boolean meltDownAndOrOperator(LinkedList<WhereClauseEntry> filtered) {
// If it is the first element
if(filtered.size() == 0)
return true;
WhereClauseEntry entry = filtered.getLast();
// The last one is "("
if(entry.isBracket() && ((BracketClauseEntry)entry).isLeft())
return true;
// AND/OR/NOT AND/OR
if(entry.isOperator()) {
return true;
}
return false;
}
private boolean meltDownRightBracket(LinkedList<WhereClauseEntry> filtered) {
int bracketCount = 1;
while(filtered.size() > 0) {
WhereClauseEntry entry = filtered.getLast();
// One ")" only remove one "("
if(entry.isBracket() && ((BracketClauseEntry)entry).isLeft() && bracketCount == 1){
filtered.removeLast();
bracketCount
continue;
}
// Remove any leading AND/OR/NOT (BOT is both operator and clause)
if(entry.isOperator()) {
filtered.removeLast();
continue;
}
break;
}
return bracketCount == 0? true : false;
}
private void meltDownNullValue(LinkedList<WhereClauseEntry> filtered) {
if(filtered.size() == 0)
return;
while(filtered.size() > 0) {
WhereClauseEntry entry = filtered.getLast();
// Remove any leading AND/OR/NOT (NOT is both operator and clause)
if(entry.isOperator()) {
filtered.removeLast();
continue;
}
break;
}
}
/**
* AND
* @return
*/
public AbstractSqlBuilder and(){
return add(OperatorClauseEntry.AND());
}
/**
* OR
* @return
*/
public AbstractSqlBuilder or(){
return add(OperatorClauseEntry.OR());
}
private static final boolean DEFAULT_SENSITIVE = false;
/**
* NULLSQLException
* @param field
* @param paramValue
* @return
* @throws SQLException
*/
public AbstractSqlBuilder equal(String field, Object paramValue, int sqlType) throws SQLException {
return equal(field, paramValue, sqlType, DEFAULT_SENSITIVE);
}
public AbstractSqlBuilder equal(String field, Object paramValue, int sqlType, boolean sensitive) throws SQLException {
return addParam(field, "=", paramValue, sqlType, sensitive);
}
/**
* NULLSQL
* @param field
* @param paramValue
* @return
* @throws SQLException
*/
public AbstractSqlBuilder equalNullable(String field, Object paramValue, int sqlType) {
return equalNullable(field, paramValue, sqlType, DEFAULT_SENSITIVE);
}
public AbstractSqlBuilder equalNullable(String field, Object paramValue, int sqlType, boolean sensitive) {
return addParamNullable(field, "=", paramValue, sqlType, sensitive);
}
/**
* NULLSQLException
* @param field
* @param paramValue
* @return
* @throws SQLException
*/
public AbstractSqlBuilder notEqual(String field, Object paramValue, int sqlType) throws SQLException {
return notEqual(field, paramValue, sqlType, DEFAULT_SENSITIVE);
}
public AbstractSqlBuilder notEqual(String field, Object paramValue, int sqlType, boolean sensitive) throws SQLException {
return addParam(field, "!=", paramValue, sqlType, sensitive);
}
/**
* NULLSQL
* @param field
* @param paramValue
* @return
* @throws SQLException
*/
public AbstractSqlBuilder notEqualNullable(String field, Object paramValue, int sqlType) {
return notEqualNullable(field, paramValue, sqlType, DEFAULT_SENSITIVE);
}
public AbstractSqlBuilder notEqualNullable(String field, Object paramValue, int sqlType, boolean sensitive) {
return addParamNullable(field, "!=", paramValue, sqlType, sensitive);
}
/**
* NULLSQLException
* @param field
* @param paramValue
* @return
* @throws SQLException
*/
public AbstractSqlBuilder greaterThan(String field, Object paramValue, int sqlType) throws SQLException {
return greaterThan(field, paramValue, sqlType, DEFAULT_SENSITIVE);
}
public AbstractSqlBuilder greaterThan(String field, Object paramValue, int sqlType, boolean sensitive) throws SQLException {
return addParam(field, ">", paramValue, sqlType, sensitive);
}
/**
* NULLSQL
* @param field
* @param paramValue
* @return
* @throws SQLException
*/
public AbstractSqlBuilder greaterThanNullable(String field, Object paramValue, int sqlType) {
return greaterThanNullable(field, paramValue, sqlType, DEFAULT_SENSITIVE);
}
public AbstractSqlBuilder greaterThanNullable(String field, Object paramValue, int sqlType, boolean sensitive) {
return addParamNullable(field, ">", paramValue, sqlType, sensitive);
}
/**
* NULLSQLException
* @param field
* @param paramValue
* @return
* @throws SQLException
*/
public AbstractSqlBuilder greaterThanEquals(String field, Object paramValue, int sqlType) throws SQLException {
return greaterThanEquals(field, paramValue, sqlType, DEFAULT_SENSITIVE);
}
public AbstractSqlBuilder greaterThanEquals(String field, Object paramValue, int sqlType, boolean sensitive) throws SQLException {
return addParam(field, ">=", paramValue, sqlType, sensitive);
}
/**
* NULLSQL
* @param field
* @param paramValue
* @return
* @throws SQLException
*/
public AbstractSqlBuilder greaterThanEqualsNullable(String field, Object paramValue, int sqlType) {
return greaterThanEqualsNullable(field, paramValue, sqlType, DEFAULT_SENSITIVE);
}
public AbstractSqlBuilder greaterThanEqualsNullable(String field, Object paramValue, int sqlType, boolean sensitive) {
return addParamNullable(field, ">=", paramValue, sqlType, sensitive);
}
/**
* NULLSQLException
* @param field
* @param paramValue
* @return
* @throws SQLException
*/
public AbstractSqlBuilder lessThan(String field, Object paramValue, int sqlType) throws SQLException {
return lessThan(field, paramValue, sqlType, DEFAULT_SENSITIVE);
}
public AbstractSqlBuilder lessThan(String field, Object paramValue, int sqlType, boolean sensitive) throws SQLException {
return addParam(field, "<", paramValue, sqlType, sensitive);
}
/**
* NULLSQL
* @param field
* @param paramValue
* @return
* @throws SQLException
*/
public AbstractSqlBuilder lessThanNullable(String field, Object paramValue, int sqlType) {
return lessThanNullable(field, paramValue, sqlType, DEFAULT_SENSITIVE);
}
public AbstractSqlBuilder lessThanNullable(String field, Object paramValue, int sqlType, boolean sensitive) {
return addParamNullable(field, "<", paramValue, sqlType, sensitive);
}
/**
* NULLSQLException
* @param field
* @param paramValue
* @return
* @throws SQLException
*/
public AbstractSqlBuilder lessThanEquals(String field, Object paramValue, int sqlType) throws SQLException {
return lessThanEquals(field, paramValue, sqlType, DEFAULT_SENSITIVE);
}
public AbstractSqlBuilder lessThanEquals(String field, Object paramValue, int sqlType, boolean sensitive) throws SQLException {
return addParam(field, "<=", paramValue, sqlType, sensitive);
}
/**
* NULLSQL
* @param field
* @param paramValue
* @return
* @throws SQLException
*/
public AbstractSqlBuilder lessThanEqualsNullable(String field, Object paramValue, int sqlType) {
return lessThanEqualsNullable(field, paramValue, sqlType, DEFAULT_SENSITIVE);
}
public AbstractSqlBuilder lessThanEqualsNullable(String field, Object paramValue, int sqlType, boolean sensitive) {
return addParamNullable(field, "<=", paramValue, sqlType, sensitive);
}
/**
* BetweenNULLSQLException
* @param field
* @param paramValue1 1
* @param paramValue2 2
* @return
* @throws SQLException
*/
public AbstractSqlBuilder between(String field, Object paramValue1, Object paramValue2, int sqlType) throws SQLException {
return between(field, paramValue1, paramValue2, sqlType, DEFAULT_SENSITIVE);
}
public AbstractSqlBuilder between(String field, Object paramValue1, Object paramValue2, int sqlType, boolean sensitive) throws SQLException {
if (paramValue1 == null || paramValue2 == null)
throw new SQLException(field + " is not support null value.");
return add(new BetweenClauseEntry(field, paramValue1, paramValue2, sqlType, sensitive, whereFieldEntrys));
}
/**
* BetweenNULLSQL
* @param field
* @param paramValue1 1
* @param paramValue2 2
* @return
* @throws SQLException
*/
public AbstractSqlBuilder betweenNullable(String field, Object paramValue1, Object paramValue2, int sqlType) {
return betweenNullable(field, paramValue1, paramValue2, sqlType, DEFAULT_SENSITIVE);
}
public AbstractSqlBuilder betweenNullable(String field, Object paramValue1, Object paramValue2, int sqlType, boolean sensitive) {
//paramValue==nullfieldSQL
if(paramValue1 == null || paramValue2 == null)
return add(new NullValueClauseEntry());
return add(new BetweenClauseEntry(field, paramValue1, paramValue2, sqlType, sensitive, whereFieldEntrys));
}
/**
* LikeNULLSQLException
* @param field
* @param paramValue
* @return
* @throws SQLException
*/
public AbstractSqlBuilder like(String field, Object paramValue, int sqlType) throws SQLException {
return like(field, paramValue, sqlType, DEFAULT_SENSITIVE);
}
public AbstractSqlBuilder like(String field, Object paramValue, int sqlType, boolean sensitive) throws SQLException {
return addParam(field, "LIKE", paramValue, sqlType, sensitive);
}
/**
* LikeNULLSQL
* @param field
* @param paramValue
* @return
* @throws SQLException
*/
public AbstractSqlBuilder likeNullable(String field, Object paramValue, int sqlType) {
return likeNullable(field, paramValue, sqlType, DEFAULT_SENSITIVE);
}
public AbstractSqlBuilder likeNullable(String field, Object paramValue, int sqlType, boolean sensitive) {
return addParamNullable(field, "LIKE", paramValue, sqlType, sensitive);
}
/**
* InNULLSQLException
* @param field
* @param paramValues
* @return
* @throws SQLException
*/
public AbstractSqlBuilder in(String field, List<?> paramValues, int sqlType) throws SQLException {
return in(field, paramValues, sqlType, DEFAULT_SENSITIVE);
}
public AbstractSqlBuilder in(String field, List<?> paramValues, int sqlType, boolean sensitive) throws SQLException {
if(null == paramValues || paramValues.size() == 0)
throw new SQLException(field + " must have more than one value.");
for(Object obj:paramValues)
if(obj==null)
throw new SQLException(field + " is not support null value.");
return addInParam(field, paramValues, sqlType, sensitive);
}
/**
* InNULL.
* 0
* @param field
* @param paramValues
* @return
* @throws SQLException
*/
public AbstractSqlBuilder inNullable(String field, List<?> paramValues, int sqlType) throws SQLException {
return inNullable(field, paramValues, sqlType, DEFAULT_SENSITIVE);
}
public AbstractSqlBuilder inNullable(String field, List<?> paramValues, int sqlType, boolean sensitive) throws SQLException {
if(null == paramValues){
return add(new NullValueClauseEntry());
}
if(paramValues.size() == 0){
throw new SQLException(field + " must have more than one value.");
}
Iterator<?> ite = paramValues.iterator();
while(ite.hasNext()){
if(ite.next()==null){
ite.remove();
}
}
if(paramValues.size() == 0){
return add(new NullValueClauseEntry());
}
return addInParam(field, paramValues, sqlType, sensitive);
}
/**
* Is null
* @param field
* @return
*/
public AbstractSqlBuilder isNull(String field){
return add(new NullClauseEntry(field, true));
}
/**
* Is not null
* @param field
* @return
*/
public AbstractSqlBuilder isNotNull(String field){
return add(new NullClauseEntry(field, false));
}
/**
* Add "("
*/
public AbstractSqlBuilder leftBracket(){
return add(BracketClauseEntry.leftBracket());
}
/**
* Add ")"
*/
public AbstractSqlBuilder rightBracket(){
return add(BracketClauseEntry.rightBracket());
}
/**
* Add "NOT"
*/
public AbstractSqlBuilder not(){
return add(new NotClauseEntry());
}
private AbstractSqlBuilder addInParam(String field, List<?> paramValues, int sqlType, boolean sensitive){
return add(new InClauseEntry(field, paramValues, sqlType, sensitive, whereFieldEntrys, compatible));
}
private AbstractSqlBuilder addParam(String field, String condition, Object paramValue, int sqlType, boolean sensitive) throws SQLException{
if(paramValue == null)
throw new SQLException(field + " is not support null value.");
return add(new SingleClauseEntry(field, condition, paramValue, sqlType, sensitive, whereFieldEntrys));
}
private AbstractSqlBuilder addParamNullable(String field, String condition, Object paramValue, int sqlType, boolean sensitive){
if(paramValue == null)
return add(new NullValueClauseEntry());
return add(new SingleClauseEntry(field, condition, paramValue, sqlType, sensitive, whereFieldEntrys));
}
private static abstract class WhereClauseEntry {
private String clause;
public boolean isOperator() {
return false;
}
public boolean isBracket() {
return false;
}
public boolean isClause() {
return false;
}
public boolean isNull() {
return false;
}
//To make it build late when DatabaseCategory is set
public abstract String getClause(DatabaseCategory dbCategory);
public String toString() {
return clause;
}
}
private static class NullValueClauseEntry extends WhereClauseEntry {
public boolean isNull() {
return true;
}
public boolean isClause() {
return true;
}
public String getClause(DatabaseCategory dbCategory) {
return "";
}
}
private static class SingleClauseEntry extends WhereClauseEntry {
private String condition;
private FieldEntry entry;
public SingleClauseEntry(String field, String condition, Object paramValue, int sqlType, boolean sensitive, List<FieldEntry> whereFieldEntrys) {
this.condition = condition;
entry = new FieldEntry(field, paramValue, sqlType, sensitive);
whereFieldEntrys.add(entry);
}
public boolean isClause() {
return true;
}
public String getClause(DatabaseCategory dbCategory) {
return String.format("%s %s ?", wrapField(dbCategory, entry.getFieldName()), condition);
}
}
private static class BetweenClauseEntry extends WhereClauseEntry {
private FieldEntry entry1;
private FieldEntry entry2;
public BetweenClauseEntry(String field, Object paramValue1, Object paramValue2, int sqlType, boolean sensitive, List<FieldEntry> whereFieldEntrys) {
entry1 = new FieldEntry(field, paramValue1, sqlType, sensitive);
entry2 = new FieldEntry(field, paramValue2, sqlType, sensitive);
whereFieldEntrys.add(entry1);
whereFieldEntrys.add(entry2);
}
public boolean isClause() {
return true;
}
public String getClause(DatabaseCategory dbCategory) {
return wrapField(dbCategory, entry1.getFieldName()) + " BETWEEN ? AND ?";
}
}
private static class InClauseEntry extends WhereClauseEntry {
private String field;
private String questionMarkList;
private boolean compatible;
private static final String IN_CLAUSE = " in ( ? )";
private List<FieldEntry> entries;
public InClauseEntry(String field, List<?> paramValues, int sqlType, boolean sensitive, List<FieldEntry> whereFieldEntrys, boolean compatible){
this.field = field;
this.compatible = compatible;
if(compatible)
create(field, paramValues, sqlType, sensitive, whereFieldEntrys);
else{
whereFieldEntrys.add(new FieldEntry(field, paramValues, sqlType, sensitive).setInParam(true));
}
}
private void create(String field, List<?> paramValues, int sqlType, boolean sensitive, List<FieldEntry> whereFieldEntrys){
StringBuilder temp = new StringBuilder();
temp.append(" in ( ");
entries = new ArrayList<>(paramValues.size());
for(int i=0,size=paramValues.size();i<size;i++){
temp.append("?");
if(i!=size-1){
temp.append(", ");
}
FieldEntry entry = new FieldEntry(field, paramValues.get(i), sqlType, sensitive);
entries.add(entry);
}
temp.append(" )");
questionMarkList = temp.toString();
whereFieldEntrys.addAll(entries);
}
public boolean isClause() {
return true;
}
public String getClause(DatabaseCategory dbCategory) {
return compatible ?
wrapField(dbCategory, field) + questionMarkList:
wrapField(dbCategory, field) + IN_CLAUSE;
}
}
private static class NullClauseEntry extends WhereClauseEntry {
private String field;
private boolean isNull;
public NullClauseEntry(String field, boolean isNull) {
this.field = field;
this.isNull= isNull;
}
public boolean isClause() {
return true;
}
public String getClause(DatabaseCategory dbCategory) {
return wrapField(dbCategory, field) + (isNull ? " IS NULL" : " IS NOT NULL");
}
}
private static class NotClauseEntry extends WhereClauseEntry {
public NotClauseEntry() {
}
public boolean isClause() {
return true;
}
public boolean isOperator() {
return true;
}
public String getClause(DatabaseCategory dbCategory) {
return "NOT";
}
}
private static class OperatorClauseEntry extends WhereClauseEntry {
private String operator;
public OperatorClauseEntry(String operator) {
this.operator = operator;
}
public String getClause(DatabaseCategory dbCategory) {
return operator;
}
@Override
public boolean isOperator() {
return true;
}
static OperatorClauseEntry AND() {
return new OperatorClauseEntry("AND");
}
static OperatorClauseEntry OR() {
return new OperatorClauseEntry("OR");
}
}
private static class BracketClauseEntry extends WhereClauseEntry {
private boolean left;
public BracketClauseEntry(boolean isLeft) {
left = isLeft;
}
public String getClause(DatabaseCategory dbCategory) {
return left? "(" : ")";
}
public boolean isBracket() {
return true;
}
public boolean isLeft() {
return left;
}
static BracketClauseEntry leftBracket() {
return new BracketClauseEntry(true);
}
static BracketClauseEntry rightBracket() {
return new BracketClauseEntry(false);
}
}
private AbstractSqlBuilder add(WhereClauseEntry entry) {
whereClauseEntries.add(entry);
return this;
}
} |
package io.debezium.connector.mysql;
import java.io.UnsupportedEncodingException;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.apache.kafka.connect.data.Struct;
import org.apache.kafka.connect.errors.ConnectException;
import org.apache.kafka.connect.source.SourceRecord;
import io.debezium.connector.SnapshotRecord;
import io.debezium.connector.mysql.RecordMakers.RecordsForTable;
import io.debezium.data.Envelope;
import io.debezium.function.BufferedBlockingConsumer;
import io.debezium.function.Predicates;
import io.debezium.heartbeat.Heartbeat;
import io.debezium.jdbc.JdbcConnection;
import io.debezium.jdbc.JdbcConnection.StatementFactory;
import io.debezium.relational.Column;
import io.debezium.relational.Table;
import io.debezium.relational.TableId;
import io.debezium.util.Clock;
import io.debezium.util.Strings;
import io.debezium.util.Threads;
/**
* A component that performs a snapshot of a MySQL server, and records the schema changes in {@link MySqlSchema}.
*
* @author Randall Hauch
*/
public class SnapshotReader extends AbstractReader {
private final boolean includeData;
private RecordRecorder recorder;
private final SnapshotReaderMetrics metrics;
private ExecutorService executorService;
private final MySqlConnectorConfig.SnapshotLockingMode snapshotLockingMode;
/**
* Create a snapshot reader.
*
* @param name the name of this reader; may not be null
* @param context the task context in which this reader is running; may not be null
*/
public SnapshotReader(String name, MySqlTaskContext context) {
super(name, context, null);
this.includeData = context.snapshotMode().includeData();
this.snapshotLockingMode = context.getConnectorConfig().getSnapshotLockingMode();
recorder = this::recordRowAsRead;
metrics = new SnapshotReaderMetrics(context, context.dbSchema(), changeEventQueueMetrics);
}
/**
* Set this reader's {@link #execute() execution} to produce a {@link io.debezium.data.Envelope.Operation#READ} event for each
* row.
*
* @return this object for method chaining; never null
*/
public SnapshotReader generateReadEvents() {
recorder = this::recordRowAsRead;
return this;
}
/**
* Set this reader's {@link #execute() execution} to produce a {@link io.debezium.data.Envelope.Operation#CREATE} event for
* each row.
*
* @return this object for method chaining; never null
*/
public SnapshotReader generateInsertEvents() {
recorder = this::recordRowAsInsert;
return this;
}
@Override
protected void doInitialize() {
metrics.register(logger);
}
@Override
public void doDestroy() {
metrics.unregister(logger);
}
/**
* Start the snapshot and return immediately. Once started, the records read from the database can be retrieved using
* {@link #poll()} until that method returns {@code null}.
*/
@Override
protected void doStart() {
executorService = Threads.newSingleThreadExecutor(MySqlConnector.class, context.getConnectorConfig().getLogicalName(), "snapshot");
executorService.execute(this::execute);
}
@Override
protected void doStop() {
logger.debug("Stopping snapshot reader");
cleanupResources();
// The parent class will change the isRunning() state, and this class' execute() uses that and will stop automatically
}
@Override
protected void doCleanup() {
executorService.shutdown();
logger.debug("Completed writing all snapshot records");
}
protected Object readField(ResultSet rs, int fieldNo, Column actualColumn, Table actualTable) throws SQLException {
if (actualColumn.jdbcType() == Types.TIME) {
return readTimeField(rs, fieldNo);
}
else if (actualColumn.jdbcType() == Types.DATE) {
return readDateField(rs, fieldNo, actualColumn, actualTable);
}
// This is for DATETIME columns (a logical date + time without time zone)
// by reading them with a calendar based on the default time zone, we make sure that the value
// is constructed correctly using the database's (or connection's) time zone
else if (actualColumn.jdbcType() == Types.TIMESTAMP) {
return readTimestampField(rs, fieldNo, actualColumn, actualTable);
}
else {
return rs.getObject(fieldNo);
}
}
private Object readTimeField(ResultSet rs, int fieldNo) throws SQLException {
Blob b = rs.getBlob(fieldNo);
if (b == null) {
return null; // Don't continue parsing time field if it is null
}
try {
return MySqlValueConverters.stringToDuration(new String(b.getBytes(1, (int) (b.length())), "UTF-8"));
}
catch (UnsupportedEncodingException e) {
logger.error("Could not read MySQL TIME value as UTF-8");
throw new RuntimeException(e);
}
}
/**
* In non-string mode the date field can contain zero in any of the date part which we need to handle as all-zero
*
*/
private Object readDateField(ResultSet rs, int fieldNo, Column column, Table table) throws SQLException {
Blob b = rs.getBlob(fieldNo);
if (b == null) {
return null; // Don't continue parsing date field if it is null
}
try {
return MySqlValueConverters.stringToLocalDate(new String(b.getBytes(1, (int) (b.length())), "UTF-8"), column, table);
}
catch (UnsupportedEncodingException e) {
logger.error("Could not read MySQL TIME value as UTF-8");
throw new RuntimeException(e);
}
}
/**
* In non-string mode the time field can contain zero in any of the date part which we need to handle as all-zero
*
*/
private Object readTimestampField(ResultSet rs, int fieldNo, Column column, Table table) throws SQLException {
Blob b = rs.getBlob(fieldNo);
if (b == null) {
return null; // Don't continue parsing timestamp field if it is null
}
try {
return MySqlValueConverters.containsZeroValuesInDatePart((new String(b.getBytes(1, (int) (b.length())), "UTF-8")), column, table) ? null
: rs.getTimestamp(fieldNo, Calendar.getInstance());
}
catch (UnsupportedEncodingException e) {
logger.error("Could not read MySQL TIME value as UTF-8");
throw new RuntimeException(e);
}
}
/**
* Perform the snapshot using the same logic as the "mysqldump" utility.
*/
protected void execute() {
context.configureLoggingContext("snapshot");
final AtomicReference<String> sql = new AtomicReference<>();
final JdbcConnection mysql = connectionContext.jdbc();
final MySqlSchema schema = context.dbSchema();
final Filters filters = schema.filters();
final SourceInfo source = context.source();
final Clock clock = context.getClock();
final long ts = clock.currentTimeInMillis();
logger.info("Starting snapshot for {} with user '{}' with locking mode '{}'", connectionContext.connectionString(), mysql.username(),
snapshotLockingMode.getValue());
logRolesForCurrentUser(mysql);
logServerInformation(mysql);
boolean isLocked = false;
boolean isTxnStarted = false;
boolean tableLocks = false;
try {
metrics.snapshotStarted();
// STEP 0
// Set the transaction isolation level to REPEATABLE READ. This is the default, but the default can be changed
// which is why we explicitly set it here.
// With REPEATABLE READ, all SELECT queries within the scope of a transaction (which we don't yet have) will read
// from the same MVCC snapshot. Thus each plain (non-locking) SELECT statements within the same transaction are
// consistent also with respect to each other.
if (!isRunning()) {
return;
}
logger.info("Step 0: disabling autocommit and enabling repeatable read transactions");
mysql.setAutoCommit(false);
sql.set("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ");
mysql.executeWithoutCommitting(sql.get());
// Generate the DDL statements that set the charset-related system variables ...
Map<String, String> systemVariables = connectionContext.readMySqlCharsetSystemVariables();
String setSystemVariablesStatement = connectionContext.setStatementFor(systemVariables);
AtomicBoolean interrupted = new AtomicBoolean(false);
long lockAcquired = 0L;
int step = 1;
try {
// LOCK TABLES
// Obtain read lock on all tables. This statement closes all open tables and locks all tables
// for all databases with a global read lock, and it prevents ALL updates while we have this lock.
// It also ensures that everything we do while we have this lock will be consistent.
if (!isRunning()) {
return;
}
if (!snapshotLockingMode.equals(MySqlConnectorConfig.SnapshotLockingMode.NONE)) {
try {
logger.info("Step 1: flush and obtain global read lock to prevent writes to database");
sql.set("FLUSH TABLES WITH READ LOCK");
mysql.executeWithoutCommitting(sql.get());
lockAcquired = clock.currentTimeInMillis();
metrics.globalLockAcquired();
isLocked = true;
}
catch (SQLException e) {
logger.info("Step 1: unable to flush and acquire global read lock, will use table read locks after reading table names");
// Continue anyway, since RDS (among others) don't allow setting a global lock
assert !isLocked;
}
// FLUSH TABLES resets TX and isolation level
sql.set("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ");
mysql.executeWithoutCommitting(sql.get());
}
// START TRANSACTION
// First, start a transaction and request that a consistent MVCC snapshot is obtained immediately.
if (!isRunning()) {
return;
}
logger.info("Step 2: start transaction with consistent snapshot");
sql.set("START TRANSACTION WITH CONSISTENT SNAPSHOT");
mysql.executeWithoutCommitting(sql.get());
isTxnStarted = true;
// READ BINLOG POSITION
if (!isRunning()) {
return;
}
step = 3;
if (isLocked) {
// Obtain the binlog position and update the SourceInfo in the context. This means that all source records
// generated as part of the snapshot will contain the binlog position of the snapshot.
readBinlogPosition(step++, source, mysql, sql);
}
// READ DATABASE NAMES
// Get the list of databases ...
if (!isRunning()) {
return;
}
logger.info("Step {}: read list of available databases", step++);
final List<String> databaseNames = new ArrayList<>();
sql.set("SHOW DATABASES");
mysql.query(sql.get(), rs -> {
while (rs.next()) {
databaseNames.add(rs.getString(1));
}
});
logger.info("\t list of available databases is: {}", databaseNames);
// READ TABLE NAMES
// Get the list of table IDs for each database. We can't use a prepared statement with MySQL, so we have to
// build the SQL statement each time. Although in other cases this might lead to SQL injection, in our case
// we are reading the database names from the database and not taking them from the user ...
if (!isRunning()) {
return;
}
logger.info("Step {}: read list of available tables in each database", step++);
List<TableId> knownTableIds = new ArrayList<>();
final List<TableId> capturedTableIds = new ArrayList<>();
final Filters createTableFilters = getCreateTableFilters(filters);
final Map<String, List<TableId>> createTablesMap = new HashMap<>();
final Set<String> readableDatabaseNames = new HashSet<>();
for (String dbName : databaseNames) {
try {
// MySQL sometimes considers some local files as databases (see DBZ-164),
// so we will simply try each one and ignore the problematic ones ...
sql.set("SHOW FULL TABLES IN " + quote(dbName) + " where Table_Type = 'BASE TABLE'");
mysql.query(sql.get(), rs -> {
while (rs.next() && isRunning()) {
TableId id = new TableId(dbName, null, rs.getString(1));
final boolean shouldRecordTableSchema = shouldRecordTableSchema(schema, filters, id);
// Apply only when the whitelist table list is not dynamically reconfigured
if ((createTableFilters == filters && shouldRecordTableSchema) || createTableFilters.tableFilter().test(id)) {
createTablesMap.computeIfAbsent(dbName, k -> new ArrayList<>()).add(id);
}
if (shouldRecordTableSchema) {
knownTableIds.add(id);
logger.info("\t including '{}' among known tables", id);
}
else {
logger.info("\t '{}' is not added among known tables", id);
}
if (filters.tableFilter().test(id)) {
capturedTableIds.add(id);
logger.info("\t including '{}' for further processing", id);
}
else {
logger.info("\t '{}' is filtered out of capturing", id);
}
}
});
readableDatabaseNames.add(dbName);
}
catch (SQLException e) {
// We were unable to execute the query or process the results, so skip this ...
logger.warn("\t skipping database '{}' due to error reading tables: {}", dbName, e.getMessage());
}
}
/*
* To achieve an ordered snapshot, we would first get a list of Regex tables.whitelist regex patterns
* + and then sort the tableIds list based on the above list
* +
*/
List<Pattern> tableWhitelistPattern = Strings.listOfRegex(context.config().getString(MySqlConnectorConfig.TABLE_WHITELIST), Pattern.CASE_INSENSITIVE);
List<TableId> tableIdsSorted = new ArrayList<>();
tableWhitelistPattern.forEach(pattern -> {
List<TableId> tablesMatchedByPattern = capturedTableIds.stream().filter(t -> pattern.asPredicate().test(t.toString()))
.collect(Collectors.toList());
tablesMatchedByPattern.forEach(t -> {
if (!tableIdsSorted.contains(t)) {
tableIdsSorted.add(t);
}
});
});
capturedTableIds.sort(Comparator.comparing(tableIdsSorted::indexOf));
final Set<String> includedDatabaseNames = readableDatabaseNames.stream().filter(filters.databaseFilter()).collect(Collectors.toSet());
logger.info("\tsnapshot continuing with database(s): {}", includedDatabaseNames);
if (!isLocked) {
if (!snapshotLockingMode.equals(MySqlConnectorConfig.SnapshotLockingMode.NONE)) {
// LOCK TABLES and READ BINLOG POSITION
// We were not able to acquire the global read lock, so instead we have to obtain a read lock on each table.
// This requires different privileges than normal, and also means we can't unlock the tables without
// implicitly committing our transaction ...
if (!connectionContext.userHasPrivileges("LOCK TABLES")) {
// We don't have the right privileges
throw new ConnectException("User does not have the 'LOCK TABLES' privilege required to obtain a "
+ "consistent snapshot by preventing concurrent writes to tables.");
}
// We have the required privileges, so try to lock all of the tables we're interested in ...
logger.info("Step {}: flush and obtain read lock for {} tables (preventing writes)", step++, knownTableIds.size());
String tableList = capturedTableIds.stream()
.map(tid -> quote(tid))
.reduce((r, element) -> r + "," + element)
.orElse(null);
if (tableList != null) {
sql.set("FLUSH TABLES " + tableList + " WITH READ LOCK");
mysql.executeWithoutCommitting(sql.get());
}
lockAcquired = clock.currentTimeInMillis();
metrics.globalLockAcquired();
isLocked = true;
tableLocks = true;
}
// Our tables are locked, so read the binlog position ...
readBinlogPosition(step++, source, mysql, sql);
}
// From this point forward, all source records produced by this connector will have an offset that includes a
// "snapshot" field (with value of "true").
// STEP 6
// Transform the current schema so that it reflects the *current* state of the MySQL server's contents.
// First, get the DROP TABLE and CREATE TABLE statement (with keys and constraint definitions) for our tables ...
try {
logger.info("Step {}: generating DROP and CREATE statements to reflect current database schemas:", step++);
schema.applyDdl(source, null, setSystemVariablesStatement, this::enqueueSchemaChanges);
// Add DROP TABLE statements for all tables that we knew about AND those tables found in the databases ...
knownTableIds.stream()
.filter(id -> isRunning()) // ignore all subsequent tables if this reader is stopped
.forEach(tableId -> schema.applyDdl(source, tableId.schema(),
"DROP TABLE IF EXISTS " + quote(tableId),
this::enqueueSchemaChanges));
// Add a DROP DATABASE statement for each database that we no longer know about ...
schema.tableIds().stream().map(TableId::catalog)
.filter(Predicates.not(readableDatabaseNames::contains))
.filter(id -> isRunning()) // ignore all subsequent tables if this reader is stopped
.forEach(missingDbName -> schema.applyDdl(source, missingDbName,
"DROP DATABASE IF EXISTS " + quote(missingDbName),
this::enqueueSchemaChanges));
// Now process all of our tables for each database ...
for (Map.Entry<String, List<TableId>> entry : createTablesMap.entrySet()) {
if (!isRunning()) {
break;
}
String dbName = entry.getKey();
// First drop, create, and then use the named database ...
schema.applyDdl(source, dbName, "DROP DATABASE IF EXISTS " + quote(dbName), this::enqueueSchemaChanges);
schema.applyDdl(source, dbName, "CREATE DATABASE " + quote(dbName), this::enqueueSchemaChanges);
schema.applyDdl(source, dbName, "USE " + quote(dbName), this::enqueueSchemaChanges);
for (TableId tableId : entry.getValue()) {
if (!isRunning()) {
break;
}
sql.set("SHOW CREATE TABLE " + quote(tableId));
mysql.query(sql.get(), rs -> {
if (rs.next()) {
schema.applyDdl(source, dbName, rs.getString(2), this::enqueueSchemaChanges);
}
});
}
}
context.makeRecord().regenerate();
}
// most likely, something went wrong while writing the history topic
catch (Exception e) {
interrupted.set(true);
throw e;
}
// STEP 7
if (snapshotLockingMode.equals(MySqlConnectorConfig.SnapshotLockingMode.MINIMAL) && isLocked) {
if (tableLocks) {
// We could not acquire a global read lock and instead had to obtain individual table-level read locks
// using 'FLUSH TABLE <tableName> WITH READ LOCK'. However, if we were to do this, the 'UNLOCK TABLES'
// would implicitly commit our active transaction, and this would break our consistent snapshot logic.
// Therefore, we cannot unlock the tables here!
logger.info("Step {}: tables were locked explicitly, but to get a consistent snapshot we cannot "
+ "release the locks until we've read all tables.", step++);
}
else {
// We are doing minimal blocking via a global read lock, so we should release the global read lock now.
// All subsequent SELECT should still use the MVCC snapshot obtained when we started our transaction
// (since we started it "...with consistent snapshot"). So, since we're only doing very simple SELECT
// without WHERE predicates, we can release the lock now ...
logger.info("Step {}: releasing global read lock to enable MySQL writes", step);
sql.set("UNLOCK TABLES");
mysql.executeWithoutCommitting(sql.get());
isLocked = false;
long lockReleased = clock.currentTimeInMillis();
metrics.globalLockReleased();
logger.info("Step {}: blocked writes to MySQL for a total of {}", step++,
Strings.duration(lockReleased - lockAcquired));
}
}
// STEP 8
// Use a buffered blocking consumer to buffer all of the records, so that after we copy all of the tables
// and produce events we can update the very last event with the non-snapshot offset ...
if (!isRunning()) {
return;
}
if (includeData) {
BufferedBlockingConsumer<SourceRecord> bufferedRecordQueue = BufferedBlockingConsumer.bufferLast(super::enqueueRecord);
// Dump all of the tables and generate source records ...
logger.info("Step {}: scanning contents of {} tables while still in transaction", step, capturedTableIds.size());
metrics.monitoredTablesDetermined(capturedTableIds);
long startScan = clock.currentTimeInMillis();
AtomicLong totalRowCount = new AtomicLong();
int counter = 0;
int completedCounter = 0;
long largeTableCount = context.rowCountForLargeTable();
Iterator<TableId> tableIdIter = capturedTableIds.iterator();
while (tableIdIter.hasNext()) {
TableId tableId = tableIdIter.next();
AtomicLong rowNum = new AtomicLong();
if (!isRunning()) {
break;
}
// Obtain a record maker for this table, which knows about the schema ...
RecordsForTable recordMaker = context.makeRecord().forTable(tableId, null, bufferedRecordQueue);
if (recordMaker != null) {
// Switch to the table's database ...
sql.set("USE " + quote(tableId.catalog()) + ";");
mysql.executeWithoutCommitting(sql.get());
AtomicLong numRows = new AtomicLong(-1);
AtomicReference<String> rowCountStr = new AtomicReference<>("<unknown>");
StatementFactory statementFactory = this::createStatementWithLargeResultSet;
if (largeTableCount > 0) {
try {
// Choose how we create statements based on the # of rows.
// This is approximate and less accurate then COUNT(*),
// but far more efficient for large InnoDB tables.
sql.set("SHOW TABLE STATUS LIKE '" + tableId.table() + "';");
mysql.query(sql.get(), rs -> {
if (rs.next()) {
numRows.set(rs.getLong(5));
}
});
if (numRows.get() <= largeTableCount) {
statementFactory = this::createStatement;
}
rowCountStr.set(numRows.toString());
}
catch (SQLException e) {
// Log it, but otherwise just use large result set by default ...
logger.debug("Error while getting number of rows in table {}: {}", tableId, e.getMessage(), e);
}
}
// Scan the rows in the table ...
long start = clock.currentTimeInMillis();
logger.info("Step {}: - scanning table '{}' ({} of {} tables)", step, tableId, ++counter, capturedTableIds.size());
Map<TableId, String> selectOverrides = context.getConnectorConfig().getSnapshotSelectOverridesByTable();
String selectStatement = selectOverrides.getOrDefault(tableId, "SELECT * FROM " + quote(tableId));
logger.info("For table '{}' using select statement: '{}'", tableId, selectStatement);
sql.set(selectStatement);
try {
int stepNum = step;
mysql.query(sql.get(), statementFactory, rs -> {
try {
// The table is included in the connector's filters, so process all of the table records
final Table table = schema.tableFor(tableId);
final int numColumns = table.columns().size();
final Object[] row = new Object[numColumns];
while (rs.next()) {
for (int i = 0, j = 1; i != numColumns; ++i, ++j) {
Column actualColumn = table.columns().get(i);
row[i] = readField(rs, j, actualColumn, table);
}
recorder.recordRow(recordMaker, row, clock.currentTimeInMillis()); // has no row number!
rowNum.incrementAndGet();
if (rowNum.get() % 100 == 0 && !isRunning()) {
// We've stopped running ...
break;
}
if (rowNum.get() % 10_000 == 0) {
if (logger.isInfoEnabled()) {
long stop = clock.currentTimeInMillis();
logger.info("Step {}: - {} of {} rows scanned from table '{}' after {}",
stepNum, rowNum, rowCountStr, tableId, Strings.duration(stop - start));
}
metrics.rowsScanned(tableId, rowNum.get());
}
}
totalRowCount.addAndGet(rowNum.get());
if (isRunning()) {
if (logger.isInfoEnabled()) {
long stop = clock.currentTimeInMillis();
logger.info("Step {}: - Completed scanning a total of {} rows from table '{}' after {}",
stepNum, rowNum, tableId, Strings.duration(stop - start));
}
metrics.rowsScanned(tableId, rowNum.get());
}
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
// We were not able to finish all rows in all tables ...
logger.info("Step {}: Stopping the snapshot due to thread interruption", stepNum);
interrupted.set(true);
}
});
}
finally {
metrics.tableSnapshotCompleted(tableId, rowNum.get());
if (interrupted.get()) {
break;
}
}
}
++completedCounter;
}
// See if we've been stopped or interrupted ...
if (!isRunning() || interrupted.get()) {
return;
}
// We've copied all of the tables and we've not yet been stopped, but our buffer holds onto the
// very last record. First mark the snapshot as complete and then apply the updated offset to
// the buffered record ...
source.markLastSnapshot(context.config());
long stop = clock.currentTimeInMillis();
try {
bufferedRecordQueue.close(this::replaceOffsetAndSource);
if (logger.isInfoEnabled()) {
logger.info("Step {}: scanned {} rows in {} tables in {}",
step, totalRowCount, capturedTableIds.size(), Strings.duration(stop - startScan));
}
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
// We were not able to finish all rows in all tables ...
if (logger.isInfoEnabled()) {
logger.info("Step {}: aborting the snapshot after {} rows in {} of {} tables {}",
step, totalRowCount, completedCounter, capturedTableIds.size(), Strings.duration(stop - startScan));
}
interrupted.set(true);
}
}
else {
logger.info("Step {}: encountered only schema based snapshot, skipping data snapshot", step);
}
step++;
}
finally {
// No matter what, we always want to do these steps if necessary ...
boolean rolledBack = false;
// STEP 9
// Either commit or roll back the transaction, BEFORE releasing the locks ...
if (isTxnStarted) {
if (interrupted.get() || !isRunning()) {
// We were interrupted or were stopped while reading the tables,
// so roll back the transaction and return immediately ...
logger.info("Step {}: rolling back transaction after abort", step++);
mysql.connection().rollback();
metrics.snapshotAborted();
rolledBack = true;
}
else {
// Otherwise, commit our transaction
logger.info("Step {}: committing transaction", step++);
mysql.connection().commit();
metrics.snapshotCompleted();
}
}
else {
// Always clean up TX resources even if no changes might be done
mysql.connection().rollback();
}
// STEP 10
// Release the read lock(s) if we have not yet done so. Locks are not released when committing/rolling back ...
if (isLocked && !rolledBack) {
if (tableLocks) {
logger.info("Step {}: releasing table read locks to enable MySQL writes", step++);
}
else {
logger.info("Step {}: releasing global read lock to enable MySQL writes", step++);
}
sql.set("UNLOCK TABLES");
mysql.executeWithoutCommitting(sql.get());
isLocked = false;
long lockReleased = clock.currentTimeInMillis();
metrics.globalLockReleased();
if (logger.isInfoEnabled()) {
if (tableLocks) {
logger.info("Writes to MySQL prevented for a total of {}", Strings.duration(lockReleased - lockAcquired));
}
else {
logger.info("Writes to MySQL tables prevented for a total of {}", Strings.duration(lockReleased - lockAcquired));
}
}
}
}
if (!isRunning()) {
// The reader (and connector) was stopped and we did not finish ...
try {
// Mark this reader as having completing its work ...
completeSuccessfully();
if (logger.isInfoEnabled()) {
long stop = clock.currentTimeInMillis();
logger.info("Stopped snapshot after {} but before completing", Strings.duration(stop - ts));
}
}
finally {
// and since there's no more work to do clean up all resources ...
cleanupResources();
}
}
else {
// We completed the snapshot...
try {
// Mark the source as having completed the snapshot. This will ensure the `source` field on records
// are not denoted as a snapshot ...
source.completeSnapshot();
Heartbeat
.create(
context.config(),
context.topicSelector().getHeartbeatTopic(),
context.getConnectorConfig().getLogicalName())
.forcedBeat(source.partition(), source.offset(), this::enqueueRecord);
}
finally {
// Set the completion flag ...
completeSuccessfully();
if (logger.isInfoEnabled()) {
long stop = clock.currentTimeInMillis();
logger.info("Completed snapshot in {}", Strings.duration(stop - ts));
}
}
}
}
catch (Throwable e) {
if (isLocked) {
try {
sql.set("UNLOCK TABLES");
mysql.executeWithoutCommitting(sql.get());
}
catch (Exception eUnlock) {
logger.error("Removing of table locks not completed successfully", eUnlock);
}
try {
mysql.connection().rollback();
}
catch (Exception eRollback) {
logger.error("Execption while rollback is executed", eRollback);
}
}
failed(e, "Aborting snapshot due to error when last running '" + sql.get() + "': " + e.getMessage());
}
finally {
try {
mysql.close();
}
catch (SQLException e) {
logger.warn("Failed to close the connection properly", e);
}
}
}
private boolean shouldRecordTableSchema(final MySqlSchema schema, final Filters filters, TableId id) {
return !schema.isStoreOnlyMonitoredTablesDdl() || filters.tableFilter().test(id);
}
protected void readBinlogPosition(int step, SourceInfo source, JdbcConnection mysql, AtomicReference<String> sql) throws SQLException {
if (context.isSchemaOnlyRecoverySnapshot()) {
// We are in schema only recovery mode, use the existing binlog position
if (Strings.isNullOrEmpty(source.binlogFilename())) {
// would like to also verify binlog position exists, but it defaults to 0 which is technically valid
throw new IllegalStateException("Could not find existing binlog information while attempting schema only recovery snapshot");
}
source.startSnapshot();
}
else {
logger.info("Step {}: read binlog position of MySQL master", step);
String showMasterStmt = "SHOW MASTER STATUS";
sql.set(showMasterStmt);
mysql.query(sql.get(), rs -> {
if (rs.next()) {
String binlogFilename = rs.getString(1);
long binlogPosition = rs.getLong(2);
source.setBinlogStartPoint(binlogFilename, binlogPosition);
if (rs.getMetaData().getColumnCount() > 4) {
// This column exists only in MySQL 5.6.5 or later ...
String gtidSet = rs.getString(5); // GTID set, may be null, blank, or contain a GTID set
source.setCompletedGtidSet(gtidSet);
logger.info("\t using binlog '{}' at position '{}' and gtid '{}'", binlogFilename, binlogPosition,
gtidSet);
}
else {
logger.info("\t using binlog '{}' at position '{}'", binlogFilename, binlogPosition);
}
source.startSnapshot();
}
else {
throw new IllegalStateException("Cannot read the binlog filename and position via '" + showMasterStmt
+ "'. Make sure your server is correctly configured");
}
});
}
}
/**
* Get the filters for table creation. Depending on the configuration, this may not be the default filter set.
*
* @param filters the default filters of this {@link SnapshotReader}
* @return {@link Filters} that represent all the tables that this snapshot reader should CREATE
*/
private Filters getCreateTableFilters(Filters filters) {
MySqlConnectorConfig.SnapshotNewTables snapshotNewTables = context.getConnectorConfig().getSnapshotNewTables();
if (snapshotNewTables == MySqlConnectorConfig.SnapshotNewTables.PARALLEL) {
// if we are snapshotting new tables in parallel, we need to make sure all the tables in the configuration
// are created.
return new Filters.Builder(context.config()).build();
}
else {
return filters;
}
}
protected String quote(String dbOrTableName) {
return "`" + dbOrTableName + "`";
}
protected String quote(TableId id) {
return quote(id.catalog()) + "." + quote(id.table());
}
private Statement createStatementWithLargeResultSet(Connection connection) throws SQLException {
int fetchSize = context.getConnectorConfig().getSnapshotFetchSize();
Statement stmt = connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
stmt.setFetchSize(fetchSize);
return stmt;
}
private Statement createStatement(Connection connection) throws SQLException {
return connection.createStatement();
}
private void logServerInformation(JdbcConnection mysql) {
try {
logger.info("MySQL server variables related to change data capture:");
mysql.query("SHOW VARIABLES WHERE Variable_name REGEXP 'version|binlog|tx_|gtid|character_set|collation|time_zone'", rs -> {
while (rs.next()) {
logger.info("\t{} = {}",
Strings.pad(rs.getString(1), 45, ' '),
Strings.pad(rs.getString(2), 45, ' '));
}
});
}
catch (SQLException e) {
logger.info("Cannot determine MySql server version", e);
}
}
private void logRolesForCurrentUser(JdbcConnection mysql) {
try {
List<String> grants = new ArrayList<>();
mysql.query("SHOW GRANTS FOR CURRENT_USER", rs -> {
while (rs.next()) {
grants.add(rs.getString(1));
}
});
if (grants.isEmpty()) {
logger.warn("Snapshot is using user '{}' but it likely doesn't have proper privileges. " +
"If tables are missing or are empty, ensure connector is configured with the correct MySQL user " +
"and/or ensure that the MySQL user has the required privileges.",
mysql.username());
}
else {
logger.info("Snapshot is using user '{}' with these MySQL grants:", mysql.username());
grants.forEach(grant -> logger.info("\t{}", grant));
}
}
catch (SQLException e) {
logger.info("Cannot determine the privileges for '{}' ", mysql.username(), e);
}
}
/**
* Utility method to replace the offset and the source in the given record with the latest. This is used on the last record produced
* during the snapshot.
*
* @param record the record
* @return the updated record
*/
protected SourceRecord replaceOffsetAndSource(SourceRecord record) {
if (record == null) {
return null;
}
Map<String, ?> newOffset = context.source().offset();
final Struct envelope = (Struct) record.value();
final Struct source = (Struct) envelope.get(Envelope.FieldName.SOURCE);
if (SnapshotRecord.fromSource(source) == SnapshotRecord.TRUE) {
SnapshotRecord.LAST.toSource(source);
}
return new SourceRecord(record.sourcePartition(),
newOffset,
record.topic(),
record.kafkaPartition(),
record.keySchema(),
record.key(),
record.valueSchema(),
record.value());
}
protected void enqueueSchemaChanges(String dbName, Set<TableId> tables, String ddlStatement) {
if (!context.includeSchemaChangeRecords() || ddlStatement.length() == 0) {
return;
}
if (context.makeRecord().schemaChanges(dbName, tables, ddlStatement, super::enqueueRecord) > 0) {
logger.info("\t{}", ddlStatement);
}
}
protected void recordRowAsRead(RecordsForTable recordMaker, Object[] row, long ts) throws InterruptedException {
recordMaker.read(row, ts);
}
protected void recordRowAsInsert(RecordsForTable recordMaker, Object[] row, long ts) throws InterruptedException {
recordMaker.create(row, ts);
}
protected static interface RecordRecorder {
void recordRow(RecordsForTable recordMaker, Object[] row, long ts) throws InterruptedException;
}
} |
package org.drools.examples.sudoku;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.Iterator;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import org.drools.examples.sudoku.rules.DroolsSudokuGridModel;
import org.drools.examples.sudoku.swing.SudokuGridSamples;
import org.drools.examples.sudoku.swing.SudokuGridView;
/**
* This example shows how Drools can be used to solve a 9x9 Sudoku Grid.
* <p
* This Class hooks together the GUI and the model and allows you to
* load different grids.
*
* @author <a href="pbennett@redhat.com">Pete Bennett</a>
* @version $Revision: 1.1 $
*/
public class Main
implements ActionListener
{
private JFrame mainFrame;
private SudokuGridView sudokuGridView;
private DroolsSudokuGridModel droolsSudokuGridModel;
private JMenuBar menuBar = new JMenuBar();
private JMenu fileMenu = new JMenu("File");
private JMenu samplesMenu = new JMenu("Samples");
private JMenuItem openMenuItem = new JMenuItem("Open...");
private JMenuItem exitMenuItem = new JMenuItem("Exit");
private BorderLayout borderLayout = new BorderLayout();
private FlowLayout flowLayout = new FlowLayout(FlowLayout.RIGHT);
private JPanel buttonPanel = new JPanel(flowLayout);
private JButton solveButton = new JButton("Solve Grid");
private JFileChooser fileChooser;
public static void main(String[] args)
{
Main main = new Main();
}
public Main()
{
mainFrame = new JFrame("Drools Sudoku Example");
Iterator iter = SudokuGridSamples.getInstance().getSampleNames().iterator();
while(iter.hasNext())
{
String sampleName = (String)iter.next();
JMenuItem menuItem = new JMenuItem(sampleName);
menuItem.addActionListener(this);
samplesMenu.add(menuItem);
}
fileMenu.add(samplesMenu);
openMenuItem.addActionListener(this);
// fileMenu.add(openMenuItem);
exitMenuItem.addActionListener(this);
fileMenu.add(exitMenuItem);
menuBar.add(fileMenu);
mainFrame.setJMenuBar(menuBar);
sudokuGridView = new SudokuGridView();
droolsSudokuGridModel = new DroolsSudokuGridModel(SudokuGridSamples.getInstance().getSample("Simple"));
mainFrame.setLayout(borderLayout);
mainFrame.add(BorderLayout.CENTER, sudokuGridView);
buttonPanel.add(solveButton);
solveButton.addActionListener(this);
mainFrame.add(BorderLayout.SOUTH, buttonPanel);
mainFrame.setSize(400,400);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setVisible(true);
sudokuGridView.setModel(droolsSudokuGridModel);
}
public void actionPerformed(ActionEvent ev)
{
if (ev.getSource().equals(solveButton))
{
long startTime = System.currentTimeMillis();
if (droolsSudokuGridModel.solve())
{
solveButton.setText("Solved ("+(System.currentTimeMillis()-startTime)+" ms)");
solveButton.setEnabled(false);
}
else
{
solveButton.setText("Unsolved ("+(System.currentTimeMillis()-startTime)+" ms)");
solveButton.setEnabled(false);
}
}
else if (ev.getSource().equals(openMenuItem))
{
if (fileChooser == null)
{
fileChooser = new JFileChooser();
}
try
{
if (fileChooser.showOpenDialog(mainFrame) == JFileChooser.APPROVE_OPTION)
{
System.out.println(fileChooser.getSelectedFile().getCanonicalPath());
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
else if (ev.getSource().equals(exitMenuItem))
{
System.exit(0);
}
else if (ev.getSource() instanceof JMenuItem)
{
JMenuItem menuItem = (JMenuItem) ev.getSource();
droolsSudokuGridModel = new DroolsSudokuGridModel(SudokuGridSamples.getInstance().getSample(menuItem.getText()));
sudokuGridView.setModel(droolsSudokuGridModel);
solveButton.setText("Solve");
solveButton.setEnabled(true);
}
else
{
}
}
} |
package io.dropwizard.health.check.tcp;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.SocketTimeoutException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
class TcpHealthCheckTest {
private ServerSocket serverSocket;
private TcpHealthCheck tcpHealthCheck;
@BeforeEach
void setUp() throws IOException {
serverSocket = new ServerSocket(0);
tcpHealthCheck = new TcpHealthCheck("127.0.0.1", serverSocket.getLocalPort());
}
@AfterEach
void tearDown() throws IOException {
serverSocket.close();
}
@Test
void tcpHealthCheckShouldReturnHealthyIfCanConnect() throws IOException {
final ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.submit(() -> serverSocket.accept());
assertThat(tcpHealthCheck.check().isHealthy())
.isTrue();
}
@Test
void tcpHealthCheckShouldReturnUnhealthyIfCannotConnect() throws IOException {
serverSocket.close();
assertThatThrownBy(() -> tcpHealthCheck.check()).isInstanceOfAny(ConnectException.class, SocketTimeoutException.class);
}
@Test
void tcpHealthCheckShouldReturnUnhealthyIfCannotConnectWithinConfiguredTimeout() throws IOException {
final int port = serverSocket.getLocalPort();
serverSocket.setReuseAddress(true);
serverSocket.close();
serverSocket = new ServerSocket();
final ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.submit(() -> {
Thread.sleep(tcpHealthCheck.getConnectionTimeout().toMillis() * 3);
serverSocket.bind(new InetSocketAddress("127.0.0.1", port));
return true;
});
assertThatThrownBy(() -> tcpHealthCheck.check()).isInstanceOfAny(ConnectException.class, SocketTimeoutException.class);
}
} |
package edu.oregonstate.cope.eclipse.installer;
import java.io.IOException;
import java.nio.file.Path;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.Platform;
import edu.oregonstate.cope.clientRecorder.Uninstaller;
import edu.oregonstate.cope.eclipse.COPEPlugin;
/**
* Runs plugin installation mode. This is implemented by storing files both in
* the eclipse installation path and in the workspace path. When either one does
* not exist, it is copied there from the other place. When none exists, the one
* time installation code is run.
*
*/
public class Installer {
public static final String LAST_PLUGIN_VERSION = "LAST_PLUGIN_VERSION";
public static final String SURVEY_FILENAME = "survey.txt";
public final static String EMAIL_FILENAME = "email.txt";
public static final String INSTALLER_EXTENSION_ID = "edu.oregonstate.cope.eclipse.installeroperation";
public void doInstall() throws IOException {
IConfigurationElement[] extensions = Platform.getExtensionRegistry().getConfigurationElementsFor(INSTALLER_EXTENSION_ID);
for (IConfigurationElement extension : extensions) {
try {
Object executableExtension = extension.createExecutableExtension("InstallerOperation");
if (executableExtension instanceof InstallerOperation)
((InstallerOperation)executableExtension).perform(SURVEY_FILENAME);
} catch (CoreException e) {
System.out.println(e);
}
}
checkForPluginUpdate(COPEPlugin.getDefault().getWorkspaceProperties().getProperty(LAST_PLUGIN_VERSION), COPEPlugin.getDefault().getPluginVersion().toString());
}
protected void checkForPluginUpdate(String propertiesVersion, String currentPluginVersion) {
if(propertiesVersion == null || !propertiesVersion.equals(currentPluginVersion)){
COPEPlugin.getDefault().getWorkspaceProperties().addProperty(LAST_PLUGIN_VERSION, currentPluginVersion.toString());
performPluginUpdate();
}
}
private void performPluginUpdate() {
COPEPlugin.getDefault().takeSnapshotOfKnownProjects();
}
} |
package org.emonocot.portal.controller;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.easymock.EasyMock;
import org.emonocot.api.FacetName;
import org.emonocot.api.ImageService;
import org.emonocot.api.SearchableObjectService;
import org.emonocot.api.Sorting;
import org.emonocot.model.common.SearchableObject;
import org.emonocot.model.media.Image;
import org.emonocot.model.pager.DefaultPageImpl;
import org.emonocot.model.pager.Page;
import org.junit.Before;
import org.junit.Test;
import org.springframework.ui.Model;
import org.springframework.validation.support.BindingAwareModelMap;
public class SearchControllerTest {
SearchController searchController;
List<FacetRequest> facets;
SearchableObjectService searchableObjectService;
ImageService imageService;
Model model;
Page<Image> page;
Page<SearchableObject> searchablePage;
FacetName[] facetNames;
@Before
public void setUp() throws Exception {
searchController = new SearchController();
facets = new ArrayList<FacetRequest>();
model = new BindingAwareModelMap();
searchableObjectService = EasyMock.createMock(SearchableObjectService.class);
imageService = EasyMock.createMock(ImageService.class);
searchController.setSearchableObjectService(searchableObjectService);
searchController.setImageService(imageService);
page = new DefaultPageImpl<Image>(0, 0, 20, new ArrayList<Image>());
searchablePage = new DefaultPageImpl<SearchableObject>(0, 0, 10, new ArrayList<SearchableObject>());
facetNames = new FacetName[] {FacetName.CLASS, FacetName.FAMILY, FacetName.CONTINENT, FacetName.AUTHORITY};
}
/**
* When the class is image and the view is null, then the limit should be 20 and the view should be null
*/
@Test
public void testSearchForImages() {
EasyMock.expect(imageService.search(EasyMock.eq(""), (String)EasyMock.isNull(), EasyMock.eq(24), EasyMock.eq(0), EasyMock.aryEq(facetNames), EasyMock.isA(Map.class), (Sorting)EasyMock.isNull(), EasyMock.eq("image-taxon"))).andReturn(page);
EasyMock.replay(searchableObjectService,imageService);
FacetRequest classFacet = new FacetRequest();
classFacet.setFacet(FacetName.CLASS);
classFacet.setSelected("org.emonocot.model.media.Image");
facets.add(classFacet);
String view = searchController.search("", 10, 0, facets, null, null, model);
EasyMock.verify(searchableObjectService,imageService);
assertEquals("View should equal 'search'","search",view);
assertNull("The view attribute should be 'null'", page.getParams().get("view"));
}
/**
* When the class is all and the view is null, then the limit should be 10 and the view should be null
*/
@Test
public void testSearchForAll() {
EasyMock.expect(searchableObjectService.search(EasyMock.eq(""), (String)EasyMock.isNull(), EasyMock.eq(10), EasyMock.eq(0), EasyMock.aryEq(facetNames), (Map)EasyMock.isNull(), (Sorting)EasyMock.isNull(), EasyMock.eq("taxon-with-image"))).andReturn(searchablePage);
EasyMock.replay(searchableObjectService,imageService);
String view = searchController.search("", 10, 0, facets, null, null, model);
EasyMock.verify(searchableObjectService,imageService);
assertEquals("View should equal 'search'","search",view);
assertNull("The view attribute should be 'null'", searchablePage.getParams().get("view"));
}
/**
* When the class is all and the view is list, then the limit should be 10 and the view should be list
*/
@Test
public void testSearchForAllListView() {
EasyMock.expect(searchableObjectService.search(EasyMock.eq(""), (String)EasyMock.isNull(), EasyMock.eq(10), EasyMock.eq(0), EasyMock.aryEq(facetNames), (Map)EasyMock.isNull(), (Sorting)EasyMock.isNull(), EasyMock.eq("taxon-with-image"))).andReturn(searchablePage);
EasyMock.replay(searchableObjectService,imageService);
String view = searchController.search("", 10, 0, facets, null, "list", model);
EasyMock.verify(searchableObjectService,imageService);
assertEquals("View should equal 'search'","search",view);
assertEquals("The view attribute should be 'list'", searchablePage.getParams().get("view"),"list");
}
/**
* When the class is all and the view is grid, then the limit should be 20 and the view should be grid
*/
@Test
public void testSearchForAllGridView() {
EasyMock.expect(searchableObjectService.search(EasyMock.eq(""), (String)EasyMock.isNull(), EasyMock.eq(24), EasyMock.eq(0), EasyMock.aryEq(facetNames), (Map)EasyMock.isNull(), (Sorting)EasyMock.isNull(), EasyMock.eq("taxon-with-image"))).andReturn(searchablePage);
EasyMock.replay(searchableObjectService,imageService);
String view = searchController.search("", 10, 0, facets, null, "grid", model);
EasyMock.verify(searchableObjectService,imageService);
assertEquals("View should equal 'search'","search",view);
assertEquals("The view attribute should be 'grid'", searchablePage.getParams().get("view"),"grid");
}
/**
* BUG #333 eMonocot map search not displaying results 11-20
*/
@Test
public void testPagination() {
EasyMock.expect(searchableObjectService.search(EasyMock.eq(""), (String)EasyMock.isNull(), EasyMock.eq(10), EasyMock.eq(1), EasyMock.aryEq(facetNames), (Map)EasyMock.isNull(), (Sorting)EasyMock.isNull(), EasyMock.eq("taxon-with-image"))).andReturn(searchablePage);
EasyMock.replay(searchableObjectService,imageService);
String view = searchController.search("", 10, 1, facets, null, "", model);
EasyMock.verify(searchableObjectService,imageService);
assertEquals("View should equal 'search'","search",view);
assertEquals("The view attribute should be ''", searchablePage.getParams().get("view"),"");
}
} |
package org.encuestame.business.service;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import org.encuestame.core.service.AbstractBaseService;
import org.encuestame.core.service.imp.IFrontEndService;
import org.encuestame.core.service.imp.SecurityOperations;
import org.encuestame.core.util.ConvertDomainBean;
import org.encuestame.core.util.EnMeUtils;
import org.encuestame.persistence.domain.AccessRate;
import org.encuestame.persistence.domain.HashTag;
import org.encuestame.persistence.domain.HashTagRanking;
import org.encuestame.persistence.domain.Hit;
import org.encuestame.persistence.domain.security.UserAccount;
import org.encuestame.persistence.domain.survey.Poll;
import org.encuestame.persistence.domain.survey.Survey;
import org.encuestame.persistence.domain.tweetpoll.TweetPoll;
import org.encuestame.persistence.domain.tweetpoll.TweetPollSavedPublishedStatus;
import org.encuestame.persistence.exception.EnMeExpcetion;
import org.encuestame.persistence.exception.EnMeNoResultsFoundException;
import org.encuestame.persistence.exception.EnMePollNotFoundException;
import org.encuestame.persistence.exception.EnMeSearchException;
import org.encuestame.utils.DateUtil;
import org.encuestame.utils.RelativeTimeEnum;
import org.encuestame.utils.enums.SearchPeriods;
import org.encuestame.utils.enums.TypeSearchResult;
import org.encuestame.utils.json.HomeBean;
import org.encuestame.utils.json.LinksSocialBean;
import org.encuestame.utils.json.TweetPollBean;
import org.encuestame.utils.web.HashTagBean;
import org.encuestame.utils.web.PollBean;
import org.encuestame.utils.web.ProfileRatedTopBean;
import org.encuestame.utils.web.SurveyBean;
import org.encuestame.utils.web.stats.GenericStatsBean;
import org.encuestame.utils.web.stats.HashTagDetailStats;
import org.encuestame.utils.web.stats.HashTagRankingBean;
import org.joda.time.DateTime;
import org.junit.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class FrontEndService extends AbstractBaseService implements IFrontEndService {
private Logger log = Logger.getLogger(this.getClass());
private final Integer MAX_RESULTS = 15;
@Autowired
private TweetPollService tweetPollService;
@Autowired
private PollService pollService;
@Autowired
private SurveyService surveyService;
@Autowired
private SecurityOperations securityService;
public List<TweetPollBean> searchItemsByTweetPoll(
final String period,
final Integer start,
Integer maxResults,
final HttpServletRequest request)
throws EnMeSearchException{
final List<TweetPollBean> results = new ArrayList<TweetPollBean>();
if(maxResults == null){
maxResults = this.MAX_RESULTS;
}
log.debug("Max Results: "+maxResults);
log.debug("Period Results: "+period);
final List<TweetPoll> items = new ArrayList<TweetPoll>();
if (period == null ) {
throw new EnMeSearchException("search params required.");
} else {
final SearchPeriods periodSelected = SearchPeriods.getPeriodString(period);
if (periodSelected.equals(SearchPeriods.TWENTYFOURHOURS)) {
items.addAll(getFrontEndDao().getTweetPollFrontEndLast24(start, maxResults));
} else if(periodSelected.equals(SearchPeriods.TWENTYFOURHOURS)) {
items.addAll(getFrontEndDao().getTweetPollFrontEndLast24(start, maxResults));
} else if(periodSelected.equals(SearchPeriods.SEVENDAYS)) {
items.addAll(getFrontEndDao().getTweetPollFrontEndLast7Days(start, maxResults));
} else if(periodSelected.equals(SearchPeriods.THIRTYDAYS)) {
items.addAll(getFrontEndDao().getTweetPollFrontEndLast30Days(start, maxResults));
} else if(periodSelected.equals(SearchPeriods.ALLTIME)) {
items.addAll(getFrontEndDao().getTweetPollFrontEndAllTime(start, maxResults));
}
results.addAll(ConvertDomainBean.convertListToTweetPollBean(items));
for (TweetPollBean tweetPoll : results) {
//log.debug("Iterate Home TweetPoll id: "+tweetPoll.getId());
//log.debug("Iterate Home Tweetpoll Hashtag Size: "+tweetPoll.getHashTags().size());
tweetPoll = convertTweetPollRelativeTime(tweetPoll, request);
tweetPoll.setTotalComments(this.getTotalCommentsbyType(tweetPoll.getId(), TypeSearchResult.TWEETPOLL));
}
}
log.debug("Search Items by TweetPoll: "+results.size());
return results;
}
public List<SurveyBean> searchItemsBySurvey(final String period,
final Integer start, Integer maxResults,
final HttpServletRequest request) throws EnMeSearchException {
final List<SurveyBean> results = new ArrayList<SurveyBean>();
if (maxResults == null) {
maxResults = this.MAX_RESULTS;
}
log.debug("Max Results " + maxResults);
final List<Survey> items = new ArrayList<Survey>();
if (period == null) {
throw new EnMeSearchException("search params required.");
} else {
final SearchPeriods periodSelected = SearchPeriods
.getPeriodString(period);
if (periodSelected.equals(SearchPeriods.TWENTYFOURHOURS)) {
items.addAll(getFrontEndDao().getSurveyFrontEndLast24(start,
maxResults));
} else if (periodSelected.equals(SearchPeriods.TWENTYFOURHOURS)) {
items.addAll(getFrontEndDao().getSurveyFrontEndLast24(start,
maxResults));
} else if (periodSelected.equals(SearchPeriods.SEVENDAYS)) {
items.addAll(getFrontEndDao().getSurveyFrontEndLast7Days(start,
maxResults));
} else if (periodSelected.equals(SearchPeriods.THIRTYDAYS)) {
items.addAll(getFrontEndDao().getSurveyFrontEndLast30Days(
start, maxResults));
} else if (periodSelected.equals(SearchPeriods.ALLTIME)) {
items.addAll(getFrontEndDao().getSurveyFrontEndAllTime(start,
maxResults));
}
log.debug("TweetPoll " + items.size());
results.addAll(ConvertDomainBean.convertListSurveyToBean(items));
for (SurveyBean surveyBean : results) {
surveyBean.setTotalComments(this.getTotalCommentsbyType(surveyBean.getSid(), TypeSearchResult.SURVEY));
}
}
return results;
}
public List<HomeBean> getFrontEndItems(final String period,
final Integer start, Integer maxResults,
final HttpServletRequest request) throws EnMeSearchException {
// Sorted list based comparable interface
final List<HomeBean> allItems = new ArrayList<HomeBean>();
final List<TweetPollBean> tweetPollItems = this.searchItemsByTweetPoll(
period, start, maxResults, request);
log.debug("FrontEnd TweetPoll items size :" + tweetPollItems.size());
allItems.addAll(ConvertDomainBean
.convertTweetPollListToHomeBean(tweetPollItems));
final List<PollBean> pollItems = this.searchItemsByPoll(period, start,
maxResults);
log.debug("FrontEnd Poll items size :" + pollItems.size());
allItems.addAll(ConvertDomainBean.convertPollListToHomeBean(pollItems));
final List<SurveyBean> surveyItems = this.searchItemsBySurvey(period,
start, maxResults, request);
log.debug("FrontEnd Survey items size :" + surveyItems.size());
allItems.addAll(ConvertDomainBean
.convertSurveyListToHomeBean(surveyItems));
log.debug("Home bean list size :" + allItems.size());
Collections.sort(allItems);
return allItems;
}
public List<PollBean> searchItemsByPoll(
final String period,
final Integer start,
Integer maxResults)
throws EnMeSearchException{
final List<PollBean> results = new ArrayList<PollBean>();
if (maxResults == null) {
maxResults = this.MAX_RESULTS;
}
final List<Poll> items = new ArrayList<Poll>();
if (period == null ) {
throw new EnMeSearchException("search params required.");
} else {
final SearchPeriods periodSelected = SearchPeriods.getPeriodString(period);
if(periodSelected.equals(SearchPeriods.TWENTYFOURHOURS)){
items.addAll(getFrontEndDao().getPollFrontEndLast24(start, maxResults));
} else if(periodSelected.equals(SearchPeriods.TWENTYFOURHOURS)){
items.addAll(getFrontEndDao().getPollFrontEndLast24(start, maxResults));
} else if(periodSelected.equals(SearchPeriods.SEVENDAYS)){
items.addAll(getFrontEndDao().getPollFrontEndLast7Days(start, maxResults));
} else if(periodSelected.equals(SearchPeriods.THIRTYDAYS)){
items.addAll(getFrontEndDao().getPollFrontEndLast30Days(start, maxResults));
} else if(periodSelected.equals(SearchPeriods.ALLTIME)){
items.addAll(getFrontEndDao().getPollFrontEndAllTime(start, maxResults));
}
log.debug("Poll "+items.size());
results.addAll(ConvertDomainBean.convertListToPollBean((items)));
for (PollBean pollbean : results) {
pollbean.setTotalComments(this.getTotalCommentsbyType(pollbean.getId(), TypeSearchResult.POLL));
}
}
return results;
}
public void search(){
}
public List<HashTagBean> getHashTags(
Integer maxResults,
final Integer start,
final String tagCriteria) {
final List<HashTagBean> hashBean = new ArrayList<HashTagBean>();
if (maxResults == null) {
maxResults = this.MAX_RESULTS;
}
final List<HashTag> tags = getHashTagDao().getHashTags(maxResults, start, tagCriteria);
hashBean.addAll(ConvertDomainBean.convertListHashTagsToBean(tags));
return hashBean;
}
public HashTag getHashTagItem(final String tagName) throws EnMeNoResultsFoundException {
final HashTag tag = getHashTagDao().getHashTagByName(tagName);
if (tag == null){
throw new EnMeNoResultsFoundException("hashtag not found");
}
return tag;
}
public List<TweetPollBean> getTweetPollsbyHashTagName(
final String tagName,
final Integer initResults,
final Integer limit,
final String filter,
final HttpServletRequest request){
final List<TweetPoll> tweetPolls = getTweetPollDao().getTweetpollByHashTagName(tagName, initResults, limit, TypeSearchResult.getTypeSearchResult(filter));
log.debug("TweetPoll by HashTagId total size ---> "+tweetPolls.size());
final List<TweetPollBean> tweetPollBean = ConvertDomainBean.convertListToTweetPollBean(tweetPolls);
for (TweetPollBean tweetPoll : tweetPollBean) {
tweetPoll = convertTweetPollRelativeTime(tweetPoll, request);
}
return tweetPollBean;
}
public List<HomeBean> searchLastPublicationsbyHashTag(
final HashTag hashTag, final String keyword,
final Integer initResults, final Integer limit,
final String filter, final HttpServletRequest request) {
final List<HomeBean> allItems = new ArrayList<HomeBean>();
final List<TweetPollBean> tweetPollItems = this
.getTweetPollsbyHashTagName(hashTag.getHashTag(), initResults,
limit, filter, request);
log.debug("FrontEnd TweetPoll items size :" + tweetPollItems.size());
allItems.addAll(ConvertDomainBean
.convertTweetPollListToHomeBean(tweetPollItems));
Collections.sort(allItems);
return allItems;
}
public Boolean checkPreviousHit(final String ipAddress, final Long id, final TypeSearchResult searchHitby){
boolean hit = false;
final List<Hit> hitList = getFrontEndDao().getHitsByIpAndType(ipAddress, id, searchHitby);
try {
if(hitList.size() == 1){
if(hitList.get(0).getIpAddress().equals(ipAddress)){
hit = true;
}
}
else if(hitList.size() > 1){
log.error("List cant'be greater than one");
}
} catch (Exception e) {
log.error(e);
}
return hit;
}
public Boolean registerHit(final TweetPoll tweetPoll, final Poll poll, final Survey survey, final HashTag tag,
final String ip) throws EnMeNoResultsFoundException{
final Hit hit ;
Long hitCount = 1L;
Boolean register = false;
// HashTag
if (ip != null){
if (tag != null){
hit = this.newHashTagHit(tag, ip);
hitCount = tag.getHits() == null ? 0L : tag.getHits() + hitCount;
tag.setHits(hitCount);
getFrontEndDao().saveOrUpdate(tag);
register = true;
}
else if(tweetPoll != null){
hit = this.newTweetPollHit(tweetPoll, ip);
hitCount = tweetPoll.getHits() + hitCount;
tweetPoll.setHits(hitCount);
getFrontEndDao().saveOrUpdate(tweetPoll);
register = true;
}
else if(poll != null){
hit = this.newPollHit(poll, ip);
hitCount = poll.getHits() + hitCount;
poll.setHits(hitCount);
getFrontEndDao().saveOrUpdate(poll);
register = true;
}
else if(survey != null ){
hit = this.newSurveyHit(survey, ip);
hitCount = survey.getHits() + hitCount;
survey.setHits(hitCount);
getFrontEndDao().saveOrUpdate(survey);
register = true;
}
}
return register;
}
@Transactional(readOnly = false)
private Hit newHitItem(final TweetPoll tweetPoll, final Poll poll, final Survey survey, final HashTag tag,
final String ipAddress) {
final Hit hitItem = new Hit();
hitItem.setHitDate(Calendar.getInstance().getTime());
hitItem.setHashTag(tag);
hitItem.setIpAddress(ipAddress);
hitItem.setTweetPoll(tweetPoll);
hitItem.setPoll(poll);
hitItem.setSurvey(survey);
getFrontEndDao().saveOrUpdate(hitItem);
return hitItem;
}
private Hit newTweetPollHit(final TweetPoll tweetPoll, final String ipAddress){
return this.newHitItem(tweetPoll, null, null, null, ipAddress);
}
private Hit newPollHit(final Poll poll, final String ipAddress){
return this.newHitItem(null, poll, null, null, ipAddress);
}
private Hit newHashTagHit(final HashTag tag, final String ipAddress){
return this.newHitItem(null, null, null, tag, ipAddress);
}
private Hit newSurveyHit(final Survey survey, final String ipAddress){
return this.newHitItem(null, null, survey, null, ipAddress);
}
public AccessRate registerAccessRate(final TypeSearchResult type,
final Long itemId, final String ipAddress, final Boolean rate)
throws EnMeExpcetion {
AccessRate recordAccessRate = new AccessRate();
if (ipAddress != null) {
if (type.equals(TypeSearchResult.TWEETPOLL)) {
// Find tweetPoll by itemId.
final TweetPoll tweetPoll = this.getTweetPoll(itemId);
Assert.assertNotNull(tweetPoll);
// Check if exist a previous tweetpoll access record.
recordAccessRate = this.checkExistTweetPollPreviousRecord(tweetPoll, ipAddress,
rate);
}
// Poll Acces rate item.
if (type.equals(TypeSearchResult.POLL)) {
// Find poll by itemId.
final Poll poll = this.getPoll(itemId);
Assert.assertNotNull(poll);
// Check if exist a previous poll access record.
recordAccessRate = this.checkExistPollPreviousRecord(poll, ipAddress,
rate);
}
// Survey Access rate item.
if (type.equals(TypeSearchResult.SURVEY)) {
// Find survey by itemId.
final Survey survey = this.getSurvey(itemId);
Assert.assertNotNull(survey);
// Check if exist a previous survey access record.
recordAccessRate = this.checkExistSurveyPreviousRecord(survey, ipAddress,
rate);
}
}
return recordAccessRate;
}
private AccessRate checkExistTweetPollPreviousRecord(final TweetPoll tpoll,
final String ipAddress, final Boolean option) throws EnMeExpcetion {
// Search record by tweetPpll in access Rate domain.
List<AccessRate> rateList = this.getAccessRateItem(ipAddress,
tpoll.getTweetPollId(), TypeSearchResult.TWEETPOLL);
final AccessRate accessRate;
if (rateList.size() > 1) {
throw new EnMeExpcetion("Access rate list found coudn't be greater than one ");
} else if (rateList.size() == 1) {
// Get first element from access rate list
accessRate = rateList.get(0);
//Check if the option selected is the same that you have registered
if (accessRate.getRate() == option) {
log.warn("The option was previously selected " + accessRate.getRate());
} else {
// We proceed to update the record in the table access Rate.
accessRate.setRate(option);
// Update the value in the fields of TweetPoll
this.setTweetPollSocialOption(option,
tpoll);
// Save access rate record.
getFrontEndDao().saveOrUpdate(accessRate);
}
} else {
// Otherwise, create access rate record.
accessRate = this.newTweetPollAccessRate(tpoll, ipAddress, option);
// update tweetPoll record.
this.setTweetPollSocialOption(option,
tpoll);
}
return accessRate;
}
private AccessRate checkExistPollPreviousRecord(final Poll poll,
final String ipAddress, final Boolean option) throws EnMeExpcetion {
// Search record by poll in access Rate domain.
List<AccessRate> rateList = this.getAccessRateItem(ipAddress,
poll.getPollId(), TypeSearchResult.POLL);
final AccessRate accessRate;
if (rateList.size() > 1) {
throw new EnMeExpcetion("Access rate list found coudn't be greater than one ");
} else if (rateList.size() == 1) {
// Get first element from access rate list
accessRate = rateList.get(0);
//Check if the option selected is the same that you have registered
if (accessRate.getRate() == option) {
log.warn("The option was previously selected " + accessRate.getRate());
} else {
// We proceed to update the record in the table access Rate.
accessRate.setRate(option);
// Update the value in the fields of TweetPoll
this.setPollSocialOption(option,
poll);
// Save access rate record.
getFrontEndDao().saveOrUpdate(accessRate);
}
} else {
// Otherwise, create access rate record.
accessRate = this.newPollAccessRate(poll, ipAddress, option);
// update poll record.
this.setPollSocialOption(option,
poll);
}
return accessRate;
}
private AccessRate checkExistSurveyPreviousRecord(final Survey survey,
final String ipAddress, final Boolean option) throws EnMeExpcetion {
// Search record by survey in access Rate domain.
List<AccessRate> rateList = this.getAccessRateItem(ipAddress,
survey.getSid(), TypeSearchResult.SURVEY);
final AccessRate accessRate;
if (rateList.size() > 1) {
throw new EnMeExpcetion("Access rate list found coudn't be greater than one ");
} else if (rateList.size() == 1) {
// Get first element from access rate list
accessRate = rateList.get(0);
//Check if the option selected is the same that you have registered
if (accessRate.getRate() == option) {
log.warn("The option was previously selected " + accessRate.getRate());
} else {
// We proceed to update the record in the table access Rate.
accessRate.setRate(option);
// Update the value in the fields of survey
this.setSurveySocialOption(option, survey);
// Save access rate record.
getFrontEndDao().saveOrUpdate(accessRate);
}
} else {
// Otherwise, create access rate record.
accessRate = this.newSurveyAccessRate(survey, ipAddress, option);
// update poll record.
this.setSurveySocialOption(option,
survey);
}
return accessRate;
}
private TweetPoll setTweetPollSocialOption(final Boolean socialOption,
final TweetPoll tpoll) {
long valueSocialVote = 1L;
long optionValue;
// If the user has voted like.
if (socialOption) {
valueSocialVote = tpoll.getLikeVote() + valueSocialVote;
tpoll.setLikeVote(valueSocialVote);
optionValue = tpoll.getLikeVote() - valueSocialVote;
tpoll.setDislikeVote(tpoll.getDislikeVote() == 0 ? 0 : optionValue);
getTweetPollDao().saveOrUpdate(tpoll);
} else {
valueSocialVote = tpoll.getDislikeVote() + valueSocialVote;
optionValue = tpoll.getLikeVote() - valueSocialVote;
tpoll.setLikeVote(tpoll.getLikeVote() == 0 ? 0 : optionValue);
tpoll.setDislikeVote(valueSocialVote);
getTweetPollDao().saveOrUpdate(tpoll);
}
return tpoll;
}
private Poll setPollSocialOption(final Boolean socialOption, final Poll poll) {
long valueSocialVote = 1L;
long optionValue;
// If the user has voted like.
if (socialOption) {
valueSocialVote = poll.getLikeVote() + valueSocialVote;
poll.setLikeVote(valueSocialVote);
optionValue = poll.getLikeVote() - valueSocialVote;
poll.setDislikeVote(poll.getDislikeVote() == 0 ? 0 : optionValue);
getTweetPollDao().saveOrUpdate(poll);
} else {
valueSocialVote = poll.getDislikeVote() + valueSocialVote;
optionValue = poll.getLikeVote() - valueSocialVote;
poll.setLikeVote(poll.getLikeVote() == 0 ? 0 : optionValue);
poll.setDislikeVote(valueSocialVote);
getTweetPollDao().saveOrUpdate(poll);
}
return poll;
}
private Survey setSurveySocialOption(final Boolean socialOption,
final Survey survey) {
long valueSocialVote = 1L;
long optionValue;
// If the user has voted like.
if (socialOption) {
valueSocialVote = survey.getLikeVote() + valueSocialVote;
survey.setLikeVote(valueSocialVote);
optionValue = survey.getLikeVote() - valueSocialVote;
survey.setDislikeVote(survey.getDislikeVote() == 0 ? 0
: optionValue);
getTweetPollDao().saveOrUpdate(survey);
} else {
valueSocialVote = survey.getDislikeVote() + valueSocialVote;
optionValue = survey.getLikeVote() - valueSocialVote;
survey.setLikeVote(survey.getLikeVote() == 0 ? 0 : optionValue);
survey.setDislikeVote(valueSocialVote);
getTweetPollDao().saveOrUpdate(survey);
}
return survey;
}
private List<AccessRate> getAccessRateItem(final String ipAddress,
final Long itemId, final TypeSearchResult searchby)
throws EnMeExpcetion {
final List<AccessRate> itemAccessList = getFrontEndDao()
.getAccessRatebyItem(ipAddress, itemId, searchby);
return itemAccessList;
}
@Transactional(readOnly = false)
private AccessRate newAccessRateItem(final TweetPoll tweetPoll,
final Poll poll, final Survey survey, final String ipAddress,
final Boolean rate) {
final AccessRate itemRate = new AccessRate();
itemRate.setTweetPoll(tweetPoll);
itemRate.setPoll(poll);
itemRate.setSurvey(survey);
itemRate.setRate(rate);
itemRate.setUser(null);
itemRate.setIpAddress(ipAddress);
getTweetPollDao().saveOrUpdate(itemRate);
return itemRate;
}
private AccessRate newTweetPollAccessRate(final TweetPoll tweetPoll,
final String ipAddress, final Boolean rate) {
return this.newAccessRateItem(tweetPoll, null, null, ipAddress, rate);
}
private AccessRate newPollAccessRate(final Poll poll,
final String ipAddress, final Boolean rate) {
return this.newAccessRateItem(null, poll, null, ipAddress, rate);
}
private AccessRate newSurveyAccessRate(final Survey survey,
final String ipAddress, final Boolean rate) {
return this.newAccessRateItem(null, null, survey, ipAddress, rate);
}
private TweetPoll getTweetPoll(final Long id) throws EnMeNoResultsFoundException{
return getTweetPollService().getTweetPollById(id);
}
private Integer getSocialAccountsLinksByItem(final TweetPoll tpoll, final Survey survey, final Poll poll, final TypeSearchResult itemType){
final List<TweetPollSavedPublishedStatus> totalAccounts = getTweetPollDao().getLinksByTweetPoll(tpoll, survey, poll, itemType);
return totalAccounts.size();
}
private long getRelevanceValue(final long likeVote, final long dislikeVote,
final long hits, final long totalComments,
final long totalSocialAccounts, final long totalNumberVotes,
final long totalHashTagHits) {
final long relevanceValue = EnMeUtils.calculateRelevance(likeVote,
dislikeVote, hits, totalComments, totalSocialAccounts,
totalNumberVotes, totalHashTagHits);
log.info("*******************************");
log.info("******* Resume of Process *****");
log.info("-------------------------------");
log.info("| Total like votes : " + likeVote + " |");
log.info("| Total dislike votes : " + dislikeVote + " |");
log.info("| Total hits : " + hits + " |");
log.info("| Total Comments : " + totalComments + " |");
log.info("| Total Social Network : " + totalSocialAccounts + " |");
log.info("| Total Votes : " + totalNumberVotes + " |");
log.info("| Total HashTag hits : " + totalHashTagHits + " |");
log.info("-------------------------------");
log.info("*******************************");
log.info("************ Finished Start Relevance calculate job **************");
return relevanceValue;
}
public void processItemstoCalculateRelevance(
final List<TweetPoll> tweetPollList,
final List<Poll> pollList,
final List<Survey> surveyList,
final Calendar datebefore,
final Calendar todayDate) {
long likeVote;
long dislikeVote;
long hits;
long relevance;
long comments;
long socialAccounts;
long numberVotes;
long hashTagHits;
for (TweetPoll tweetPoll : tweetPollList) {
likeVote = tweetPoll.getLikeVote() == null ? 0 : tweetPoll
.getLikeVote();
dislikeVote = tweetPoll.getDislikeVote() == null ? 0
: tweetPoll.getDislikeVote();
hits = tweetPoll.getHits() == null ? 0 : tweetPoll.getHits();
// final Long userId = tweetPoll.getEditorOwner().getUid();
socialAccounts = this.getSocialAccountsLinksByItem(tweetPoll, null, null, TypeSearchResult.TWEETPOLL);
numberVotes = tweetPoll.getNumbervotes();
comments = getTotalCommentsbyType(tweetPoll.getTweetPollId(), TypeSearchResult.TWEETPOLL);
log.debug("Total comments by TweetPoll ---->" + comments);
hashTagHits = this.getHashTagHits(tweetPoll.getTweetPollId(), TypeSearchResult.HASHTAG);
relevance = this.getRelevanceValue(likeVote, dislikeVote, hits, comments, socialAccounts, numberVotes, hashTagHits);
tweetPoll.setRelevance(relevance);
getTweetPollDao().saveOrUpdate(tweetPoll);
}
for (Poll poll : pollList) {
likeVote = poll.getLikeVote() == null ? 0 : poll.getLikeVote();
dislikeVote = poll.getDislikeVote() == null ? 0 : poll
.getDislikeVote();
hits = poll.getHits() == null ? 0 : poll.getHits();
socialAccounts = this.getSocialAccountsLinksByItem(null, null,
poll, TypeSearchResult.POLL);
numberVotes = poll.getNumbervotes();
comments = getTotalCommentsbyType(poll.getPollId(), TypeSearchResult.POLL);
log.debug("Total Comments by Poll ---->" + comments);
hashTagHits = this.getHashTagHits(poll.getPollId(),
TypeSearchResult.HASHTAG);
relevance = this.getRelevanceValue(likeVote, dislikeVote, hits,
comments, socialAccounts, numberVotes, hashTagHits);
poll.setRelevance(relevance);
getPollDao().saveOrUpdate(poll);
}
}
private Long getHashTagHits(final Long id, final TypeSearchResult filterby){
final Long totalHashTagHits = getFrontEndDao().getTotalHitsbyType(id,
TypeSearchResult.HASHTAG);
return totalHashTagHits;
}
public Long getHashTagHitsbyName(final String tagName, final TypeSearchResult filterBy){
final HashTag tag = getHashTagDao().getHashTagByName(tagName);
final Long hits = this.getHashTagHits(tag.getHashTagId(), TypeSearchResult.HASHTAG);
return hits;
}
private Long getTotalCommentsbyType(final Long itemId, final TypeSearchResult itemType){
final Long totalComments = getCommentsOperations().getTotalCommentsbyItem(itemId, itemType);
return totalComments;
}
public Long getTotalUsageByHashTag(final String tagName,
final Integer initResults, final Integer maxResults,
final TypeSearchResult filter) {
// Validate if tag belongs to hashtag and filter isn't empty.
Long totalUsagebyHashTag = 0L;
final HashTag tag = getHashTagDao().getHashTagByName(tagName);
if (tag != null) {
final List<TweetPoll> tweetsbyTag = this.getTweetPollsByHashTag(tagName, initResults, maxResults, filter);
final int totatTweetPolls = tweetsbyTag.size();
final List<Poll> pollsbyTag = this.getPollsByHashTag(tagName, initResults, maxResults, filter);
final int totalPolls = pollsbyTag.size();
final List<Survey> surveysbyTag = this.getSurveysByHashTag(tagName, initResults, maxResults, filter);
final int totalSurveys = surveysbyTag.size();
totalUsagebyHashTag = (long) (totatTweetPolls + totalPolls + totalSurveys);
}
return totalUsagebyHashTag;
}
public Long getSocialNetworkUseByHashTag(final String tagName,
final Integer initResults, final Integer maxResults) {
// 1- Get tweetPoll, Polls o Survey
Long linksbyTweetPoll = 0L;
Long linksbyPoll = 0L;
Long totalSocialLinks = 0L;
linksbyTweetPoll = this.getTweetPollSocialNetworkLinksbyTag(tagName,
initResults, maxResults, TypeSearchResult.TWEETPOLL);
linksbyPoll = this.getPollsSocialNetworkLinksByTag(tagName,
initResults, maxResults, TypeSearchResult.POLL);
totalSocialLinks = linksbyTweetPoll + linksbyPoll;
return totalSocialLinks;
}
private Long getPollsSocialNetworkLinksByTag(final String tagName,
final Integer initResults, final Integer maxResults,
final TypeSearchResult filter) {
Long linksbyItem = 0L;
Long totalLinksByPoll = 0L;
final List<Poll> polls = this.getPollsByHashTag(tagName, initResults,
maxResults, filter);
for (Poll poll : polls) {
linksbyItem = getTweetPollDao().getSocialLinksByType(null, null,
poll, TypeSearchResult.POLL);
totalLinksByPoll = totalLinksByPoll + linksbyItem;
}
return totalLinksByPoll;
}
private Long getTweetPollSocialNetworkLinksbyTag(final String tagName,
final Integer initResults, final Integer maxResults,
final TypeSearchResult filter) {
Long linksbyItem = 0L;
Long totalLinksByTweetPoll = 0L;
final List<TweetPoll> tp = this.getTweetPollsByHashTag(tagName,
initResults, maxResults, filter);
for (TweetPoll tweetPoll : tp) {
// Get total value by links
linksbyItem = getTweetPollDao().getSocialLinksByType(tweetPoll,
null, null, TypeSearchResult.TWEETPOLL);
totalLinksByTweetPoll = totalLinksByTweetPoll + linksbyItem;
}
return totalLinksByTweetPoll;
}
private List<Survey> getSurveysByHashTag(final String tagName, final Integer initResults, final Integer maxResults, final TypeSearchResult filter){
final List<Survey> surveysByTag = getSurveyDaoImp()
.getSurveysByHashTagName(tagName, initResults, maxResults,
filter);
return surveysByTag;
}
private List<Poll> getPollsByHashTag(final String tagName, final Integer initResults, final Integer maxResults, final TypeSearchResult filter){
final List<Poll> pollsByTag = getPollDao().getPollByHashTagName(
tagName, initResults, maxResults, filter);
return pollsByTag;
}
private List<TweetPoll> getTweetPollsByHashTag(final String tagName,
final Integer initResults, final Integer maxResults,
final TypeSearchResult filter) {
final List<TweetPoll> tweetsbyTag = getTweetPollDao()
.getTweetpollByHashTagName(tagName, initResults, maxResults, filter);
return tweetsbyTag;
}
public Long getHashTagUsedOnItemsVoted(final String tagName, final Integer initResults, final Integer maxResults){
Long totalVotesbyTweetPoll= 0L;
Long total=0L;
final List<TweetPoll> tp = this.getTweetPollsByHashTag(tagName, 0, 100, TypeSearchResult.HASHTAG);
for (TweetPoll tweetPoll : tp) {
totalVotesbyTweetPoll = getTweetPollDao().getTotalVotesByTweetPollId(tweetPoll.getTweetPollId());
total = total + totalVotesbyTweetPoll;
}
log.debug("Total HashTag used by Tweetpoll voted: " + total);
return total;
}
public List<HashTagRankingBean> getHashTagRanking(final String tagName) {
List<HashTagRanking> hashTagRankingList = getHashTagDao()
.getHashTagRankStats();
final Integer value = 1;
Integer position = 0;
final List<HashTagRankingBean> tagRankingBeanList = new ArrayList<HashTagRankingBean>();
final HashTagRankingBean tagRank = new HashTagRankingBean();
final HashTagRankingBean tagRankBef = new HashTagRankingBean();
final HashTagRankingBean tagRankAfter = new HashTagRankingBean();
final Integer hashTagRankListSize = hashTagRankingList.size() - value;
Integer positionBefore;
Integer positionAfter;
log.debug("Hashtag ranking list --->" + hashTagRankListSize);
for (int i = 0; i < hashTagRankingList.size(); i++) {
if (hashTagRankingList.get(i).getHashTag().getHashTag()
.equals(tagName)) {
// Retrieve hashtag main.
position = i;
tagRank.setAverage(hashTagRankingList.get(i).getAverage());
tagRank.setPosition(i);
tagRank.setTagName(tagName);
tagRank.setRankId(hashTagRankingList.get(i).getRankId());
tagRankingBeanList.add(tagRank);
log.debug("HashTag ranking main ---> "
+ hashTagRankingList.get(i).getHashTag().getHashTag());
log.debug("HashTag ranking main position---> " + position);
positionBefore = position - value;
positionAfter = position + value;
if ((position > 0) && (position < hashTagRankListSize)) {
log.debug(" --- HashTag ranking first option ---");
// Save hashTag before item
tagRankBef.setAverage(hashTagRankingList
.get(positionBefore).getAverage());
tagRankBef.setPosition(positionBefore);
tagRankBef.setTagName(hashTagRankingList
.get(positionBefore).getHashTag().getHashTag());
tagRankBef.setRankId(hashTagRankingList.get(positionBefore)
.getRankId());
tagRankingBeanList.add(tagRankBef);
// Save hashTag after item
tagRankAfter.setAverage(hashTagRankingList.get(
positionAfter).getAverage());
tagRankAfter.setPosition(positionAfter);
tagRankAfter.setTagName(hashTagRankingList
.get(positionAfter).getHashTag().getHashTag());
tagRankAfter.setRankId(hashTagRankingList
.get(positionAfter).getRankId());
tagRankingBeanList.add(tagRankAfter);
} else if ((position > 0) && (position == hashTagRankListSize)) {
log.debug(" --- HashTag ranking second option --- ");
// Save hashTag before item
tagRankBef.setAverage(hashTagRankingList
.get(positionBefore).getAverage());
tagRankBef.setPosition(positionBefore);
tagRankBef.setTagName(hashTagRankingList
.get(positionBefore).getHashTag().getHashTag());
tagRankBef.setRankId(hashTagRankingList.get(positionBefore)
.getRankId());
tagRankingBeanList.add(tagRankBef);
} else if ((position == 0)) {
log.debug(" --- HashTag ranking second option --- ");
// Save hashTag after item
tagRankAfter.setAverage(hashTagRankingList.get(
positionAfter).getAverage());
tagRankAfter.setPosition(positionAfter);
tagRankAfter.setTagName(hashTagRankingList
.get(positionAfter).getHashTag().getHashTag());
tagRankAfter.setRankId(hashTagRankingList
.get(positionAfter).getRankId());
tagRankingBeanList.add(tagRankAfter);
}
}
}
Collections.sort(tagRankingBeanList);
return tagRankingBeanList;
}
public GenericStatsBean retrieveGenericStats(final String itemId, final TypeSearchResult itemType) throws EnMeNoResultsFoundException{
Long totalHits = 0L;
String createdBy = " ";
Date createdAt = null;
double average= 0;
Long likeDislikeRate = 0L;
Long likeVotes;
Long dislikeVotes;
Long id;
HashMap<Integer, RelativeTimeEnum> relative;
if (itemType.equals(TypeSearchResult.TWEETPOLL)) {
id = new Long(Long.parseLong(itemId));
final TweetPoll tweetPoll = this.getTweetPoll(id);
totalHits = tweetPoll.getHits() == null ? 0 : tweetPoll.getHits();
createdBy = tweetPoll.getEditorOwner().getUsername() == null ? "" : tweetPoll.getEditorOwner().getUsername();
createdAt = tweetPoll.getCreateDate();
relative = DateUtil.getRelativeTime(createdAt);
likeVotes = tweetPoll.getLikeVote() == null ? 0L : tweetPoll.getLikeVote();
dislikeVotes = tweetPoll.getDislikeVote() == null ? 0L : tweetPoll.getDislikeVote();
// Like/Dislike Rate = Total Like votes minus total dislike votes.
likeDislikeRate = (likeVotes - dislikeVotes);
} else if (itemType.equals(TypeSearchResult.POLL)) {
id = new Long(Long.parseLong(itemId));
final Poll poll = this.getPoll(id);
totalHits = poll.getHits() == null ? 0 : poll.getHits();
createdBy = poll.getEditorOwner().getUsername() ;
createdAt = poll.getCreatedAt();
relative = DateUtil.getRelativeTime(createdAt);
likeVotes = poll.getLikeVote() == null ? 0L : poll.getLikeVote();
dislikeVotes = poll.getDislikeVote() == null ? 0L : poll.getDislikeVote();
} else if (itemType.equals(TypeSearchResult.SURVEY)) {
id = new Long(Long.parseLong(itemId));
final Survey survey = this.getSurvey(id);
totalHits = survey.getHits();
createdBy = survey.getEditorOwner().getUsername() == null ? " " : survey.getEditorOwner().getUsername();
createdAt = survey.getCreatedAt();
relative = DateUtil.getRelativeTime(createdAt);
likeVotes = survey.getLikeVote();
dislikeVotes = survey.getDislikeVote();
} else if (itemType.equals(TypeSearchResult.HASHTAG)) {
final HashTag tag = getHashTagItem(itemId);
totalHits = tag.getHits();
createdAt = tag.getUpdatedDate();
relative = DateUtil.getRelativeTime(createdAt);
}
final GenericStatsBean genericBean = new GenericStatsBean();
genericBean.setLikeDislikeRate(likeDislikeRate);;
genericBean.setHits(totalHits);
genericBean.setCreatedBy(createdBy);
genericBean.setAverage(average);
genericBean.setCreatedAt(createdAt);
return genericBean;
}
public void retrieveHashTagGraphData(){
}
private Survey getSurvey(final Long id) throws EnMeNoResultsFoundException{
return getSurveyService().getSurveyById(id);
}
private Poll getPoll(final Long id) throws EnMePollNotFoundException{
return getPollService().getPollById(id);
}
public List<ProfileRatedTopBean> getTopRatedProfile(final Boolean status)
throws EnMeNoResultsFoundException {
Long topValue = 0L;
Long totalTweetPollPublished;
Long totalPollPublished;
Long total;
final List<UserAccount> users = getSecurityService()
.getUserAccountsAvailable(status);
final List<ProfileRatedTopBean> profiles = ConvertDomainBean
.convertUserAccountListToProfileRated(users);
for (ProfileRatedTopBean profileRatedTopBean : profiles) {
totalTweetPollPublished = getTweetPollDao().getTotalTweetPoll(
getUserAccount(profileRatedTopBean.getUsername()), status);
log.debug("total tweetPolss published by -->" + totalTweetPollPublished);
totalPollPublished = getPollDao().getTotalPollsbyUser(
getUserAccount(profileRatedTopBean.getUsername()), status);
log.debug("total tweetPolss published by -->" + totalTweetPollPublished);
total = totalTweetPollPublished + totalPollPublished;
topValue = topValue + total;
log.debug("total value asigned to -->" + totalTweetPollPublished);
profileRatedTopBean.setTopValue(topValue);
}
Collections.sort(profiles);
return profiles;
}
/*
* (non-Javadoc)
* @see org.encuestame.core.service.imp.IFrontEndService#getHashTagLinks(org.encuestame.persistence.domain.HashTag)
*/
public List<LinksSocialBean> getHashTagLinks(final HashTag hash) {
final List<TweetPollSavedPublishedStatus> links = getFrontEndDao()
.getLinksByHomeItem(hash, null, null, null, null,
TypeSearchResult.HASHTAG);
log.debug("getTweetPollLinks "+links.size());
return ConvertDomainBean.convertTweetPollSavedPublishedStatus(links);
}
// Total Usage by item.
public void getTotalUsagebyHashTagAndDateRange(){
}
/**
* Create hashTag details stats.
* @param label
* @param value
* @return
*/
private HashTagDetailStats createTagDetailsStats(final String label, final Long value){
final HashTagDetailStats tagDetails = new HashTagDetailStats();
tagDetails.setLabel(label);
tagDetails.setValue(value);
return tagDetails;
}
/**
* Counter items by HashTag.
* @param month
* @param counter
* @return
*/
private Long counterItemsbyHashTag(final int month, Long counter){
switch(month) {
case 1:
counter ++;
break;
case 2:
counter ++;
break;
case 3:
counter ++;
break;
case 4:
counter ++;
break;
case 5:
counter ++;
break;
case 6:
counter ++;
break;
case 7:
counter ++;
break;
case 8:
counter ++;
break;
case 9:
counter ++;
break;
case 10:
counter ++;
break;
case 11:
counter ++;
break;
case 12:
counter ++;
break;
default:
log.debug("Month not found");
}
return counter;
}
/**
*
* @param tpolls
* @param polls
* @param surveys
* @param counter
* @return
*/
private DateTime getAfterOrCurrentlyItemCreationDate(
final List<TweetPoll> tpolls, final List<Poll> polls,
final List<Survey> surveys, final int counter) {
DateTime monthValue;
if (tpolls != null) {
monthValue = new DateTime(tpolls.get(counter).getCreateDate());
} else if (polls != null) {
monthValue = new DateTime(polls.get(counter).getCreatedAt());
} else {
monthValue = new DateTime(surveys.get(counter).getCreatedAt());
}
return monthValue;
}
/**
*
* @param tpolls
* @param polls
* @param surveys
* @return
*/
private List<HashTagDetailStats> getTagDetail(final List<TweetPoll> tpolls,
final List<Poll> polls, final List<Survey> surveys) {
// Tamano del array segun venga.
int totalList = 0;
List<HashTagDetailStats> statDetail = new ArrayList<HashTagDetailStats>();
if (tpolls != null) {
totalList = tpolls.size();
System.out.println(" Tweetpolls List size --->" + tpolls.size());
} else if (polls != null) {
totalList = polls.size();
} else {
totalList = surveys.size();
}
int counterI = 0;
if (totalList > 0) {
log.debug(" Total items by hashTag ---> " + totalList);
for (int i = 0; i < totalList; i++) {
statDetail = this.addHashTagStatsDetail(totalList, tpolls, polls, surveys, i);
}
} else
log.error("Items by HashTag not found");
return statDetail;
}
private List<HashTagDetailStats> addHashTagStatsDetail(final int totalList,
final List<TweetPoll> tpolls, final List<Poll> polls,
final List<Survey> surveys, final int counterIValue) {
int month = 0;
Long counterTweetPoll = 0L;
int afterMonth = 0;
int counterAfterMonthValue = 0;
HashTagDetailStats tagDetail = new HashTagDetailStats();
List<HashTagDetailStats> tagStatsDetail = new ArrayList<HashTagDetailStats>();
DateTime currentlyMonth = this.getAfterOrCurrentlyItemCreationDate(
tpolls, polls, surveys, counterIValue);
month = currentlyMonth.getMonthOfYear();
if (counterIValue < totalList - 1) {
counterAfterMonthValue = counterAfterMonthValue + 1;
DateTime dt2 = this.getAfterOrCurrentlyItemCreationDate(tpolls,
polls, surveys, counterAfterMonthValue);
afterMonth = dt2.getMonthOfYear();
System.out.println(" Currently month --> " + month + " After month --> " + afterMonth);
} else {
counterAfterMonthValue = counterIValue;
afterMonth = 0;
}
counterTweetPoll = this.counterItemsbyHashTag(month, counterTweetPoll);
if (month != afterMonth) {
System.out.println(" \n Added month --> " + month);
tagDetail = this.createTagDetailsStats(String.valueOf(month),
counterTweetPoll);
tagStatsDetail.add(tagDetail);
counterTweetPoll = 0L;
}
return tagStatsDetail;
}
private List<HashTagDetailStats> getTotalTweetPollUsageByHashTagAndDateRange(
final String tagName, final Integer period,
final Integer startResults, final Integer maxResults) {
List<TweetPoll> tweetPollsByHashTag = new ArrayList<TweetPoll>();
List<HashTagDetailStats> tagStatsDetailbyTweetPoll = new ArrayList<HashTagDetailStats>();
tweetPollsByHashTag = getTweetPollDao()
.getTweetPollsbyHashTagNameAndDateRange(tagName, period,
startResults, maxResults);
System.out.println(" Tweetpolls List por HashTag --->" + tweetPollsByHashTag.size());
// Obtiene el detalle de hashtags por tweetpoll.
tagStatsDetailbyTweetPoll = this.getTagDetail(tweetPollsByHashTag,
null, null);
System.out.println(" tagStatsDetailbyTweetPoll --->" + tweetPollsByHashTag.size());
return tagStatsDetailbyTweetPoll;
}
/*
* (non-Javadoc)
* @see org.encuestame.core.service.imp.IFrontEndService#getTotalUsagebyHashTagAndDateRange(java.lang.String, java.lang.Integer, java.lang.Integer, java.lang.Integer)
*/
public List<HashTagDetailStats> getTotalUsagebyHashTagAndDateRange(
final String hashTagName, final Integer period,
final Integer startResults, final Integer maxResults)
throws EnMeNoResultsFoundException {
final HashTag tag = this.getHashTag(hashTagName, Boolean.TRUE);
// Get tweetPoll List
List<HashTagDetailStats> tagStatsDetail = new ArrayList<HashTagDetailStats>();
System.out.println("Tag Stats Detail Total --->" + tagStatsDetail);
if (tag != null) {
tagStatsDetail = this.getTotalTweetPollUsageByHashTagAndDateRange(hashTagName, period, startResults, maxResults);
//int month = 0;
//Long counterTweetPoll = 0L;
//int afterMonth = 0;
//int totalList = tweetPollsByHashTag.size();
//int counterI = 0;
}
return tagStatsDetail;
}
/**
* @return the tweetPollService
*/
public TweetPollService getTweetPollService() {
return tweetPollService;
}
/**
* @param tweetPollService the tweetPollService to set
*/
public void setTweetPollService(TweetPollService tweetPollService) {
this.tweetPollService = tweetPollService;
}
/**
* @return the pollService
*/
public PollService getPollService() {
return pollService;
}
/**
* @param pollService the pollService to set
*/
public void setPollService(final PollService pollService) {
this.pollService = pollService;
}
/**
* @return the surveyService
*/
public SurveyService getSurveyService() {
return surveyService;
}
/**
* @param surveyService the surveyService to set
*/
public void setSurveyService(final SurveyService surveyService) {
this.surveyService = surveyService;
}
/**
* @return the securityService
*/
public SecurityOperations getSecurityService() {
return securityService;
}
/**
* @param securityService the securityService to set
*/
public void setSecurityService(SecurityOperations securityService) {
this.securityService = securityService;
}
} |
package org.opens.tanaguru.util.http;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.nio.charset.IllegalCharsetNameException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.HeadMethod;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.httpclient.util.URIUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHost;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.log4j.Logger;
/**
*
* @author jkowalczyk
*/
public class HttpRequestHandler {
private static final Logger LOGGER = Logger.getLogger(HttpRequestHandler.class);
/**
* The holder that handles the unique instance of LanguageDetector
*/
private static class HttpRequestHandlerHolder {
public static HttpRequestHandler INSTANCE = new HttpRequestHandler();
}
private String proxyPort;
public void setProxyPort(String proxyPort) {
this.proxyPort = proxyPort;
}
private String proxyHost;
public void setProxyHost(String proxyHost) {
this.proxyHost = proxyHost;
}
/**
* Multiple Url can be set through a unique String separated by ;
*/
private List<String> proxyExclusionUrlList = new ArrayList<String>();
public List<String> getProxyExclusionUrlList() {
return proxyExclusionUrlList;
}
public void setProxyExclusionUrl(String proxyExclusionUrl) {
proxyExclusionUrlList.addAll(Arrays.asList(proxyExclusionUrl.split(";")));
}
private int connectionTimeout = 20000;
public void setConnectionTimeout(int connectionTimeout) {
this.connectionTimeout = connectionTimeout;
}
private int socketTimeout = 20000;
public void setSocketTimeout(int socketTimeout) {
this.socketTimeout = socketTimeout;
}
/**
* Private constructor, singleton pattern
*/
private HttpRequestHandler() {
if (HttpRequestHandlerHolder.INSTANCE != null) {
throw new IllegalStateException("Already instantiated");
}
}
public static synchronized HttpRequestHandler getInstance() {
return HttpRequestHandlerHolder.INSTANCE;
}
public boolean isUrlAccessible (String url) {
int statusFromHead = computeStatus(getHttpStatus(url));
switch (statusFromHead) {
case 1 :
return true;
case 0 :
int statusFromGet = computeStatus(getHttpStatusFromGet(url));
switch (statusFromGet) {
case 0 :
return false;
case 1 :
return true;
}
}
return false;
}
public int getHttpStatus (String url) {
String encodedUrl = getEncodedUrl(url);
HttpClient httpClient = getHttpClient(encodedUrl);
HeadMethod head = new HeadMethod(encodedUrl);
try {
LOGGER.debug("executing head request to retrieve page status on " + head.getURI());
int status = httpClient.executeMethod(head);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("received " + status + " from head request");
for (Header h : head.getResponseHeaders()) {
LOGGER.debug("header : " + h.toExternalForm());
}
}
return status;
} catch (UnknownHostException uhe) {
LOGGER.warn("UnknownHostException on " + encodedUrl);
return HttpStatus.SC_NOT_FOUND;
} catch (IllegalArgumentException iae) {
LOGGER.warn("IllegalArgumentException on " + encodedUrl);
return HttpStatus.SC_NOT_FOUND;
} catch (IOException ioe) {
LOGGER.warn("IOException on " + encodedUrl);
ioe.fillInStackTrace();
return HttpStatus.SC_NOT_FOUND;
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
head.releaseConnection();
}
}
public String getHttpContent (String url) throws URISyntaxException, UnknownHostException, IOException, IllegalCharsetNameException {
if (StringUtils.isEmpty(url)){
return "";
}
String encodedUrl = getEncodedUrl(url);
HttpClient httpClient = getHttpClient(encodedUrl);
GetMethod get = new GetMethod(encodedUrl);
try {
LOGGER.debug("executing request to retrieve content on " + get.getURI());
int status = httpClient.executeMethod(get);
LOGGER.debug("received " + status + " from get request");
if (status == HttpStatus.SC_OK) {
LOGGER.debug("status == HttpStatus.SC_OK " );
byte[] responseBody = get.getResponseBody();
return new String(responseBody);
} else {
LOGGER.debug("status != HttpStatus.SC_OK " );
return "";
}
} catch (NullPointerException ioe) {
LOGGER.debug("NullPointerException");
return "";
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
get.releaseConnection();
LOGGER.debug("finally");
}
}
public int getHttpStatusFromGet (String url) {
String encodedUrl = getEncodedUrl(url);
HttpClient httpClient = getHttpClient(encodedUrl);
GetMethod get = new GetMethod(encodedUrl);
try {
LOGGER.debug("executing get request to retrieve status on " + get.getURI());
int status = httpClient.executeMethod(get);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("received " + status + " from get request");
for (Header h : get.getResponseHeaders()) {
LOGGER.debug("header : " + h.toExternalForm());
}
}
return status;
} catch (UnknownHostException uhe) {
LOGGER.warn("UnknownHostException on " + encodedUrl);
return HttpStatus.SC_NOT_FOUND;
} catch (IOException ioe) {
LOGGER.warn("IOException on " + encodedUrl);
return HttpStatus.SC_NOT_FOUND;
}finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
get.releaseConnection();
}
}
private HttpClient getHttpClient(String url) {
HttpClient httpclient = new HttpClient();
boolean isExcludedUrl=false;
for (String excludedUrl : proxyExclusionUrlList) {
if (url.contains(excludedUrl)) {
isExcludedUrl=true;
}
}
if (StringUtils.isNotEmpty(proxyPort) && StringUtils.isNotEmpty(proxyPort) && !isExcludedUrl) {
HttpHost proxy = new HttpHost(proxyHost, Integer.valueOf(proxyPort));
httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
}
setTimeouts(httpclient.getParams());
return httpclient;
}
private void setTimeouts(HttpClientParams params) {
params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
connectionTimeout);
params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, socketTimeout);
}
private int computeStatus(int status) {
switch (status) {
case HttpStatus.SC_FORBIDDEN:
case HttpStatus.SC_METHOD_NOT_ALLOWED:
case HttpStatus.SC_BAD_REQUEST:
case HttpStatus.SC_UNAUTHORIZED:
case HttpStatus.SC_PAYMENT_REQUIRED:
case HttpStatus.SC_NOT_FOUND:
case HttpStatus.SC_NOT_ACCEPTABLE:
case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED:
case HttpStatus.SC_REQUEST_TIMEOUT:
case HttpStatus.SC_CONFLICT:
case HttpStatus.SC_GONE:
case HttpStatus.SC_LENGTH_REQUIRED:
case HttpStatus.SC_PRECONDITION_FAILED:
case HttpStatus.SC_REQUEST_TOO_LONG:
case HttpStatus.SC_REQUEST_URI_TOO_LONG:
case HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE:
case HttpStatus.SC_REQUESTED_RANGE_NOT_SATISFIABLE:
case HttpStatus.SC_EXPECTATION_FAILED:
case HttpStatus.SC_INSUFFICIENT_SPACE_ON_RESOURCE:
case HttpStatus.SC_METHOD_FAILURE:
case HttpStatus.SC_UNPROCESSABLE_ENTITY:
case HttpStatus.SC_LOCKED:
case HttpStatus.SC_FAILED_DEPENDENCY:
case HttpStatus.SC_INTERNAL_SERVER_ERROR:
case HttpStatus.SC_NOT_IMPLEMENTED:
case HttpStatus.SC_BAD_GATEWAY:
case HttpStatus.SC_SERVICE_UNAVAILABLE:
case HttpStatus.SC_GATEWAY_TIMEOUT:
case HttpStatus.SC_HTTP_VERSION_NOT_SUPPORTED:
case HttpStatus.SC_INSUFFICIENT_STORAGE:
return 0;
case HttpStatus.SC_CONTINUE:
case HttpStatus.SC_SWITCHING_PROTOCOLS:
case HttpStatus.SC_PROCESSING:
case HttpStatus.SC_OK:
case HttpStatus.SC_CREATED:
case HttpStatus.SC_ACCEPTED:
case HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION:
case HttpStatus.SC_NO_CONTENT:
case HttpStatus.SC_RESET_CONTENT:
case HttpStatus.SC_PARTIAL_CONTENT:
case HttpStatus.SC_MULTI_STATUS:
case HttpStatus.SC_MULTIPLE_CHOICES:
case HttpStatus.SC_MOVED_PERMANENTLY:
case HttpStatus.SC_MOVED_TEMPORARILY:
case HttpStatus.SC_SEE_OTHER:
case HttpStatus.SC_NOT_MODIFIED:
case HttpStatus.SC_USE_PROXY:
case HttpStatus.SC_TEMPORARY_REDIRECT:
return 1;
default :
return 1;
}
}
private String getEncodedUrl(String url) {
try {
return URIUtil.encodeQuery(URIUtil.decode(url));
} catch (URIException ue) {
LOGGER.warn("URIException on " + url);
return url;
}
}
} |
package com.metamatrix.common.config;
/**
* ResourceNames defines the different resources that require
* connection properties. These properties are loaded up by
* the {@link CurrentConfiguration} and made availble by calling
* the method {@link #getResourceProperties}. The following
* are the basis for the names:
* - CompTypes, excluding connectors (e.g., Config Service, Session Service, etc).
* - internal operations (e.g., Runtime Metadata, logging, cursors, etc.)
*/
public interface ResourceNames {
public static final String RUNTIME_METADATA_SERVICE = "RuntimeMetadataService"; //$NON-NLS-1$
public static final String DIRECTORY_SERVICE = "DirectoryService"; //$NON-NLS-1$
public static final String MEMBERSHIP_SERVICE = "MembershipService"; //$NON-NLS-1$
// Txn Mgr properties for Transactional Server product
public static final String XA_TRANSACTION_MANAGER = "XATransactionManager"; //$NON-NLS-1$
public static final String INDEXING_SERVICE = "IndexingService"; //$NON-NLS-1$
public static final String WEB_SERVICES = "WebServices"; //$NON-NLS-1$
public static final String JGROUPS = "JGroups"; //$NON-NLS-1$
public static final String SSL = "SSL"; //$NON-NLS-1$
} |
package edu.umd.cs.findbugs.detect;
import java.util.BitSet;
import java.util.Iterator;
import javax.annotation.meta.When;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.generic.ReferenceType;
import org.apache.bcel.generic.Type;
import edu.umd.cs.findbugs.FindBugsAnalysisFeatures;
import edu.umd.cs.findbugs.SystemProperties;
import edu.umd.cs.findbugs.ba.AnalysisContext;
import edu.umd.cs.findbugs.ba.CFG;
import edu.umd.cs.findbugs.ba.ClassContext;
import edu.umd.cs.findbugs.ba.SignatureParser;
import edu.umd.cs.findbugs.ba.XFactory;
import edu.umd.cs.findbugs.ba.XMethod;
import edu.umd.cs.findbugs.ba.deref.UnconditionalValueDerefDataflow;
import edu.umd.cs.findbugs.ba.deref.UnconditionalValueDerefSet;
import edu.umd.cs.findbugs.ba.jsr305.TypeQualifierAnnotation;
import edu.umd.cs.findbugs.ba.jsr305.TypeQualifierApplications;
import edu.umd.cs.findbugs.ba.jsr305.TypeQualifierValue;
import edu.umd.cs.findbugs.ba.npe.ParameterNullnessProperty;
import edu.umd.cs.findbugs.ba.vna.ValueNumber;
import edu.umd.cs.findbugs.ba.vna.ValueNumberDataflow;
import edu.umd.cs.findbugs.classfile.CheckedAnalysisException;
import edu.umd.cs.findbugs.classfile.ClassDescriptor;
import edu.umd.cs.findbugs.classfile.DescriptorFactory;
import edu.umd.cs.findbugs.util.Util;
/**
* Build database of unconditionally dereferenced parameters.
*
* @author David Hovemeyer
*/
public class BuildUnconditionalParamDerefDatabase {
public static final boolean VERBOSE_DEBUG = SystemProperties.getBoolean("fnd.debug.nullarg.verbose");
private static final boolean DEBUG = SystemProperties.getBoolean("fnd.debug.nullarg") || VERBOSE_DEBUG;
public final TypeQualifierValue nonnullTypeQualifierValue;
public BuildUnconditionalParamDerefDatabase() {
ClassDescriptor nonnullClassDesc = DescriptorFactory.createClassDescriptor(javax.annotation.Nonnull.class);
this.nonnullTypeQualifierValue = TypeQualifierValue.getValue(nonnullClassDesc, null);
}
public void visitClassContext(ClassContext classContext) {
boolean fullAnalysis = AnalysisContext.currentAnalysisContext().getBoolProperty(FindBugsAnalysisFeatures.INTERPROCEDURAL_ANALYSIS_OF_REFERENCED_CLASSES);
if (!fullAnalysis && !AnalysisContext.currentAnalysisContext()/*.getSubtypes()*/.isApplicationClass(classContext.getJavaClass()))
return;
if (VERBOSE_DEBUG) System.out.println("Visiting class " + classContext.getJavaClass().getClassName());
for(Method m : classContext.getMethodsInCallOrder())
considerMethod(classContext, m);
}
private void considerMethod(ClassContext classContext, Method method) {
boolean hasReferenceParameters = false;
for (Type argument : method.getArgumentTypes())
if (argument instanceof ReferenceType) {
hasReferenceParameters = true;
referenceParameters++;
}
if (hasReferenceParameters && classContext.getMethodGen(method) != null) {
if (VERBOSE_DEBUG) System.out.println("Check " + method);
analyzeMethod(classContext, method);
}
}
protected int referenceParameters;
protected int nonnullReferenceParameters;
private void analyzeMethod(ClassContext classContext, Method method) {
try {
CFG cfg = classContext.getCFG(method);
XMethod xmethod = XFactory.createXMethod(classContext.getJavaClass(), method);
ValueNumberDataflow vnaDataflow = classContext.getValueNumberDataflow(method);
UnconditionalValueDerefDataflow dataflow =
classContext.getUnconditionalValueDerefDataflow(method);
SignatureParser parser = new SignatureParser(method.getSignature());
int paramLocalOffset = method.isStatic() ? 0 : 1;
// Build BitSet of params that are unconditionally dereferenced
BitSet unconditionalDerefSet = new BitSet();
UnconditionalValueDerefSet entryFact = dataflow.getResultFact(cfg.getEntry());
Iterator<String> paramIterator = parser.parameterSignatureIterator();
int i = 0;
while (paramIterator.hasNext()) {
String paramSig = paramIterator.next();
ValueNumber paramVN = vnaDataflow.getAnalysis().getEntryValue(paramLocalOffset);
if (entryFact.isUnconditionallyDereferenced(paramVN)) {
TypeQualifierAnnotation directTypeQualifierAnnotation = TypeQualifierApplications.getDirectTypeQualifierAnnotation(xmethod, i, nonnullTypeQualifierValue);
if (directTypeQualifierAnnotation == null && directTypeQualifierAnnotation.when == When.ALWAYS)
unconditionalDerefSet.set(i);
}
i++;
if (paramSig.equals("D") || paramSig.equals("J")) paramLocalOffset += 2;
else paramLocalOffset += 1;
}
// No need to add properties if there are no unconditionally dereferenced params
if (unconditionalDerefSet.isEmpty()) {
if (VERBOSE_DEBUG) {
System.out.println("\tResult is empty");
}
return;
}
if (VERBOSE_DEBUG) {
ClassContext.dumpDataflowInformation(method, cfg, vnaDataflow, classContext.getIsNullValueDataflow(method), dataflow, classContext.getTypeDataflow(method));
}
ParameterNullnessProperty property = new ParameterNullnessProperty();
nonnullReferenceParameters += unconditionalDerefSet.cardinality();
property.setNonNullParamSet(unconditionalDerefSet);
AnalysisContext.currentAnalysisContext().getUnconditionalDerefParamDatabase().setProperty(xmethod.getMethodDescriptor(), property);
if (DEBUG) {
System.out.println("Unconditional deref: " + xmethod + "=" + property);
}
} catch (CheckedAnalysisException e) {
XMethod xmethod = XFactory.createXMethod(classContext.getJavaClass(), method);
AnalysisContext.currentAnalysisContext().getLookupFailureCallback().logError(
"Error analyzing " + xmethod + " for unconditional deref training", e);
}
}
} |
/**
* Autogenerated by Thrift Compiler (0.9.2)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
package com.xiaomi.infra.galaxy.emq.thrift;
import libthrift091.scheme.IScheme;
import libthrift091.scheme.SchemeFactory;
import libthrift091.scheme.StandardScheme;
import libthrift091.scheme.TupleScheme;
import libthrift091.protocol.TTupleProtocol;
import libthrift091.protocol.TProtocolException;
import libthrift091.EncodingUtils;
import libthrift091.TException;
import libthrift091.async.AsyncMethodCallback;
import libthrift091.server.AbstractNonblockingServer.*;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.EnumMap;
import java.util.Set;
import java.util.HashSet;
import java.util.EnumSet;
import java.util.Collections;
import java.util.BitSet;
import java.nio.ByteBuffer;
import java.util.Arrays;
import javax.annotation.Generated;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked"})
public class RangeConstants {
/**
* message delay seconds in this queue, default 0s (0s ~ 15min)
*/
public static final int GALAXY_EMQ_QUEUE_DELAY_SECONDS_DEFAULT = 0;
public static final int GALAXY_EMQ_QUEUE_DELAY_SECONDS_MINIMAL = 0;
public static final int GALAXY_EMQ_QUEUE_DELAY_SECONDS_MAXIMAL = 900;
/**
* message invisibility seconds in this queue, default 30s (1s ~ 12hour)
*/
public static final int GALAXY_EMQ_QUEUE_INVISIBILITY_SECONDS_DEFAULT = 30;
public static final int GALAXY_EMQ_QUEUE_INVISIBILITY_SECONDS_MINIMAL = 2;
public static final int GALAXY_EMQ_QUEUE_INVISIBILITY_SECONDS_MAXIMAL = 43200;
/**
* receive message seconds in this queue, default 0s which means no wait (0s ~ 20s)
*/
public static final int GALAXY_EMQ_QUEUE_RECEIVE_WAIT_SECONDS_DEFAULT = 0;
public static final int GALAXY_EMQ_QUEUE_RECEIVE_WAIT_SECONDS_MINIMAL = 0;
public static final int GALAXY_EMQ_QUEUE_RECEIVE_WAIT_SECONDS_MAXIMAL = 20;
/**
* maximum receive message number in this queue, default 100(1 ~ 100)
*/
public static final int GALAXY_EMQ_QUEUE_RECEIVE_NUMBER_DEFAULT = 100;
public static final int GALAXY_EMQ_QUEUE_RECEIVE_NUMBER_MINIMAL = 1;
public static final int GALAXY_EMQ_QUEUE_RECEIVE_NUMBER_MAXIMAL = 100;
/**
* message retention seconds in this queue, default 4days (60s ~ 14days)
*/
public static final int GALAXY_EMQ_QUEUE_RETENTION_SECONDS_DEFAULT = 345600;
public static final int GALAXY_EMQ_QUEUE_RETENTION_SECONDS_MINIMAL = 60;
public static final int GALAXY_EMQ_QUEUE_RETENTION_SECONDS_MAXIMAL = 1209600;
/**
* max message size in this queue, default 256K (1K ~ 256K)
*/
public static final int GALAXY_EMQ_QUEUE_MAX_MESSAGE_BYTES_DEFAULT = 262144;
public static final int GALAXY_EMQ_QUEUE_MAX_MESSAGE_BYTES_MINIMAL = 1024;
public static final int GALAXY_EMQ_QUEUE_MAX_MESSAGE_BYTES_MAXIMAL = 262144;
public static final int GALAXY_EMQ_QUEUE_PARTITION_NUMBER_DEFAULT = 4;
public static final int GALAXY_EMQ_QUEUE_PARTITION_NUMBER_MINIMAL = 1;
public static final int GALAXY_EMQ_QUEUE_PARTITION_NUMBER_MAXIMAL = 255;
/**
* message delay seconds that overwrite GALAXY_EMQ_QUEUE_DELAY_SECONDS,
* default 0s (0s ~ 15min)
*/
public static final int GALAXY_EMQ_MESSAGE_DELAY_SECONDS_DEFAULT = 0;
public static final int GALAXY_EMQ_MESSAGE_DELAY_SECONDS_MINIMAL = 0;
public static final int GALAXY_EMQ_MESSAGE_DELAY_SECONDS_MAXIMAL = 900;
/**
* message invisibility seconds that overwrite
* GALAXY_EMQ_QUEUE_INVISIBILITY_SECONDS, default 30s (0s ~ 12hour)
*/
public static final int GALAXY_EMQ_MESSAGE_INVISIBILITY_SECONDS_DEFAULT = 30;
public static final int GALAXY_EMQ_MESSAGE_INVISIBILITY_SECONDS_MINIMAL = 2;
public static final int GALAXY_EMQ_MESSAGE_INVISIBILITY_SECONDS_MAXIMAL = 43200;
/**
* queue read qps, default 0 (0 ~ 100000)
*/
public static final long GALAXY_EMQ_QUEUE_READ_QPS_DEFAULT = 0L;
public static final long GALAXY_EMQ_QUEUE_READ_QPS_MINIMAL = 0L;
public static final long GALAXY_EMQ_QUEUE_READ_QPS_MAXIMAL = 100000L;
/**
* queue write qps, default 0 (0 ~ 100000)
*/
public static final long GALAXY_EMQ_QUEUE_WRITE_QPS_DEFAULT = 0L;
public static final long GALAXY_EMQ_QUEUE_WRITE_QPS_MINIMAL = 0L;
public static final long GALAXY_EMQ_QUEUE_WRITE_QPS_MAXIMAL = 100000L;
/**
* queue redrive policy max receive time, default 2 (1 ~ 100)
*/
public static final int GALAXY_EMQ_QUEUE_REDRIVE_POLICY_MAX_RECEIVE_TIME_DEFAULT = 2;
public static final int GALAXY_EMQ_QUEUE_REDRIVE_POLICY_MAX_RECEIVE_TIME_MINIMAL = 1;
public static final int GALAXY_EMQ_QUEUE_REDRIVE_POLICY_MAX_RECEIVE_TIME_MAXIMAL = 100;
} |
package org.jnosql.artemis.graph.spi;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.jnosql.artemis.Database;
import org.jnosql.artemis.Databases;
import org.jnosql.artemis.Repository;
import org.jnosql.artemis.graph.query.RepositoryGraphBean;
import javax.enterprise.event.Observes;
import javax.enterprise.inject.spi.AfterBeanDiscovery;
import javax.enterprise.inject.spi.BeanManager;
import javax.enterprise.inject.spi.Extension;
import javax.enterprise.inject.spi.ProcessAnnotatedType;
import javax.enterprise.inject.spi.ProcessProducer;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.logging.Logger;
import java.util.stream.Stream;
import static org.jnosql.artemis.DatabaseType.GRAPH;
/**
* Extension to start up the GraphTemplate, Repository
* from the {@link Database} qualifier
*/
public class GraphProducerExtension implements Extension {
private static final Logger LOGGER = Logger.getLogger(GraphProducerExtension.class.getName());
private final List<Database> databases = new ArrayList<>();
private final Collection<Class<?>> crudTypes = new HashSet<>();
<T extends Repository> void onProcessAnnotatedType(@Observes final ProcessAnnotatedType<T> repo) {
Class<T> javaClass = repo.getAnnotatedType().getJavaClass();
if (Repository.class.equals(javaClass)) {
return;
}
if (Stream.of(javaClass.getInterfaces()).anyMatch(Repository.class::equals)
&& Modifier.isInterface(javaClass.getModifiers())) {
LOGGER.info("Adding a new Repository as discovered on Graph: " + javaClass);
crudTypes.add(javaClass);
}
}
<T, X extends Graph> void processProducer(@Observes final ProcessProducer<T, X> pp) {
Databases.addDatabase(pp, GRAPH, databases);
}
void onAfterBeanDiscovery(@Observes final AfterBeanDiscovery afterBeanDiscovery, final BeanManager beanManager) {
LOGGER.info(String.format("Starting to process on graphs: %d databases crud %d",
databases.size(), crudTypes.size()));
databases.forEach(type -> {
final GraphTemplateBean bean = new GraphTemplateBean(beanManager, type.provider());
afterBeanDiscovery.addBean(bean);
});
crudTypes.forEach(type -> {
afterBeanDiscovery.addBean(new RepositoryGraphBean(type, beanManager, ""));
databases.forEach(database -> afterBeanDiscovery
.addBean(new RepositoryGraphBean(type, beanManager, database.provider())));
});
}
} |
package org.jboss.as.console.client.domain.profiles;
import com.google.gwt.user.client.ui.DisclosurePanel;
import com.google.gwt.user.client.ui.Widget;
import com.gwtplatform.mvp.client.annotations.NameToken;
import org.jboss.as.console.client.Console;
import org.jboss.as.console.client.core.NameTokens;
import org.jboss.as.console.client.widgets.DisclosureStackHeader;
import org.jboss.as.console.client.widgets.LHSNavTree;
import org.jboss.as.console.client.widgets.LHSNavTreeItem;
/**
* @author Heiko Braun
* @date 2/15/11
*/
class CommonConfigSection {
private DisclosurePanel panel;
private LHSNavTree commonTree;
public CommonConfigSection() {
super();
panel = new DisclosureStackHeader(Console.CONSTANTS.common_label_generalConfig()).asWidget();
commonTree = new LHSNavTree("profiles");
panel.setContent(commonTree);
//LHSNavTreeItem paths = new LHSNavTreeItem(Console.CONSTANTS.common_label_paths(), "domain/paths");
LHSNavTreeItem interfaces = new LHSNavTreeItem(Console.CONSTANTS.common_label_interfaces(), NameTokens.InterfacePresenter);
LHSNavTreeItem sockets = new LHSNavTreeItem(Console.CONSTANTS.common_label_socketBindingGroups(), "domain/socket-bindings");
LHSNavTreeItem properties = new LHSNavTreeItem(Console.CONSTANTS.common_label_systemProperties(), NameTokens.PropertiesPresenter);
//commonTree.addItem(paths);
commonTree.addItem(interfaces);
commonTree.addItem(sockets);
commonTree.addItem(properties);
}
public Widget asWidget() {
return panel;
}
} |
package uk.co.vurt.taskhelper.client;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.auth.AuthenticationException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import uk.co.vurt.hakken.domain.job.JobDefinition;
import uk.co.vurt.hakken.domain.job.Submission;
import uk.co.vurt.hakken.domain.task.TaskDefinition;
import uk.co.vurt.hakken.security.HashUtils;
import uk.co.vurt.hakken.security.model.LoginResponse;
import uk.co.vurt.taskhelper.domain.JSONUtil;
import android.accounts.Account;
import android.content.Context;
import android.net.ParseException;
import android.preference.PreferenceManager;
import android.util.Log;
final public class NetworkUtilities {
/** The tag used to log to adb console. **/
private static final String TAG = "NetworkUtilities";
/** The Intent extra to store password. **/
public static final String PARAM_PASSWORD = "password";
public static final String PARAM_AUTHTOKEN = "authToken";
/** The Intent extra to store username. **/
public static final String PARAM_USERNAME = "username";
public static final String PARAM_UPDATED = "timestamp";
public static final String USER_AGENT = "TaskHelper/1.0";
public static final int REQUEST_TIMEOUT_MS = 30 * 1000;
// /**TODO: Load Server URL from resource file?? */
// public static final String BASE_URL =
// public static final String BASE_URL =
public static final String AUTH_URI = "/auth/login";
public static final String FETCH_JOBS_URI = "/jobs/for/[username]/[hmac]/since/[timestamp]";
//getBaseUrl(context) + FETCH_JOBS_URI + "/"
//+ parameterMap.get("username") + "/"
//+ HashUtils.hash(parameterMap) + "/since/"
//+ parameterMap.get("timestamp")
// public static final String FETCH_TASK_DEFINITIONS_URI =
// "/taskdefinitions";
public static final String SUBMIT_JOB_DATA_URI = "/submissions/job/";
private NetworkUtilities() {
}
private static String getBaseUrl(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context)
.getString("sync_server", null);
}
/**
* Configures the httpClient to connect to the URL provided.
*/
public static HttpClient getHttpClient() {
HttpClient httpClient = new DefaultHttpClient();
final HttpParams params = httpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, REQUEST_TIMEOUT_MS);
HttpConnectionParams.setSoTimeout(params, REQUEST_TIMEOUT_MS);
ConnManagerParams.setTimeout(params, REQUEST_TIMEOUT_MS);
return httpClient;
}
/**
* Connects to the server, authenticates the provided username and password.
*
* @param username
* The user's username
* @param password
* The user's password
* @param handler
* The hander instance from the calling UI thread.
* @param context
* The context of the calling Activity.
* @return boolean The boolean result indicating whether the user was
* successfully authenticated.
*/
public static LoginResponse authenticate(Context context, String username,
String password) {
final HttpResponse resp;
final ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(PARAM_USERNAME, username));
params.add(new BasicNameValuePair(PARAM_PASSWORD, password));
HttpEntity entity = null;
try {
entity = new UrlEncodedFormEntity(params);
} catch (final UnsupportedEncodingException e) {
// this should never happen.
throw new AssertionError(e);
}
String baseUrl = getBaseUrl(context);
if (Log.isLoggable(TAG, Log.INFO)) {
Log.i(TAG, "Authentication to: " + baseUrl + AUTH_URI);
}
final HttpPost post = new HttpPost(baseUrl + AUTH_URI);
post.addHeader(entity.getContentType());
post.setEntity(entity);
String authToken = null;
LoginResponse response = new LoginResponse();
try {
resp = getHttpClient().execute(post);
if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
JSONObject loginJson;
try {
loginJson = new JSONObject(EntityUtils.toString(resp
.getEntity()));
response.setSuccess(loginJson.getBoolean("success"));
if (loginJson.has("reason")) {
response.setReason(loginJson.getString("reason"));
}
if (loginJson.has("token")) {
response.setToken(loginJson.getString("token"));
}
} catch (org.apache.http.ParseException e) {
response.setSuccess(false);
response.setReason(e.getMessage());
Log.e(TAG, "Unable to parse login response", e);
} catch (JSONException e) {
response.setSuccess(false);
response.setReason(e.getMessage());
Log.e(TAG, "Unable to parse login response", e);
}
// InputStream inputStream = (resp.getEntity() != null) ?
// resp.getEntity().getContent() : null;
// if(inputStream != null){
// BufferedReader reader = new BufferedReader(new
// InputStreamReader(inputStream));
// authToken = reader.readLine().trim();
}
// if((authToken != null) && (authToken.length() > 0)){
// if (Log.isLoggable(TAG, Log.INFO)) {
// Log.i(TAG, "Successful authentication: " + authToken);
// } else {
// if (Log.isLoggable(TAG, Log.INFO)) {
// Log.i(TAG, "Error authenticating" + resp.getStatusLine());
if (Log.isLoggable(TAG, Log.INFO)) {
Log.i(TAG, "Login Response: " + response);
}
} catch (final IOException e) {
if (Log.isLoggable(TAG, Log.INFO)) {
Log.i(TAG, "IOException when getting authtoken", e);
}
response.setReason(e.getMessage());
} finally {
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.v(TAG, "getAuthtoken completing");
}
}
return response;
}
/**
* Submit job data back to the server
*
* essentially json encoded version of the dataitems submitted as form data.
*
* @param account
* @param authToken
* @return
*/
public static boolean submitData(Context context, Account account,
String authToken, Submission submission) {
StringEntity stringEntity;
try {
stringEntity = new StringEntity(JSONUtil.getInstance().toJson(submission));
final HttpPost post = new HttpPost(getBaseUrl(context)
+ SUBMIT_JOB_DATA_URI);
post.setEntity(stringEntity);
post.setHeader("Accept", "application/json");
post.setHeader("Content-type", "application/json");
final HttpResponse httpResponse = getHttpClient().execute(post);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
return true;
} else {
Log.e(TAG, "Data submission failed: "
+ httpResponse.getStatusLine().getStatusCode());
return false;
}
} catch (UnsupportedEncodingException e) {
Log.e(TAG, "Unable to convert submission to JSON", e);
} catch (ClientProtocolException e) {
Log.e(TAG, "Error submitting json", e);
} catch (IOException e) {
Log.e(TAG, "Error submitting json", e);
}
return false;
}
public static List<JobDefinition> fetchJobs(Context context,
Account account, String authToken, Date lastUpdated)
throws JSONException, ParseException, IOException,
AuthenticationException {
final ArrayList<JobDefinition> jobList = new ArrayList<JobDefinition>();
SimpleDateFormat dateFormatter = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss");
Map<String, String> parameterMap = new HashMap<String, String>();
parameterMap.put("username", account.name);
parameterMap.put("timestamp", dateFormatter.format(lastUpdated));
String hmac = HashUtils.hash(parameterMap);
parameterMap.put("hmac", hmac);
String data = fetchData(replaceTokens(getBaseUrl(context) + FETCH_JOBS_URI, parameterMap)/*, null, null, null*/);
// getBaseUrl(context) + FETCH_JOBS_URI + "/"
// + parameterMap.get("username") + "/"
// + HashUtils.hash(parameterMap) + "/since/"
// + parameterMap.get("timestamp"), null, null, null);
Log.d(TAG, "JOBS DATA: " + data);
final JSONArray jobs = new JSONArray(data);
for (int i = 0; i < jobs.length(); i++) {
jobList.add(JSONUtil.getInstance().parseJobDefinition(jobs.getJSONObject(i).toString()));
}
return jobList;
}
private static String fetchData(String url /*, Account account,
String authToken, ArrayList<NameValuePair> params*/)
throws ClientProtocolException, IOException,
AuthenticationException {
Log.d(TAG, "Fetching data from: " + url);
String data = null;
// if (params == null) {
// params = new ArrayList<NameValuePair>();
// if (account != null) {
// params.add(new BasicNameValuePair(PARAM_USERNAME, account.name));
// params.add(new BasicNameValuePair(PARAM_AUTHTOKEN, authToken));
// Log.i(TAG, params.toString());
// HttpEntity entity = new UrlEncodedFormEntity(params);
// final HttpPost post = new HttpPost(url);
// post.addHeader(entity.getContentType());
// post.setEntity(entity);
final HttpGet get = new HttpGet(url);
// final HttpResponse httpResponse = getHttpClient().execute(post);
final HttpResponse httpResponse = getHttpClient().execute(get);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
data = EntityUtils.toString(httpResponse.getEntity());
} else if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
Log.e(TAG,
"Authentication exception in fetching remote task definitions");
throw new AuthenticationException();
} else {
Log.e(TAG, "Server error in fetching remote task definitions: "
+ httpResponse.getStatusLine());
throw new IOException();
}
return data;
}
public static List<TaskDefinition> fetchTaskDefinitions(Account account,
String authToken, Date lastUpdated) throws JSONException,
ParseException, IOException, AuthenticationException {
final ArrayList<TaskDefinition> definitionList = new ArrayList<TaskDefinition>();
/**
* I'm commenting this out for the time being as the current emphasis is
* on working with lists of pre-set jobs, rather than choosing from a
* list of possible tasks. It'll be reinstated as and when required.
*/
// final ArrayList<NameValuePair> params = new
// ArrayList<NameValuePair>();
// params.add(new BasicNameValuePair(PARAM_USERNAME, account.name));
// params.add(new BasicNameValuePair(PARAM_AUTHTOKEN, authToken));
// if (lastUpdated != null) {
// final SimpleDateFormat formatter = new
// SimpleDateFormat("yyyy/MM/dd HH:mm");
// formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
// params.add(new BasicNameValuePair(PARAM_UPDATED,
// formatter.format(lastUpdated)));
// Log.i(TAG, params.toString());
// HttpEntity entity = null;
// entity = new UrlEncodedFormEntity(params);
// final HttpPost post = new HttpPost(FETCH_TASK_DEFINITIONS_URI);
// post.addHeader(entity.getContentType());
// post.setEntity(entity);
// final HttpResponse resp = getHttpClient().execute(post);
// final String response = EntityUtils.toString(resp.getEntity());
// if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// // Succesfully connected to the samplesyncadapter server and
// // authenticated.
// final JSONArray definitions = new JSONArray(response);
// Log.d(TAG, response);
// for (int i = 0; i < definitions.length(); i++) {
// definitionList.add(TaskDefinition.valueOf(definitions.getJSONObject(i)));
// } else {
// if (resp.getStatusLine().getStatusCode() ==
// HttpStatus.SC_UNAUTHORIZED) {
// Log.e(TAG,
// "Authentication exception in fetching remote task definitions");
// throw new AuthenticationException();
// } else {
// Log.e(TAG, "Server error in fetching remote task definitions: " +
// resp.getStatusLine());
// throw new IOException();
return definitionList;
}
/**
* Utility method to replace named tokens in a string
*
* @param text
* @param replacements
* @return
*/
public static String replaceTokens(String text,
Map<String, String> replacements) {
Pattern pattern = Pattern.compile("\\[(.+?)\\]");
Matcher matcher = pattern.matcher(text);
StringBuffer buffer = new StringBuffer();
while (matcher.find()) {
String replacement = replacements.get(matcher.group(1));
if (replacement != null) {
matcher.appendReplacement(buffer, "");
buffer.append(replacement);
}
}
matcher.appendTail(buffer);
return buffer.toString();
}
} |
package com.heartbeat.pin.command.system;
import com.heartbeat.common.cli.RuntimeCommandException;
import com.heartbeat.common.cli.RuntimeCommandExec;
import com.heartbeat.pin.Pin;
import com.heartbeat.pin.command.PinCommand;
import com.heartbeat.pin.command.PinCommandException;
import java.io.File;
import java.util.Locale;
import static java.lang.String.format;
/**
* An implementation of {@link PinCommand} which holds the specific commands for C.H.I.P.
*/
public class ChipSystemPinCommand implements PinCommand {
@Override
public Pin.Mode getMode(Pin pin) throws PinCommandException {
try {
String result = RuntimeCommandExec.exec(Commands.GET_MODE.command(pin));
return Pin.Mode.valueOf(result.toUpperCase(Locale.ENGLISH));
} catch (RuntimeCommandException e) {
throw new PinCommandException(e);
}
}
@Override
public void setMode(Pin pin, Pin.Mode mode) throws PinCommandException {
try {
switch (mode) {
case IN:
RuntimeCommandExec.exec(Commands.SET_MODE_IN.command(pin));
break;
case OUT:
RuntimeCommandExec.exec(Commands.SET_MODE_OUT.command(pin));
break;
default:
throw new PinCommandException("System command is missing for mode " + mode.name());
}
return;
} catch (RuntimeCommandException e) {
throw new PinCommandException(e);
}
}
@Override
public void enable(Pin pin) throws PinCommandException {
try {
RuntimeCommandExec.exec(Commands.ENABLE.command(pin));
return;
} catch (RuntimeCommandException e) {
throw new PinCommandException(e);
}
}
@Override
public void disable(Pin pin) throws PinCommandException {
try {
RuntimeCommandExec.exec(Commands.DISABLE.command(pin));
return;
} catch (RuntimeCommandException e) {
throw new PinCommandException(e);
}
}
@Override
public boolean read(Pin pin) throws PinCommandException {
try {
String result = RuntimeCommandExec.exec(Commands.READ.command(pin));
switch (result) {
case "1":
return true;
case "0":
return false;
default:
throw new PinCommandException("Pin value is invalid :" + result);
}
} catch (RuntimeCommandException e) {
throw new PinCommandException(e);
}
}
@Override
public void write(Pin pin, boolean value) throws PinCommandException {
try {
if (value)
RuntimeCommandExec.exec(Commands.WRITE_HIGH.command(pin));
else
RuntimeCommandExec.exec(Commands.WRITE_LOW.command(pin));
} catch (RuntimeCommandException e) {
throw new PinCommandException(e);
}
}
@Override
public File path(Pin pin) {
return new File(Commands.PATH.command(pin));
}
/**
* Template of the commands.
*/
private enum Commands {
GET_MODE("cat /sys/class/gpio/gpio%s/direction"),//in/out
SET_MODE_IN("echo in > /sys/class/gpio/gpio%s/direction"),
SET_MODE_OUT("echo out > /sys/class/gpio/gpio%s/direction"),
ENABLE("echo %s | sudo tee /sys/class/gpio/export"),
DISABLE("echo %s | sudo tee /sys/class/gpio/unexport"),
READ("cat /sys/class/gpio/gpio%s/value"),
WRITE_HIGH("echo 1 > /sys/class/gpio/gpio%s/value"),
WRITE_LOW("echo 0 > /sys/class/gpio/gpio%s/value"),
PATH("/sys/class/gpio/gpio%s");
private final String command;
Commands(String command) {
this.command = command;
}
/**
* Returns sys command template of the command.
*
* @return
*/
public String command() {
return command;
}
/**
* Returns sys command of the command for the given Pin.
*
* @return
*/
public String command(Pin pin) {
return format(command(), pin.getCode());
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.