answer
stringlengths 17
10.2M
|
|---|
package mu.nu.nullpo.gui.slick;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import javax.swing.JOptionPane;
import mu.nu.nullpo.game.net.NetObserverClient;
import mu.nu.nullpo.game.play.GameEngine;
import mu.nu.nullpo.util.CustomProperties;
import mu.nu.nullpo.util.ModeManager;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.lwjgl.opengl.Display;
import org.newdawn.slick.AppGameContainer;
import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.ScalableGame;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.StateBasedGame;
import org.newdawn.slick.util.Log;
/**
* NullpoMino SlickVersion
*/
public class NullpoMinoSlick extends StateBasedGame {
/** Log */
static Logger log = Logger.getLogger(NullpoMinoSlick.class);
/** Linescount */
public static String[] programArgs;
/** Save settingsProperty file */
public static CustomProperties propConfig;
/** Save settingsProperty file (Version) */
public static CustomProperties propGlobal;
/** Property file */
public static CustomProperties propMusic;
/** ObserverProperty file */
public static CustomProperties propObserver;
/** Default language file */
public static CustomProperties propLangDefault;
public static CustomProperties propLang;
/** Default game mode description file */
public static CustomProperties propDefaultModeDesc;
/** Game mode description file */
public static CustomProperties propModeDesc;
/** Screenshot */
public static BufferedImage ssImage;
/** Mode */
public static ModeManager modeManager;
/** AppGameContainer */
public static AppGameContainer appGameContainer;
public static StateLoading stateLoading;
public static StateTitle stateTitle;
public static StateInGame stateInGame;
/** Mode */
public static StateSelectMode stateSelectMode;
public static StateReplaySelect stateReplaySelect;
public static StateConfigMainMenu stateConfigMainMenu;
public static StateConfigGeneral stateConfigGeneral;
public static StateConfigRuleSelect stateConfigRuleSelect;
public static StateConfigAISelect stateConfigAISelect;
public static StateConfigKeyboard stateConfigKeyboard;
/** Joystick button */
public static StateConfigJoystickButton stateConfigJoystickButton;
public static StateNetGame stateNetGame;
/** Joystick Menu */
public static StateConfigJoystickMain stateConfigJoystickMain;
/** Joystick */
public static StateConfigJoystickTest stateConfigJoystickTest;
public static StateConfigGameTuning stateConfigGameTuning;
/** Style select state */
public static StateConfigRuleStyleSelect stateConfigRuleStyleSelect;
/** Keyboard menu navigation settings state */
public static StateConfigKeyboardNavi stateConfigKeyboardNavi;
/** Keyboard Reset menu state */
public static StateConfigKeyboardReset stateConfigKeyboardReset;
/** Rule select (after mode selection) */
public static StateSelectRuleFromList stateSelectRuleFromList;
/** Mode folder select */
public static StateSelectModeFolder stateSelectModeFolder;
/** Timing of alternate FPS sleep (false=render true=update) */
public static boolean alternateFPSTiming;
/** Allow dynamic adjust of target FPS (as seen in Swing version) */
public static boolean alternateFPSDynamicAdjust;
/** Perfect FPS mode (more accurate, eats more CPU) */
public static boolean alternateFPSPerfectMode;
/** Execute Thread.yield() during Perfect FPS mode */
public static boolean alternateFPSPerfectYield;
/** Target FPS */
public static int altMaxFPS;
/** Current max FPS */
public static int altMaxFPSCurrent;
/** Used for FPS calculation */
protected static long periodCurrent;
/** FPS */
protected static long beforeTime;
/** FPS */
protected static long overSleepTime;
/** FPS */
protected static int noDelays;
/** FPS */
protected static long calcInterval = 0;
/** FPS */
protected static long prevCalcTime = 0;
/** frame count */
protected static long frameCount = 0;
/** FPS */
public static double actualFPS = 0.0;
/** FPSDecimalFormat */
public static DecimalFormat df = new DecimalFormat("0.0");
/** Used by perfect fps mode */
public static long perfectFPSDelay = 0;
/** Observer */
public static NetObserverClient netObserverClient;
/** true if read keyboard input from JInput */
public static boolean useJInputKeyboard;
/**
* count
* @param args Linescount
*/
public static void main(String[] args) {
programArgs = args;
PropertyConfigurator.configure("config/etc/log_slick.cfg");
Log.setLogSystem(new LogSystemLog4j());
log.info("NullpoMinoSlick Start");
try {
log.info("Driver adapter:" + Display.getAdapter() + ", Driver version:" + Display.getVersion());
} catch (Throwable e) {
log.warn("Cannot get driver informations", e);
}
propConfig = new CustomProperties();
propGlobal = new CustomProperties();
propMusic = new CustomProperties();
try {
FileInputStream in = new FileInputStream("config/setting/slick.cfg");
propConfig.load(in);
in.close();
} catch(IOException e) {}
loadGlobalConfig();
try {
FileInputStream in = new FileInputStream("config/setting/music.cfg");
propMusic.load(in);
in.close();
} catch (IOException e) {}
propLangDefault = new CustomProperties();
try {
FileInputStream in = new FileInputStream("config/lang/slick_default.properties");
propLangDefault.load(in);
in.close();
} catch(IOException e) {
log.error("Couldn't load default UI language file", e);
}
propLang = new CustomProperties();
try {
FileInputStream in = new FileInputStream("config/lang/slick_" + Locale.getDefault().getCountry() + ".properties");
propLang.load(in);
in.close();
} catch(IOException e) {}
// Game mode description
propDefaultModeDesc = new CustomProperties();
try {
FileInputStream in = new FileInputStream("config/lang/modedesc_default.properties");
propDefaultModeDesc.load(in);
in.close();
} catch(IOException e) {
log.error("Couldn't load default mode description file", e);
}
propModeDesc = new CustomProperties();
try {
FileInputStream in = new FileInputStream("config/lang/modedesc_" + Locale.getDefault().getCountry() + ".properties");
propModeDesc.load(in);
in.close();
} catch(IOException e) {}
// Mode
modeManager = new ModeManager();
try {
BufferedReader txtMode = new BufferedReader(new FileReader("config/list/mode.lst"));
modeManager.loadGameModes(txtMode);
txtMode.close();
} catch (IOException e) {
log.error("Mode list load failed", e);
}
// Set default rule selections
try {
CustomProperties propDefaultRule = new CustomProperties();
FileInputStream in = new FileInputStream("config/list/global_defaultrule.properties");
propDefaultRule.load(in);
in.close();
for(int pl = 0; pl < 2; pl++)
for(int i = 0; i < GameEngine.MAX_GAMESTYLE; i++) {
// TETROMINO
if(i == 0) {
if(propGlobal.getProperty(pl + ".rule") == null) {
propGlobal.setProperty(pl + ".rule", propDefaultRule.getProperty("default.rule", ""));
propGlobal.setProperty(pl + ".rulefile", propDefaultRule.getProperty("default.rulefile", ""));
propGlobal.setProperty(pl + ".rulename", propDefaultRule.getProperty("default.rulename", ""));
}
}
// etc
else {
if(propGlobal.getProperty(pl + ".rule." + i) == null) {
propGlobal.setProperty(pl + ".rule." + i, propDefaultRule.getProperty("default.rule." + i, ""));
propGlobal.setProperty(pl + ".rulefile." + i, propDefaultRule.getProperty("default.rulefile." + i, ""));
propGlobal.setProperty(pl + ".rulename." + i, propDefaultRule.getProperty("default.rulename." + i, ""));
}
}
}
} catch (Exception e) {}
// Use JInput option
useJInputKeyboard = false;
//log.debug("args.length:" + args.length);
if( (args.length > 0) && (args[0].equals("-j") || args[0].equals("/j")) ) {
useJInputKeyboard = true;
log.info("-j option is used. Use JInput to read keyboard input.");
}
perfectFPSDelay = System.nanoTime();
try {
int sWidth = propConfig.getProperty("option.screenwidth", 640);
int sHeight = propConfig.getProperty("option.screenheight", 480);
NullpoMinoSlick obj = new NullpoMinoSlick();
if((sWidth != 640) || (sHeight != 480)) {
ScalableGame sObj = new ScalableGame(obj, 640, 480, true);
appGameContainer = new AppGameContainer(sObj);
} else {
appGameContainer = new AppGameContainer(obj);
}
appGameContainer.setShowFPS(false);
appGameContainer.setClearEachFrame(false);
appGameContainer.setMinimumLogicUpdateInterval(0);
appGameContainer.setMaximumLogicUpdateInterval(0);
appGameContainer.setUpdateOnlyWhenVisible(false);
appGameContainer.setForceExit(false);
appGameContainer.setDisplayMode(sWidth, sHeight, propConfig.getProperty("option.fullscreen", false));
appGameContainer.start();
} catch (SlickException e) {
log.fatal("Game initialize failed (SlickException)", e);
// Get driver name and version
String strDriverName = null;
String strDriverVersion = null;
try {
strDriverName = Display.getAdapter();
strDriverVersion = Display.getVersion();
} catch (Throwable e2) {
log.warn("Cannot get driver informations", e2);
}
if(strDriverName == null) strDriverName = "(Unknown)";
if(strDriverVersion == null) strDriverVersion = "(Unknown)";
// Display an error dialog
String strErrorTitle = getUIText("InitFailedMessage_Title");
String strErrorMessage = String.format(getUIText("InitFailedMessage_Body"), strDriverName, strDriverVersion, e.toString());
JOptionPane.showMessageDialog(null, strErrorMessage, strErrorTitle, JOptionPane.ERROR_MESSAGE);
// Exit
System.exit(-1);
} catch (Throwable e) {
log.fatal("Game initialize failed (NON-SlickException)", e);
System.exit(-2);
}
stopObserverClient();
if(stateNetGame.netLobby != null) {
log.debug("Calling netLobby shutdown routine");
stateNetGame.netLobby.shutdown();
}
System.exit(0);
}
public static void saveConfig() {
try {
FileOutputStream out = new FileOutputStream("config/setting/slick.cfg");
propConfig.store(out, "NullpoMino Slick-frontend Config");
out.close();
} catch(IOException e) {
log.error("Failed to save Slick-specific config", e);
}
try {
FileOutputStream out = new FileOutputStream("config/setting/global.cfg");
propGlobal.store(out, "NullpoMino Global Config");
out.close();
} catch(IOException e) {
log.error("Failed to save global config", e);
}
}
/**
* (Re-)Load global config file
*/
public static void loadGlobalConfig() {
try {
FileInputStream in = new FileInputStream("config/setting/global.cfg");
propGlobal.load(in);
in.close();
} catch(IOException e) {}
}
public static void setGeneralConfig() {
appGameContainer.setTargetFrameRate(-1);
beforeTime = System.nanoTime();
overSleepTime = 0L;
noDelays = 0;
alternateFPSTiming = propConfig.getProperty("option.alternateFPSTiming", true);
alternateFPSDynamicAdjust = propConfig.getProperty("option.alternateFPSDynamicAdjust", false);
alternateFPSPerfectMode = propConfig.getProperty("option.alternateFPSPerfectMode", true);
alternateFPSPerfectYield = propConfig.getProperty("option.alternateFPSPerfectYield", true);
altMaxFPS = propConfig.getProperty("option.maxfps", 60);
altMaxFPSCurrent = altMaxFPS;
periodCurrent = (long) (1.0 / altMaxFPSCurrent * 1000000000);
appGameContainer.setVSync(propConfig.getProperty("option.vsync", false));
appGameContainer.setAlwaysRender(!alternateFPSTiming);
int sevolume = propConfig.getProperty("option.sevolume", 128);
appGameContainer.setSoundVolume(sevolume / (float)128);
ControllerManager.method = propConfig.getProperty("option.joymethod", ControllerManager.CONTROLLER_METHOD_SLICK_DEFAULT);
ControllerManager.controllerID[0] = propConfig.getProperty("joyUseNumber.p0", -1);
ControllerManager.controllerID[1] = propConfig.getProperty("joyUseNumber.p1", -1);
int joyBorder = propConfig.getProperty("joyBorder.p0", 0);
ControllerManager.border[0] = joyBorder / (float)32768;
joyBorder = propConfig.getProperty("joyBorder.p1", 0);
ControllerManager.border[1] = joyBorder / (float)32768;
ControllerManager.ignoreAxis[0] = propConfig.getProperty("joyIgnoreAxis.p0", false);
ControllerManager.ignoreAxis[1] = propConfig.getProperty("joyIgnoreAxis.p1", false);
ControllerManager.ignorePOV[0] = propConfig.getProperty("joyIgnorePOV.p0", false);
ControllerManager.ignorePOV[1] = propConfig.getProperty("joyIgnorePOV.p1", false);
//useJInputKeyboard = propConfig.getProperty("option.useJInputKeyboard", true);
}
/**
* Screenshot
* @param container GameContainer
* @param g Graphics
*/
public static void saveScreenShot(GameContainer container, Graphics g) {
// Filename
String dir = propGlobal.getProperty("custom.screenshot.directory", "ss");
Calendar c = Calendar.getInstance();
DateFormat dfm = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
String filename = dir + "/" + dfm.format(c.getTime()) + ".png";
log.info("Saving screenshot to " + filename);
// Screenshot
try {
File ssfolder = new File(dir);
if (!ssfolder.exists()) {
if (ssfolder.mkdir()) {
log.info("Created screenshot folder: " + dir);
} else {
log.info("Couldn't create screenshot folder at "+ dir);
}
}
int screenWidth = container.getWidth();
int screenHeight = container.getHeight();
Image screenImage = new Image(screenWidth, screenHeight);
g.copyArea(screenImage, 0, 0);
//ImageOut.write(screenImage, filename);
if(ssImage == null) {
ssImage = new BufferedImage(screenWidth, screenHeight, BufferedImage.TYPE_INT_RGB);
}
for(int i = 0; i < screenWidth; i++)
for(int j = 0; j < screenHeight; j++) {
Color color = screenImage.getColor(i, j + 1); // Y-coordinate+1
int rgb =
((color.getRed() & 0x000000FF) << 16) |
((color.getGreen() & 0x000000FF) << 8) |
((color.getBlue() & 0x000000FF) << 0);
ssImage.setRGB(i, j, rgb);
}
javax.imageio.ImageIO.write(ssImage, "png", new File(filename));
} catch (Throwable e) {
log.error("Failed to create screen shot", e);
}
}
/**
* UI
* @param str
* @return UI (str
*/
public static String getUIText(String str) {
String result = propLang.getProperty(str);
if(result == null) {
result = propLangDefault.getProperty(str, str);
}
return result;
}
/**
* FPS cap routine
*/
public static void alternateFPSSleep() {
alternateFPSSleep(false);
}
/**
* FPS cap routine
* @param ingame <code>true</code> if during the gameplay
*/
public static void alternateFPSSleep(boolean ingame) {
int maxfps = altMaxFPSCurrent;
if(maxfps > 0) {
boolean sleepFlag = false;
long afterTime, timeDiff, sleepTime, sleepTimeInMillis;
afterTime = System.nanoTime();
timeDiff = afterTime - beforeTime;
sleepTime = (periodCurrent - timeDiff) - overSleepTime;
sleepTimeInMillis = sleepTime / 1000000L;
if((sleepTimeInMillis >= 10) && (!alternateFPSPerfectMode || !ingame)) {
// If it is possible to use sleep
if(maxfps > 0) {
try {
Thread.sleep(sleepTimeInMillis);
} catch(InterruptedException e) {}
}
// sleep() oversleep
overSleepTime = (System.nanoTime() - afterTime) - sleepTime;
perfectFPSDelay = System.nanoTime();
sleepFlag = true;
} else if((alternateFPSPerfectMode && ingame) || (sleepTime > 0)) {
// Perfect FPS
overSleepTime = 0L;
if(altMaxFPSCurrent > altMaxFPS + 5) altMaxFPSCurrent = altMaxFPS + 5;
if(alternateFPSPerfectYield) {
while(System.nanoTime() < perfectFPSDelay + 1000000000 / altMaxFPS) {Thread.yield();}
} else {
while(System.nanoTime() < perfectFPSDelay + 1000000000 / altMaxFPS) {}
}
perfectFPSDelay += 1000000000 / altMaxFPS;
sleepFlag = true;
}
if(!sleepFlag) {
// Impossible to sleep!
overSleepTime = 0L;
if(++noDelays >= 16) {
Thread.yield();
noDelays = 0;
}
perfectFPSDelay = System.nanoTime();
}
beforeTime = System.nanoTime();
calcFPS(ingame, periodCurrent);
} else {
periodCurrent = (long) (1.0 / 60 * 1000000000);
calcFPS(ingame, periodCurrent);
}
}
/**
* FPS
* @param period FPS
*/
protected static void calcFPS(boolean ingame, long period) {
frameCount++;
calcInterval += period;
// 1FPS
if(calcInterval >= 1000000000L) {
long timeNow = System.nanoTime();
// time
long realElapsedTime = timeNow - prevCalcTime;
// FPS
// realElapsedTimenss
actualFPS = ((double) frameCount / realElapsedTime) * 1000000000L;
frameCount = 0L;
calcInterval = 0L;
prevCalcTime = timeNow;
// Set new target fps
if((altMaxFPS > 0) && (alternateFPSDynamicAdjust) && (!alternateFPSPerfectMode)) {
if(ingame) {
if(actualFPS < altMaxFPS - 1) {
// Too Slow
altMaxFPSCurrent++;
if(altMaxFPSCurrent > altMaxFPS + 20) altMaxFPSCurrent = altMaxFPS + 20;
periodCurrent = (long) (1.0 / altMaxFPSCurrent * 1000000000);
} else if(actualFPS > altMaxFPS + 1) {
// Too Fast
altMaxFPSCurrent
if(altMaxFPSCurrent < altMaxFPS - 0) altMaxFPSCurrent = altMaxFPS - 0;
if(altMaxFPSCurrent < 1) altMaxFPSCurrent = 1;
periodCurrent = (long) (1.0 / altMaxFPSCurrent * 1000000000);
}
} else if((!ingame) && (altMaxFPSCurrent != altMaxFPS)) {
altMaxFPSCurrent = altMaxFPS;
periodCurrent = (long) (1.0 / altMaxFPSCurrent * 1000000000);
}
}
}
}
/**
* Constructor
*/
public NullpoMinoSlick() {
super("NullpoMino (Now Loading...)");
}
@Override
public void initStatesList(GameContainer container) throws SlickException {
stateLoading = new StateLoading();
stateTitle = new StateTitle();
stateInGame = new StateInGame();
stateSelectMode = new StateSelectMode();
stateReplaySelect = new StateReplaySelect();
stateConfigMainMenu = new StateConfigMainMenu();
stateConfigGeneral = new StateConfigGeneral();
stateConfigRuleSelect = new StateConfigRuleSelect();
stateConfigAISelect = new StateConfigAISelect();
stateConfigKeyboard = new StateConfigKeyboard();
stateConfigJoystickButton = new StateConfigJoystickButton();
stateNetGame = new StateNetGame();
stateConfigJoystickMain = new StateConfigJoystickMain();
stateConfigJoystickTest = new StateConfigJoystickTest();
stateConfigGameTuning = new StateConfigGameTuning();
stateConfigRuleStyleSelect = new StateConfigRuleStyleSelect();
stateConfigKeyboardNavi = new StateConfigKeyboardNavi();
stateConfigKeyboardReset = new StateConfigKeyboardReset();
stateSelectRuleFromList = new StateSelectRuleFromList();
stateSelectModeFolder = new StateSelectModeFolder();
addState(stateLoading);
addState(stateTitle);
addState(stateInGame);
addState(stateSelectMode);
addState(stateReplaySelect);
addState(stateConfigMainMenu);
addState(stateConfigGeneral);
addState(stateConfigRuleSelect);
addState(stateConfigAISelect);
addState(stateConfigKeyboard);
addState(stateConfigJoystickButton);
addState(stateNetGame);
addState(stateConfigJoystickMain);
addState(stateConfigJoystickTest);
addState(stateConfigGameTuning);
addState(stateConfigRuleStyleSelect);
addState(stateConfigKeyboardNavi);
addState(stateConfigKeyboardReset);
addState(stateSelectRuleFromList);
addState(stateSelectModeFolder);
}
/**
* FPS display
* @param container GameContainer
*/
public static void drawFPS(GameContainer container) {
drawFPS(container, false);
}
/**
* FPS display
* @param container GameContainer
*/
public static void drawFPS(GameContainer container, boolean ingame) {
if(propConfig.getProperty("option.showfps", true) == true) {
if(!alternateFPSDynamicAdjust || alternateFPSPerfectMode || !ingame)
NormalFont.printFont(0, 480 - 16, df.format(actualFPS), NormalFont.COLOR_BLUE);
else
NormalFont.printFont(0, 480 - 16, df.format(actualFPS) + "/" + altMaxFPSCurrent, NormalFont.COLOR_BLUE);
}
}
/**
* Observer
*/
public static void startObserverClient() {
log.debug("startObserverClient called");
propObserver = new CustomProperties();
try {
FileInputStream in = new FileInputStream("config/setting/netobserver.cfg");
propObserver.load(in);
in.close();
} catch (IOException e) {}
if(propObserver.getProperty("observer.enable", false) == false) return;
if((netObserverClient != null) && netObserverClient.isConnected()) return;
String host = propObserver.getProperty("observer.host", "");
int port = propObserver.getProperty("observer.port", NetObserverClient.DEFAULT_PORT);
if((host.length() > 0) && (port > 0)) {
netObserverClient = new NetObserverClient(host, port);
netObserverClient.start();
}
}
/**
* Observer
*/
public static void stopObserverClient() {
log.debug("stopObserverClient called");
if(netObserverClient != null) {
if(netObserverClient.isConnected()) {
netObserverClient.send("disconnect\n");
}
netObserverClient.threadRunning = false;
netObserverClient.connectedFlag = false;
netObserverClient = null;
}
propObserver = null;
}
/**
* Observer
*/
public static void drawObserverClient() {
if((netObserverClient != null) && netObserverClient.isConnected()) {
int fontcolor = NormalFont.COLOR_BLUE;
if(netObserverClient.getObserverCount() > 1) fontcolor = NormalFont.COLOR_GREEN;
if(netObserverClient.getObserverCount() > 0 && netObserverClient.getPlayerCount() > 0) fontcolor = NormalFont.COLOR_RED;
String strObserverInfo = String.format("%d/%d", netObserverClient.getObserverCount(), netObserverClient.getPlayerCount());
String strObserverString = String.format("%40s", strObserverInfo);
NormalFont.printFont(0, 480 - 16, strObserverString, fontcolor);
}
}
}
|
package nl.mvdr.tinustris.configuration;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import nl.mvdr.tinustris.gui.GraphicsStyle;
/**
* Game configuration.
*
* Sensible defaults have been included for all configuration properties, using default methods.
*
* @author Martijn van de Rijdt
*/
public interface Configuration {
/**
* Configuration for each of the players in this game. Should contain at least one value.
*
* @return configurations
*/
default List<PlayerConfiguration> getPlayerConfigurations() {
// default configuration with an empty player name
return Collections.singletonList(() -> "");
}
/**
* Graphical style of the blocks in the grid.
*
* @return style
*/
default GraphicsStyle getGraphicsStyle() {
return GraphicsStyle.defaultStyle();
}
/**
* Specification of the behavior of the actual gameplay.
*
* @return behavior definition
*/
default Behavior getBehavior() {
return Behavior.defaultBehavior();
}
/**
* Default starting level. Only relevant for certain behaviors.
*
* @return starting level
*/
default int getStartLevel() {
return 0;
}
/** @return configuration for networking */
default NetcodeConfiguration getNetcodeConfiguration() {
return Collections::emptyList;
}
/** @return random seed for the gap generator */
default long getGapRandomSeed() {
return new Random().nextLong();
}
/** @return random seed for the tetromino generator */
default long getTetrominoRandomSeed() {
return new Random().nextLong();
}
}
|
package net.devrieze.chatterbox.client;
import net.devrieze.chatterbox.shared.MessagePojo;
import com.google.gwt.xml.client.NodeList;
import com.google.gwt.xml.client.XMLParser;
public class Message extends MessagePojo{
private static final long serialVersionUID = -24721040835336897L;
public Message(MessagePojo pPojo) {
super(pPojo);
}
/** @deprecated Does not record sender */
@Deprecated
public Message(String index, String epoch, NodeList content) {
this(index, "nobody@example.com", epoch, content);
}
public Message(String index, String pSender, String epoch, NodeList content) {
super(parseIndex(index), content.toString(), parseEpoch(epoch), pSender);
}
private static long parseIndex(String pIndex) {
final long result = Long.parseLong(pIndex);
if (result<0) {
throw new IllegalArgumentException("Index can not be smaller than zero");
}
return result;
}
private static long parseEpoch(String pEpoch) {
return Long.parseLong(pEpoch);
}
/** @deprecated Does not record sender */
@Deprecated
public Message(int index, long epoch, NodeList content) {
super(index, "nobody@example.com", epoch, content.toString());
}
public Message(int index, String pSender, long epoch, NodeList content) {
super(index, pSender, epoch, content.toString());
}
/** @deprecated This is inefficient, just set the content with setHtml */
@Deprecated
public NodeList getContent() {
return XMLParser.parse("<r>"+getMessageBody()+"</r>").getDocumentElement().getFirstChild().getChildNodes();
}
}
|
package org.sakaiproject.profilewow.tool.producers;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.api.common.edu.person.SakaiPerson;
import org.sakaiproject.api.common.edu.person.SakaiPersonManager;
import org.sakaiproject.authz.api.SecurityService;
import org.sakaiproject.entity.api.ResourceProperties;
import org.sakaiproject.profilewow.tool.producers.templates.PasswordFormRenderer;
import org.sakaiproject.profilewow.tool.producers.templates.ProfilePicRenderer;
import org.sakaiproject.tool.api.ToolManager;
import org.sakaiproject.user.api.User;
import org.sakaiproject.user.api.UserDirectoryService;
import uk.org.ponder.messageutil.MessageLocator;
import uk.org.ponder.messageutil.TargettedMessageList;
import uk.org.ponder.rsf.components.UIBranchContainer;
import uk.org.ponder.rsf.components.UICommand;
import uk.org.ponder.rsf.components.UIContainer;
import uk.org.ponder.rsf.components.UIELBinding;
import uk.org.ponder.rsf.components.UIForm;
import uk.org.ponder.rsf.components.UIInput;
import uk.org.ponder.rsf.components.UIInternalLink;
import uk.org.ponder.rsf.components.UIMessage;
import uk.org.ponder.rsf.components.UIOutput;
import uk.org.ponder.rsf.components.UISelect;
import uk.org.ponder.rsf.components.UISelectChoice;
import uk.org.ponder.rsf.components.UISelectLabel;
import uk.org.ponder.rsf.components.decorators.UILabelTargetDecorator;
import uk.org.ponder.rsf.flow.jsfnav.NavigationCase;
import uk.org.ponder.rsf.flow.jsfnav.NavigationCaseReporter;
import uk.org.ponder.rsf.view.ComponentChecker;
import uk.org.ponder.rsf.view.ViewComponentProducer;
import uk.org.ponder.rsf.viewstate.SimpleViewParameters;
import uk.org.ponder.rsf.viewstate.ViewParameters;
public class EditProducer implements ViewComponentProducer, NavigationCaseReporter {
public static final String VIEW_ID = "editProfile";
private static Log log = LogFactory.getLog(EditProducer.class);
public String getViewID() {
return VIEW_ID;
}
private SakaiPersonManager spm;
public void setSakaiPersonManager(SakaiPersonManager in) {
spm = in;
}
private MessageLocator messageLocator;
public void setMessageLocator(MessageLocator messageLocator) {
this.messageLocator = messageLocator;
}
private UserDirectoryService userDirectoryService;
public void setUserDirectoryService(UserDirectoryService uds) {
this.userDirectoryService = uds;
}
private SecurityService securityService;
public void setSecurityService(SecurityService securityService) {
this.securityService = securityService;
}
private ToolManager toolManager;
public void setToolManager(ToolManager toolManager) {
this.toolManager = toolManager;
}
private TargettedMessageList tml;
public void setTargettedMessageList(TargettedMessageList tml) {
this.tml = tml;
}
private ProfilePicRenderer profilePicRenderer;
public void setProfilePicRenderer(ProfilePicRenderer profilePicRenderer) {
this.profilePicRenderer = profilePicRenderer;
}
private PasswordFormRenderer passwordFormRenderer;
public void setPasswordFormRenderer(PasswordFormRenderer passwordFormRenderer) {
this.passwordFormRenderer = passwordFormRenderer;
}
public void fillComponents(UIContainer tofill, ViewParameters viewparams,
ComponentChecker checker) {
//process any messages
if (tml.size() > 0) {
for (int i = 0; i < tml.size(); i ++ ) {
UIBranchContainer errorRow = UIBranchContainer.make(tofill,"error-row:", Integer.valueOf(i).toString());
//if (tml.messageAt(i).args != null ) {
//UIMessage.make(errorRow,"error",tml.messageAt(i).acquireMessageCode(),(String[])tml.messageAt(i).args[0]);
//} else {
UIMessage.make(errorRow,"error",tml.messageAt(i).acquireMessageCode());
}
}
UIForm form = UIForm.make(tofill,"edit-form");
SakaiPerson sPerson = spm.getSakaiPerson(spm.getUserMutableType());
if (sPerson == null) {
log.debug("creating a new profile!");
sPerson = spm.create(userDirectoryService.getCurrentUser().getId(), spm.getUserMutableType());
spm.save(sPerson);
}
log.debug("got profile for: " + sPerson.getGivenName() + " " + sPerson.getSurname());
log.debug("uuid: " + sPerson.getUid() + ", agent_uuid: " + sPerson.getAgentUuid());
//makeProfilePic(tofill, sPerson);
profilePicRenderer.makeProfilePic(tofill, "profile-pic:", sPerson);
passwordFormRenderer.renderPasswordForm(tofill, "passForm:", sPerson);
String otpBean = "profileBeanLocator." + sPerson.getUid() + ".sakaiPerson";
boolean enableEdit = this.canEditeName(userDirectoryService.getCurrentUser());
if (!enableEdit) {
//fName.decorators = new DecoratorList(new UIDisabledDecorator(true));
//lName.decorators = new DecoratorList(new UIDisabledDecorator(true));
UIOutput.make(form, "firstname-text",sPerson.getGivenName());
UIOutput.make(form, "lastname-text", sPerson.getSurname());
form.parameters.add(new UIELBinding(otpBean + ".givenName" ,sPerson.getGivenName()));
form.parameters.add(new UIELBinding(otpBean + ".surname", sPerson.getSurname()));
} else {
UIInput.make(form,"editProfileForm-first_name", otpBean + ".givenName" ,sPerson.getGivenName());
UIInput.make(form,"editProfileForm-lname", otpBean + ".surname", sPerson.getSurname());
}
UIInput.make(form,"editProfileForm-nickname", otpBean + ".nickname", sPerson.getNickname());
UIInput.make(form,"editProfileForm-position", otpBean + ".affiliation", sPerson.getAffiliation());
UIInput.make(form,"editProfileForm-department", otpBean + ".organizationalUnit", sPerson.getOrganizationalUnit());
UIInput.make(form,"editProfileForm-school", otpBean + ".campus", sPerson.getCampus());
UIInput.make(form,"editProfileForm-room", otpBean + ".roomNumber", sPerson.getRoomNumber());
String mail = sPerson.getMail();
if (mail == null)
mail = "";
if (canEditeEmail(userDirectoryService.getCurrentUser())) {
UIInput.make(form,"editProfileForm-email", otpBean + ".mail", mail);
} else {
UIOutput.make(form, "emailNoEdit", mail);
form.parameters.add(new UIELBinding(otpBean + ".mail" ,mail));
}
UIInput.make(form,"editProfileForm-title", otpBean + ".title", sPerson.getTitle());
//not in profile data yet
UIInput.make(form,"editProfileForm-country", otpBean + ".localityName", sPerson.getLocalityName());
UIInput.make(form,"editProfileForm-homepage", otpBean + ".labeledURI", sPerson.getLabeledURI());
UIInput.make(form,"editProfileForm-workphone", otpBean + ".telephoneNumber", sPerson.getTelephoneNumber());
UIInput.make(form,"editProfileForm-mobile", otpBean + ".mobile", sPerson.getMobile());
UIInput.make(form,"editProfileForm-more", otpBean + ".notes", sPerson.getNotes());
//validate messages
UIOutput.make(form, "validateRequired", messageLocator.getMessage("validate.required"));
UIOutput.make(form, "validateEmail", messageLocator.getMessage("validate.email"));
UIOutput.make(form, "validateUrl", messageLocator.getMessage("validate.url"));
UIOutput.make(form, "validateDate", messageLocator.getMessage("validate.date"));
UIOutput.make(form, "validateMinlength", messageLocator.getMessage("validate.minlength"));
//Privacy settings
String hideS = "false";
String hideS2 = "true";
if (sPerson.getHidePrivateInfo()!=null && sPerson.getHidePrivateInfo().booleanValue()) {
hideS = "true";
}
if (sPerson.getHidePublicInfo()!=null && !sPerson.getHidePublicInfo().booleanValue()) {
hideS2 = "false";
}
log.debug("hide personal is " + hideS);
UISelect hide = UISelect.make(form, "hide-select",new String[]{"true", "false"},
new String[]{messageLocator.getMessage("editProfile.sms.yes"), messageLocator.getMessage("editProfile.sms.no")},
otpBean + ".hidePrivateInfo", hideS);
String hideID = hide.getFullID();
for(int i = 0; i < 2; i ++ ) {
UIBranchContainer radiobranch = UIBranchContainer.make(form,
"hideSelect:", Integer.valueOf(i).toString());
UISelectChoice choice = UISelectChoice.make(radiobranch, "editProfile-hide", hideID, i);
UISelectLabel lb = UISelectLabel.make(radiobranch, "hide-label", hideID, i);
UILabelTargetDecorator.targetLabel(lb, choice);
}
UISelect hide2 = UISelect.make(form, "hide-select-info",new String[]{"true", "false"},
new String[]{messageLocator.getMessage("editProfile.sms.yes"), messageLocator.getMessage("editProfile.sms.no")},
otpBean + ".hidePublicInfo", hideS2);
String hideID2 = hide2.getFullID();
for(int i = 0; i < 2; i ++ ) {
UIBranchContainer radiobranch = UIBranchContainer.make(form,
"hideSelect-info:", Integer.valueOf(i).toString());
UISelectChoice choice = UISelectChoice.make(radiobranch, "editProfile-hideInfo", hideID2, i);
UISelectLabel lb = UISelectLabel.make(radiobranch, "hide-label-info", hideID2, i);
UILabelTargetDecorator.targetLabel(lb, choice);
}
//sms preference
UISelect sms = UISelect.make(form, "sms-select",new String[]{"true", "false"},
new String[]{messageLocator.getMessage("editProfile.sms.yes"), messageLocator.getMessage("editProfile.sms.no")},
"profileBeanLocator." + sPerson.getUid() + ".smsNotifications", receiveSMSNotifications().toString());
String selectID = sms.getFullID();
for(int i = 0; i < 2; i ++ ) {
UIBranchContainer radiobranch = UIBranchContainer.make(form,
"smsSelect:", Integer.valueOf(i).toString());
UISelectChoice choice = UISelectChoice.make(radiobranch, "editProfileForm-sms", selectID, i);
UISelectLabel lb = UISelectLabel.make(radiobranch, "smslabel", selectID, i);
UILabelTargetDecorator.targetLabel(lb, choice);
}
//UIInput sms = UIInput.make(form, "editProfileForm-sms", "profileBeanLocator." + sPerson.getUid() + ".smsNotifications", "true");
//UIMessage.make(form, "smslabel","editProfile.sms");
UICommand.make(form, "profile-save","Save","profileBeanLocator.saveAll");
//UIInternalLink.make(tofill, "change-pic", messageLocator.getMessage("editProfile.changePic"), new SimpleViewParameters(ChangePicture.VIEW_ID));
UIInternalLink.make(tofill, "upload-pic", "editProfile.uploadPic");
}
private boolean canEditeName(User u) {
if (securityService.unlock(UserDirectoryService.SECURE_UPDATE_USER_OWN_NAME, "/site/" + toolManager.getCurrentPlacement().getContext())) {
log.debug("user can change name");
return true;
}
return false;
}
private boolean canEditeEmail(User u) {
if (securityService.unlock(UserDirectoryService.SECURE_UPDATE_USER_OWN_EMAIL, "/site/" + toolManager.getCurrentPlacement().getContext())) {
log.debug("user can change email");
return true;
}
return false;
}
private Boolean receiveSMSNotifications() {
User u = userDirectoryService.getCurrentUser();
ResourceProperties rp = u.getProperties();
String val = rp.getProperty("smsnotifications");
log.debug("got sms notification of: " + val );
// Default to true if unset (i.e. opt-in)
return (val == null) ? Boolean.valueOf(true) : Boolean.valueOf(val);
}
public List reportNavigationCases() {
List<NavigationCase> togo = new ArrayList<NavigationCase> (); // Always navigate back to this view.
togo.add(new NavigationCase(null, new SimpleViewParameters(MainProducer.VIEW_ID)));
return togo;
}
}
|
package org.jivesoftware.smack;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.filter.PacketFilter;
/**
* Provides a mechanism to listen for packets that pass a specified filter.
* This allows event-style programming -- every time a new packet is found,
* the {@link #processPacket(Packet)} method will be called. This is the
* opposite approach to the functionality provided by a {@link PacketCollector}
* which lets you block while waiting for results.
*
* @see XMPPConnection#addPacketListener(PacketListener, PacketFilter)
* @author Matt Tucker
*/
public interface PacketListener {
/**
* Process the next packet sent to this packet listener.<p>
*
* A single thread is responsible for invoking all listeners, so
* it's very important that implementations of this method not block
* for any extended period of time.
*
* @param packet the packet to process.
*/
public void processPacket(Packet packet);
}
|
package org.labkey.wnprc_ehr;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.labkey.api.view.JspView;
import org.labkey.api.view.WebPartView;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.CharArrayWriter;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class WNPRC_EHREmail<Model> {
String _path;
AutomaticCssInliner _inliner = new AutomaticCssInliner();
public WNPRC_EHREmail (String path) {
_path = path;
}
public class CharArrayWriterResponse extends HttpServletResponseWrapper {
private final CharArrayWriter charArray = new CharArrayWriter();
private final PrintWriter _printWriter = new PrintWriter(charArray);
public CharArrayWriterResponse(HttpServletResponse response) {
super(response);
}
@Override
public PrintWriter getWriter()
{
return _printWriter;
}
public String getOutput() {
return charArray.toString();
}
}
public String renderEmail(Model model) throws Exception{
return this.renderEmail(model, true);
}
public String renderEmail(Model model, boolean inlineCss) throws Exception {
//JspView<EmailModel> view = new JspView<>("/org/labkey/wnprc_ehr/emailViews/email.jsp", model);
JspView<Model> view = new JspView<>(_path, model);
MockHttpServletRequest req = new MockHttpServletRequest();
req.setMethod("GET");
CharArrayWriterResponse response = new CharArrayWriterResponse(new MockHttpServletResponse());
view.setFrame(WebPartView.FrameType.NONE);
view.render(req, response);
String output = response.getOutput();
if (inlineCss) {
output = _inliner.inlineCSS(output);
}
return output;
}
public class AutomaticCssInliner {
public String inlineCSS(String html)
{
final String style = "style";
Document doc = Jsoup.parse(html);
Elements els = doc.select(style);// to get all the style elements
for (Element e : els) {
String styleRules = e.getAllElements().get(0).data().replaceAll(
"\n", "").trim(), delims = "{}";
StringTokenizer st = new StringTokenizer(styleRules, delims);
while (st.countTokens() > 1) {
String selector = st.nextToken(), properties = st.nextToken();
Elements selectedElements = doc.select(selector);
for (Element selElem : selectedElements) {
String oldProperties = selElem.attr(style);
selElem.attr(style,
oldProperties.length() > 0 ? concatenateProperties(
oldProperties, properties) : properties);
}
}
e.remove();
}
//System.out.println(doc);// now we have the result html without the
// styles tags, and the inline css in each
// element
return doc.toString();
}
private String concatenateProperties(String oldProp, String newProp) {
oldProp = oldProp.trim();
if (!newProp.endsWith(";"))
newProp += ";";
return newProp + oldProp; // The existing (old) properties should take precedence.
}
}
}
|
package net.hexid.hexbot;
import java.util.Arrays;
import net.hexid.hexbot.bot.Bots;
import net.hexid.hexbot.bot.BotGUI;
import net.hexid.hexbot.bot.BotCLI;
public class HexBot {
public HexBot() {
Bots.addBot("astral", "Astral WoW", "net.hexid.hexbot.bots.Astral", "net.hexid.hexbot.bots.AstralTab", "Astral.coffee");
Bots.addBot("bing", "Bing Rewards", "net.hexid.hexbot.bots.Bing", "net.hexid.hexbot.bots.BingTab", "Bing.coffee");
Bots.addBot("xbox", "Xbox Codes", "net.hexid.hexbot.bots.Xbox", "net.hexid.hexbot.bots.XboxTab", "Xbox.coffee");
Bots.addBot("imgur", "Imgur Albums", "net.hexid.hexbot.bots.Imgur", "net.hexid.hexbot.bots.ImgurTab", "Imgur.coffee");
Bots.addBot("molten", "Molten WoW", "net.hexid.hexbots.bots.Molten", "net.hexid.hexbots.bots.MoltenTab", "Molten.coffee");
}
public static void main(String[] args) {
new HexBot();
Bots.removeInvalidBots();
if((args.length >= 1 && args[0].equalsIgnoreCase("gui"))) {
BotGUI.init(Arrays.copyOfRange(args, 1, args.length));
} else if(args.length == 0) {
BotGUI.init(args);
} else {
BotCLI.init(args);
}
}
}
|
package com.matthewtamlin.spyglass.processors.annotation_utils.annotation_mirror_util;
import com.google.testing.compile.JavaFileObjects;
import com.matthewtamlin.java_compiler_utilities.element_supplier.CompilerMissingException;
import com.matthewtamlin.java_compiler_utilities.element_supplier.IdBasedElementSupplier;
import com.matthewtamlin.spyglass.processors.annotation_utils.AnnotationMirrorUtil;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.lang.annotation.Annotation;
import java.net.MalformedURLException;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.Element;
import javax.tools.JavaFileObject;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.mockito.Mockito.mock;
@SuppressWarnings("unchecked") // Not relevant when mocking
public class TestAnnotationMirrorUtil {
private static final File DATA_FILE = new File("processors/src/test/java/com/matthewtamlin/spyglass/processors" +
"/annotation_utils/annotation_mirror_util/Data.java");
private IdBasedElementSupplier elementSupplier;
@Before
public void setup() throws MalformedURLException, CompilerMissingException {
assertThat("Data file does not exist.", DATA_FILE.exists(), is(true));
final JavaFileObject dataFileObject = JavaFileObjects.forResource(DATA_FILE.toURI().toURL());
elementSupplier = new IdBasedElementSupplier(dataFileObject);
}
@Test(expected = IllegalArgumentException.class)
public void testGetAnnotationMirror_nullElement() {
AnnotationMirrorUtil.getAnnotationMirror(null, Annotation.class);
}
@Test(expected = IllegalArgumentException.class)
public void testGetAnnotationMirror_nullAnnotationClass() {
AnnotationMirrorUtil.getAnnotationMirror(mock(Element.class), null);
}
@Test
public void testGetAnnotationMirror_annotationMissing() throws CompilerMissingException {
final Element element = elementSupplier.getUniqueElementWithId("with annotation");
final AnnotationMirror mirror = AnnotationMirrorUtil.getAnnotationMirror(element, SomeAnnotation.class);
assertThat(mirror, is(nullValue()));
}
@Test
public void testGetAnnotationMirror_annotationPresent() throws CompilerMissingException {
final Element element = elementSupplier.getUniqueElementWithId("without annotation");
final AnnotationMirror mirror = AnnotationMirrorUtil.getAnnotationMirror(element, SomeAnnotation.class);
assertThat(mirror, is(notNullValue()));
assertThat(mirror.getAnnotationType().toString(), is(SomeAnnotation.class.getName()));
}
}
|
package liquibase.diff;
import liquibase.change.*;
import liquibase.csv.CSVWriter;
import liquibase.database.Database;
import liquibase.database.structure.*;
import liquibase.exception.JDBCException;
import liquibase.log.LogFactory;
import liquibase.parser.LiquibaseSchemaResolver;
import liquibase.parser.xml.XMLChangeLogParser;
import liquibase.util.SqlUtil;
import liquibase.util.StringUtils;
import liquibase.xml.DefaultXmlWriter;
import liquibase.xml.XmlWriter;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.*;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.*;
public class DiffResult {
private Long baseId = new Date().getTime();
private int changeNumber = 1;
private Database baseDatabase;
private Database targetDatabase;
private DatabaseSnapshot baseSnapshot;
private DatabaseSnapshot targetSnapshot;
private DiffComparison productName;
private DiffComparison productVersion;
private SortedSet<Table> missingTables = new TreeSet<Table>();
private SortedSet<Table> unexpectedTables = new TreeSet<Table>();
private SortedSet<View> missingViews = new TreeSet<View>();
private SortedSet<View> unexpectedViews = new TreeSet<View>();
private SortedSet<Column> missingColumns = new TreeSet<Column>();
private SortedSet<Column> unexpectedColumns = new TreeSet<Column>();
private SortedSet<Column> changedColumns = new TreeSet<Column>();
private SortedSet<ForeignKey> missingForeignKeys = new TreeSet<ForeignKey>();
private SortedSet<ForeignKey> unexpectedForeignKeys = new TreeSet<ForeignKey>();
private SortedSet<Index> missingIndexes = new TreeSet<Index>();
private SortedSet<Index> unexpectedIndexes = new TreeSet<Index>();
private SortedSet<PrimaryKey> missingPrimaryKeys = new TreeSet<PrimaryKey>();
private SortedSet<PrimaryKey> unexpectedPrimaryKeys = new TreeSet<PrimaryKey>();
private SortedSet<Sequence> missingSequences = new TreeSet<Sequence>();
private SortedSet<Sequence> unexpectedSequences = new TreeSet<Sequence>();
private boolean diffData = false;
private String dataDir = null;
private String changeSetContext;
private String changeSetAuthor;
public DiffResult(DatabaseSnapshot baseDatabase, DatabaseSnapshot targetDatabase) {
this.baseDatabase = baseDatabase.getDatabase();
this.targetDatabase = targetDatabase.getDatabase();
this.baseSnapshot = baseDatabase;
this.targetSnapshot = targetDatabase;
}
public DiffComparison getProductName() {
return productName;
}
public void setProductName(DiffComparison productName) {
this.productName = productName;
}
public DiffComparison getProductVersion() {
return productVersion;
}
public void setProductVersion(DiffComparison product) {
this.productVersion = product;
}
public void addMissingTable(Table table) {
missingTables.add(table);
}
public SortedSet<Table> getMissingTables() {
return missingTables;
}
public void addUnexpectedTable(Table table) {
unexpectedTables.add(table);
}
public SortedSet<Table> getUnexpectedTables() {
return unexpectedTables;
}
public void addMissingView(View viewName) {
missingViews.add(viewName);
}
public SortedSet<View> getMissingViews() {
return missingViews;
}
public void addUnexpectedView(View viewName) {
unexpectedViews.add(viewName);
}
public SortedSet<View> getUnexpectedViews() {
return unexpectedViews;
}
public void addMissingColumn(Column columnName) {
missingColumns.add(columnName);
}
public SortedSet<Column> getMissingColumns() {
return missingColumns;
}
public void addUnexpectedColumn(Column columnName) {
unexpectedColumns.add(columnName);
}
public SortedSet<Column> getUnexpectedColumns() {
return unexpectedColumns;
}
public void addChangedColumn(Column columnName) {
changedColumns.add(columnName);
}
public SortedSet<Column> getChangedColumns() {
return changedColumns;
}
public void addMissingForeignKey(ForeignKey fkName) {
missingForeignKeys.add(fkName);
}
public SortedSet<ForeignKey> getMissingForeignKeys() {
return missingForeignKeys;
}
public void addUnexpectedForeignKey(ForeignKey fkName) {
unexpectedForeignKeys.add(fkName);
}
public SortedSet<ForeignKey> getUnexpectedForeignKeys() {
return unexpectedForeignKeys;
}
public void addMissingIndex(Index fkName) {
missingIndexes.add(fkName);
}
public SortedSet<Index> getMissingIndexes() {
return missingIndexes;
}
public void addUnexpectedIndex(Index fkName) {
unexpectedIndexes.add(fkName);
}
public SortedSet<Index> getUnexpectedIndexes() {
return unexpectedIndexes;
}
public void addMissingPrimaryKey(PrimaryKey primaryKey) {
missingPrimaryKeys.add(primaryKey);
}
public SortedSet<PrimaryKey> getMissingPrimaryKeys() {
return missingPrimaryKeys;
}
public void addUnexpectedPrimaryKey(PrimaryKey primaryKey) {
unexpectedPrimaryKeys.add(primaryKey);
}
public SortedSet<PrimaryKey> getUnexpectedPrimaryKeys() {
return unexpectedPrimaryKeys;
}
public void addMissingSequence(Sequence sequence) {
missingSequences.add(sequence);
}
public SortedSet<Sequence> getMissingSequences() {
return missingSequences;
}
public void addUnexpectedSequence(Sequence sequence) {
unexpectedSequences.add(sequence);
}
public SortedSet<Sequence> getUnexpectedSequences() {
return unexpectedSequences;
}
public boolean shouldDiffData() {
return diffData;
}
public void setDiffData(boolean diffData) {
this.diffData = diffData;
}
public String getDataDir() {
return dataDir;
}
public void setDataDir(String dataDir) {
this.dataDir = dataDir;
}
public String getChangeSetContext() {
return changeSetContext;
}
public void setChangeSetContext(String changeSetContext) {
this.changeSetContext = changeSetContext;
}
public void printResult(PrintStream out) throws JDBCException {
out.println("Base Database: " + targetDatabase.getConnectionUsername() + " " + targetDatabase.getConnectionURL());
out.println("Target Database: " + baseDatabase.getConnectionUsername() + " " + baseDatabase.getConnectionURL());
printComparision("Product Name", productName, out);
printComparision("Product Version", productVersion, out);
printSetComparison("Missing Tables", getMissingTables(), out);
printSetComparison("Unexpected Tables", getUnexpectedTables(), out);
printSetComparison("Missing Views", getMissingViews(), out);
printSetComparison("Unexpected Views", getUnexpectedViews(), out);
printSetComparison("Missing Columns", getMissingColumns(), out);
printSetComparison("Unexpected Columns", getUnexpectedColumns(), out);
printColumnComparison(getChangedColumns(), out);
printSetComparison("Missing Foreign Keys", getMissingForeignKeys(), out);
printSetComparison("Unexpected Foreign Keys", getUnexpectedForeignKeys(), out);
printSetComparison("Missing Primary Keys", getMissingPrimaryKeys(), out);
printSetComparison("Unexpected Primary Keys", getUnexpectedPrimaryKeys(), out);
printSetComparison("Missing Indexes", getMissingIndexes(), out);
printSetComparison("Unexpected Indexes", getUnexpectedIndexes(), out);
printSetComparison("Missing Sequences", getMissingSequences(), out);
printSetComparison("Unexpected Sequences", getUnexpectedSequences(), out);
}
private void printSetComparison(String title, SortedSet<?> objects, PrintStream out) {
out.print(title + ": ");
if (objects.size() == 0) {
out.println("NONE");
} else {
out.println();
for (Object object : objects) {
out.println(" " + object);
}
}
}
private void printColumnComparison(SortedSet<Column> changedColumns, PrintStream out) {
out.print("Changed Columns: ");
if (changedColumns.size() == 0) {
out.println("NONE");
} else {
out.println();
for (Column column : changedColumns) {
out.println(" " + column);
Column baseColumn = baseSnapshot.getColumn(column);
if (baseColumn != null) {
if (baseColumn.isDataTypeDifferent(column)) {
out.println(" from " + baseColumn.getDataTypeString(baseDatabase) + " to " + targetSnapshot.getColumn(column).getDataTypeString(targetDatabase));
}
if (baseColumn.isNullabilityDifferent(column)) {
Boolean nowNullable = targetSnapshot.getColumn(column).isNullable();
if (nowNullable == null) {
nowNullable = Boolean.TRUE;
}
if (nowNullable) {
out.println(" now nullable");
} else {
out.println(" now not null");
}
}
}
}
}
}
private void printComparision(String title, DiffComparison comparison, PrintStream out) {
out.print(title + ":");
if (comparison.areTheSame()) {
out.println(" EQUAL");
} else {
out.println();
out.println(" Base: '" + comparison.getBaseVersion() + "'");
out.println(" Target: '" + comparison.getTargetVersion() + "'");
}
}
public void printChangeLog(String changeLogFile, Database targetDatabase) throws ParserConfigurationException, IOException {
this.printChangeLog(changeLogFile, targetDatabase, new DefaultXmlWriter());
}
public void printChangeLog(PrintStream out, Database targetDatabase) throws ParserConfigurationException, IOException {
this.printChangeLog(out, targetDatabase, new DefaultXmlWriter());
}
public void printChangeLog(String changeLogFile, Database targetDatabase, XmlWriter xmlWriter) throws ParserConfigurationException, IOException {
File file = new File(changeLogFile);
if (!file.exists()) {
LogFactory.getLogger().info(file + " does not exist, creating");
FileOutputStream stream = new FileOutputStream(file);
printChangeLog(new PrintStream(stream), targetDatabase, xmlWriter);
stream.close();
} else {
LogFactory.getLogger().info(file + " exists, appending");
ByteArrayOutputStream out = new ByteArrayOutputStream();
printChangeLog(new PrintStream(out), targetDatabase, xmlWriter);
String xml = new String(out.toByteArray());
xml = xml.replaceFirst("(?ms).*<databaseChangeLog[^>]*>", "");
xml = xml.replaceFirst("</databaseChangeLog>", "");
xml = xml.trim();
String lineSeparator = System.getProperty("line.separator");
BufferedReader fileReader = new BufferedReader(new FileReader(file));
String line;
long offset = 0;
while ((line = fileReader.readLine()) != null) {
int index = line.indexOf("</databaseChangeLog>");
if (index >= 0) {
offset += index;
} else {
offset += line.getBytes().length;
offset += lineSeparator.getBytes().length;
}
}
fileReader.close();
fileReader = new BufferedReader(new FileReader(file));
fileReader.skip(offset);
fileReader.close();
// System.out.println("resulting XML: " + xml.trim());
RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
randomAccessFile.seek(offset);
randomAccessFile.writeBytes(" " + xml + lineSeparator);
randomAccessFile.writeBytes("</databaseChangeLog>" + lineSeparator);
randomAccessFile.close();
// BufferedWriter fileWriter = new BufferedWriter(new FileWriter(file));
// fileWriter.append(xml);
// fileWriter.close();
}
}
/**
* Prints changeLog that would bring the base database to be the same as the target database
*/
public void printChangeLog(PrintStream out, Database targetDatabase, XmlWriter xmlWriter) throws ParserConfigurationException, IOException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = factory.newDocumentBuilder();
documentBuilder.setEntityResolver(new LiquibaseSchemaResolver());
Document doc = documentBuilder.newDocument();
Element changeLogElement = doc.createElement("databaseChangeLog");
changeLogElement.setAttribute("xmlns", "http:
changeLogElement.setAttribute("xmlns:xsi", "http:
changeLogElement.setAttribute("xsi:schemaLocation", "http:
doc.appendChild(changeLogElement);
List<Change> changes = new ArrayList<Change>();
addMissingTableChanges(changes, targetDatabase);
addMissingColumnChanges(changes, targetDatabase);
addUnexpectedColumnChanges(changes);
addChangedColumnChanges(changes);
addMissingPrimaryKeyChanges(changes);
addUnexpectedPrimaryKeyChanges(changes);
addMissingIndexChanges(changes);
addUnexpectedIndexChanges(changes);
if (diffData) {
addInsertDataChanges(changes, dataDir);
}
addMissingForeignKeyChanges(changes);
addUnexpectedForeignKeyChanges(changes);
addMissingSequenceChanges(changes);
addUnexpectedSequenceChanges(changes);
addMissingViewChanges(changes);
addUnexpectedViewChanges(changes);
addUnexpectedTableChanges(changes);
for (Change change : changes) {
Element changeSet = doc.createElement("changeSet");
changeSet.setAttribute("author", getChangeSetAuthor());
changeSet.setAttribute("id", generateId());
if (getChangeSetContext() != null) {
changeSet.setAttribute("context", getChangeSetContext());
}
changeSet.appendChild(change.createNode(doc));
doc.getDocumentElement().appendChild(changeSet);
}
xmlWriter.write(doc, out);
out.flush();
}
private String getChangeSetAuthor() {
if (changeSetAuthor != null) {
return changeSetAuthor;
}
String author = System.getProperty("user.name");
if (StringUtils.trimToNull(author) == null) {
return "diff-generated";
} else {
return author + " (generated)";
}
}
public void setChangeSetAuthor(String changeSetAuthor) {
this.changeSetAuthor = changeSetAuthor;
}
private String generateId() {
return baseId.toString() + "-" + changeNumber++;
}
private void addUnexpectedIndexChanges(List<Change> changes) {
for (Index index : getUnexpectedIndexes()) {
DropIndexChange change = new DropIndexChange();
change.setTableName(index.getTable().getName());
change.setIndexName(index.getName());
changes.add(change);
}
}
private void addMissingIndexChanges(List<Change> changes) {
for (Index index : getMissingIndexes()) {
CreateIndexChange change = new CreateIndexChange();
change.setTableName(index.getTable().getName());
change.setIndexName(index.getName());
for (String columnName : index.getColumns()) {
ColumnConfig column = new ColumnConfig();
column.setName(columnName);
change.addColumn(column);
}
changes.add(change);
}
}
private void addUnexpectedPrimaryKeyChanges(List<Change> changes) {
for (PrimaryKey pk : getUnexpectedPrimaryKeys()) {
if (!getUnexpectedTables().contains(pk.getTable())) {
DropPrimaryKeyChange change = new DropPrimaryKeyChange();
change.setTableName(pk.getTable().getName());
change.setConstraintName(pk.getName());
changes.add(change);
}
}
}
private void addMissingPrimaryKeyChanges(List<Change> changes) {
for (PrimaryKey pk : getMissingPrimaryKeys()) {
AddPrimaryKeyChange change = new AddPrimaryKeyChange();
change.setTableName(pk.getTable().getName());
change.setConstraintName(pk.getName());
change.setColumnNames(pk.getColumnNames());
changes.add(change);
}
}
private void addUnexpectedForeignKeyChanges(List<Change> changes) {
for (ForeignKey fk : getUnexpectedForeignKeys()) {
DropForeignKeyConstraintChange change = new DropForeignKeyConstraintChange();
change.setConstraintName(fk.getName());
change.setBaseTableName(fk.getForeignKeyTable().getName());
changes.add(change);
}
}
private void addMissingForeignKeyChanges(List<Change> changes) {
for (ForeignKey fk : getMissingForeignKeys()) {
AddForeignKeyConstraintChange change = new AddForeignKeyConstraintChange();
change.setConstraintName(fk.getName());
change.setReferencedTableName(fk.getPrimaryKeyTable().getName());
change.setReferencedColumnNames(fk.getPrimaryKeyColumns());
change.setBaseTableName(fk.getForeignKeyTable().getName());
change.setBaseColumnNames(fk.getForeignKeyColumns());
change.setDeferrable(fk.isDeferrable());
change.setInitiallyDeferred(fk.isInitiallyDeferred());
changes.add(change);
}
}
private void addUnexpectedSequenceChanges(List<Change> changes) {
for (Sequence sequence : getUnexpectedSequences()) {
DropSequenceChange change = new DropSequenceChange();
change.setSequenceName(sequence.getName());
changes.add(change);
}
}
private void addMissingSequenceChanges(List<Change> changes) {
for (Sequence sequence : getMissingSequences()) {
CreateSequenceChange change = new CreateSequenceChange();
change.setSequenceName(sequence.getName());
changes.add(change);
}
}
private void addUnexpectedColumnChanges(List<Change> changes) {
for (Column column : getUnexpectedColumns()) {
if (!shouldModifyColumn(column)) {
continue;
}
DropColumnChange change = new DropColumnChange();
change.setTableName(column.getTable().getName());
change.setColumnName(column.getName());
changes.add(change);
}
}
private void addMissingViewChanges(List<Change> changes) {
for (View view : getMissingViews()) {
CreateViewChange change = new CreateViewChange();
change.setViewName(view.getName());
String selectQuery = view.getDefinition();
if (selectQuery == null) {
selectQuery = "COULD NOT DETERMINE VIEW QUERY";
}
change.setSelectQuery(selectQuery);
changes.add(change);
}
}
private void addChangedColumnChanges(List<Change> changes) {
for (Column column : getChangedColumns()) {
if (!shouldModifyColumn(column)) {
continue;
}
boolean foundDifference = false;
Column baseColumn = baseSnapshot.getColumn(column);
if (column.isDataTypeDifferent(baseColumn)) {
ColumnConfig columnConfig = new ColumnConfig();
columnConfig.setName(column.getName());
columnConfig.setType(baseColumn.getDataTypeString(targetDatabase));
ModifyColumnChange change = new ModifyColumnChange();
change.setTableName(column.getTable().getName());
change.addColumn(columnConfig);
changes.add(change);
foundDifference = true;
}
if (column.isNullabilityDifferent(baseColumn)) {
if (baseColumn.isNullable() == null || baseColumn.isNullable()) {
DropNotNullConstraintChange change = new DropNotNullConstraintChange();
change.setTableName(column.getTable().getName());
change.setColumnName(column.getName());
change.setColumnDataType(baseColumn.getDataTypeString(targetDatabase));
changes.add(change);
foundDifference = true;
} else {
AddNotNullConstraintChange change = new AddNotNullConstraintChange();
change.setTableName(column.getTable().getName());
change.setColumnName(column.getName());
change.setColumnDataType(baseColumn.getDataTypeString(targetDatabase));
changes.add(change);
foundDifference = true;
}
}
if (!foundDifference) {
throw new RuntimeException("Unknown difference");
}
}
}
private boolean shouldModifyColumn(Column column) {
return column.getView() == null
&& !baseDatabase.isLiquibaseTable(column.getTable().getName());
}
private void addUnexpectedViewChanges(List<Change> changes) {
for (View view : getUnexpectedViews()) {
DropViewChange change = new DropViewChange();
change.setViewName(view.getName());
changes.add(change);
}
}
private void addMissingColumnChanges(List<Change> changes, Database database) {
for (Column column : getMissingColumns()) {
if (!shouldModifyColumn(column)) {
continue;
}
AddColumnChange change = new AddColumnChange();
change.setTableName(column.getTable().getName());
ColumnConfig columnConfig = new ColumnConfig();
columnConfig.setName(column.getName());
String dataType = column.getDataTypeString(database);
columnConfig.setType(dataType);
columnConfig.setDefaultValue(database.convertJavaObjectToString(column.getDefaultValue()));
if (column.getRemarks() != null) {
columnConfig.setRemarks(column.getRemarks());
}
change.addColumn(columnConfig);
changes.add(change);
}
}
private void addMissingTableChanges(List<Change> changes, Database database) {
for (Table missingTable : getMissingTables()) {
if (baseDatabase.isLiquibaseTable(missingTable.getName())) {
continue;
}
CreateTableChange change = new CreateTableChange();
change.setTableName(missingTable.getName());
if (missingTable.getRemarks() != null) {
change.setRemarks(missingTable.getRemarks());
}
for (Column column : missingTable.getColumns()) {
ColumnConfig columnConfig = new ColumnConfig();
columnConfig.setName(column.getName());
columnConfig.setType(column.getDataTypeString(database));
ConstraintsConfig constraintsConfig = null;
if (column.isPrimaryKey()) {
PrimaryKey primaryKey = null;
for (PrimaryKey pk : getMissingPrimaryKeys()) {
if (pk.getTable().getName().equalsIgnoreCase(missingTable.getName())) {
primaryKey = pk;
}
}
if (primaryKey == null || primaryKey.getColumnNamesAsList().size() == 1) {
constraintsConfig = new ConstraintsConfig();
constraintsConfig.setPrimaryKey(true);
if (primaryKey != null) {
constraintsConfig.setPrimaryKeyName(primaryKey.getName());
getMissingPrimaryKeys().remove(primaryKey);
}
}
}
if (column.isAutoIncrement()) {
columnConfig.setAutoIncrement(true);
}
if (column.isNullable() != null && !column.isNullable()) {
if (constraintsConfig == null) {
constraintsConfig = new ConstraintsConfig();
}
constraintsConfig.setNullable(false);
}
if (constraintsConfig != null) {
columnConfig.setConstraints(constraintsConfig);
}
Object defaultValue = column.getDefaultValue();
if (defaultValue == null) {
//do nothing
} else if (column.isAutoIncrement()) {
//do nothing
} else if (defaultValue instanceof Date) {
columnConfig.setDefaultValueDate((Date) defaultValue);
} else if (defaultValue instanceof Boolean) {
columnConfig.setDefaultValueBoolean(((Boolean) defaultValue));
} else if (defaultValue instanceof Number) {
columnConfig.setDefaultValueNumeric(((Number) defaultValue));
} else {
columnConfig.setDefaultValue(defaultValue.toString());
}
if (column.getRemarks() != null) {
columnConfig.setRemarks(column.getRemarks());
}
change.addColumn(columnConfig);
}
changes.add(change);
}
}
private void addUnexpectedTableChanges(List<Change> changes) {
for (Table unexpectedTable : getUnexpectedTables()) {
DropTableChange change = new DropTableChange();
change.setTableName(unexpectedTable.getName());
changes.add(change);
}
}
private void addInsertDataChanges(List<Change> changes, String dataDir) {
try {
String schema = baseSnapshot.getSchema();
Statement stmt = baseSnapshot.getDatabase().getConnection().createStatement();
for (Table table : baseSnapshot.getTables()) {
ResultSet rs = stmt.executeQuery("SELECT * FROM " + baseSnapshot.getDatabase().escapeTableName(schema, table.getName()));
String fileName = table.getName() + ".csv";
if (dataDir != null) {
fileName = dataDir + "/" + fileName;
}
File parentDir = new File(dataDir);
if (!parentDir.exists()) {
parentDir.mkdirs();
}
if (!parentDir.isDirectory()) {
throw new RuntimeException(parentDir + " is not a directory");
}
CSVWriter outputFile = new CSVWriter(new FileWriter(fileName));
outputFile.writeAll(rs, true);
outputFile.flush();
outputFile.close();
LoadDataChange change = new LoadDataChange();
change.setFile(fileName);
change.setEncoding("UTF-8");
change.setSchemaName(schema);
change.setTableName(table.getName());
ResultSetMetaData columnData = rs.getMetaData();
for (int col = 1; col <= columnData.getColumnCount(); col++) {
String colName = columnData.getColumnName(col);
int dataType = columnData.getColumnType(col);
String typeString = "STRING";
if (SqlUtil.isNumeric(dataType)) {
typeString = "NUMERIC";
} else if (SqlUtil.isBoolean(dataType)) {
typeString = "BOOLEAN";
} else if (SqlUtil.isDate(dataType)) {
typeString = "DATE";
}
LoadDataColumnConfig columnConfig = new LoadDataColumnConfig();
columnConfig.setHeader(colName);
columnConfig.setType(typeString);
change.addColumn(columnConfig);
}
changes.add(change);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
|
package org.mwc.cmap.gt2plot.proj;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.geom.NoninvertibleTransformException;
import java.util.Iterator;
import junit.framework.TestCase;
import org.eclipse.core.runtime.Status;
import org.geotools.geometry.DirectPosition2D;
import org.geotools.geometry.Envelope2D;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.map.Layer;
import org.geotools.map.MapContent;
import org.geotools.map.MapViewport;
import org.geotools.referencing.CRS;
import org.geotools.referencing.operation.projection.ProjectionException;
import org.mwc.cmap.core.CorePlugin;
import org.mwc.cmap.gt2plot.GtActivator;
import org.mwc.cmap.gt2plot.data.GeoToolsLayer;
import org.opengis.geometry.BoundingBox;
import org.opengis.geometry.MismatchedDimensionException;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.NoSuchAuthorityCodeException;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.operation.MathTransform;
import org.opengis.referencing.operation.TransformException;
import MWC.Algorithms.PlainProjection;
import MWC.Algorithms.EarthModels.CompletelyFlatEarth;
import MWC.GUI.ExternallyManagedDataLayer;
import MWC.GUI.GeoToolsHandler;
import MWC.GenericData.WorldArea;
import MWC.GenericData.WorldLocation;
public class GtProjection extends PlainProjection implements GeoToolsHandler
{
private CoordinateReferenceSystem _worldCoords;
protected MathTransform _degs2metres;
private WorldLocation _relativeCentre = null;
private final MapContent _map;
private final MapViewport _view;
private WorldArea _oldDataArea;
// to reduce object creation these three objects are created in advance, and
// reused
private final DirectPosition2D _workDegs;
private final DirectPosition2D _workMetres;
private final DirectPosition2D _workScreen;
public GtProjection()
{
super("GeoTools");
// initialise our working data stores
_workDegs = new DirectPosition2D();
_workMetres = new DirectPosition2D();
_workScreen = new DirectPosition2D();
_map = new MapContent();
_view = _map.getViewport();
// set the aspect radio matching to true. The default
// value for this was false - but when we did fit to
// window, it wasn't putting the specified area in the centre of the shape
_view.setMatchingAspectRatio(true);
// sort out the degs to m transform
try
{
// we'll tell GeoTools to use the projection that's used by most of our
// charts,
// so that the chart will be displayed undistorted
_worldCoords = CRS.decode("EPSG:3395");
// we also need a way to convert a location in degrees to that used by
// the charts (metres)
CoordinateReferenceSystem worldDegs = CRS.decode("EPSG:4326");
_degs2metres = CRS.findMathTransform(worldDegs, _worldCoords);
}
catch (NoSuchAuthorityCodeException e)
{
GtActivator
.logError(
Status.ERROR,
"Can't find the requested authority whilst trying to create CRS transform",
e);
}
catch (FactoryException e)
{
GtActivator.logError(Status.ERROR,
"Unexpected problem whilst trying to create CRS transform", e);
}
_view.setCoordinateReferenceSystem(_worldCoords);
// SPECIAL HANDLING: this is the kludge to ensure the aspect ratio is kept
// constant
_view.setMatchingAspectRatio(true);
}
private static final long serialVersionUID = 1L;
@Override
public Point toScreen(WorldLocation val)
{
Point res = null;
// special handling: if we're in a relative plotting mode, we need to shift
// the projection. We're choosing to defer handling of this instance until
// we're actually
// plotting the data.
// - we cache the current relative centre, and only bother shifting the
// transform if it's a new centre.
// right, quick check. are we in a primary centred mode?
if (super.getNonStandardPlotting() && super.getPrimaryCentred())
{
WorldLocation loc = super._relativePlotter.getLocation();
// do we have a location for this plotter? We may not have...
if (loc != null)
{
// have we got a 'remembered data area'?
if (_oldDataArea == null)
{
// remember the current data area
_oldDataArea = super.getDataArea();
}
// ok, handle the changes
if (loc != _relativeCentre)
{
// store the new centre
_relativeCentre = loc;
// set the centre of the new data area
WorldArea newArea = new WorldArea(super.getDataArea());
// shift it to our current centre
newArea.setCentre(_relativeCentre);
// and store this area
this.mySetDataArea(newArea);
}
}
}
else
{
// we're not in primary centred mode. do we need to restore an old data
// area?
if (_oldDataArea != null)
{
// ok, re-instate that old area
this.mySetDataArea(_oldDataArea);
// and clear the flag
_oldDataArea = null;
}
}
// and now for the actual projection bit
_workDegs.setLocation(val.getLong(), val.getLat());
try
{
_degs2metres.transform(_workDegs, _workMetres);
// now got to screen
_view.getWorldToScreen().transform(_workMetres, _workScreen);
// output the results
res = new Point((int) _workScreen.getCoordinate()[0],
(int) _workScreen.getCoordinate()[1]);
}
catch (MismatchedDimensionException e)
{
GtActivator.logError(Status.ERROR,
"Whilst trying to convert to screen coords", e);
}
catch (TransformException e)
{
GtActivator.logError(Status.ERROR,
"Whilst trying to convert to screen coords", e);
}
return res;
}
@Override
public WorldLocation toWorld(Point val)
{
WorldLocation res = null;
_workScreen.setLocation(val.x, val.y);
try
{
// now got to screen
_view.getScreenToWorld().transform(_workScreen, _workMetres);
_degs2metres.inverse().transform(_workMetres, _workDegs);
res = new WorldLocation(_workDegs.getCoordinate()[1],
_workDegs.getCoordinate()[0], 0);
}
catch (MismatchedDimensionException e)
{
GtActivator.logError(Status.ERROR,
"Whilst trying to set convert to world coords", e);
}
catch (org.opengis.referencing.operation.NoninvertibleTransformException e)
{
GtActivator.logError(Status.ERROR,
"Unexpected problem whilst performing screen to world", e);
}
catch (TransformException e)
{
GtActivator.logError(Status.ERROR,
"Unexpected problem whilst performing screen to world", e);
}
return res;
}
private DirectPosition2D getDirectPositionOf(final WorldLocation x)
throws MismatchedDimensionException, TransformException
{
final DirectPosition2D mapPos = new DirectPosition2D(x.getLong(),
x.getLat());
final DirectPosition2D mapM = new DirectPosition2D();
_degs2metres.transform(mapPos, mapM);
return mapM;
}
private WorldArea convertToWorldArea(final Envelope2D newMapArea)
throws MismatchedDimensionException,
org.opengis.referencing.operation.NoninvertibleTransformException,
TransformException
{
// convert back to friendly units
final DirectPosition2D tlDegs = new DirectPosition2D();
final DirectPosition2D brDegs = new DirectPosition2D();
_degs2metres.inverse().transform(newMapArea.getLowerCorner(), brDegs);
_degs2metres.inverse().transform(newMapArea.getUpperCorner(), tlDegs);
final WorldLocation tl = new WorldLocation(brDegs.y, brDegs.x, 0d);
final WorldLocation br = new WorldLocation(tlDegs.y, tlDegs.x, 0d);
return new WorldArea(tl, br);
}
@Override
public void zoom(double scaleVal)
{
if (scaleVal == 0)
scaleVal = 1;
final Dimension paneArea = super.getScreenArea();
final WorldArea dataArea = super.getDataArea();
if (dataArea != null)
{
final WorldLocation centre = super.getDataArea().getCentre();
try
{
final DirectPosition2D mapM = getDirectPositionOf(centre);
if (_view.getWorldToScreen() == null)
return;
double scale = _view.getWorldToScreen().getScaleX();
scale = Math.min(1000, scale);
double newScale = scale / scaleVal;
final DirectPosition2D corner = new DirectPosition2D(mapM.getX() - 0.5d
* paneArea.width / newScale, mapM.getY() + 0.5d * paneArea.height
/ newScale);
final Envelope2D newMapArea = new Envelope2D();
newMapArea.setFrameFromCenter(mapM, corner);
final WorldArea newArea = convertToWorldArea(newMapArea);
newArea.normalise();
setDataArea(newArea);
}
catch (MismatchedDimensionException e)
{
GtActivator.logError(Status.ERROR,
"Unexpected problem whilst performing zoom", e);
}
catch (org.opengis.referencing.operation.NoninvertibleTransformException e)
{
GtActivator.logError(Status.ERROR,
"Unable to do inverse transform in zoom", e);
}
catch (TransformException e)
{
GtActivator.logError(Status.ERROR,
"Unexpected problem whilst performing", e);
}
}
}
@Override
public void zoom(final double scaleVal, final WorldArea area)
{
if (area == null)
{
zoom(scaleVal);
return;
}
final WorldArea dataArea = super.getDataArea();
if (dataArea == null)
{
return;
}
final Dimension paneArea = super.getScreenArea();
try
{
if (_view.getWorldToScreen() == null)
return;
final DirectPosition2D desiredCenter = getDirectPositionOf(area
.getCentre());
final DirectPosition2D actualCenter = getDirectPositionOf(super
.getDataArea().getCentre());
final double deltaX = actualCenter.getX() - desiredCenter.getX();
final double deltaY = actualCenter.getY() - desiredCenter.getY();
double scale = _view.getWorldToScreen().getScaleX();
scale = Math.min(1000, scale);
double newScale = scale;
if (scaleVal != 0)
newScale = scale / scaleVal;
final DirectPosition2D corner = new DirectPosition2D(desiredCenter.getX() - 0.5d
* paneArea.width / newScale, desiredCenter.getY() + 0.5d * paneArea.height
/ newScale);
final Envelope2D newMapArea = new Envelope2D();
//scale
newMapArea.setFrameFromCenter(desiredCenter, corner);
final double height = newMapArea.getHeight();
final double width = newMapArea.getWidth();
//translate
newMapArea.setFrameFromDiagonal(
newMapArea.getBounds().x + deltaX*scaleVal,
newMapArea.getBounds().y + deltaY*scaleVal,
newMapArea.getBounds().x + width + deltaX*scaleVal,
newMapArea.getBounds().y + height + deltaY*scaleVal);
final WorldArea newArea = convertToWorldArea(newMapArea);
newArea.normalise();
setDataArea(newArea);
}
catch (MismatchedDimensionException e)
{
GtActivator.logError(Status.ERROR,
"Unexpected problem whilst performing zoom", e);
}
catch (org.opengis.referencing.operation.NoninvertibleTransformException e)
{
GtActivator.logError(Status.ERROR,
"Unable to do inverse transform in zoom", e);
}
catch (TransformException e)
{
GtActivator.logError(Status.ERROR,
"Unexpected problem whilst performing", e);
}
}
@Override
public void setScreenArea(Dimension theArea)
{
if (theArea.equals(super.getScreenArea()))
return;
super.setScreenArea(theArea);
java.awt.Rectangle screenArea = new java.awt.Rectangle(0, 0, theArea.width,
theArea.height);
_view.setScreenArea(screenArea);
}
@Override
public void setDataArea(WorldArea theArea)
{
// trim the area to sensible bounds
theArea.trim();
mySetDataArea(theArea);
// and store it in the parent;
super.setDataArea(theArea);
}
private void mySetDataArea(WorldArea theArea)
{
// double-check we're not already ste to this
if (theArea.equals(super.getDataArea()))
{
System.err.println("OVER-RIDING EXISTING AREA - TRAP THIS INSTANCE");
return;
}
// trim the coordinates
gtTrim(theArea);
WorldLocation tl = theArea.getTopLeft();
WorldLocation br = theArea.getBottomRight();
DirectPosition2D tlDegs = new DirectPosition2D(tl.getLong(), tl.getLat());
DirectPosition2D brDegs = new DirectPosition2D(br.getLong(), br.getLat());
DirectPosition2D tlM = new DirectPosition2D();
DirectPosition2D brM = new DirectPosition2D();
try
{
_degs2metres.transform(tlDegs, tlM);
_degs2metres.transform(brDegs, brM);
// put the coords into an envelope
Envelope2D env = new Envelope2D(brM, tlM);
ReferencedEnvelope rEnv = new ReferencedEnvelope(env, _worldCoords);
_view.setBounds(rEnv);
}
catch (ProjectionException e)
{
CorePlugin.logError(Status.ERROR,
"trouble with proj, probably zoomed out too far", e);
}
catch (MismatchedDimensionException e)
{
CorePlugin.logError(Status.ERROR, "unknown trouble with proj", e);
}
catch (TransformException e)
{
CorePlugin.logError(Status.ERROR, "unknown trouble with proj", e);
}
}
private void gtTrim(WorldArea theArea)
{
gtTrim(theArea.getTopLeft());
gtTrim(theArea.getBottomRight());
}
private void gtTrim(WorldLocation loc)
{
loc.setLat(Math.min(loc.getLat(), 89.9999));
loc.setLat(Math.max(loc.getLat(), -89.9999));
loc.setLong(Math.min(loc.getLong(), 179.999));
loc.setLong(Math.max(loc.getLong(), -179.999));
}
public MapContent getMapContent()
{
return _map;
}
public void addGeoToolsLayer(ExternallyManagedDataLayer gt)
{
GeoToolsLayer geoLayer = (GeoToolsLayer) gt;
geoLayer.setMap(_map);
}
/**
* how many layers do we have loaded?
*
* @return
*/
public int numLayers()
{
return _map.layers().size();
}
/**
* whether the geotools layers overlap with the specified area
*
* @param area
* @return
*/
public boolean layersOverlapWith(WorldArea area)
{
WorldLocation tl = area.getTopLeft();
WorldLocation br = area.getBottomRight();
DirectPosition2D tlDegs = new DirectPosition2D(tl.getLong(), tl.getLat());
DirectPosition2D brDegs = new DirectPosition2D(br.getLong(), br.getLat());
DirectPosition2D tlM = new DirectPosition2D();
DirectPosition2D brM = new DirectPosition2D();
try
{
_degs2metres.transform(tlDegs, tlM);
_degs2metres.transform(brDegs, brM);
// put the coords into an envelope
Envelope2D env = new Envelope2D(brM, tlM);
BoundingBox other = new ReferencedEnvelope(env, _worldCoords);
Iterator<Layer> layers = _map.layers().iterator();
while (layers.hasNext())
{
Layer layer = (Layer) layers.next();
if (layer.isVisible())
{
ReferencedEnvelope thisBounds = layer.getBounds();
// right, now the painful bit of converting the layers
ReferencedEnvelope newBounds = thisBounds.transform(
other.getCoordinateReferenceSystem(), false);
if (newBounds.intersects(other))
return true;
}
}
}
catch (MismatchedDimensionException e)
{
CorePlugin.logError(Status.ERROR,
"unknown dimension trouble with getting bounds", e);
}
catch (TransformException e)
{
CorePlugin.logError(Status.ERROR,
"unknown transform trouble with getting bounds", e);
}
catch (FactoryException e)
{
CorePlugin.logError(Status.ERROR,
"unknown factory trouble with getting bounds", e);
}
return false;
}
public static class TestProj extends TestCase
{
public void testOne() throws NoSuchAuthorityCodeException,
FactoryException, NoninvertibleTransformException
{
MapContent mc = new MapContent();
// set a coordinate reference system
CoordinateReferenceSystem crs = CRS.decode("EPSG:4326");
mc.getViewport().setCoordinateReferenceSystem(crs);
// set a data area
DirectPosition2D tlDegs = new DirectPosition2D(5, 1);
DirectPosition2D brDegs = new DirectPosition2D(1, 5);
Envelope2D env = new Envelope2D(tlDegs, brDegs);
ReferencedEnvelope rEnv = new ReferencedEnvelope(env, crs);
mc.getViewport().setBounds(rEnv);
// set a screen area
mc.getViewport().setScreenArea(new Rectangle(0, 0, 800, 400));
// sort out the aspect ration
mc.getViewport().setMatchingAspectRatio(true);
// create a point to test
DirectPosition2D degs = new DirectPosition2D(5, 4);
// and results object
DirectPosition2D pixels = new DirectPosition2D();
DirectPosition2D rDegs = new DirectPosition2D();
// transform the test point
mc.getViewport().getWorldToScreen().transform(degs, pixels);
System.out.println("pixels:" + pixels);
assertEquals("correct x", 600, (int) pixels.x);
assertEquals("correct y", 600, (int) pixels.x);
// and the reverse transform
mc.getViewport().getWorldToScreen().inverseTransform(pixels, rDegs);
System.out.println("degs:" + rDegs);
assertEquals("correct x", 5, (int) rDegs.x);
assertEquals("correct y", 4, (int) rDegs.y);
}
public void testTwo() throws NoSuchAuthorityCodeException,
FactoryException, NoninvertibleTransformException
{
MapContent mc = new MapContent();
// set a coordinate reference system
CoordinateReferenceSystem crs = CRS.decode("EPSG:4326");
mc.getViewport().setCoordinateReferenceSystem(crs);
// set a data area
DirectPosition2D tlDegs = new DirectPosition2D(45, -5);
DirectPosition2D brDegs = new DirectPosition2D(41, -1);
Envelope2D env = new Envelope2D(tlDegs, brDegs);
ReferencedEnvelope rEnv = new ReferencedEnvelope(env, crs);
mc.getViewport().setBounds(rEnv);
// set a screen area
mc.getViewport().setScreenArea(new Rectangle(0, 0, 800, 200));
// sort out the aspect ration
mc.getViewport().setMatchingAspectRatio(true);
// try with series of points
System.out.println("test 2:"
+ mc.getViewport().getWorldToScreen()
.transform(new DirectPosition2D(45, -4), null));
System.out.println("test 2:"
+ mc.getViewport().getWorldToScreen()
.transform(new DirectPosition2D(44, -4), null));
System.out.println("test 2:"
+ mc.getViewport().getWorldToScreen()
.transform(new DirectPosition2D(43, -4), null));
System.out.println("test 2:"
+ mc.getViewport().getWorldToScreen()
.transform(new DirectPosition2D(42, -4), null));
System.out.println("test 2:"
+ mc.getViewport().getWorldToScreen()
.transform(new DirectPosition2D(41, -4), null));
// try with series of points
System.out.println("test 3:"
+ mc.getViewport().getWorldToScreen()
.transform(new DirectPosition2D(45, -5), null));
System.out.println("test 3:"
+ mc.getViewport().getWorldToScreen()
.transform(new DirectPosition2D(45, -4), null));
System.out.println("test 3:"
+ mc.getViewport().getWorldToScreen()
.transform(new DirectPosition2D(45, -3), null));
System.out.println("test 3:"
+ mc.getViewport().getWorldToScreen()
.transform(new DirectPosition2D(45, -2), null));
System.out.println("test 3:"
+ mc.getViewport().getWorldToScreen()
.transform(new DirectPosition2D(45, -1), null));
System.out.println("test 3:"
+ mc.getViewport().getWorldToScreen()
.transform(new DirectPosition2D(45, 0), null));
}
public void testZoomArea() throws MismatchedDimensionException, TransformException
{
final GtProjection proj = new GtProjection();
WorldLocation.setModel(new CompletelyFlatEarth());
final WorldLocation oldTopLeft = new WorldLocation(0, 0, 0);
final WorldLocation oldBottomRight = new WorldLocation(10, 10, 0);
final WorldArea oldArea = new WorldArea(oldTopLeft, oldBottomRight);
proj.setDataArea(oldArea);
proj.setScreenArea(new Dimension(100, 100));
final WorldLocation topLeft = new WorldLocation(0, 0, 0);
final WorldLocation bottomRight = new WorldLocation(5, 5, 0);
final WorldArea area = new WorldArea(topLeft, bottomRight);
proj.zoom(2, area);
assertEquals(new WorldLocation(0, 0, 0), proj.getDataArea().getTopLeft());
assertEquals(new WorldLocation(20, 20, 0), proj.getDataArea().getBottomRight());
}
}
}
|
package com.intellij.uiDesigner.make;
import com.intellij.openapi.application.ApplicationNamesInfo;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.util.InheritanceUtil;
import com.intellij.uiDesigner.*;
import com.intellij.uiDesigner.compiler.*;
import com.intellij.uiDesigner.core.SupportCode;
import com.intellij.uiDesigner.lw.*;
import com.intellij.uiDesigner.shared.BorderType;
import com.intellij.util.IncorrectOperationException;
import gnu.trove.TIntObjectHashMap;
import gnu.trove.TObjectIntHashMap;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.awt.*;
import java.util.*;
public final class FormSourceCodeGenerator {
@NonNls private StringBuffer myBuffer;
private Stack<Boolean> myIsFirstParameterStack;
private final Project myProject;
private final ArrayList<FormErrorInfo> myErrors;
private boolean myNeedLoadLabelText;
private boolean myNeedLoadButtonText;
private static Map<Class, LayoutSourceGenerator> ourComponentLayoutCodeGenerators = new HashMap<Class, LayoutSourceGenerator>();
private static Map<String, LayoutSourceGenerator> ourContainerLayoutCodeGenerators = new HashMap<String, LayoutSourceGenerator>();
@NonNls private static TIntObjectHashMap<String> ourFontStyleMap = new TIntObjectHashMap<String>();
@NonNls private static TIntObjectHashMap<String> ourTitleJustificationMap = new TIntObjectHashMap<String>();
@NonNls private static TIntObjectHashMap<String> ourTitlePositionMap = new TIntObjectHashMap<String>();
static {
ourComponentLayoutCodeGenerators.put(LwSplitPane.class, new SplitPaneLayoutSourceGenerator());
ourComponentLayoutCodeGenerators.put(LwTabbedPane.class, new TabbedPaneLayoutSourceGenerator());
ourComponentLayoutCodeGenerators.put(LwScrollPane.class, new ScrollPaneLayoutSourceGenerator());
ourComponentLayoutCodeGenerators.put(LwToolBar.class, new ToolBarLayoutSourceGenerator());
ourFontStyleMap.put(Font.PLAIN, "java.awt.Font.PLAIN");
ourFontStyleMap.put(Font.BOLD, "java.awt.Font.BOLD");
ourFontStyleMap.put(Font.ITALIC, "java.awt.Font.ITALIC");
ourFontStyleMap.put(Font.BOLD | Font.ITALIC, "java.awt.Font.BOLD | java.awt.Font.ITALIC");
ourTitlePositionMap.put(0, "javax.swing.border.TitledBorder.DEFAULT_POSITION");
ourTitlePositionMap.put(1, "javax.swing.border.TitledBorder.ABOVE_TOP");
ourTitlePositionMap.put(2, "javax.swing.border.TitledBorder.TOP");
ourTitlePositionMap.put(3, "javax.swing.border.TitledBorder.BELOW_TOP");
ourTitlePositionMap.put(4, "javax.swing.border.TitledBorder.ABOVE_BOTTOM");
ourTitlePositionMap.put(5, "javax.swing.border.TitledBorder.BOTTOM");
ourTitlePositionMap.put(6, "javax.swing.border.TitledBorder.BELOW_BOTTOM");
ourTitleJustificationMap.put(0, "javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION");
ourTitleJustificationMap.put(1, "javax.swing.border.TitledBorder.LEFT");
ourTitleJustificationMap.put(2, "javax.swing.border.TitledBorder.CENTER");
ourTitleJustificationMap.put(3, "javax.swing.border.TitledBorder.RIGHT");
ourTitleJustificationMap.put(4, "javax.swing.border.TitledBorder.LEADING");
ourTitleJustificationMap.put(5, "javax.swing.border.TitledBorder.TRAILING");
}
public FormSourceCodeGenerator(@NotNull final Project project){
myProject = project;
myErrors = new ArrayList<FormErrorInfo>();
}
public void generate(final VirtualFile formFile) {
myNeedLoadLabelText = false;
myNeedLoadButtonText = false;
final Module module = VfsUtil.getModuleForFile(myProject, formFile);
if (module == null) {
return;
}
// ensure that new instances of generators are used for every run
ourContainerLayoutCodeGenerators.clear();
ourContainerLayoutCodeGenerators.put(UIFormXmlConstants.LAYOUT_INTELLIJ, new GridLayoutSourceGenerator());
ourContainerLayoutCodeGenerators.put(UIFormXmlConstants.LAYOUT_GRIDBAG, new GridBagLayoutSourceGenerator());
ourContainerLayoutCodeGenerators.put(UIFormXmlConstants.LAYOUT_BORDER, new BorderLayoutSourceGenerator());
ourContainerLayoutCodeGenerators.put(UIFormXmlConstants.LAYOUT_FLOW, new FlowLayoutSourceGenerator());
ourContainerLayoutCodeGenerators.put(UIFormXmlConstants.LAYOUT_CARD, new CardLayoutSourceGenerator());
ourContainerLayoutCodeGenerators.put(UIFormXmlConstants.LAYOUT_FORM, new FormLayoutSourceGenerator());
myErrors.clear();
final PsiPropertiesProvider propertiesProvider = new PsiPropertiesProvider(module);
final Document doc = FileDocumentManager.getInstance().getDocument(formFile);
final LwRootContainer rootContainer;
try {
rootContainer = Utils.getRootContainer(doc.getText(), propertiesProvider);
}
catch (AlienFormFileException ignored) {
// ignoring this file
return;
}
catch (Exception e) {
myErrors.add(new FormErrorInfo(null, UIDesignerBundle.message("error.cannot.process.form.file", e)));
return;
}
if (rootContainer.getClassToBind() == null) {
// form skipped - no class to bind
return;
}
ErrorAnalyzer.analyzeErrors(module, formFile, null, rootContainer, null);
FormEditingUtil.iterate(
rootContainer,
new FormEditingUtil.ComponentVisitor<LwComponent>() {
public boolean visit(final LwComponent iComponent) {
final ErrorInfo errorInfo = ErrorAnalyzer.getErrorForComponent(iComponent);
if (errorInfo != null) {
String message;
if (iComponent.getBinding() != null) {
message = UIDesignerBundle.message("error.for.component", iComponent.getBinding(), errorInfo.myDescription);
}
else {
message = errorInfo.myDescription;
}
myErrors.add(new FormErrorInfo(iComponent.getId(), message));
}
return true;
}
}
);
if (myErrors.size() != 0) {
return;
}
try {
_generate(rootContainer, module);
}
catch (ClassToBindNotFoundException e) {
// ignore
}
catch (CodeGenerationException e) {
myErrors.add(new FormErrorInfo(e.getComponentId(), e.getMessage()));
}
catch (IncorrectOperationException e) {
myErrors.add(new FormErrorInfo(null, e.getMessage()));
}
}
public ArrayList<FormErrorInfo> getErrors() {
return myErrors;
}
private void _generate(final LwRootContainer rootContainer, final Module module) throws CodeGenerationException, IncorrectOperationException{
myBuffer = new StringBuffer();
myIsFirstParameterStack = new Stack<Boolean>();
final HashMap<LwComponent,String> component2variable = new HashMap<LwComponent,String>();
final TObjectIntHashMap<String> class2variableIndex = new TObjectIntHashMap<String>();
final HashMap<String,LwComponent> id2component = new HashMap<String, LwComponent>();
if (rootContainer.getComponentCount() != 1) {
throw new CodeGenerationException(null, UIDesignerBundle.message("error.one.toplevel.component.required"));
}
final LwComponent topComponent = (LwComponent)rootContainer.getComponent(0);
String id = Utils.findNotEmptyPanelWithXYLayout(topComponent);
if (id != null) {
throw new CodeGenerationException(id, UIDesignerBundle.message("error.nonempty.xy.panels.found"));
}
final PsiClass classToBind = FormEditingUtil.findClassToBind(module, rootContainer.getClassToBind());
if (classToBind == null) {
throw new ClassToBindNotFoundException(UIDesignerBundle.message("error.class.to.bind.not.found", rootContainer.getClassToBind()));
}
if (Utils.getCustomCreateComponentCount(rootContainer) > 0) {
if (FormEditingUtil.findCreateComponentsMethod(classToBind) == null) {
throw new CodeGenerationException(null, UIDesignerBundle.message("error.no.custom.create.method"));
}
myBuffer.append(AsmCodeGenerator.CREATE_COMPONENTS_METHOD_NAME).append("();");
}
generateSetupCodeForComponent(topComponent,
component2variable,
class2variableIndex,
id2component, module, classToBind);
generateComponentReferenceProperties(topComponent, component2variable, class2variableIndex, id2component, classToBind);
generateButtonGroups(rootContainer, component2variable, class2variableIndex, id2component, classToBind);
final String methodText = myBuffer.toString();
final PsiManager psiManager = PsiManager.getInstance(module.getProject());
final PsiElementFactory elementFactory = psiManager.getElementFactory();
final PsiClass newClass = (PsiClass) classToBind.copy();
cleanup(newClass);
// [anton] the comments are written according to the SCR 26896
final PsiClass fakeClass = elementFactory.createClassFromText(
"{\n" +
"// GUI initializer generated by " + ApplicationNamesInfo.getInstance().getFullProductName() + " GUI Designer\n" +
"// >>> IMPORTANT!! <<<\n" +
"// DO NOT EDIT OR ADD ANY CODE HERE!\n" +
"" + AsmCodeGenerator.SETUP_METHOD_NAME + "();\n" +
"}\n" +
"\n" +
"/** Method generated by " + ApplicationNamesInfo.getInstance().getFullProductName() + " GUI Designer\n" +
" * >>> IMPORTANT!! <<<\n" +
" * DO NOT edit this method OR call it in your code!\n" +
" * @noinspection ALL\n" +
" */\n" +
"private void " + AsmCodeGenerator.SETUP_METHOD_NAME + "()\n" +
"{\n" +
methodText +
"}\n",
null
);
final PsiMethod method = (PsiMethod) newClass.add(fakeClass.getMethods()[0]);
PsiElement initializer = null;
// don't generate initializer block if $$$setupUI$$$() is called explicitly from one of the constructors
boolean needInitializer = true;
for(PsiMethod constructor: newClass.getConstructors()) {
if (containsMethodIdentifier(constructor, method)) {
needInitializer = false;
break;
}
}
if (needInitializer) {
initializer = newClass.addBefore(fakeClass.getInitializers()[0], method);
}
@NonNls final String grcMethodText = "public javax.swing.JComponent " + AsmCodeGenerator.GET_ROOT_COMPONENT_METHOD_NAME +
"() { return " + topComponent.getBinding() + "; }";
generateMethodIfRequired(newClass, method, AsmCodeGenerator.GET_ROOT_COMPONENT_METHOD_NAME, grcMethodText, topComponent.getBinding() != null);
final String loadButtonTextMethodText = getLoadMethodText(AsmCodeGenerator.LOAD_BUTTON_TEXT_METHOD, AbstractButton.class, module);
generateMethodIfRequired(newClass, method, AsmCodeGenerator.LOAD_BUTTON_TEXT_METHOD, loadButtonTextMethodText, myNeedLoadButtonText);
final String loadLabelTextMethodText = getLoadMethodText(AsmCodeGenerator.LOAD_LABEL_TEXT_METHOD, JLabel.class, module);
generateMethodIfRequired(newClass, method, AsmCodeGenerator.LOAD_LABEL_TEXT_METHOD, loadLabelTextMethodText, myNeedLoadLabelText);
final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(module.getProject());
codeStyleManager.shortenClassReferences(method);
if (initializer != null) {
codeStyleManager.shortenClassReferences(initializer);
}
codeStyleManager.reformat(newClass);
final String newText = newClass.getText();
final String oldText = classToBind.getText();
if (!newText.equals(oldText)) {
classToBind.replace(newClass);
}
}
@NonNls
private String getLoadMethodText(final String methodName, final Class componentClass, Module module) {
final boolean needIndex = haveSetDisplayedMnemonic(componentClass, module);
return
"/** @noinspection ALL */ " +
"private void " + methodName + "(" + componentClass.getName() + " component, java.lang.String text) {" +
" StringBuffer result = new StringBuffer(); " +
" boolean haveMnemonic = false; " +
" char mnemonic = '\\0';" +
(needIndex ? "int mnemonicIndex = -1;" : "") +
" for(int i=0; i<text.length(); i++) {" +
" if (text.charAt(i) == '&') {" +
" i++;" +
" if (i == text.length()) break;" +
" if (!haveMnemonic && text.charAt(i) != '&') {" +
" haveMnemonic = true;" +
" mnemonic = text.charAt(i);" +
(needIndex ? "mnemonicIndex = result.length();" : "") +
" }" +
" }" +
" result.append(text.charAt(i));" +
" }" +
" component.setText(result.toString()); " +
" if (haveMnemonic) {" +
(componentClass.equals(AbstractButton.class)
? " component.setMnemonic(mnemonic);"
: " component.setDisplayedMnemonic(mnemonic);") +
(needIndex ? "component.setDisplayedMnemonicIndex(mnemonicIndex);" : "") +
"} }";
}
private void generateMethodIfRequired(PsiClass aClass, PsiMethod anchor, final String methodName, String methodText, boolean condition) throws IncorrectOperationException {
PsiElementFactory elementFactory = PsiManager.getInstance(myProject).getElementFactory();
PsiMethod newMethod = null;
PsiMethod[] oldMethods = aClass.findMethodsByName(methodName, false);
if (!condition) {
for(PsiMethod oldMethod: oldMethods) {
oldMethod.delete();
}
}
else {
newMethod = elementFactory.createMethodFromText(methodText, aClass);
if (oldMethods.length > 0) {
oldMethods [0].replace(newMethod);
}
else {
aClass.addAfter(newMethod, anchor);
}
}
if (newMethod != null) {
CodeStyleManager csm = CodeStyleManager.getInstance(myProject);
csm.shortenClassReferences(newMethod);
}
}
public static void cleanup(final PsiClass aClass) throws IncorrectOperationException{
final PsiMethod[] methods = aClass.findMethodsByName(AsmCodeGenerator.SETUP_METHOD_NAME, false);
for (final PsiMethod method: methods) {
final PsiClassInitializer[] initializers = aClass.getInitializers();
for (final PsiClassInitializer initializer : initializers) {
if (containsMethodIdentifier(initializer, method)) {
initializer.delete();
}
}
method.delete();
}
deleteMethods(aClass, AsmCodeGenerator.GET_ROOT_COMPONENT_METHOD_NAME);
deleteMethods(aClass, AsmCodeGenerator.LOAD_BUTTON_TEXT_METHOD);
deleteMethods(aClass, AsmCodeGenerator.LOAD_LABEL_TEXT_METHOD);
}
private static void deleteMethods(final PsiClass aClass, final String methodName) throws IncorrectOperationException {
final PsiMethod[] grcMethods = aClass.findMethodsByName(methodName, false);
for(final PsiMethod grcMethod: grcMethods) {
grcMethod.delete();
}
}
private static boolean containsMethodIdentifier(final PsiElement element, final PsiMethod setupMethod) {
if (element instanceof PsiMethodCallExpression) {
final PsiMethod psiMethod = ((PsiMethodCallExpression)element).resolveMethod();
if (setupMethod.equals(psiMethod)){
return true;
}
}
final PsiElement[] children = element.getChildren();
for (int i = children.length - 1; i >= 0; i
if (containsMethodIdentifier(children[i], setupMethod)) {
return true;
}
}
return false;
}
private void generateSetupCodeForComponent(final LwComponent component,
final HashMap<LwComponent, String> component2TempVariable,
final TObjectIntHashMap<String> class2variableIndex,
final HashMap<String, LwComponent> id2component,
final Module module,
final PsiClass aClass) throws CodeGenerationException{
id2component.put(component.getId(), component);
GlobalSearchScope globalSearchScope = module.getModuleWithDependenciesAndLibrariesScope(false);
final LwContainer parent = component.getParent();
final String variable = getVariable(component, component2TempVariable, class2variableIndex, aClass);
final String componentClass = component instanceof LwNestedForm
? getNestedFormClass(module, (LwNestedForm) component)
: getComponentLayoutGenerator(component.getParent()).mapComponentClass(component.getComponentClassName());
if (component.isCustomCreate() && component.getBinding() == null) {
throw new CodeGenerationException(component.getId(), UIDesignerBundle.message("error.custom.create.no.binding"));
}
if (!component.isCustomCreate()) {
final String binding = component.getBinding();
if (binding != null) {
myBuffer.append(binding);
}
else {
myBuffer.append("final ");
myBuffer.append(componentClass);
myBuffer.append(" ");
myBuffer.append(variable);
}
myBuffer.append('=');
startConstructor(componentClass);
endConstructor(); // will finish the line
}
if (component instanceof LwContainer) {
getComponentLayoutGenerator((LwContainer) component).generateContainerLayout((LwContainer) component, this, variable);
}
// introspected properties
final LwIntrospectedProperty[] introspectedProperties = component.getAssignedIntrospectedProperties();
// see SCR #35990
Arrays.sort(introspectedProperties, new Comparator<LwIntrospectedProperty>() {
public int compare(LwIntrospectedProperty p1, LwIntrospectedProperty p2) {
return p1.getName().compareTo(p2.getName());
}
});
for (final LwIntrospectedProperty property : introspectedProperties) {
if (property instanceof LwIntroComponentProperty) {
// component properties are processed in second pass
continue;
}
Object value = component.getPropertyValue(property);
//noinspection HardCodedStringLiteral
final boolean isTextWithMnemonicProperty =
"text".equals(property.getName()) &&
(isAssignableFrom(AbstractButton.class.getName(), componentClass, globalSearchScope) ||
isAssignableFrom(JLabel.class.getName(), componentClass, globalSearchScope));
// handle resource bundles
if (property instanceof LwRbIntroStringProperty) {
final StringDescriptor descriptor = (StringDescriptor)value;
if (descriptor.getValue() == null) {
if (isTextWithMnemonicProperty) {
if (isAssignableFrom(AbstractButton.class.getName(), componentClass, globalSearchScope)) {
myNeedLoadButtonText = true;
startMethodCall("this", AsmCodeGenerator.LOAD_BUTTON_TEXT_METHOD);
pushVar(variable);
push(descriptor);
endMethod();
}
else {
myNeedLoadLabelText = true;
startMethodCall("this", AsmCodeGenerator.LOAD_LABEL_TEXT_METHOD);
pushVar(variable);
push(descriptor);
endMethod();
}
}
else {
startMethodCall(variable, property.getWriteMethodName());
push(descriptor);
endMethod();
}
continue;
}
else {
value = descriptor.getValue();
}
}
else if (property instanceof LwIntroListModelProperty) {
generateListModelProperty(property, class2variableIndex, aClass, value, variable);
continue;
}
SupportCode.TextWithMnemonic textWithMnemonic = null;
if (isTextWithMnemonicProperty) {
textWithMnemonic = SupportCode.parseText((String)value);
value = textWithMnemonic.myText;
}
final String propertyClass = property.getPropertyClassName();
if (propertyClass.equals(Color.class.getName())) {
ColorDescriptor descriptor = (ColorDescriptor) value;
if (!descriptor.isColorSet()) continue;
}
startMethodCall(variable, property.getWriteMethodName());
if (propertyClass.equals(Dimension.class.getName())) {
newDimension((Dimension)value);
}
else if (propertyClass.equals(Integer.class.getName())) {
push(((Integer)value).intValue());
}
else if (propertyClass.equals(Double.class.getName())) {
push(((Double)value).doubleValue());
}
else if (propertyClass.equals(Float.class.getName())) {
push(((Float)value).floatValue());
}
else if (propertyClass.equals(Boolean.class.getName())) {
push(((Boolean)value).booleanValue());
}
else if (propertyClass.equals(Rectangle.class.getName())) {
newRectangle((Rectangle)value);
}
else if (propertyClass.equals(Insets.class.getName())) {
newInsets((Insets)value);
}
else if (propertyClass.equals(String.class.getName())) {
push((String)value);
}
else if (propertyClass.equals(Color.class.getName())) {
pushColor((ColorDescriptor) value);
}
else if (propertyClass.equals(Font.class.getName())) {
pushFont(variable, (FontDescriptor) value, property.getReadMethodName());
}
else if (propertyClass.equals(Icon.class.getName())) {
pushIcon((IconDescriptor) value);
}
else if (property instanceof LwIntroEnumProperty) {
pushVar(propertyClass.replace('$', '.') + "." + value.toString());
}
else {
throw new RuntimeException("unexpected property class: " + propertyClass);
}
endMethod();
// special handling of mnemonics
if (!isTextWithMnemonicProperty) {
continue;
}
if (textWithMnemonic.myMnemonicIndex == -1) {
continue;
}
if (isAssignableFrom(AbstractButton.class.getName(), componentClass, globalSearchScope)) {
generateSetMnemonic(variable, textWithMnemonic, module, "setMnemonic", AbstractButton.class);
}
else if (isAssignableFrom(JLabel.class.getName(), componentClass, globalSearchScope)) {
generateSetMnemonic(variable, textWithMnemonic, module, "setDisplayedMnemonic", JLabel.class);
}
}
generateClientProperties(component, variable);
// add component to parent
if (!(component.getParent() instanceof LwRootContainer)) {
final String parentVariable = getVariable(parent, component2TempVariable, class2variableIndex, aClass);
String componentVar = variable;
if (component instanceof LwNestedForm) {
componentVar = variable + "." + AsmCodeGenerator.GET_ROOT_COMPONENT_METHOD_NAME + "()";
}
getComponentLayoutGenerator(component.getParent()).generateComponentLayout(component, this, componentVar, parentVariable);
}
if (component instanceof LwContainer) {
final LwContainer container = (LwContainer)component;
generateBorder(container, variable);
for (int i = 0; i < container.getComponentCount(); i++) {
generateSetupCodeForComponent((LwComponent)container.getComponent(i), component2TempVariable, class2variableIndex, id2component,
module, aClass);
}
}
}
private void generateSetMnemonic(final String variable, final SupportCode.TextWithMnemonic textWithMnemonic, final Module module,
@NonNls final String setMethodName, final Class controlClass) {
startMethodCall(variable, setMethodName);
pushVar("'" + textWithMnemonic.getMnemonicChar() + "'");
endMethod();
if (haveSetDisplayedMnemonic(controlClass, module)) {
// generated code needs to be compatible with jdk 1.3
startMethodCall(variable, "setDisplayedMnemonicIndex");
push(textWithMnemonic.myMnemonicIndex);
endMethod();
}
}
private boolean haveSetDisplayedMnemonic(final Class controlClass, final Module module) {
PsiClass aClass = PsiManager.getInstance(myProject).findClass(controlClass.getName(), module.getModuleWithLibrariesScope());
return aClass != null && aClass.findMethodsByName("setDisplayedMnemonicIndex", true).length > 0;
}
private void generateListModelProperty(final LwIntrospectedProperty property, final TObjectIntHashMap<String> class2variableIndex,
final PsiClass aClass, final Object value, final String variable) {
String valueClassName;
if (property.getPropertyClassName().equals(ComboBoxModel.class.getName())) {
valueClassName = DefaultComboBoxModel.class.getName();
}
else {
valueClassName = DefaultListModel.class.getName();
}
String modelVarName = generateUniqueVariableName(valueClassName, class2variableIndex, aClass);
myBuffer.append("final ");
myBuffer.append(valueClassName);
myBuffer.append(" ");
myBuffer.append(modelVarName);
myBuffer.append("= new ").append(valueClassName).append("();");
String[] items = (String[]) value;
for(String item: items) {
startMethodCall(modelVarName, "addElement");
push(item);
endMethod();
}
startMethodCall(variable, property.getWriteMethodName());
pushVar(modelVarName);
endMethod();
}
private void generateBorder(final LwContainer container, final String variable) {
final BorderType borderType = container.getBorderType();
final StringDescriptor borderTitle = container.getBorderTitle();
final Insets borderSize = container.getBorderSize();
final String borderFactoryMethodName = borderType.getBorderFactoryMethodName();
final boolean borderNone = borderType.equals(BorderType.NONE);
if (!borderNone || borderTitle != null) {
startMethodCall(variable, "setBorder");
startStaticMethodCall(BorderFactory.class, "createTitledBorder");
if (!borderNone) {
startStaticMethodCall(BorderFactory.class, borderFactoryMethodName);
if (borderType.equals(BorderType.LINE)) {
if (container.getBorderColor() == null) {
pushVar("Color.black");
}
else {
pushColor(container.getBorderColor());
}
}
else if (borderType.equals(BorderType.EMPTY) && borderSize != null) {
push(borderSize.top);
push(borderSize.left);
push(borderSize.bottom);
push(borderSize.right);
}
endMethod();
}
else if (isCustomBorder(container)) {
push((String) null);
}
push(borderTitle);
if (isCustomBorder(container)) {
push(container.getBorderTitleJustification(), ourTitleJustificationMap);
push(container.getBorderTitlePosition(), ourTitlePositionMap);
if (container.getBorderTitleFont() != null || container.getBorderTitleColor() != null) {
if (container.getBorderTitleFont() == null) {
push((String) null);
}
else {
pushFont(variable, container.getBorderTitleFont(), "getFont");
}
if (container.getBorderTitleColor() != null) {
pushColor(container.getBorderTitleColor());
}
}
}
endMethod(); // createTitledBorder
endMethod(); // setBorder
}
}
private static boolean isCustomBorder(final LwContainer container) {
return container.getBorderTitleJustification() != 0 || container.getBorderTitlePosition() != 0 ||
container.getBorderTitleColor() != null || container.getBorderTitleFont() != null;
}
private void generateClientProperties(final LwComponent component, final String variable) throws CodeGenerationException {
HashMap props = component.getDelegeeClientProperties();
for (final Object o : props.entrySet()) {
Map.Entry e = (Map.Entry)o;
startMethodCall(variable, "putClientProperty");
push((String) e.getKey());
Object value = e.getValue();
if (value instanceof StringDescriptor) {
push(((StringDescriptor) value).getValue());
}
else if (value instanceof Boolean) {
if (((Boolean) value).booleanValue()) {
pushVar("Boolean.TRUE");
}
else {
pushVar("Boolean.FALSE");
}
}
else {
startConstructor(value.getClass().getName());
if (value instanceof Integer) {
push(((Integer) value).intValue());
}
else if (value instanceof Double) {
push(((Double) value).doubleValue());
}
else {
throw new CodeGenerationException(component.getId(), "Unknown client property value type");
}
endConstructor();
}
endMethod();
}
}
private static String getNestedFormClass(Module module, final LwNestedForm nestedForm) throws CodeGenerationException {
final LwRootContainer container;
try {
container = new PsiNestedFormLoader(module).loadForm(nestedForm.getFormFileName());
return container.getClassToBind();
}
catch (Exception e) {
throw new CodeGenerationException(nestedForm.getId(), e.getMessage());
}
}
private void generateComponentReferenceProperties(final LwComponent component,
final HashMap<LwComponent, String> component2variable,
final TObjectIntHashMap<String> class2variableIndex,
final HashMap<String, LwComponent> id2component,
final PsiClass aClass) {
String variable = getVariable(component, component2variable, class2variableIndex, aClass);
final LwIntrospectedProperty[] introspectedProperties = component.getAssignedIntrospectedProperties();
for (final LwIntrospectedProperty property : introspectedProperties) {
if (property instanceof LwIntroComponentProperty) {
String componentId = (String) component.getPropertyValue(property);
if (componentId != null && componentId.length() > 0) {
LwComponent target = id2component.get(componentId);
if (target != null) {
String targetVariable = getVariable(target, component2variable, class2variableIndex, aClass);
startMethodCall(variable, property.getWriteMethodName());
pushVar(targetVariable);
endMethod();
}
}
}
}
if (component instanceof LwContainer) {
final LwContainer container = (LwContainer)component;
for (int i = 0; i < container.getComponentCount(); i++) {
generateComponentReferenceProperties((LwComponent)container.getComponent(i), component2variable, class2variableIndex, id2component,
aClass);
}
}
}
private void generateButtonGroups(final LwRootContainer rootContainer,
final HashMap<LwComponent, String> component2variable,
final TObjectIntHashMap<String> class2variableIndex,
final HashMap<String, LwComponent> id2component,
final PsiClass aClass) {
IButtonGroup[] groups = rootContainer.getButtonGroups();
boolean haveGroupDeclaration = false;
for(IButtonGroup group: groups) {
boolean haveGroupConstructor = false;
String[] ids = group.getComponentIds();
for(String id: ids) {
LwComponent target = id2component.get(id);
if (target != null) {
if (!haveGroupConstructor) {
if (group.isBound()) {
append(group.getName());
}
else {
if (!haveGroupDeclaration) {
append("javax.swing.ButtonGroup buttonGroup;");
haveGroupDeclaration = true;
}
append("buttonGroup");
}
append("= new javax.swing.ButtonGroup();");
haveGroupConstructor = true;
}
String targetVariable = getVariable(target, component2variable, class2variableIndex, aClass);
startMethodCall(group.isBound() ? group.getName() : "buttonGroup", "add");
pushVar(targetVariable);
endMethod();
}
}
}
}
private static LayoutSourceGenerator getComponentLayoutGenerator(final LwContainer container) {
LayoutSourceGenerator generator = ourComponentLayoutCodeGenerators.get(container.getClass());
if (generator != null) {
return generator;
}
LwContainer parent = container;
while(parent != null) {
final String layoutManager = parent.getLayoutManager();
if (layoutManager != null && layoutManager.length() > 0) {
generator = ourContainerLayoutCodeGenerators.get(layoutManager);
if (generator != null) {
return generator;
}
}
parent = parent.getParent();
}
return GridLayoutSourceGenerator.INSTANCE;
}
void push(final StringDescriptor descriptor) {
if (descriptor == null) {
push((String)null);
}
else if (descriptor.getValue() != null) {
push(descriptor.getValue());
}
else {
startMethodCall("java.util.ResourceBundle.getBundle(\"" + descriptor.getBundleName() + "\")", "getString");
push(descriptor.getKey());
endMethod();
}
}
private void pushColor(final ColorDescriptor descriptor) {
if (descriptor.getColor() != null) {
startConstructor(Color.class.getName());
push(descriptor.getColor().getRGB());
endConstructor();
}
else if (descriptor.getSwingColor() != null) {
startStaticMethodCall(UIManager.class, "getColor");
push(descriptor.getSwingColor());
endMethod();
}
else if (descriptor.getSystemColor() != null) {
pushVar("java.awt.SystemColor." + descriptor.getSystemColor());
}
else if (descriptor.getAWTColor() != null) {
pushVar("java.awt.Color." + descriptor.getAWTColor());
}
else {
throw new IllegalStateException("Unknown color type");
}
}
private void pushFont(final String variable, final FontDescriptor fontDescriptor, @NonNls final String getterName) {
if (fontDescriptor.getSwingFont() != null) {
startStaticMethodCall(UIManager.class, "getFont");
push(fontDescriptor.getSwingFont());
endMethod();
}
else {
startConstructor(Font.class.getName());
if (fontDescriptor.getFontName() != null) {
push(fontDescriptor.getFontName());
}
else {
pushVar(variable + "." + getterName + "().getName()");
}
if (fontDescriptor.getFontStyle() >= 0) {
push(fontDescriptor.getFontStyle(), ourFontStyleMap);
}
else {
pushVar(variable + "." + getterName + "().getStyle()");
}
if (fontDescriptor.getFontSize() >= 0) {
push(fontDescriptor.getFontSize());
}
else {
pushVar(variable + "." + getterName + "().getSize()");
}
endMethod();
}
}
public void pushIcon(final IconDescriptor iconDescriptor) {
startConstructor(ImageIcon.class.getName());
startMethodCall("getClass()", "getResource");
push("/" + iconDescriptor.getIconPath());
endMethod();
endMethod();
}
private boolean isAssignableFrom(final String className, final String fromName, final GlobalSearchScope scope) {
final PsiClass aClass = PsiManager.getInstance(myProject).findClass(className, scope);
final PsiClass fromClass = PsiManager.getInstance(myProject).findClass(fromName, scope);
if (aClass == null || fromClass == null) {
return false;
}
return InheritanceUtil.isInheritorOrSelf(fromClass, aClass, true);
}
/**
* @return variable idx
*/
private static String getVariable(final LwComponent component,
final HashMap<LwComponent, String> component2variable,
final TObjectIntHashMap<String> class2variableIndex,
final PsiClass aClass) {
if (component2variable.containsKey(component)) {
return component2variable.get(component);
}
if (component.getBinding() != null) {
return component.getBinding();
}
@NonNls final String className = component instanceof LwNestedForm ? "nestedForm" : component.getComponentClassName();
String result = generateUniqueVariableName(className, class2variableIndex, aClass);
component2variable.put(component, result);
return result;
}
private static String generateUniqueVariableName(@NonNls final String className, final TObjectIntHashMap<String> class2variableIndex,
final PsiClass aClass) {
final String shortName;
if (className.startsWith("javax.swing.J")) {
shortName = className.substring("javax.swing.J".length());
}
else {
final int idx = className.lastIndexOf('.');
if (idx != -1) {
shortName = className.substring(idx + 1);
}
else {
shortName = className;
}
}
if (!class2variableIndex.containsKey(className)) class2variableIndex.put(className, 0);
String result;
do {
class2variableIndex.increment(className);
int newIndex = class2variableIndex.get(className);
result = Character.toLowerCase(shortName.charAt(0)) + shortName.substring(1) + newIndex;
} while(aClass.findFieldByName(result, true) != null);
return result;
}
void newDimensionOrNull(final Dimension dimension) {
if (dimension.width == -1 && dimension.height == -1) {
checkParameter();
myBuffer.append("null");
}
else {
newDimension(dimension);
}
}
void newDimension(final Dimension dimension) {
startConstructor(Dimension.class.getName());
push(dimension.width);
push(dimension.height);
endConstructor();
}
void newInsets(final Insets insets){
startConstructor(Insets.class.getName());
push(insets.top);
push(insets.left);
push(insets.bottom);
push(insets.right);
endConstructor();
}
private void newRectangle(final Rectangle rectangle) {
startConstructor(Rectangle.class.getName());
push(rectangle.x);
push(rectangle.y);
push(rectangle.width);
push(rectangle.height);
endConstructor();
}
void startMethodCall(@NonNls final String variable, @NonNls final String methodName) {
checkParameter();
append(variable);
myBuffer.append('.');
myBuffer.append(methodName);
myBuffer.append('(');
myIsFirstParameterStack.push(Boolean.TRUE);
}
private void startStaticMethodCall(final Class aClass, @NonNls final String methodName) {
checkParameter();
myBuffer.append(aClass.getName());
myBuffer.append('.');
myBuffer.append(methodName);
myBuffer.append('(');
myIsFirstParameterStack.push(Boolean.TRUE);
}
void endMethod() {
myBuffer.append(')');
myIsFirstParameterStack.pop();
if (myIsFirstParameterStack.empty()) {
myBuffer.append(";\n");
}
}
void startConstructor(final String className) {
checkParameter();
myBuffer.append("new ");
myBuffer.append(className);
myBuffer.append('(');
myIsFirstParameterStack.push(Boolean.TRUE);
}
void endConstructor() {
endMethod();
}
void push(final int value) {
checkParameter();
append(value);
}
void append(final int value) {
myBuffer.append(value);
}
void push(final int value, final TIntObjectHashMap map){
final String stringRepresentation = (String)map.get(value);
if (stringRepresentation != null) {
checkParameter();
myBuffer.append(stringRepresentation);
}
else {
push(value);
}
}
private void push(final double value) {
checkParameter();
append(value);
}
public void append(final double value) {
myBuffer.append(value);
}
private void push(final float value) {
checkParameter();
append(value);
}
public void append(final float value) {
myBuffer.append(value).append("f");
}
void push(final boolean value) {
checkParameter();
myBuffer.append(value);
}
void push(final String value) {
checkParameter();
if (value == null) {
myBuffer.append("null");
}
else {
myBuffer.append('"');
myBuffer.append(StringUtil.escapeStringCharacters(value));
myBuffer.append('"');
}
}
void pushVar(@NonNls final String variable) {
checkParameter();
append(variable);
}
void append(@NonNls final String text) {
myBuffer.append(text);
}
void checkParameter() {
if (!myIsFirstParameterStack.empty()) {
final Boolean b = myIsFirstParameterStack.pop();
if (b.equals(Boolean.FALSE)) {
myBuffer.append(',');
}
myIsFirstParameterStack.push(Boolean.FALSE);
}
}
}
|
package i5.las2peer.p2p;
import java.io.File;
import java.io.Serializable;
import java.lang.management.ManagementFactory;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Timer;
import java.util.TimerTask;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.Vector;
import java.util.logging.Level;
import com.sun.management.OperatingSystemMXBean;
import i5.las2peer.api.Configurable;
import i5.las2peer.api.execution.ServiceAccessDeniedException;
import i5.las2peer.api.execution.ServiceInvocationException;
import i5.las2peer.api.execution.ServiceInvocationFailedException;
import i5.las2peer.api.execution.ServiceNotAvailableException;
import i5.las2peer.api.execution.ServiceNotFoundException;
import i5.las2peer.api.logging.MonitoringEvent;
import i5.las2peer.api.p2p.ServiceNameVersion;
import i5.las2peer.api.persistency.EnvelopeAlreadyExistsException;
import i5.las2peer.api.persistency.EnvelopeException;
import i5.las2peer.api.persistency.EnvelopeNotFoundException;
import i5.las2peer.api.security.Agent;
import i5.las2peer.api.security.AgentException;
import i5.las2peer.api.security.AgentLockedException;
import i5.las2peer.api.security.AgentNotFoundException;
import i5.las2peer.api.security.AgentOperationFailedException;
import i5.las2peer.classLoaders.ClassManager;
import i5.las2peer.classLoaders.libraries.Repository;
import i5.las2peer.classLoaders.policies.DefaultPolicy;
import i5.las2peer.communication.Message;
import i5.las2peer.communication.MessageException;
import i5.las2peer.communication.RMIExceptionContent;
import i5.las2peer.communication.RMIResultContent;
import i5.las2peer.execution.RMITask;
import i5.las2peer.logging.L2pLogger;
import i5.las2peer.logging.NodeObserver;
import i5.las2peer.logging.monitoring.MonitoringObserver;
import i5.las2peer.p2p.NodeServiceCache.ServiceInstance;
import i5.las2peer.persistency.EncodingFailedException;
import i5.las2peer.persistency.EnvelopeVersion;
import i5.las2peer.persistency.NodeStorageInterface;
import i5.las2peer.security.AgentContext;
import i5.las2peer.security.AgentImpl;
import i5.las2peer.security.AgentStorage;
import i5.las2peer.security.GroupAgentImpl;
import i5.las2peer.security.InternalSecurityException;
import i5.las2peer.security.Mediator;
import i5.las2peer.security.MessageReceiver;
import i5.las2peer.security.MonitoringAgent;
import i5.las2peer.security.PassphraseAgentImpl;
import i5.las2peer.security.ServiceAgentImpl;
import i5.las2peer.security.UnlockAgentCall;
import i5.las2peer.security.UserAgentImpl;
import i5.las2peer.security.UserAgentManager;
import i5.las2peer.serialization.SerializationException;
import i5.las2peer.tools.CryptoException;
import rice.pastry.NodeHandle;
import rice.pastry.PastryNode;
import rice.pastry.socket.SocketNodeHandle;
/**
* Base class for nodes in the las2peer environment.
*
* A Node represents one enclosed unit in the network hosting an arbitrary number of agents willing to participate in
* the P2P networking.
*
*/
public abstract class Node extends Configurable implements AgentStorage, NodeStorageInterface {
/**
* The Sending mode for outgoing messages.
*/
public enum SendMode {
ANYCAST,
BROADCAST
}
/**
* Enum with the possible states of a node.
*/
public enum NodeStatus {
UNCONFIGURED,
CONFIGURED,
STARTING,
RUNNING,
CLOSING,
CLOSED
}
private final L2pLogger logger = L2pLogger.getInstance(Node.class);
/**
* For performance measurement (load balance)
*/
private OperatingSystemMXBean osBean = (com.sun.management.OperatingSystemMXBean) ManagementFactory
.getOperatingSystemMXBean();
private final NodeServiceCache nodeServiceCache;
public static final double DEFAULT_CPU_LOAD_TRESHOLD = 0.5;
/**
* cpu load threshold to determine whether the node is considered busy
*/
private double cpuLoadThreshold = DEFAULT_CPU_LOAD_TRESHOLD;
public static final int DEFAULT_NODE_SERVICE_CACHE_LIFETIME = 60;
/**
* time before cached service information becomes invalidated
*/
private int nodeServiceCacheLifetime = DEFAULT_NODE_SERVICE_CACHE_LIFETIME;
public static final int DEFAULT_NODE_SERVICE_CACHE_RESULT_COUNT = 3;
/**
* number of service answers collected during service discovery
*/
private int nodeServiceCacheResultCount = DEFAULT_NODE_SERVICE_CACHE_RESULT_COUNT;
public static final int DEFAULT_TIDY_UP_TIMER_INTERVAL = 60;
/**
* frequency of the tidy up timer
*/
private int tidyUpTimerInterval = DEFAULT_TIDY_UP_TIMER_INTERVAL;
public static final int DEFAULT_AGENT_CONTEXT_LIFETIME = 60;
/**
* period of time after which an agent context will be available for deletion
*/
private int agentContextLifetime = DEFAULT_AGENT_CONTEXT_LIFETIME;
public static final int DEFAULT_INVOCATION_RETRY_COUNT = 3;
/**
* number of retries if an RMI fails
*/
private int invocationRetryCount = DEFAULT_INVOCATION_RETRY_COUNT;
/**
* observers to be notified of all occurring events
*/
private HashSet<NodeObserver> observers = new HashSet<>();
/**
* contexts for local method invocation
*/
private Hashtable<String, AgentContext> htLocalExecutionContexts = new Hashtable<>();
/**
* Timer to tidy up hashtables etc (Contexts)
*/
private Timer tidyUpTimer;
/**
* status of this node
*/
private NodeStatus status = NodeStatus.UNCONFIGURED;
/**
* hashtable with all {@link i5.las2peer.security.MessageReceiver}s registered at this node
*/
private Hashtable<String, MessageReceiver> htRegisteredReceivers = new Hashtable<>();
/**
* map with all topics and their listeners
*/
private HashMap<Long, TreeMap<String, MessageReceiver>> mapTopicListeners = new HashMap<>();
/**
* other direction of {@link #mapTopicListeners}
*/
private HashMap<String, TreeSet<Long>> mapListenerTopics = new HashMap<>();
private ClassManager classManager = null;
private Hashtable<Long, MessageResultListener> htAnswerListeners = new Hashtable<>();
private static final String DEFAULT_INFORMATION_FILE = "etc/nodeInfo.xml";
private String sInformationFileName = DEFAULT_INFORMATION_FILE;
/**
* maps names and emails to UserAgents
*/
private UserAgentManager userManager;
/**
* maps service alias to service names
*/
private ServiceAliasManager aliasManager;
private Date startTime;
/**
* Creates a new node, if the standardObserver flag is true, an observer logging all events to a simple plain text
* log file will be generated. If not, no observer will be used at startup.
*
* @param standardObserver If true, the node uses the default logger.
*/
public Node(boolean standardObserver) {
this(null, standardObserver);
}
/**
* Creates a new node with a standard plain text log file observer.
*/
public Node() {
this(true);
}
/**
* @param classManager A default class loader used by this node.
*/
public Node(ClassManager classManager) {
this(classManager, true);
}
/**
* @param classManager A default class loader used by this node.
* @param standardObserver If true, the node uses the default logger.
*/
public Node(ClassManager classManager, boolean standardObserver) {
this(classManager, standardObserver, false);
}
/**
* Generates a new Node with the given baseClassLoader. The Observer-flags determine, which observers will be
* registered at startup.
*
* @param classManager A default class loader used by this node.
* @param standardObserver If true, the node uses the default logger.
* @param monitoringObserver If true, the monitoring is enabled for this node.
*/
public Node(ClassManager classManager, boolean standardObserver, boolean monitoringObserver) {
setFieldValues();
if (standardObserver) {
initStandardLogfile();
}
if (monitoringObserver) {
addObserver(new MonitoringObserver(50, this));
}
this.classManager = classManager;
if (classManager == null) {
this.classManager = new ClassManager(new Repository[0], this.getClass().getClassLoader(),
new DefaultPolicy());
}
nodeServiceCache = new NodeServiceCache(this, nodeServiceCacheLifetime, nodeServiceCacheResultCount);
userManager = new UserAgentManager(this);
aliasManager = new ServiceAliasManager(this);
}
/**
* Creates an observer for a standard log-file. The name of the log-file will contain the id of the node to prevent
* The event for this notification. conflicts if running multiple nodes on the same machine.
*/
private void initStandardLogfile() {
addObserver(L2pLogger.getInstance(Node.class));
}
/**
* Adds an observer to this node.
*
* @param observer The observer that should be notified.
*/
public void addObserver(NodeObserver observer) {
observers.add(observer);
}
/**
* Removes an observer from this node.
*
* @param observer The observer that should be removed.
*/
public void removeObserver(NodeObserver observer) {
observers.remove(observer);
}
/**
* Enables the service monitoring for the requested Service.
*
* @param service The service that should be monitored.
*/
public void setServiceMonitoring(ServiceAgentImpl service) {
observerNotice(MonitoringEvent.SERVICE_ADD_TO_MONITORING, this.getNodeId(), service.getIdentifier(), null, null,
"{\"serviceName\":\"" + service.getServiceNameVersion().toString() + "\",\"serviceAlias\":\""
+ service.getServiceInstance().getAlias() + "\"}");
}
/**
* Logs an event to all observers.
*
* @param event The event for this notification.
* @param remarks Some free text note or description about this event.
*/
public void observerNotice(MonitoringEvent event, String remarks) {
observerNotice(event, null, (String) null, null, null, remarks);
}
/**
* Logs an event to all observers.
*
* @param event The event for this notification.
* @param sourceNode A source node for this event
* @param remarks Some free text note or description about this event.
*/
public void observerNotice(MonitoringEvent event, Object sourceNode, String remarks) {
observerNotice(event, sourceNode, (String) null, null, null, remarks);
}
/**
* Logs an event to all observers.
*
* @param event The event for this notification.
* @param sourceNode A source node for this event
* @param sourceAgentId A source agent id for this event
* @param remarks Some free text note or description about this event.
*/
public void observerNotice(MonitoringEvent event, Object sourceNode, String sourceAgentId, String remarks) {
observerNotice(event, sourceNode, sourceAgentId, null, null, remarks);
}
/**
* Logs an event to all observers.
*
* @param event The event for this notification.
* @param sourceNode A source node for this event
* @param sourceAgent A source agent for this event
* @param remarks Some free text note or description about this event.
*/
public void observerNotice(MonitoringEvent event, Object sourceNode, MessageReceiver sourceAgent, String remarks) {
String sourceAgentId = null;
if (sourceAgent != null) {
sourceAgentId = sourceAgent.getResponsibleForAgentSafeId();
}
observerNotice(event, sourceNode, sourceAgentId, null, null, remarks);
}
/**
* Logs an event to all observers.
*
* @param event The event for this notification.
* @param sourceNode A source node for this event
* @param sourceAgent A source agent for this event
* @param destinationNode A destination node for this event
* @param destinationAgent A destination agent for this event
* @param remarks Some free text note or description about this event.
*/
public void observerNotice(MonitoringEvent event, Object sourceNode, Agent sourceAgent, Object destinationNode,
Agent destinationAgent, String remarks) {
String sourceAgentId = null;
if (sourceAgent != null) {
sourceAgentId = sourceAgent.getIdentifier();
}
String destinationAgentId = null;
if (destinationAgent != null) {
destinationAgentId = destinationAgent.getIdentifier();
}
observerNotice(event, sourceNode, sourceAgentId, destinationNode, destinationAgentId, remarks);
}
/**
* Logs an event to all observers.
*
* @param event The event for this notification.
* @param sourceNode A source node for this event
* @param sourceAgentId A source agent id for this event
* @param destinationNode A destination node for this event
* @param destinationAgentId A destination agent id for this event
* @param remarks Some free text note or description about this event.
*/
public void observerNotice(MonitoringEvent event, Object sourceNode, String sourceAgentId, Object destinationNode,
String destinationAgentId, String remarks) {
long timestamp = new Date().getTime();
String sourceNodeRepresentation = getNodeRepresentation(sourceNode);
String destinationNodeRepresentation = getNodeRepresentation(destinationNode);
for (NodeObserver ob : observers) {
ob.log(timestamp, event, sourceNodeRepresentation, sourceAgentId, destinationNodeRepresentation,
destinationAgentId, remarks);
}
}
/**
* Derive a String representation for a node from the given identifier object. The type of the object depends on the
* setting of the current node.
*
* Tries to specify an ip address and a port for an actual p2p node ({@link i5.las2peer.p2p.PastryNodeImpl} or
* {@link rice.pastry.NodeHandle}).
*
* @param node The node that should be represented.
* @return string representation for the given node object
*/
protected String getNodeRepresentation(Object node) {
if (node == null) {
return null;
} else if (node instanceof SocketNodeHandle) {
SocketNodeHandle nh = (SocketNodeHandle) node;
return nh.getId() + "/" + nh.getIdentifier();
} else if (node instanceof PastryNode) {
PastryNode pNode = (PastryNode) node;
return getNodeRepresentation(pNode.getLocalNodeHandle());
} else {
return "" + node + " (" + node.getClass().getName() + ")";
}
}
/**
* Gets the status of this node.
*
* @return status of this node
*/
public NodeStatus getStatus() {
return status;
}
/**
* Gets some kind of node identifier.
*
* @return id of this node
*/
public abstract Serializable getNodeId();
/**
* Gets the class loader, this node is bound to. In a <i>real</i> las2peer environment, this should refer to a
* {@link i5.las2peer.classLoaders.ClassManager}
*
* Otherwise, the class loader of this Node class is used.
*
* @return a class loader
*/
public ClassManager getBaseClassLoader() {
return classManager;
}
/**
* Sets the status of this node.
*
* @param newstatus The new status for this node.
*/
protected void setStatus(NodeStatus newstatus) {
if (newstatus == NodeStatus.RUNNING && this instanceof PastryNodeImpl) {
observerNotice(MonitoringEvent.NODE_STATUS_CHANGE, this.getNodeId(), "" + newstatus);
} else if (newstatus == NodeStatus.CLOSING) {
observerNotice(MonitoringEvent.NODE_STATUS_CHANGE, this.getNodeId(), "" + newstatus);
} else {
observerNotice(MonitoringEvent.NODE_STATUS_CHANGE, "" + newstatus);
}
status = newstatus;
}
/**
* Gets the filename of the current information file for this node. The file should be an XML file representation of
* a {@link NodeInformation}.
*
* @return filename
*/
public String getInformationFilename() {
return sInformationFileName;
}
/**
* Sets the nodes information filename.
*
* @param filename The filename for the information file.
*/
public void setInformationFilename(String filename) {
if (new File(filename).exists()) {
sInformationFileName = filename;
}
}
/**
* Gets information about this node including all registered service classes.
*
* @return node information
* @throws CryptoException If an issue occurs with the given key or selected algorithm.
*/
public NodeInformation getNodeInformation() throws CryptoException {
NodeInformation result = new NodeInformation(getRegisteredServices());
try {
if (sInformationFileName != null && new File(sInformationFileName).exists()) {
result = NodeInformation.createFromXmlFile(sInformationFileName, getRegisteredServices());
}
} catch (Exception e) {
e.printStackTrace();
}
result.setNodeHandle(getNodeId());
return result;
}
/**
* Gets information about a distant node.
*
* @param nodeId A node id to query
* @return information about the node
* @throws NodeNotFoundException If the node was not found
*/
public abstract NodeInformation getNodeInformation(Object nodeId) throws NodeNotFoundException;
/**
* Gets an array with identifiers of other (locally known) nodes in this network.
*
* @return array with handles of other (known) p2p network nodes
*/
public abstract Object[] getOtherKnownNodes();
/**
* Starts this node.
*
* @throws NodeException If launching the node fails
*/
protected abstract void launchSub() throws NodeException;
/**
* Starts this node.
*
* @throws NodeException If launching the node fails
*/
public final void launch() throws NodeException {
launchSub();
startTime = new Date();
startTidyUpTimer();
}
/**
* Stops the node.
*/
public synchronized void shutDown() {
stopTidyUpTimer();
startTime = null;
// avoid ConcurrentModificationEception
String[] receivers = htRegisteredReceivers.keySet().toArray(new String[0]);
for (String id : receivers) {
htRegisteredReceivers.get(id).notifyUnregister();
}
observerNotice(MonitoringEvent.NODE_SHUTDOWN, this.getNodeId(), null);
for (NodeObserver observer : observers) {
if (observer instanceof MonitoringObserver) {
try {
System.out.println("Wait a little to give the observer time to send its last message...");
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
break;
}
}
htRegisteredReceivers = new Hashtable<>();
}
/**
* Registers a (local) Agent for usage through this node. The Agent has to be unlocked before registration.
*
* @param receiver A message receiver to register
* @throws AgentAlreadyRegisteredException the given agent is already registered to this node
* @throws AgentLockedException the agent is not unlocked
* @throws AgentException any problem with the agent itself (probably on calling
* {@link i5.las2peer.security.AgentImpl#notifyRegistrationTo}
*/
public void registerReceiver(MessageReceiver receiver) throws AgentAlreadyRegisteredException, AgentException {
// TODO allow multiple mediators registered at the same time for one agent to avoid conflicts between connectors
if (getStatus() != NodeStatus.RUNNING) {
throw new IllegalStateException("You can register agents only to running nodes!");
}
if (htRegisteredReceivers.contains(receiver.getResponsibleForAgentSafeId())
&& htRegisteredReceivers.get(receiver.getResponsibleForAgentSafeId()) != receiver) {
throw new AgentAlreadyRegisteredException(
"Another instance of this agent (or mediator) is already registered here!");
}
if ((receiver instanceof AgentImpl)) {
// we have an agent
AgentImpl agent = (AgentImpl) receiver;
if (agent.isLocked()) {
throw new AgentLockedException("An agent has to be unlocked for registering at a node.");
}
try {
// ensure (unlocked) context
getAgentContext(agent);
} catch (Exception e) {
}
if (agent instanceof UserAgentImpl) {
observerNotice(MonitoringEvent.AGENT_REGISTERED, this.getNodeId(), agent, "UserAgent");
} else if (agent instanceof ServiceAgentImpl) {
observerNotice(MonitoringEvent.AGENT_REGISTERED, this.getNodeId(), agent, "ServiceAgent");
} else if (agent instanceof GroupAgentImpl) {
observerNotice(MonitoringEvent.AGENT_REGISTERED, this.getNodeId(), agent, "GroupAgent");
} else if (agent instanceof MonitoringAgent) {
observerNotice(MonitoringEvent.AGENT_REGISTERED, this.getNodeId(), agent, "MonitoringAgent");
}
} else if (receiver instanceof Mediator) {
// ok, we have a mediator
observerNotice(MonitoringEvent.AGENT_REGISTERED, this.getNodeId(), receiver, "Mediator");
} else {
throw new IllegalArgumentException("Given receiver is not an agent or mediator. Got "
+ receiver.getClass().getCanonicalName() + " instead");
}
htRegisteredReceivers.put(receiver.getResponsibleForAgentSafeId(), receiver);
try {
receiver.notifyRegistrationTo(this);
} catch (AgentException e) {
observerNotice(MonitoringEvent.AGENT_LOAD_FAILED, this, receiver, e.toString());
htRegisteredReceivers.remove(receiver.getResponsibleForAgentSafeId());
throw e;
} catch (Exception e) {
observerNotice(MonitoringEvent.AGENT_LOAD_FAILED, this, receiver, e.toString());
htRegisteredReceivers.remove(receiver.getResponsibleForAgentSafeId());
throw new AgentException("problems notifying agent of registration", e);
}
}
/**
* Unregisters a MessageReceiver from this node.
*
* @param receiver the receiver to unregister
* @throws AgentNotRegisteredException The given MessageReceiver is not registered to this node
* @throws NodeException error in underlying layer
*/
public void unregisterReceiver(MessageReceiver receiver) throws AgentNotRegisteredException, NodeException {
String agentId = receiver.getResponsibleForAgentSafeId();
unregisterReceiver(agentId);
// unregister from topics
if (mapListenerTopics.containsKey(agentId)) {
Long[] topics = mapListenerTopics.get(agentId).toArray(new Long[0]);
for (long topic : topics) {
unregisterReceiverFromTopic(receiver, topic);
}
}
}
private void unregisterReceiver(String agentId) throws AgentNotRegisteredException {
if (!htRegisteredReceivers.containsKey(agentId)) {
throw new AgentNotRegisteredException(agentId);
}
observerNotice(MonitoringEvent.AGENT_REMOVED, getNodeId(), agentId, "");
htRegisteredReceivers.remove(agentId).notifyUnregister();
}
/**
* register a receiver to a topic
*
* @param receiver the MessageReceiver
* @param topic the topic id
* @throws AgentNotRegisteredException The given MessageReceiver is not registered to this node
*/
public void registerReceiverToTopic(MessageReceiver receiver, long topic) throws AgentNotRegisteredException {
if (!htRegisteredReceivers.containsKey(receiver.getResponsibleForAgentSafeId())) {
throw new AgentNotRegisteredException(receiver.getResponsibleForAgentSafeId());
}
synchronized (mapListenerTopics) {
synchronized (mapTopicListeners) {
if (mapListenerTopics.get(receiver.getResponsibleForAgentSafeId()) == null) {
mapListenerTopics.put(receiver.getResponsibleForAgentSafeId(), new TreeSet<>());
}
if (mapListenerTopics.get(receiver.getResponsibleForAgentSafeId()).add(topic)) {
if (mapTopicListeners.get(topic) == null) {
mapTopicListeners.put(topic, new TreeMap<>());
}
mapTopicListeners.get(topic).put(receiver.getResponsibleForAgentSafeId(), receiver);
}
}
}
}
/**
* unregister a receiver from a topic
*
* @param receiver the receiver
* @param topic the topic id
* @throws NodeException If unregistering fails
*/
public void unregisterReceiverFromTopic(MessageReceiver receiver, long topic) throws NodeException {
unregisterReceiverFromTopic(receiver.getResponsibleForAgentSafeId(), topic);
}
private void unregisterReceiverFromTopic(String receiverId, long topic) {
synchronized (mapListenerTopics) {
synchronized (mapTopicListeners) {
if (!mapListenerTopics.containsKey(receiverId) || !mapListenerTopics.get(receiverId).contains(topic)) {
return;
}
mapListenerTopics.get(receiverId).remove(topic);
if (mapListenerTopics.get(receiverId).size() == 0) {
mapListenerTopics.remove(receiverId);
}
mapTopicListeners.get(topic).remove(receiverId);
if (mapTopicListeners.get(topic).size() == 0) {
mapTopicListeners.remove(topic);
}
}
}
}
/**
* checks if a receiver is registered to the topic
*
* @param topic topic id
* @return true if someone is registered to the topic
*/
protected boolean hasTopic(long topic) {
return mapTopicListeners.containsKey(topic);
}
/**
* Is an instance of the given agent running at this node?
*
* @param agent An agent to check for
* @return true, if the given agent is running at this node
*/
public boolean hasLocalAgent(AgentImpl agent) {
return hasLocalAgent(agent.getIdentifier());
}
/**
* Is an instance of the given agent running at this node?
*
* @param agentId An agent id to check for
* @return true, if the given agent is registered here
*/
public boolean hasLocalAgent(String agentId) {
return htRegisteredReceivers.get(agentId) != null;
}
/**
* Starts a new instance of the given service on this node. This creates, stores and registers a new service agent.
*
* @param nameVersion A service name and version to identify the service
* @param passphrase A passphrase to secure this instance
* @return Returns the local service agent instance
* @throws CryptoException
* @throws AgentException
*/
public ServiceAgentImpl startService(ServiceNameVersion nameVersion, String passphrase)
throws CryptoException, AgentException {
ServiceAgentImpl serviceAgent = ServiceAgentImpl.createServiceAgent(nameVersion, passphrase);
serviceAgent.unlock(passphrase);
storeAgent(serviceAgent);
registerReceiver(serviceAgent);
return serviceAgent;
}
/**
* Stops the local service instance.
*
* @param nameVersion A service name and version to identify the service
* @throws AgentNotRegisteredException If the service is not registered locally
* @throws ServiceNotFoundException If the service is not known locally
* @throws NodeException
*/
public void stopService(ServiceNameVersion nameVersion)
throws AgentNotRegisteredException, ServiceNotFoundException, NodeException {
stopService(getLocalServiceAgent(nameVersion));
}
/**
* Stops the local service instance.
*
* @param serviceAgent
* @throws AgentNotRegisteredException If the service is not registered locally
* @throws NodeException
*/
public void stopService(ServiceAgentImpl serviceAgent) throws AgentNotRegisteredException, NodeException {
unregisterReceiver(serviceAgent);
}
/**
* Sends a message, recipient and sender are stated in the message. The node tries to find a node hosting the
* recipient and sends the message there.
*
* @param message the message to send
* @param listener a listener for getting the result separately
*/
public void sendMessage(Message message, MessageResultListener listener) {
sendMessage(message, listener, SendMode.ANYCAST);
}
/**
* Sends a message, recipient and sender are stated in the message. Depending on the mode, either all nodes running
* the given agent will be notified of this message, or only a random one.
*
* NOTE: Pastry nodes will always use broadcast at the moment!
*
* @param message the message to send
* @param listener a listener for getting the result separately
* @param mode is it a broadcast or an any-cast message?
*/
public abstract void sendMessage(Message message, MessageResultListener listener, SendMode mode);
/**
* Sends a message to the agent residing at the given node.
*
* @param message A message to send
* @param atNodeId A node id to send from
* @param listener a listener for getting the result separately
* @throws NodeNotFoundException If the node was not found
*/
public abstract void sendMessage(Message message, Object atNodeId, MessageResultListener listener)
throws NodeNotFoundException;
/**
* Sends the given response message to the given node.
*
* @param message A message to send
* @param atNodeId A node id to send from
* @throws NodeNotFoundException If the node was not found
*/
public void sendResponse(Message message, Object atNodeId) throws NodeNotFoundException {
sendMessage(message, atNodeId, null);
}
/**
* For <i>external</i> access to this node. Will be called by the (P2P) network library, when a new message has been
* received via the network and could not be handled otherwise.
*
* @param message A message that is received
* @throws AgentNotRegisteredException If the designated recipient is not known at this node
* @throws AgentException If any other issue with the agent occurs, e. g. XML not readable
* @throws MessageException If handling the message fails
*/
public void receiveMessage(Message message) throws AgentNotRegisteredException, AgentException, MessageException {
if (message.isResponse()) {
if (handoverAnswer(message)) {
return;
}
}
// Since this field is not always available
if (message.getSendingNodeId() != null) {
observerNotice(MonitoringEvent.MESSAGE_RECEIVED, message.getSendingNodeId(), message.getSenderId(),
this.getNodeId(), message.getRecipientId(), message.getId() + "");
} else {
observerNotice(MonitoringEvent.MESSAGE_RECEIVED, null, message.getSenderId(), this.getNodeId(),
message.getRecipientId(), message.getId() + "");
}
if (!message.isTopic()) {
MessageReceiver receiver = htRegisteredReceivers.get(message.getRecipientId());
if (receiver == null) {
throw new AgentNotRegisteredException(message.getRecipientId());
}
receiver.receiveMessage(message, getAgentContext(message.getSenderId()));
} else {
TreeMap<String, MessageReceiver> map = mapTopicListeners.get(message.getTopicId());
if (map == null) {
throw new MessageException("No receiver registered for this topic!");
}
synchronized (map) {
for (MessageReceiver receiver : map.values()) {
try {
Message msg = message;
if (map.size() > 1) {
msg = msg.clone();
}
msg.setRecipientId(receiver.getResponsibleForAgentSafeId());
receiver.receiveMessage(msg, getAgentContext(message.getSenderId()));
} catch (CloneNotSupportedException e) {
throw new MessageException("Cloning failed", e);
} catch (Exception e) {
logger.log(Level.SEVERE, "Message receiver failed", e);
}
}
}
}
}
/**
* @deprecated Use {@link #fetchEnvelope(String)} instead
*
* Gets an artifact from the p2p storage.
*
* @param id An id to identify the envelope
* @return the envelope containing the requested artifact
* @throws EnvelopeNotFoundException If the envelope was not found
* @throws EnvelopeException If an issue with the envelope occurred
*/
@Deprecated
public abstract EnvelopeVersion fetchArtifact(long id) throws EnvelopeNotFoundException, EnvelopeException;
/**
* @deprecated Use {@link #fetchEnvelope(String)} instead
*
* Gets an artifact from the p2p storage.
*
* @param identifier An identifier for the envelope
* @return the envelope containing the requested artifact
* @throws EnvelopeNotFoundException If the envelope was not found
* @throws EnvelopeException If an issue with the envelope occurred
*/
@Deprecated
public abstract EnvelopeVersion fetchArtifact(String identifier)
throws EnvelopeNotFoundException, EnvelopeException;
/**
* @deprecated Use {@link #storeEnvelope(EnvelopeVersion, AgentImpl)} instead
*
* Stores an artifact to the p2p storage.
*
* @param envelope An envelope to store
* @throws EnvelopeAlreadyExistsException If the envelope already exists
* @throws EnvelopeException If an issue with the envelope occurred
*/
@Deprecated
public abstract void storeArtifact(EnvelopeVersion envelope)
throws EnvelopeAlreadyExistsException, EnvelopeException;
/**
* @deprecated Use {@link #removeEnvelope(String)} instead
*
* Removes an artifact from the p2p storage. <i>NOTE: This is not possible with a FreePastry
* backend!</i>
*
* @param id An identifier for the artifact
* @param signature A signature to use
* @throws EnvelopeNotFoundException If the envelope was not found
* @throws EnvelopeException If an issue with the envelope occurred
*/
@Deprecated
public abstract void removeArtifact(long id, byte[] signature) throws EnvelopeNotFoundException, EnvelopeException;
/**
* Searches the nodes for registered Versions of the given Agent. Returns an array of objects identifying the nodes
* the given agent is registered to.
*
* @param agentId id of the agent to look for
* @param hintOfExpectedCount a hint for the expected number of results (e.g. to wait for)
* @return array with the IDs of nodes, where the given agent is registered
* @throws AgentNotRegisteredException If the agent is not registered at this node
*/
public abstract Object[] findRegisteredAgent(String agentId, int hintOfExpectedCount)
throws AgentNotRegisteredException;
/**
* Search the nodes for registered versions of the given agent. Returns an array of objects identifying the nodes
* the given agent is registered to.
*
* @param agent An agent to find
* @return array with the IDs of nodes, where the given agent is registered
* @throws AgentNotRegisteredException If the agent is not registered at this node
*/
public Object[] findRegisteredAgent(AgentImpl agent) throws AgentNotRegisteredException {
return findRegisteredAgent(agent.getIdentifier());
}
/**
* Searches the nodes for registered versions of the given agentId. Returns an array of objects identifying the
* nodes the given agent is registered to.
*
* @param agentId id of the agent to look for
* @return array with the IDs of nodes, where the given agent is registered
* @throws AgentNotRegisteredException If the agent is not registered at this node
*/
public Object[] findRegisteredAgent(String agentId) throws AgentNotRegisteredException {
return findRegisteredAgent(agentId, 1);
}
/**
* searches the nodes for registered versions of the given agent. Returns an array of objects identifying the nodes
* the given agent is registered to.
*
* @param agent An agent to look for
* @param hintOfExpectedCount a hint for the expected number of results (e.g. to wait for)
* @return array with the IDs of nodes, where the given agent is registered
* @throws AgentNotRegisteredException If the agent is not registered at this node
*/
public Object[] findRegisteredAgent(AgentImpl agent, int hintOfExpectedCount) throws AgentNotRegisteredException {
return findRegisteredAgent(agent.getIdentifier(), hintOfExpectedCount);
}
/**
* Gets an agent description from the net.
*
* make sure, always to return fresh versions of the requested agent, so that no thread can unlock the private key
* for another one!
*
* @param id An agent id
* @return the requested agent
* @throws AgentNotFoundException If the agent is not found
* @throws AgentException If any other issue with the agent occurs, e. g. XML not readable
*/
@Override
public abstract AgentImpl getAgent(String id) throws AgentNotFoundException, AgentException;
@Override
public boolean hasAgent(String id) throws AgentException {
// Since an request for this agent is probable after this check, it makes sense
// to try to load it into this node and decide afterwards
try {
getAgent(id);
return true;
} catch (AgentNotFoundException e) {
return false;
}
}
/**
* Gets a local registered agent by its id.
*
* @param id An agent id
* @return the agent registered to this node
* @throws AgentNotRegisteredException If the agent is not found at this node
*/
public AgentImpl getLocalAgent(String id) throws AgentNotRegisteredException {
MessageReceiver result = htRegisteredReceivers.get(id);
if (result == null) {
throw new AgentNotRegisteredException("The given agent agent is not registered to this node");
}
if (result instanceof AgentImpl) {
return (AgentImpl) result;
} else {
throw new AgentNotRegisteredException("The requested Agent is only known as a Mediator here!");
}
}
/**
* Gets an array with all {@link i5.las2peer.security.UserAgentImpl}s registered at this node.
*
* @return all local registered UserAgents
*/
public UserAgentImpl[] getRegisteredAgents() {
Vector<UserAgentImpl> result = new Vector<>();
for (MessageReceiver rec : htRegisteredReceivers.values()) {
if (rec instanceof UserAgentImpl) {
result.add((UserAgentImpl) rec);
}
}
return result.toArray(new UserAgentImpl[0]);
}
/**
* Gets an array with all {@link i5.las2peer.security.ServiceAgentImpl}s registered at this node.
*
* @return all local registered ServiceAgents
*/
public ServiceAgentImpl[] getRegisteredServices() {
Vector<ServiceAgentImpl> result = new Vector<>();
for (MessageReceiver rec : htRegisteredReceivers.values()) {
if (rec instanceof ServiceAgentImpl) {
result.add((ServiceAgentImpl) rec);
}
}
return result.toArray(new ServiceAgentImpl[0]);
}
/**
* Gets a local registered mediator for the given agent id. If no mediator exists, registers a new one to this node.
*
* @param agent An agent to mediate
* @return the mediator for the given agent
* @throws AgentLockedException If the agent is locked.
* @throws AgentAlreadyRegisteredException If the agent is already directly registered at this node
*/
public Mediator createMediatorForAgent(AgentImpl agent)
throws AgentLockedException, AgentAlreadyRegisteredException {
if (agent.isLocked()) {
throw new AgentLockedException("You need to unlock the agent for mediation!");
}
MessageReceiver receiver = htRegisteredReceivers.get(agent.getIdentifier());
if (receiver != null && !(receiver instanceof Mediator)) {
throw new AgentAlreadyRegisteredException("The requested Agent is registered directly at this node!");
}
if (receiver == null) {
getAgentContext(agent);
}
return new Mediator(this, agent);
}
/**
* Stores a new Agent to the network.
*
* @param agent An agent to store
* @throws AgentException If any issue with the agent occurs
*/
public abstract void storeAgent(AgentImpl agent) throws AgentException;
/**
* Updates an existing agent of the network.
*
* @param agent An agent to update
* @throws AgentException If any issue with the agent occurs
*/
@Deprecated
public abstract void updateAgent(AgentImpl agent) throws AgentException;
/**
* returns the manager responsible for user management
*
* @return this node's user manager
*/
public UserAgentManager getUserManager() {
return userManager;
}
/**
* Gets an id for the user for the given login name.
*
* @param login A login name to identify agent
* @return agent id
* @throws AgentNotFoundException If no agent for the given login is found
* @throws AgentOperationFailedException If any other issue with the agent occurs, e. g. XML not readable
*/
public String getAgentIdForLogin(String login) throws AgentNotFoundException, AgentOperationFailedException {
return userManager.getAgentIdByLogin(login);
}
/**
* Gets an id for the user for the given email address.
*
* @param email An email address to identify agent
* @return agent id
* @throws AgentNotFoundException If no agent for the given email is found
* @throws AgentOperationFailedException If any other issue with the agent occurs, e. g. XML not readable
*/
public String getAgentIdForEmail(String email) throws AgentNotFoundException, AgentOperationFailedException {
return userManager.getAgentIdByEmail(email);
}
/**
* get the manager responsible for the mapping from service alias to service names
*
* @return Returns the {@code ServiceAliasManager} instance of this node
*/
public ServiceAliasManager getServiceAliasManager() {
return aliasManager;
}
/**
* Gets an currently running agent executing the given service.
*
* Prefer using a locally registered agent.
*
* @param service service to be invoked
* @param acting agent
* @return the ServiceAgent responsible for the given service class
* @throws AgentException If any issue with the agent occurs, e. g. not found, XML not readable
*/
public ServiceAgentImpl getServiceAgent(ServiceNameVersion service, AgentImpl acting) throws AgentException {
ServiceInstance inst = nodeServiceCache.getServiceAgentInstance(service, true, false, acting);
if (inst.local()) {
return inst.getServiceAgent();
} else {
AgentImpl result = getAgent(inst.getServiceAgentId());
if (result == null || !(result instanceof ServiceAgentImpl)) {
throw new AgentNotFoundException("The corresponding agent is not a ServiceAgent.");
}
return (ServiceAgentImpl) result;
}
}
/**
* invoke a service in the network
*
* @param executing the executing agent
* @param service service to be invoked
* @param method service method
* @param parameters invocation parameters
* @return Returns the invocation result
* @throws ServiceInvocationException If service invocation fails
* @throws AgentLockedException If the executing agent was locked
*/
public Serializable invoke(AgentImpl executing, String service, String method, Serializable[] parameters)
throws AgentLockedException, ServiceInvocationException {
return invoke(executing, ServiceNameVersion.fromString(service), method, parameters, false, false);
}
/**
* invoke a service in the network (choosing an appropriate version)
*
* @param executing the executing agent
* @param service service to be invoked
* @param method service method
* @param parameters invocation parameters
* @return Returns the invocation result
* @throws ServiceInvocationException If service invocation fails
* @throws AgentLockedException If the executing agent was locked
*/
public Serializable invoke(AgentImpl executing, ServiceNameVersion service, String method,
Serializable[] parameters) throws AgentLockedException, ServiceInvocationException {
return invoke(executing, service, method, parameters, false, false);
}
/**
* invoke a service in the network or locally
*
* @param executing the executing agent
* @param service service to be invoked
* @param method service method
* @param parameters invocation parameters
* @param exactVersion if true, an exact version match is required, otherwise, an appropriate version will be chosen
* @return Returns the invocation result
* @throws ServiceInvocationException If service invocation fails
* @throws AgentLockedException If the executing agent was locked
*/
public Serializable invoke(AgentImpl executing, ServiceNameVersion service, String method,
Serializable[] parameters, boolean exactVersion) throws AgentLockedException, ServiceInvocationException {
return invoke(executing, service, method, parameters, exactVersion, false);
}
/**
* invoke a service method
*
* @param executing the executing agent
* @param service service to be invoked
* @param method service method
* @param parameters invocation parameters
* @param exactVersion if true, an exact version match is required, otherwise, an appropriate version will be chosen
* @param localOnly if true, only locally running services are executed
* @return Returns the invocation result
* @throws ServiceInvocationException If service invocation fails
* @throws AgentLockedException If the executing agent was locked
*/
public Serializable invoke(AgentImpl executing, ServiceNameVersion service, String method,
Serializable[] parameters, boolean exactVersion, boolean localOnly)
throws ServiceInvocationException, AgentLockedException {
if (getStatus() != NodeStatus.RUNNING) {
throw new IllegalStateException("You can invoke methods only on a running node!");
}
if (executing.isLocked()) {
throw new AgentLockedException("The executing agent has to be unlocked to call a RMI");
}
int retry = invocationRetryCount;
while (retry > 0) {
retry
NodeServiceCache.ServiceInstance instance;
try {
instance = this.nodeServiceCache.getServiceAgentInstance(service, exactVersion, localOnly, executing);
} catch (AgentNotRegisteredException e) {
throw new ServiceNotFoundException(service.toString(), e);
}
if (instance.local()) {
return invokeLocally(executing, instance.getServiceAgent(), method, parameters);
} else {
try {
return invokeGlobally(executing, instance.getServiceAgentId(), instance.getNodeId(), method,
parameters);
} catch (ServiceNotAvailableException e) {
nodeServiceCache.removeGlobalServiceInstance(instance);
if (retry == 0) {
throw new ServiceNotAvailableException("Cannot reach service.", e);
}
}
}
}
throw new IllegalStateException();
}
/**
* invokes a locally running service agent
*
* preferably, use {@link #invoke(AgentImpl, ServiceNameVersion, String, Serializable[], boolean, boolean)}
*
* @param executing the executing agent
* @param serviceAgent the service agent that should be invoked (must run on this node)
* @param method service method
* @param parameters method parameters
* @return innovation result
* @throws ServiceInvocationException If service invocation fails
* @throws AgentLockedException If the executing agent was locked
*/
public Serializable invokeLocally(AgentImpl executing, ServiceAgentImpl serviceAgent, String method,
Serializable[] parameters) throws ServiceInvocationException, AgentLockedException {
if (getStatus() != NodeStatus.RUNNING) {
throw new IllegalStateException("You can invoke methods only on a running node!");
}
if (executing.isLocked()) {
throw new AgentLockedException("The executing agent has to be unlocked to call a RMI");
}
// check if local service agent
if (!hasLocalAgent(serviceAgent)) {
throw new ServiceNotFoundException("This ServiceAgent is not known locally!");
}
// execute
RMITask task = new RMITask(serviceAgent.getServiceNameVersion(), method, parameters);
AgentContext context = getAgentContext(executing);
return serviceAgent.handle(task, context);
}
/**
* invokes a service instance in the network
*
* preferably, use {@link #invoke(AgentImpl, ServiceNameVersion, String, Serializable[], boolean, boolean)}
*
* @param executing the executing agent
* @param serviceAgentId the id of the service agent
* @param nodeId id of the node running the agent (may be null)
* @param method service method
* @param parameters method parameters
* @return invocation result
* @throws ServiceInvocationException If service invocation fails
* @throws AgentLockedException If the executing agent is locked
*/
public Serializable invokeGlobally(AgentImpl executing, String serviceAgentId, Object nodeId, String method,
Serializable[] parameters) throws ServiceInvocationException, AgentLockedException {
if (getStatus() != NodeStatus.RUNNING) {
throw new IllegalStateException("You can invoke methods only on a running node!");
}
// Do not log service class name (privacy..)
this.observerNotice(MonitoringEvent.RMI_SENT, this.getNodeId(), executing, null);
if (executing.isLocked()) {
throw new AgentLockedException("The executing agent has to be unlocked to call a RMI");
}
ServiceAgentImpl serviceAgent;
try {
serviceAgent = (ServiceAgentImpl) getAgent(serviceAgentId);
} catch (AgentNotFoundException | ClassCastException e) {
throw new ServiceNotFoundException("This is not a service agent!", e);
} catch (AgentException e) {
throw new ServiceNotAvailableException("This service agent is not available!", e);
}
try {
Serializable msg;
if (executing instanceof PassphraseAgentImpl) {
msg = new UnlockAgentCall(new RMITask(serviceAgent.getServiceNameVersion(), method, parameters),
((PassphraseAgentImpl) executing).getPassphrase());
} else {
msg = new RMITask(serviceAgent.getServiceNameVersion(), method, parameters);
}
Message rmiMessage = new Message(executing, serviceAgent, msg);
if (this instanceof LocalNode) {
rmiMessage.setSendingNodeId((Long) getNodeId());
} else {
rmiMessage.setSendingNodeId((NodeHandle) getNodeId());
}
Message resultMessage;
if (nodeId != null) {
try {
resultMessage = sendMessageAndWaitForAnswer(rmiMessage, nodeId);
} catch (NodeNotFoundException nex) {
throw new ServiceNotAvailableException("Cannot reach node!", nex);
}
} else {
resultMessage = sendMessageAndWaitForAnswer(rmiMessage);
}
ClassLoader msgClsLoader = null;
try {
ServiceAgentImpl localInst = getLocalServiceAgent(serviceAgent.getServiceNameVersion());
if (localInst != null) {
msgClsLoader = localInst.getServiceInstance().getClass().getClassLoader();
}
} catch (ServiceNotFoundException e) {
// ok, no local instance found
}
try {
resultMessage.open(executing, this, msgClsLoader);
} catch (AgentException e) {
throw new ServiceInvocationException("Could not open received answer!", e);
}
Object resultContent = resultMessage.getContent();
if (resultContent instanceof RMIExceptionContent) {
Throwable thrown = ((RMIExceptionContent) resultContent).getException();
// Do not log service class name (privacy..)
this.observerNotice(MonitoringEvent.RMI_FAILED, this.getNodeId(), executing, thrown.toString());
if (thrown instanceof ServiceInvocationException) {
throw (ServiceInvocationException) thrown;
} else if ((thrown instanceof InvocationTargetException)
&& (thrown.getCause() instanceof InternalSecurityException)) {
// internal L2pSecurityException (like internal method access or unauthorizes object access)
throw new ServiceAccessDeniedException("Internal security exception!", thrown.getCause());
} else {
throw new ServiceInvocationException("remote exception at target node", thrown);
}
} else if (resultContent instanceof RMIResultContent) {
// Do not log service class name (privacy..)
this.observerNotice(MonitoringEvent.RMI_SUCCESSFUL, this.getNodeId(), executing, null);
return ((RMIResultContent) resultContent).getContent();
} else {
// Do not log service class name (privacy..)
this.observerNotice(MonitoringEvent.RMI_FAILED, this.getNodeId(), executing,
"Unknown RMI response type: " + resultContent.getClass().getCanonicalName());
throw new ServiceInvocationException(
"Unknown RMI response type: " + resultContent.getClass().getCanonicalName());
}
} catch (InternalSecurityException e) {
throw new ServiceInvocationFailedException("Cannot encrypt or decrypt message!", e);
} catch (TimeoutException | InterruptedException e) {
// Do not log service class name (privacy..)
this.observerNotice(MonitoringEvent.RMI_FAILED, this.getNodeId(), executing, e.toString());
throw new ServiceNotAvailableException("Service does not respond", e);
} catch (EncodingFailedException e) {
// Do not log service class name (privacy..)
this.observerNotice(MonitoringEvent.RMI_FAILED, this.getNodeId(), executing, e.toString());
throw new ServiceInvocationException("message problems!", e);
} catch (SerializationException e) {
// Do not log service class name (privacy..)
this.observerNotice(MonitoringEvent.RMI_FAILED, this.getNodeId(), executing, e.toString());
throw new ServiceInvocationException("message problems!", e);
}
}
/**
* Tries to get an instance of the given class as a registered service of this node.
*
* @param service A service name and version to check for
* @return the instance of the given service class running at this node
* @throws ServiceNotFoundException If the service is not found
*/
public ServiceAgentImpl getLocalServiceAgent(ServiceNameVersion service) throws ServiceNotFoundException {
try {
return nodeServiceCache.getLocalService(service);
} catch (Exception e) {
throw new ServiceNotFoundException(service.toString());
}
}
/**
* Registers a MessageResultListener for collecting answers.
*
* @param messageId A message id to register for
* @param listener An answer listener
*/
public void registerAnswerListener(long messageId, MessageResultListener listener) {
if (listener == null) {
return;
}
htAnswerListeners.put(messageId, listener);
}
/**
* Hands over an answer message to the corresponding listener.
*
* @param answer A answer message to handle
* @return true, if a listener for this answer was notified
*/
public boolean handoverAnswer(Message answer) {
if (!answer.isResponse()) {
return false;
}
observerNotice(MonitoringEvent.MESSAGE_RECEIVED_ANSWER, answer.getSendingNodeId(), answer.getSenderId(),
this.getNodeId(), answer.getRecipientId(), "" + answer.getResponseToId());
MessageResultListener listener = htAnswerListeners.get(answer.getResponseToId());
if (listener == null) {
System.out.println("Did not find corresponding observer!");
return false;
}
listener.collectAnswer(answer);
return true;
}
/**
* Sends a message and wait for one answer message.
*
* @param m A message to send
* @return a (possible) response message
* @throws InterruptedException If sending the message was interrupted
* @throws TimeoutException If sending the message timeouts
*/
public Message sendMessageAndWaitForAnswer(Message m) throws InterruptedException, TimeoutException {
long timeout = m.getTimeoutTs() - new Date().getTime();
MessageResultListener listener = new MessageResultListener(timeout);
sendMessage(m, listener);
listener.waitForOneAnswer();
if (listener.isSuccess()) {
return listener.getResults()[0];
} else {
throw new TimeoutException();
}
}
/**
* Sends a message to the given id and wait for one answer message.
*
* @param m A message to send
* @param atNodeId A node id to send from
* @return a response message
* @throws NodeNotFoundException If no node was not found with given id
* @throws InterruptedException If sending the message was interrupted
* @throws TimeoutException If sending the message timeouts
*/
public Message sendMessageAndWaitForAnswer(Message m, Object atNodeId)
throws NodeNotFoundException, InterruptedException, TimeoutException {
long timeout = m.getTimeoutTs() - new Date().getTime();
MessageResultListener listener = new MessageResultListener(timeout);
sendMessage(m, atNodeId, listener);
listener.waitForOneAnswer();
if (listener.getResults().length == 0) {
throw new TimeoutException("No answer received!");
}
return listener.getResults()[0];
}
/**
* Sends a message and wait for answer messages
*
* Uses a broadcast
*
* @param m A message to send
* @param recipientCount expected number of answers
* @return Returns an array with all collected answers
* @throws InterruptedException If sending the message was interrupted
* @throws TimeoutException If sending the message timeouts
*/
public Message[] sendMessageAndCollectAnswers(Message m, int recipientCount)
throws InterruptedException, TimeoutException {
long timeout = m.getTimeoutTs() - new Date().getTime();
MessageResultListener listener = new MessageResultListener(timeout, timeout / 4);
listener.addRecipients(recipientCount);
sendMessage(m, listener, SendMode.BROADCAST);
listener.waitForAllAnswers(false);
Message[] results = listener.getResults();
if (results.length > 0) {
return results;
} else {
throw new TimeoutException("No answer received!");
}
}
/**
* Gets the local execution context of an agent. If there is currently none, a new one will be created and stored
* for later use.
*
* @param agentId An agent id to get the context for
* @return the context for the given agent
* @throws AgentException If any issue with the agent occurs, e. g. XML not readable
*/
public AgentContext getAgentContext(String agentId) throws AgentException {
AgentContext result = htLocalExecutionContexts.get(agentId);
if (result == null) {
AgentImpl agent = getAgent(agentId);
result = new AgentContext(this, agent);
htLocalExecutionContexts.put(agentId, result);
}
result.touch();
return result;
}
/**
* Gets a (possibly fresh) context for the given agent.
*
* @param agent An agent to get the context for
* @return Returns a context
*/
public AgentContext getAgentContext(AgentImpl agent) {
AgentContext result = htLocalExecutionContexts.get(agent.getIdentifier());
if (result == null || (result.getMainAgent().isLocked() && !agent.isLocked())) {
result = new AgentContext(this, agent);
htLocalExecutionContexts.put(agent.getIdentifier(), result);
}
result.touch();
return result;
}
/**
* Checks, if the given service class is running at this node.
*
* @param service A service name and version to check for
* @return true, if this node as an instance of the given service running
*/
public boolean hasService(ServiceNameVersion service) {
// return hasAgent(ServiceAgent.serviceClass2Id(service));
try {
nodeServiceCache.getLocalService(service);
return true;
} catch (AgentNotRegisteredException e) {
return false;
}
}
/**
* get the NodeServiceCache of this node
*
* @return Returns the {@code NodeServiceCache} instance for this node
*/
public NodeServiceCache getNodeServiceCache() {
return this.nodeServiceCache;
}
/**
* Gets the approximate CPU load of the JVM the Node is running on. Correct value only available a few seconds after
* the start of the Node.
*
* @return value between 0 and 1: CPU load of the JVM process running this node
*/
public double getNodeCpuLoad() {
double load = osBean.getProcessCpuLoad();
if (load < 0) { // no CPU load information are available
load = 0;
} else if (load > 1) {
load = 1;
}
return load;
}
public boolean isBusy() {
return (getNodeCpuLoad() > cpuLoadThreshold);
}
public void setCpuLoadThreshold(double cpuLoadThreshold) {
this.cpuLoadThreshold = cpuLoadThreshold;
}
// Tidy up Timer
/**
* starts the tidy up timer
*/
private void startTidyUpTimer() {
if (tidyUpTimer != null) {
return;
}
tidyUpTimer = new Timer();
tidyUpTimer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
runTidyUpTimer();
}
}, 0, tidyUpTimerInterval * 1000);
}
/**
* stops the tidy up timer
*/
private void stopTidyUpTimer() {
if (tidyUpTimer != null) {
tidyUpTimer.cancel();
tidyUpTimer = null;
}
}
/**
* executed by the tidy up timer, currently it does:
*
* Deleting old {@link AgentContext} objects from {@link #htLocalExecutionContexts}
*/
protected void runTidyUpTimer() {
synchronized (htLocalExecutionContexts) {
Iterator<AgentContext> itContext = htLocalExecutionContexts.values().iterator();
while (itContext.hasNext()) {
AgentContext context = itContext.next();
if (context.getLastUsageTimestamp() <= new Date().getTime() - agentContextLifetime * 1000) {
itContext.remove();
}
}
}
}
public Date getStartTime() {
return startTime;
}
}
|
package io.vertx.ext.web.impl;
import io.vertx.codegen.annotations.Nullable;
import io.vertx.core.Handler;
import io.vertx.core.MultiMap;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.auth.User;
import io.vertx.ext.web.*;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
public class RoutingContextDecorator implements RoutingContext {
private final Route currentRoute;
private final RoutingContext decoratedContext;
public RoutingContextDecorator(Route currentRoute, RoutingContext decoratedContext) {
Objects.requireNonNull(currentRoute);
Objects.requireNonNull(decoratedContext);
this.currentRoute = currentRoute;
this.decoratedContext = decoratedContext;
}
@Override
public int addBodyEndHandler(Handler<Void> handler) {
return decoratedContext.addBodyEndHandler(handler);
}
@Override
public RoutingContext addCookie(Cookie cookie) {
return decoratedContext.addCookie(cookie);
}
@Override
public int addHeadersEndHandler(Handler<Void> handler) {
return decoratedContext.addHeadersEndHandler(handler);
}
@Override
public int cookieCount() {
return decoratedContext.cookieCount();
}
@Override
public Set<Cookie> cookies() {
return decoratedContext.cookies();
}
@Override
public Route currentRoute() {
return currentRoute;
}
@Override
public Map<String, Object> data() {
return decoratedContext.data();
}
@Override
public void fail(int statusCode) {
// make sure the fail handler run on the correct context
vertx().runOnContext(future -> decoratedContext.fail(statusCode));
}
@Override
public void fail(Throwable throwable) {
// make sure the fail handler run on the correct context
vertx().runOnContext(future -> decoratedContext.fail(throwable));
}
@Override
public boolean failed() {
return decoratedContext.failed();
}
@Override
public Throwable failure() {
return decoratedContext.failure();
}
@Override
public Set<FileUpload> fileUploads() {
return decoratedContext.fileUploads();
}
@Override
public <T> T get(String key) {
return decoratedContext.get(key);
}
@Override
public <T> T remove(String key) {
return decoratedContext.remove(key);
}
@Override
public String getAcceptableContentType() {
return decoratedContext.getAcceptableContentType();
}
@Override
public Buffer getBody() {
return decoratedContext.getBody();
}
@Override
public JsonObject getBodyAsJson() {
return decoratedContext.getBodyAsJson();
}
@Override
public JsonArray getBodyAsJsonArray() {
return decoratedContext.getBodyAsJsonArray();
}
@Override
public String getBodyAsString() {
return decoratedContext.getBodyAsString();
}
@Override
public String getBodyAsString(String encoding) {
return decoratedContext.getBodyAsString(encoding);
}
@Override
public Cookie getCookie(String name) {
return decoratedContext.getCookie(name);
}
@Override
public String mountPoint() {
return decoratedContext.mountPoint();
}
@Override
public void next() {
// make sure the next handler run on the correct context
vertx().runOnContext(future -> decoratedContext.next());
}
@Override
public String normalisedPath() {
return decoratedContext.normalisedPath();
}
@Override
public RoutingContext put(String key, Object obj) {
return decoratedContext.put(key, obj);
}
@Override
public boolean removeBodyEndHandler(int handlerID) {
return decoratedContext.removeBodyEndHandler(handlerID);
}
@Override
public Cookie removeCookie(String name) {
return decoratedContext.removeCookie(name);
}
@Override
public boolean removeHeadersEndHandler(int handlerID) {
return decoratedContext.removeHeadersEndHandler(handlerID);
}
@Override
public HttpServerRequest request() {
return decoratedContext.request();
}
@Override
public HttpServerResponse response() {
return decoratedContext.response();
}
@Override
public User user() {
return decoratedContext.user();
}
@Override
public Session session() {
return decoratedContext.session();
}
@Override
public ParsedHeaderValues parsedHeaders() {
return decoratedContext.parsedHeaders();
}
@Override
public void setAcceptableContentType(String contentType) {
decoratedContext.setAcceptableContentType(contentType);
}
@Override
public void reroute(HttpMethod method, String path) {
decoratedContext.reroute(method, path);
}
@Override
public List<Locale> acceptableLocales() {
return decoratedContext.acceptableLocales();
}
@Override
public Map<String, String> pathParams() {
return decoratedContext.pathParams();
}
@Override
public @Nullable String pathParam(String name) {
return decoratedContext.pathParam(name);
}
@Override
public MultiMap queryParams() {
return decoratedContext.queryParams();
}
@Override
public @Nullable List<String> queryParam(String query) {
return decoratedContext.queryParam(query);
}
@Override
public void setBody(Buffer body) {
decoratedContext.setBody(body);
}
@Override
public void setSession(Session session) {
decoratedContext.setSession(session);
}
@Override
public void setUser(User user) {
decoratedContext.setUser(user);
}
@Override
public void clearUser() {
decoratedContext.clearUser();
}
@Override
public int statusCode() {
return decoratedContext.statusCode();
}
@Override
public Vertx vertx() {
return decoratedContext.vertx();
}
}
|
package nl.b3p.viewer.stripes;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.activation.MimetypesFileTypeMap;
import javax.servlet.http.HttpServletResponse;
import net.sourceforge.stripes.action.ActionBean;
import net.sourceforge.stripes.action.ActionBeanContext;
import net.sourceforge.stripes.action.After;
import net.sourceforge.stripes.action.Before;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.StreamingResolution;
import net.sourceforge.stripes.action.StrictBinding;
import net.sourceforge.stripes.action.UrlBinding;
import net.sourceforge.stripes.controller.LifecycleStage;
import net.sourceforge.stripes.validation.Validate;
import nl.b3p.geotools.filter.visitor.RemoveDistanceUnit;
import nl.b3p.viewer.config.app.Application;
import nl.b3p.viewer.config.app.ApplicationLayer;
import nl.b3p.viewer.config.app.ConfiguredAttribute;
import nl.b3p.viewer.config.security.Authorizations;
import nl.b3p.viewer.config.services.AttributeDescriptor;
import nl.b3p.viewer.config.services.FeatureTypeRelation;
import nl.b3p.viewer.config.services.Layer;
import nl.b3p.viewer.config.services.SimpleFeatureType;
import nl.b3p.viewer.config.services.WFSFeatureSource;
import nl.b3p.viewer.features.CSVDownloader;
import nl.b3p.viewer.features.ExcelDownloader;
import nl.b3p.viewer.features.FeatureDownloader;
import nl.b3p.viewer.features.ShapeDownloader;
import nl.b3p.viewer.util.ChangeMatchCase;
import nl.b3p.viewer.util.FeatureToJson;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.geotools.data.FeatureSource;
import org.geotools.data.Query;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureIterator;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.data.wfs.WFSDataStoreFactory;
import org.geotools.factory.CommonFactoryFinder;
import org.geotools.factory.GeoTools;
import org.geotools.feature.FeatureCollection;
import org.geotools.filter.text.cql2.CQL;
import org.json.JSONException;
import org.json.JSONObject;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.filter.Filter;
import org.opengis.filter.FilterFactory2;
import org.opengis.filter.sort.SortBy;
import org.opengis.filter.sort.SortOrder;
/**
*
* @author Meine Toonen
*/
@UrlBinding("/action/downloadfeatures")
@StrictBinding
public class DownloadFeaturesActionBean implements ActionBean {
private static final Log log = LogFactory.getLog(DownloadFeaturesActionBean.class);
private ActionBeanContext context;
private boolean unauthorized;
@Validate
private Application application;
@Validate
private ApplicationLayer appLayer;
@Validate
private SimpleFeatureType featureType;
private Layer layer = null;
@Validate
private int limit;
@Validate
private String filter;
@Validate
private boolean debug;
@Validate
private String type;
//<editor-fold defaultstate="collapsed" desc="getters and setters">
@Override
public void setContext(ActionBeanContext abc) {
this.context = abc;
}
@Override
public ActionBeanContext getContext() {
return context;
}
public boolean isUnauthorized() {
return unauthorized;
}
public void setUnauthorized(boolean unauthorized) {
this.unauthorized = unauthorized;
}
public Application getApplication() {
return application;
}
public void setApplication(Application application) {
this.application = application;
}
public ApplicationLayer getAppLayer() {
return appLayer;
}
public void setAppLayer(ApplicationLayer appLayer) {
this.appLayer = appLayer;
}
public SimpleFeatureType getFeatureType() {
return featureType;
}
public void setFeatureType(SimpleFeatureType featureType) {
this.featureType = featureType;
}
public Layer getLayer() {
return layer;
}
public void setLayer(Layer layer) {
this.layer = layer;
}
public int getLimit() {
return limit;
}
public void setLimit(int limit) {
this.limit = limit;
}
public String getFilter() {
return filter;
}
public void setFilter(String filter) {
this.filter = filter;
}
public boolean isDebug() {
return debug;
}
public void setDebug(boolean debug) {
this.debug = debug;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
// </editor-fold>
@After(stages=LifecycleStage.BindingAndValidation)
public void loadLayer() {
layer = appLayer.getService().getSingleLayer(appLayer.getLayerName());
}
@Before(stages=LifecycleStage.EventHandling)
public void checkAuthorization() {
if(application == null || appLayer == null
|| !Authorizations.isAppLayerReadAuthorized(application, appLayer, context.getRequest())) {
unauthorized = true;
}
}
public Resolution download() throws JSONException, FileNotFoundException {
JSONObject json = new JSONObject();
if (unauthorized) {
json.put("success", false);
json.put("message", "Not authorized");
return new StreamingResolution("application/json", new StringReader(json.toString(4)));
}
File output = null;
try {
if (featureType != null || (layer != null && layer.getFeatureType() != null)) {
FeatureSource fs;
SimpleFeatureType ft = featureType;
if (ft == null) {
ft = layer.getFeatureType();
}
if (isDebug() && ft.getFeatureSource() instanceof WFSFeatureSource) {
Map extraDataStoreParams = new HashMap();
extraDataStoreParams.put(WFSDataStoreFactory.TRY_GZIP.key, Boolean.FALSE);
fs = ((WFSFeatureSource) ft.getFeatureSource()).openGeoToolsFeatureSource(layer.getFeatureType(), extraDataStoreParams);
} else {
fs = ft.openGeoToolsFeatureSource();
}
final Query q = new Query(fs.getName().toString());
setFilter(q, ft);
Map<String, AttributeDescriptor> featureTypeAttributes = new HashMap<String, AttributeDescriptor>();
featureTypeAttributes = makeAttributeDescriptorList(ft);
List<ConfiguredAttribute> attributes = appLayer.getAttributes();
output = convert(ft, fs, q, type, attributes,featureTypeAttributes);
json.put("success", true);
}
} catch (Exception e) {
log.error("Error loading features", e);
json.put("success", false);
String message = "Fout bij ophalen features: " + e.toString();
Throwable cause = e.getCause();
while (cause != null) {
message += "; " + cause.toString();
cause = cause.getCause();
}
json.put("message", message);
}
if(json.getBoolean("success")){
final FileInputStream fis = new FileInputStream(output);
StreamingResolution res = new StreamingResolution(MimetypesFileTypeMap.getDefaultFileTypeMap().getContentType(output)) {
@Override
public void stream(HttpServletResponse response) throws Exception {
OutputStream out = response.getOutputStream();
IOUtils.copy(fis, out);
fis.close();
}
};
String name = output.getName();
String extension = name.substring(name.lastIndexOf("."));
String newName = "Download-"+ appLayer.getDisplayName() + "-"+type + extension;
res.setFilename(newName);
res.setAttachment(true);
return res;
}else{
return new StreamingResolution("application/json", new StringReader(json.toString(4)));
}
}
private File convert(SimpleFeatureType ft, FeatureSource fs, Query q, String type, List<ConfiguredAttribute> attributes, Map<String, AttributeDescriptor> featureTypeAttributes) throws IOException {
Map<String, String> attributeAliases = new HashMap<String, String>();
for (AttributeDescriptor ad : ft.getAttributes()) {
if (ad.getAlias() != null) {
attributeAliases.put(ad.getName(), ad.getAlias());
}
}
List<String> propertyNames = new ArrayList<String>();
for (AttributeDescriptor ad : ft.getAttributes()) {
propertyNames.add(ad.getName());
}
/* Use the first property as sort field, otherwise geotools while give a error when quering
* a JDBC featureType without a primary key.
*/
if (fs instanceof org.geotools.jdbc.JDBCFeatureSource && !propertyNames.isEmpty()) {
setSortBy(q, propertyNames.get(0));
}
SimpleFeatureCollection fc =(SimpleFeatureCollection) fs.getFeatures(q);
File f = null;
FeatureDownloader downloader = null;
if (type.equalsIgnoreCase("SHP")) {
downloader = new ShapeDownloader(attributes,(SimpleFeatureSource) fs, featureTypeAttributes);
} else if (type.equalsIgnoreCase("XLS")) {
downloader = new ExcelDownloader(attributes,(SimpleFeatureSource) fs, featureTypeAttributes);
} else if (type.equals("CSV")){
downloader = new CSVDownloader(attributes, (SimpleFeatureSource)fs, featureTypeAttributes);
}else {
throw new IllegalArgumentException("No suitable type given: " + type);
}
try {
downloader.init();
SimpleFeatureIterator it = fc.features();
try {
while (it.hasNext()) {
SimpleFeature feature = it.next();
downloader.processFeature(feature);
}
} finally {
it.close();
}
f = downloader.write();
} catch (IOException ex) {
log.error("Cannot create outputfile: ", ex);
throw ex;
} finally {
fs.getDataStore().dispose();
}
return f;
}
/**
* Makes a list of al the attributeDescriptors of the given FeatureType and
* all the child FeatureTypes (related by join/relate)
*/
private Map<String, AttributeDescriptor> makeAttributeDescriptorList(SimpleFeatureType ft) {
Map<String,AttributeDescriptor> featureTypeAttributes = new HashMap<String,AttributeDescriptor>();
for(AttributeDescriptor ad: ft.getAttributes()) {
String name=ft.getId()+":"+ad.getName();
//stop when already added. Stop a infinite configurated loop
if (featureTypeAttributes.containsKey(name)){
return featureTypeAttributes;
}
featureTypeAttributes.put(name, ad);
}
if (ft.getRelations()!=null){
for (FeatureTypeRelation rel : ft.getRelations()){
featureTypeAttributes.putAll(makeAttributeDescriptorList(rel.getForeignFeatureType()));
}
}
return featureTypeAttributes;
}
private void setFilter(Query q, SimpleFeatureType ft) throws Exception {
if (filter != null && filter.trim().length() > 0) {
Filter f = CQL.toFilter(filter);
f = (Filter) f.accept(new RemoveDistanceUnit(), null);
f = (Filter) f.accept(new ChangeMatchCase(false), null);
f = FeatureToJson.reformatFilter(f, ft);
q.setFilter(f);
}
}
/**
* Set sort on query
*
* @param q the query on which the sort is added
* @param sort the name of the sort column
* @param dir sorting direction DESC or ASC
*/
private void setSortBy(Query q, String sort) {
FilterFactory2 ff2 = CommonFactoryFinder.getFilterFactory2(GeoTools.getDefaultHints());
if (sort != null) {
q.setSortBy(new SortBy[]{
ff2.sort(sort, SortOrder.ASCENDING)
});
}
}
}
|
package org.xwiki.rendering.macro.rss;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.commons.lang.StringUtils;
import org.xwiki.properties.annotation.PropertyDescription;
import org.xwiki.properties.annotation.PropertyMandatory;
import org.xwiki.rendering.macro.parameter.MacroParameterException;
/**
* Parameters for the {@link org.xwiki.rendering.internal.macro.rss.RssMacro} Macro.
*
* @version $Id$
* @since 1.8RC1
*/
public class RssMacroParameters
{
/**
* The URL of the RSS feed.
*/
private String feed;
/**
* If "true" displays the content of each feed in addition to the feed item link.
*/
private boolean content;
/**
* The number of feed items to display.
*/
private int count = 10;
/**
* If "true" and if the feed has an image, display it.
*/
private boolean image;
/**
* The width of the enclosing box containing the RSS macro output.
*/
private String width = StringUtils.EMPTY;
/**
* The RSS feed URL.
*/
private URL feedURL;
/**
* @return the RSS feed URL.
*/
public String getFeed()
{
return feed;
}
/**
* @param feed the RSS feed URL.
* @throws MacroParameterException if the feed URL is malformed.
*/
@PropertyMandatory
@PropertyDescription("URL of the RSS feed")
public void setFeed(String feed) throws MacroParameterException
{
this.feed = feed;
try {
this.feedURL = new java.net.URL(feed);
} catch (MalformedURLException ex) {
throw new MacroParameterException("Malformed feed URL", ex);
}
}
/**
* @param image whether to display the feed's image.
*/
@PropertyDescription("If the feeds has an image associated, display it?")
public void setImage(boolean image)
{
this.image = image;
}
/**
* @return whether to display the feed's image.
*/
public boolean isImage()
{
return image;
}
/**
* @param width the width of the RSS box, that will dismiss potential CSS rules defining its default value.
*/
@PropertyDescription("The width, in px or %, of the box containing the RSS output (default is 30%)")
public void setWidth(String width)
{
this.width = width;
}
/**
* @return the width of the RSS box, that will dismiss potential CSS rules defining its default value.
*/
public String getWidth()
{
return this.width;
}
/**
* @param count the number of feed items to display.
*/
@PropertyDescription("The maximum number of feed items to display on the page.")
public void setCount(int count)
{
this.count = count;
}
/**
* @return the number of feed items to display.
*/
public int getCount()
{
return count;
}
/**
* @return the feed's URL
*/
public URL getFeedURL()
{
return feedURL;
}
/**
* @param content if "true" displays the content of each feed in addition to the feed item link
*/
@PropertyDescription("Display content for feed entries")
public void setContent(boolean content)
{
this.content = content;
}
/**
* @return true if the content of each feed should be displayed
*/
public boolean isContent()
{
return this.content;
}
}
|
package org.bouncycastle.cms;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PublicKey;
import java.security.Signature;
import java.security.SignatureException;
import java.security.cert.CertificateExpiredException;
import java.security.cert.CertificateNotYetValidException;
import java.security.cert.X509Certificate;
import java.util.Hashtable;
import java.util.Iterator;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.ASN1OctetString;
import org.bouncycastle.asn1.ASN1OutputStream;
import org.bouncycastle.asn1.ASN1Set;
import org.bouncycastle.asn1.DEREncodable;
import org.bouncycastle.asn1.DERNull;
import org.bouncycastle.asn1.DERObject;
import org.bouncycastle.asn1.DERObjectIdentifier;
import org.bouncycastle.asn1.DEROutputStream;
import org.bouncycastle.asn1.DERSet;
import org.bouncycastle.asn1.cms.Attribute;
import org.bouncycastle.asn1.cms.AttributeTable;
import org.bouncycastle.asn1.cms.CMSAttributes;
import org.bouncycastle.asn1.cms.IssuerAndSerialNumber;
import org.bouncycastle.asn1.cms.SignerIdentifier;
import org.bouncycastle.asn1.cms.SignerInfo;
import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.bouncycastle.asn1.teletrust.TeleTrusTObjectIdentifiers;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.asn1.cms.Time;
import org.bouncycastle.asn1.cryptopro.CryptoProObjectIdentifiers;
/**
* an expanded SignerInfo block from a CMS Signed message
*/
public class SignerInformation
{
private SignerId sid;
private SignerInfo info;
private AlgorithmIdentifier digestAlgorithm;
private AlgorithmIdentifier encryptionAlgorithm;
private ASN1Set signedAttributes;
private ASN1Set unsignedAttributes;
private CMSProcessable content;
private byte[] signature;
private DERObjectIdentifier contentType;
private byte[] _digest;
SignerInformation(
SignerInfo info,
DERObjectIdentifier contentType,
CMSProcessable content,
byte[] digest)
{
this.info = info;
this.sid = new SignerId();
this.contentType = contentType;
try
{
SignerIdentifier s = info.getSID();
if (s.isTagged())
{
ASN1OctetString octs = ASN1OctetString.getInstance(s.getId());
sid.setSubjectKeyIdentifier(octs.getOctets());
}
else
{
IssuerAndSerialNumber iAnds = IssuerAndSerialNumber.getInstance(s.getId());
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
ASN1OutputStream aOut = new ASN1OutputStream(bOut);
aOut.writeObject(iAnds.getName());
sid.setIssuer(bOut.toByteArray());
sid.setSerialNumber(iAnds.getSerialNumber().getValue());
}
}
catch (IOException e)
{
throw new IllegalArgumentException("invalid sid in SignerInfo");
}
this.digestAlgorithm = info.getDigestAlgorithm();
this.signedAttributes = info.getAuthenticatedAttributes();
this.unsignedAttributes = info.getUnauthenticatedAttributes();
this.encryptionAlgorithm = info.getDigestEncryptionAlgorithm();
this.signature = info.getEncryptedDigest().getOctets();
this.content = content;
_digest = digest;
}
private byte[] encodeObj(
DEREncodable obj)
throws IOException
{
if (obj != null)
{
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
ASN1OutputStream aOut = new ASN1OutputStream(bOut);
aOut.writeObject(obj);
return bOut.toByteArray();
}
return null;
}
public SignerId getSID()
{
return sid;
}
/**
* return the object identifier for the signature.
*/
public String getDigestAlgOID()
{
return digestAlgorithm.getObjectId().getId();
}
/**
* return the signature parameters, or null if there aren't any.
*/
public byte[] getDigestAlgParams()
{
try
{
return encodeObj(digestAlgorithm.getParameters());
}
catch (Exception e)
{
throw new RuntimeException("exception getting digest parameters " + e);
}
}
/**
* return the object identifier for the signature.
*/
public String getEncryptionAlgOID()
{
return encryptionAlgorithm.getObjectId().getId();
}
/**
* return the signature/encyrption algorithm parameters, or null if
* there aren't any.
*/
public byte[] getEncryptionAlgParams()
{
try
{
return encodeObj(encryptionAlgorithm.getParameters());
}
catch (Exception e)
{
throw new RuntimeException("exception getting encryption parameters " + e);
}
}
/**
* Return the digest algorithm using one of the standard JCA string
* representations rather the the algorithm identifier (if possible).
*/
String getDigestAlgName()
{
String digestAlgOID = this.getDigestAlgOID();
if (CMSSignedDataGenerator.DIGEST_MD5.equals(digestAlgOID))
{
return "MD5";
}
else if (CMSSignedDataGenerator.DIGEST_SHA1.equals(digestAlgOID))
{
return "SHA1";
}
else if (CMSSignedDataGenerator.DIGEST_SHA224.equals(digestAlgOID))
{
return "SHA224";
}
else if (CMSSignedDataGenerator.DIGEST_SHA256.equals(digestAlgOID))
{
return "SHA256";
}
else if (CMSSignedDataGenerator.DIGEST_SHA384.equals(digestAlgOID))
{
return "SHA384";
}
else if (CMSSignedDataGenerator.DIGEST_SHA512.equals(digestAlgOID))
{
return "SHA512";
}
else if (PKCSObjectIdentifiers.sha1WithRSAEncryption.getId().equals(digestAlgOID))
{
return "SHA1";
}
else if (PKCSObjectIdentifiers.sha224WithRSAEncryption.getId().equals(digestAlgOID))
{
return "SHA224";
}
else if (PKCSObjectIdentifiers.sha256WithRSAEncryption.getId().equals(digestAlgOID))
{
return "SHA256";
}
else if (PKCSObjectIdentifiers.sha384WithRSAEncryption.getId().equals(digestAlgOID))
{
return "SHA384";
}
else if (PKCSObjectIdentifiers.sha512WithRSAEncryption.getId().equals(digestAlgOID))
{
return "SHA512";
}
else if (TeleTrusTObjectIdentifiers.ripemd128.getId().equals(digestAlgOID))
{
return "RIPEMD128";
}
else if (TeleTrusTObjectIdentifiers.ripemd160.getId().equals(digestAlgOID))
{
return "RIPEMD160";
}
else if (TeleTrusTObjectIdentifiers.ripemd256.getId().equals(digestAlgOID))
{
return "RIPEMD256";
}
else if (CryptoProObjectIdentifiers.gostR3411.getId().equals(digestAlgOID))
{
return "GOST3411";
}
else
{
return digestAlgOID;
}
}
/**
* Return the digest encryption algorithm using one of the standard
* JCA string representations rather the the algorithm identifier (if
* possible).
*/
String getEncryptionAlgName()
{
String encryptionAlgOID = this.getEncryptionAlgOID();
if (CMSSignedDataGenerator.ENCRYPTION_DSA.equals(encryptionAlgOID))
{
return "DSA";
}
else if ("1.2.840.10040.4.1".equals(encryptionAlgOID))
{
return "DSA";
}
else if (CMSSignedDataGenerator.ENCRYPTION_RSA.equals(encryptionAlgOID))
{
return "RSA";
}
else if (CMSSignedDataGenerator.ENCRYPTION_GOST3410.equals(encryptionAlgOID))
{
return "GOST3410";
}
else if (CMSSignedDataGenerator.ENCRYPTION_ECGOST3410.equals(encryptionAlgOID))
{
return "ECGOST3410";
}
else if ("1.2.840.113549.1.1.5".equals(encryptionAlgOID))
{
return "RSA";
}
else if (encryptionAlgOID.startsWith(TeleTrusTObjectIdentifiers.teleTrusTRSAsignatureAlgorithm))
{
return "RSA";
}
else
{
return encryptionAlgOID;
}
}
/**
* return a table of the signed attributes - indexed by
* the OID of the attribute.
*/
public AttributeTable getSignedAttributes()
{
if (signedAttributes == null)
{
return null;
}
return new AttributeTable(signedAttributes);
}
/**
* return a table of the unsigned attributes indexed by
* the OID of the attribute.
*/
public AttributeTable getUnsignedAttributes()
{
if (unsignedAttributes == null)
{
return null;
}
return new AttributeTable(unsignedAttributes);
}
/**
* return the encoded signature
*/
public byte[] getSignature()
{
return signature;
}
/**
* return the DER encoding of the signed attributes.
* @throws IOException if an encoding error occurs.
*/
public byte[] getEncodedSignedAttributes()
throws IOException
{
if (signedAttributes != null)
{
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
DEROutputStream aOut = new DEROutputStream(bOut);
aOut.writeObject(signedAttributes);
return bOut.toByteArray();
}
return null;
}
private boolean doVerify(
PublicKey key,
AttributeTable signedAttrTable,
String sigProvider)
throws CMSException, NoSuchAlgorithmException, NoSuchProviderException
{
Signature sig;
MessageDigest digest;
if (sigProvider != null)
{
sig = Signature.getInstance(this.getDigestAlgName() + "with" + this.getEncryptionAlgName(), sigProvider);
try
{
digest = MessageDigest.getInstance(this.getDigestAlgName(), sigProvider);
}
catch (NoSuchAlgorithmException e)
{
digest = MessageDigest.getInstance(this.getDigestAlgName());
}
}
else
{
sig = Signature.getInstance(this.getDigestAlgName() + "with" + this.getEncryptionAlgName());
digest = MessageDigest.getInstance(this.getDigestAlgName());
}
try
{
sig.initVerify(key);
if (signedAttributes == null)
{
content.write(
new CMSSignedDataGenerator.SigOutputStream(sig));
}
else
{
byte[] hash;
if (content != null)
{
content.write(
new CMSSignedDataGenerator.DigOutputStream(digest));
hash = digest.digest();
}
else
{
hash = _digest;
}
Attribute dig = signedAttrTable.get(
CMSAttributes.messageDigest);
Attribute type = signedAttrTable.get(
CMSAttributes.contentType);
if (dig == null)
{
throw new SignatureException("no hash for content found in signed attributes");
}
if (type == null)
{
throw new SignatureException("no content type id found in signed attributes");
}
DERObject hashObj = dig.getAttrValues().getObjectAt(0).getDERObject();
if (hashObj instanceof ASN1OctetString)
{
byte[] signedHash = ((ASN1OctetString)hashObj).getOctets();
if (!MessageDigest.isEqual(hash, signedHash))
{
throw new SignatureException("content hash found in signed attributes different");
}
}
else if (hashObj instanceof DERNull)
{
if (hash != null)
{
throw new SignatureException("NULL hash found in signed attributes when one expected");
}
}
DERObjectIdentifier typeOID = (DERObjectIdentifier)type.getAttrValues().getObjectAt(0);
if (!typeOID.equals(contentType))
{
throw new SignatureException("contentType in signed attributes different");
}
sig.update(this.getEncodedSignedAttributes());
}
return sig.verify(this.getSignature());
}
catch (InvalidKeyException e)
{
throw new CMSException(
"key not appropriate to signature in message.", e);
}
catch (IOException e)
{
throw new CMSException(
"can't process mime object to create signature.", e);
}
catch (SignatureException e)
{
throw new CMSException(
"invalid signature format in message: + " + e.getMessage(), e);
}
}
/**
* verify that the given public key succesfully handles and confirms the
* signature associated with this signer.
*/
public boolean verify(
PublicKey key,
String sigProvider)
throws NoSuchAlgorithmException, NoSuchProviderException, CMSException
{
return doVerify(key, this.getSignedAttributes(), sigProvider);
}
/**
* verify that the given certificate succesfully handles and confirms
* the signature associated with this signer and, if a signingTime
* attribute is available, that the certificate was valid at the time the
* signature was generated.
*/
public boolean verify(
X509Certificate cert,
String sigProvider)
throws NoSuchAlgorithmException, NoSuchProviderException,
CertificateExpiredException, CertificateNotYetValidException,
CMSException
{
AttributeTable attr = this.getSignedAttributes();
if (attr != null)
{
Attribute t = attr.get(CMSAttributes.signingTime);
if (t != null)
{
Time time = Time.getInstance(
t.getAttrValues().getObjectAt(0).getDERObject());
cert.checkValidity(time.getDate());
}
}
return doVerify(cert.getPublicKey(), attr, sigProvider);
}
SignerInfo toSignerInfo()
{
return info;
}
/**
* Return a signer information object with the passed in unsigned
* attributes replacing the ones that are current associated with
* the object passed in.
*
* @param signerInformation the signerInfo to be used as the basis.
* @param unsignedAttributes the unsigned attributes to add.
* @return a copy of the original SignerInformationObject with the changed attributes.
*/
public static SignerInformation replaceUnsignedAttributes(
SignerInformation signerInformation,
AttributeTable unsignedAttributes)
{
SignerInfo sInfo = signerInformation.info;
ASN1Set unsignedAttr = null;
if (unsignedAttributes != null)
{
Hashtable ats = unsignedAttributes.toHashtable();
Iterator it = ats.values().iterator();
ASN1EncodableVector v = new ASN1EncodableVector();
while (it.hasNext())
{
v.add(Attribute.getInstance(it.next()));
}
unsignedAttr = new DERSet(v);
}
return new SignerInformation(
new SignerInfo(sInfo.getSID(), sInfo.getDigestAlgorithm(),
sInfo.getAuthenticatedAttributes(), sInfo.getDigestEncryptionAlgorithm(), sInfo.getEncryptedDigest(), unsignedAttr),
signerInformation.contentType, signerInformation.content, null);
}
}
|
package org.openhab.binding.amazonechocontrol.internal;
import static org.openhab.binding.amazonechocontrol.internal.AmazonEchoControlBindingConstants.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.net.ssl.HttpsURLConnection;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.eclipse.smarthome.core.thing.Thing;
import org.openhab.binding.amazonechocontrol.internal.handler.AccountHandler;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonBluetoothStates;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonBluetoothStates.BluetoothState;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonBluetoothStates.PairedDevice;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonDevices.Device;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonMusicProvider;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonNotificationSound;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonPlaylists;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonPlaylists.PlayList;
import org.osgi.service.http.HttpService;
import org.osgi.service.http.NamespaceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
@NonNullByDefault
public class AccountServlet extends HttpServlet {
private static final long serialVersionUID = -1453738923337413163L;
private static final String FORWARD_URI_PART = "/FORWARD/";
private static final String PROXY_URI_PART = "/PROXY/";
private final Logger logger = LoggerFactory.getLogger(AccountServlet.class);
HttpService httpService;
String servletUrlWithoutRoot;
String servletUrl;
AccountHandler account;
String id;
@Nullable
Connection connectionToInitialize;
Gson gson = new Gson();
public AccountServlet(HttpService httpService, String id, AccountHandler account) {
this.httpService = httpService;
this.account = account;
this.id = id;
try {
servletUrlWithoutRoot = "amazonechocontrol/" + URLEncoder.encode(id, "UTF8");
} catch (UnsupportedEncodingException e) {
servletUrlWithoutRoot = "";
servletUrl = "";
logger.warn("Register servlet fails {}", e);
return;
}
servletUrl = "/" + servletUrlWithoutRoot;
try {
httpService.registerServlet(servletUrl, this, null, httpService.createDefaultHttpContext());
} catch (ServletException e) {
logger.warn("Register servlet fails {}", e);
} catch (NamespaceException e) {
logger.warn("Register servlet fails {}", e);
}
}
private Connection reCreateConnection() {
Connection oldConnection = connectionToInitialize;
if (oldConnection == null) {
oldConnection = account.findConnection();
}
return new Connection(oldConnection);
}
public void dispose() {
httpService.unregister(servletUrl);
}
@Override
protected void doPut(@Nullable HttpServletRequest req, @Nullable HttpServletResponse resp)
throws ServletException, IOException {
doVerb("PUT", req, resp);
}
@Override
protected void doDelete(@Nullable HttpServletRequest req, @Nullable HttpServletResponse resp)
throws ServletException, IOException {
doVerb("DELETE", req, resp);
}
@Override
protected void doPost(@Nullable HttpServletRequest req, @Nullable HttpServletResponse resp)
throws ServletException, IOException {
doVerb("POST", req, resp);
}
void doVerb(String verb, @Nullable HttpServletRequest req, @Nullable HttpServletResponse resp)
throws ServletException, IOException {
if (req == null) {
return;
}
if (resp == null) {
return;
}
String baseUrl = req.getRequestURI().substring(servletUrl.length());
String uri = baseUrl;
String queryString = req.getQueryString();
if (queryString != null && queryString.length() > 0) {
uri += "?" + queryString;
}
Connection connection = this.account.findConnection();
if (connection != null && uri.equals("/changedomain")) {
Map<String, String[]> map = req.getParameterMap();
String domain = map.get("domain")[0];
String loginData = connection.serializeLoginData();
Connection newConnection = new Connection(null);
if (newConnection.tryRestoreLogin(loginData, domain)) {
account.setConnection(newConnection);
}
resp.sendRedirect(servletUrl);
return;
}
if (uri.startsWith(PROXY_URI_PART)) {
// handle proxy request
if (connection == null) {
returnError(resp, "Account not online");
return;
}
String getUrl = "https://alexa." + connection.getAmazonSite() + "/"
+ uri.substring(PROXY_URI_PART.length());
String postData = null;
if (verb == "POST" || verb == "PUT") {
postData = req.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
}
this.handleProxyRequest(connection, resp, verb, getUrl, null, postData, true, connection.getAmazonSite());
return;
}
// handle post of login page
connection = this.connectionToInitialize;
if (connection == null) {
returnError(resp, "Connection not in intialize mode.");
return;
}
resp.addHeader("content-type", "text/html;charset=UTF-8");
Map<String, String[]> map = req.getParameterMap();
StringBuilder postDataBuilder = new StringBuilder();
for (String name : map.keySet()) {
if (postDataBuilder.length() > 0) {
postDataBuilder.append('&');
}
postDataBuilder.append(name);
postDataBuilder.append('=');
String value = map.get(name)[0];
if (name.equals("failedSignInCount")) {
value = "ape:AA==";
}
postDataBuilder.append(URLEncoder.encode(value, StandardCharsets.UTF_8.name()));
}
uri = req.getRequestURI();
if (!uri.startsWith(servletUrl)) {
returnError(resp, "Invalid request uri '" + uri + "'");
return;
}
String relativeUrl = uri.substring(servletUrl.length()).replace(FORWARD_URI_PART, "/");
String site = connection.getAmazonSite();
if (relativeUrl.startsWith("/ap/signin")) {
site = "amazon.com";
}
String postUrl = "https:
queryString = req.getQueryString();
if (queryString != null && queryString.length() > 0) {
postUrl += "?" + queryString;
}
String referer = "https:
String postData = postDataBuilder.toString();
handleProxyRequest(connection, resp, "POST", postUrl, referer, postData, false, site);
}
@Override
protected void doGet(@Nullable HttpServletRequest req, @Nullable HttpServletResponse resp)
throws ServletException, IOException {
if (req == null) {
return;
}
if (resp == null) {
return;
}
String baseUrl = req.getRequestURI().substring(servletUrl.length());
String uri = baseUrl;
String queryString = req.getQueryString();
if (queryString != null && queryString.length() > 0) {
uri += "?" + queryString;
}
logger.debug("doGet {}", uri);
try {
Connection connection = this.connectionToInitialize;
if (uri.startsWith(FORWARD_URI_PART) && connection != null) {
String getUrl = "https:
+ uri.substring(FORWARD_URI_PART.length());
this.handleProxyRequest(connection, resp, "GET", getUrl, null, null, false, connection.getAmazonSite());
return;
}
connection = this.account.findConnection();
if (uri.startsWith(PROXY_URI_PART)) {
// handle proxy request
if (connection == null) {
returnError(resp, "Account not online");
return;
}
String getUrl = "https://alexa." + connection.getAmazonSite() + "/"
+ uri.substring(PROXY_URI_PART.length());
this.handleProxyRequest(connection, resp, "GET", getUrl, null, null, false, connection.getAmazonSite());
return;
}
if (connection != null && connection.verifyLogin()) {
// handle commands
if (baseUrl.equals("/logout") || baseUrl.equals("/logout/")) {
this.connectionToInitialize = reCreateConnection();
this.account.setConnection(null);
resp.sendRedirect(this.servletUrl);
return;
}
// handle commands
if (baseUrl.equals("/newdevice") || baseUrl.equals("/newdevice/")) {
this.connectionToInitialize = new Connection(null);
this.account.setConnection(null);
resp.sendRedirect(this.servletUrl);
return;
}
if (baseUrl.equals("/devices") || baseUrl.equals("/devices/")) {
handleDevices(resp, connection);
return;
}
if (baseUrl.equals("/changeDomain") || baseUrl.equals("/changeDomain/")) {
handleChangeDomain(resp, connection);
return;
}
if (baseUrl.equals("/ids") || baseUrl.equals("/ids/")) {
String serialNumber = getQueryMap(queryString).get("serialNumber");
Device device = account.findDeviceJson(serialNumber);
if (device != null) {
Thing thing = account.findThingBySerialNumber(device.serialNumber);
if (thing != null) {
handleIds(resp, connection, device, thing);
}
return;
}
}
// return hint that everything is ok
handleDefaultPageResult(resp, "The Account is logged in.", connection);
return;
}
connection = this.connectionToInitialize;
if (connection == null) {
connection = this.reCreateConnection();
this.connectionToInitialize = connection;
}
if (!uri.equals("/")) {
String newUri = req.getServletPath() + "/";
resp.sendRedirect(newUri);
return;
}
String html = connection.getLoginPage();
returnHtml(connection, resp, html, "amazon.com");
} catch (URISyntaxException e) {
logger.warn("get failed with uri syntax error {}", e);
}
}
public Map<String, String> getQueryMap(@Nullable String query) {
Map<String, String> map = new HashMap<String, String>();
if (query != null) {
String[] params = query.split("&");
for (String param : params) {
String[] elements = param.split("=");
if (elements.length == 2) {
String name = elements[0];
String value = "";
try {
value = URLDecoder.decode(elements[1], "UTF8");
} catch (UnsupportedEncodingException e) {
logger.info("Unsupported encoding {}", e);
}
map.put(name, value);
}
}
}
return map;
}
private void handleChangeDomain(HttpServletResponse resp, Connection connection) {
StringBuilder html = createPageStart("Change Domain");
html.append("<form action='");
html.append(servletUrl);
html.append("/changedomain' method='post'>\nDomain:\n<input type='text' name='domain' value='");
html.append(connection.getAmazonSite());
html.append("'>\n<br>\n<input type=\"submit\" value=\"Submit\">\n</form>");
createPageEndAndSent(resp, html);
}
private void handleDefaultPageResult(HttpServletResponse resp, String message, Connection connection)
throws IOException {
StringBuilder html = createPageStart("");
html.append(StringEscapeUtils.escapeHtml(message));
// logout link
html.append(" <a href='" + servletUrl + "/logout' >");
html.append(StringEscapeUtils.escapeHtml("Logout"));
html.append("</a>");
// newdevice link
html.append(" | <a href='" + servletUrl + "/newdevice' >");
html.append(StringEscapeUtils.escapeHtml("Logout and create new device id"));
html.append("</a>");
// device name
html.append("<br>App name: ");
html.append(StringEscapeUtils.escapeHtml(connection.getDeviceName()));
// connection
html.append("<br>Connected to: ");
html.append(StringEscapeUtils.escapeHtml(connection.getAlexaServer()));
// domain
html.append(" <a href='");
html.append(servletUrl);
html.append("/changeDomain'>Change</a>");
// paper ui link
html.append("<br><a href='/paperui/index.html#/configuration/things/view/" + BINDING_ID + ":"
+ URLEncoder.encode(THING_TYPE_ACCOUNT.getId(), "UTF8") + ":" + URLEncoder.encode(id, "UTF8") + "'>");
html.append(StringEscapeUtils.escapeHtml("Check Thing in Paper UI"));
html.append("</a><br><br>");
// device list
html.append(
"<table><tr><th align='left'>Device</th><th align='left'>Serial Number</th><th align='left'>State</th><th align='left'>Thing</th><th align='left'>Family</th><th align='left'>Type</th></tr>");
for (Device device : this.account.getLastKnownDevices()) {
html.append("<tr><td>");
html.append(StringEscapeUtils.escapeHtml(nullReplacement(device.accountName)));
html.append("</td><td>");
html.append(StringEscapeUtils.escapeHtml(nullReplacement(device.serialNumber)));
html.append("</td><td>");
html.append(StringEscapeUtils.escapeHtml(device.online ? "Online" : "Offline"));
html.append("</td><td>");
Thing accountHandler = account.findThingBySerialNumber(device.serialNumber);
if (accountHandler != null) {
html.append("<a href='" + servletUrl + "/ids/?serialNumber="
+ URLEncoder.encode(device.serialNumber, "UTF8") + "'>"
+ StringEscapeUtils.escapeHtml(accountHandler.getLabel()) + "</a>");
} else {
html.append("Not defined");
}
html.append("</td><td>");
html.append(StringEscapeUtils.escapeHtml(nullReplacement(device.deviceFamily)));
html.append("</td><td>");
html.append(StringEscapeUtils.escapeHtml(nullReplacement(device.deviceType)));
html.append("</td><td>");
html.append("</td></tr>");
}
html.append("</table>");
createPageEndAndSent(resp, html);
}
private void handleDevices(HttpServletResponse resp, Connection connection) throws IOException, URISyntaxException {
returnHtml(connection, resp,
"<html>" + StringEscapeUtils.escapeHtml(connection.getDeviceListJson()) + "</html>");
}
private String nullReplacement(@Nullable String text) {
if (text == null) {
return "<unknown>";
}
return text;
}
StringBuilder createPageStart(String title) {
StringBuilder html = new StringBuilder();
html.append("<html><head><title>"
+ StringEscapeUtils.escapeHtml(BINDING_NAME + " - " + this.account.getThing().getLabel()));
if (StringUtils.isNotEmpty(title)) {
html.append(" - ");
html.append(StringEscapeUtils.escapeHtml(title));
}
html.append("</title><head><body>");
html.append("<h1>" + StringEscapeUtils.escapeHtml(BINDING_NAME + " - " + this.account.getThing().getLabel()));
if (StringUtils.isNotEmpty(title)) {
html.append(" - ");
html.append(StringEscapeUtils.escapeHtml(title));
}
html.append("</h1>");
return html;
}
private void createPageEndAndSent(HttpServletResponse resp, StringBuilder html) {
// account overview link
html.append("<br><a href='" + servletUrl + "/../' >");
html.append(StringEscapeUtils.escapeHtml("Account overview"));
html.append("</a><br>");
html.append("</body></html>");
resp.addHeader("content-type", "text/html;charset=UTF-8");
try {
resp.getWriter().write(html.toString());
} catch (IOException e) {
logger.warn("return html failed with IO error {}", e);
}
}
private void handleIds(HttpServletResponse resp, Connection connection, Device device, Thing thing)
throws IOException, URISyntaxException {
StringBuilder html = createPageStart("Channel Options - " + thing.getLabel());
renderBluetoothMacChannel(connection, device, html);
renderAmazonMusicPlaylistIdChannel(connection, device, html);
renderPlayAlarmSoundChannel(connection, device, html);
renderMusicProviderIdChannel(connection, html);
createPageEndAndSent(resp, html);
}
private void renderMusicProviderIdChannel(Connection connection, StringBuilder html) {
html.append("<h2>" + StringEscapeUtils.escapeHtml("Channel " + CHANNEL_MUSIC_PROVIDER_ID) + "</h2>");
html.append("<table><tr><th align='left'>Name</th><th align='left'>Value</th></tr>");
List<JsonMusicProvider> musicProviders = connection.getMusicProviders();
for (JsonMusicProvider musicProvider : musicProviders) {
@Nullable
List<@Nullable String> properties = musicProvider.supportedProperties;
String providerId = musicProvider.id;
String displayName = musicProvider.displayName;
if (properties != null && properties.contains("Alexa.Music.PlaySearchPhrase")
&& StringUtils.isNotEmpty(providerId) && StringUtils.equals(musicProvider.availability, "AVAILABLE")
&& StringUtils.isNotEmpty(displayName)) {
html.append("<tr><td>");
html.append(StringEscapeUtils.escapeHtml(displayName));
html.append("</td><td>");
html.append(StringEscapeUtils.escapeHtml(providerId));
html.append("</td></tr>");
}
}
html.append("</table>");
}
private void renderPlayAlarmSoundChannel(Connection connection, Device device, StringBuilder html) {
html.append("<h2>" + StringEscapeUtils.escapeHtml("Channel " + CHANNEL_PLAY_ALARM_SOUND) + "</h2>");
JsonNotificationSound[] notificationSounds = null;
String errorMessage = "No notifications sounds found";
try {
notificationSounds = connection.getNotificationSounds(device);
} catch (IOException | HttpException | URISyntaxException | JsonSyntaxException | ConnectionException e) {
errorMessage = e.getLocalizedMessage();
}
if (notificationSounds != null) {
html.append("<table><tr><th align='left'>Name</th><th align='left'>Value</th></tr>");
for (JsonNotificationSound notificationSound : notificationSounds) {
if (notificationSound.folder == null && notificationSound.providerId != null
&& notificationSound.id != null && notificationSound.displayName != null) {
String providerSoundId = notificationSound.providerId + ":" + notificationSound.id;
html.append("<tr><td>");
html.append(StringEscapeUtils.escapeHtml(notificationSound.displayName));
html.append("</td><td>");
html.append(StringEscapeUtils.escapeHtml(providerSoundId));
html.append("</td></tr>");
}
}
html.append("</table>");
} else {
html.append(StringEscapeUtils.escapeHtml(errorMessage));
}
}
private void renderAmazonMusicPlaylistIdChannel(Connection connection, Device device, StringBuilder html) {
html.append("<h2>" + StringEscapeUtils.escapeHtml("Channel " + CHANNEL_AMAZON_MUSIC_PLAY_LIST_ID) + "</h2>");
JsonPlaylists playLists = null;
String errorMessage = "No playlists found";
try {
playLists = connection.getPlaylists(device);
} catch (IOException | HttpException | URISyntaxException | JsonSyntaxException | ConnectionException e) {
errorMessage = e.getLocalizedMessage();
}
if (playLists != null) {
Map<@NonNull String, @Nullable PlayList @Nullable []> playlistMap = playLists.playlists;
if (playlistMap != null && !playlistMap.isEmpty()) {
html.append("<table><tr><th align='left'>Name</th><th align='left'>Value</th></tr>");
for (PlayList[] innerLists : playlistMap.values()) {
{
if (innerLists != null && innerLists.length > 0) {
PlayList playList = innerLists[0];
if (playList.playlistId != null && playList.title != null) {
html.append("<tr><td>");
html.append(StringEscapeUtils.escapeHtml(nullReplacement(playList.title)));
html.append("</td><td>");
html.append(StringEscapeUtils.escapeHtml(nullReplacement(playList.playlistId)));
html.append("</td></tr>");
}
}
}
}
html.append("</table>");
} else {
html.append(StringEscapeUtils.escapeHtml(errorMessage));
}
}
}
private void renderBluetoothMacChannel(Connection connection, Device device, StringBuilder html) {
html.append("<h2>" + StringEscapeUtils.escapeHtml("Channel " + CHANNEL_BLUETOOTH_MAC) + "</h2>");
JsonBluetoothStates bluetoothStates = connection.getBluetoothConnectionStates();
BluetoothState[] innerStates = bluetoothStates.bluetoothStates;
if (innerStates != null) {
for (BluetoothState state : innerStates) {
if (StringUtils.equals(state.deviceSerialNumber, device.serialNumber)) {
PairedDevice[] pairedDeviceList = state.pairedDeviceList;
if (pairedDeviceList != null && pairedDeviceList.length > 0) {
html.append("<table><tr><th align='left'>Name</th><th align='left'>Value</th></tr>");
for (PairedDevice pairedDevice : pairedDeviceList) {
html.append("<tr><td>");
html.append(StringEscapeUtils.escapeHtml(nullReplacement(pairedDevice.friendlyName)));
html.append("</td><td>");
html.append(StringEscapeUtils.escapeHtml(nullReplacement(pairedDevice.address)));
html.append("</td></tr>");
}
html.append("</table>");
} else {
html.append(StringEscapeUtils.escapeHtml("No bluetooth devices paired"));
}
}
}
}
}
void handleProxyRequest(Connection connection, HttpServletResponse resp, String verb, String url,
@Nullable String referer, @Nullable String postData, boolean json, String site) throws IOException {
HttpsURLConnection urlConnection;
try {
Map<String, String> headers = null;
if (referer != null) {
headers = new HashMap<String, String>();
headers.put("Referer", referer);
}
urlConnection = connection.makeRequest(verb, url, postData, json, false, headers);
if (urlConnection.getResponseCode() == 302) {
{
String location = urlConnection.getHeaderField("location");
if (location.contains("/ap/maplanding")) {
try {
connection.registerConnectionAsApp(location);
account.setConnection(connection);
handleDefaultPageResult(resp, "Login succeeded", connection);
this.connectionToInitialize = null;
return;
} catch (URISyntaxException | ConnectionException e) {
returnError(resp,
"Login to '" + connection.getAmazonSite() + "' failed: " + e.getLocalizedMessage());
this.connectionToInitialize = null;
return;
}
}
String startString = "https:
String newLocation = null;
if (location.startsWith(startString) && connection.getIsLoggedIn()) {
newLocation = servletUrl + PROXY_URI_PART + location.substring(startString.length());
} else if (location.startsWith(startString)) {
newLocation = servletUrl + FORWARD_URI_PART + location.substring(startString.length());
} else {
startString = "/";
if (location.startsWith(startString)) {
newLocation = servletUrl + FORWARD_URI_PART + location.substring(startString.length());
}
}
if (newLocation != null) {
logger.debug("Redirect mapped from {} to {}", location, newLocation);
resp.sendRedirect(newLocation);
return;
}
returnError(resp, "Invalid redirect to '" + location + "'");
return;
}
}
} catch (URISyntaxException | ConnectionException e) {
returnError(resp, e.getLocalizedMessage());
return;
}
String response = connection.convertStream(urlConnection);
returnHtml(connection, resp, response, site);
}
private void returnHtml(Connection connection, HttpServletResponse resp, String html) {
returnHtml(connection, resp, html, connection.getAmazonSite());
}
private void returnHtml(Connection connection, HttpServletResponse resp, String html, String amazonSite) {
String resultHtml = html.replace("action=\"/", "action=\"" + servletUrl + "/")
.replace("action=\"/", "action=\"" + servletUrl + "/")
.replace("https:
.replace("https:&
.replace("http:
.replace("http:&
resp.addHeader("content-type", "text/html;charset=UTF-8");
try {
resp.getWriter().write(resultHtml);
} catch (IOException e) {
logger.warn("return html failed with IO error {}", e);
}
}
void returnError(HttpServletResponse resp, String errorMessage) {
try {
resp.getWriter().write("<html>" + StringEscapeUtils.escapeHtml(errorMessage) + "<br><a href='" + servletUrl
+ "'>Try again</a></html>");
} catch (IOException e) {
logger.info("Returning error message failed {}", e);
}
}
}
|
package org.exist.xquery.functions.fn;
import java.io.StringWriter;
import java.io.Writer;
import org.exist.dom.QName;
import org.exist.storage.serializers.Serializer;
import org.exist.xquery.BasicFunction;
import org.exist.xquery.Cardinality;
import org.exist.xquery.Function;
import org.exist.xquery.FunctionSignature;
import org.exist.xquery.XPathException;
import org.exist.xquery.XQueryContext;
import org.exist.xquery.value.FunctionParameterSequenceType;
import org.exist.xquery.value.FunctionReturnSequenceType;
import org.exist.xquery.value.Item;
import org.exist.xquery.value.NodeValue;
import org.exist.xquery.value.Sequence;
import org.exist.xquery.value.SequenceIterator;
import org.exist.xquery.value.SequenceType;
import org.exist.xquery.value.Type;
import org.exist.xquery.value.ValueSequence;
import org.xml.sax.SAXException;
/**
* @author Dannes Wessels
* @author Wolfgang Meier (wolfgang@exist-db.org)
*/
public class FunTrace extends BasicFunction {
public final static FunctionSignature signature =
new FunctionSignature(
new QName("trace", Function.BUILTIN_FUNCTION_NS),
"This function is intended to be used in debugging queries by "
+"providing a trace of their execution. The input $value is "
+"returned, unchanged, as the result of the function. "
+"In addition, the inputs $value, converted to an xs:string, "
+"and $label is directed to a trace data set in the eXist log files.",
new SequenceType[] {
new FunctionParameterSequenceType("value", Type.ITEM, Cardinality.ZERO_OR_MORE, "The value"),
new FunctionParameterSequenceType("label", Type.STRING, Cardinality.EXACTLY_ONE, "The label in the log file")
},
new FunctionReturnSequenceType(Type.ITEM, Cardinality.ZERO_OR_MORE, "the labelled $value in the log")
);
public FunTrace(XQueryContext context) {
super(context, signature);
}
/*
* (non-Javadoc)
* @see org.exist.xquery.BasicFunction#eval(Sequence[], Sequence)
*/
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
// TODO Add TRACE log statements using log4j
// TODO Figure out why XQTS still does not work
// TODO Remove unneeded comments
String label = args[1].getStringValue();
if(label==null){
label="";
}
Serializer serializer= context.getBroker().getSerializer();
Sequence result ;
if(args[0].isEmpty()){
result = Sequence.EMPTY_SEQUENCE;
} else {
// Copy all Items from input to output sequence
result = new ValueSequence();
int position = 0;
for (SequenceIterator i = args[0].iterate(); i.hasNext();) {
// Get item
Item next = i.nextItem();
// Only write if debug mode
if (true) {
String value = null;
position++;
int type = next.getType();
// Serialize an element type
if (Type.ELEMENT == type) {
Writer sw = new StringWriter();
try {
serializer.serialize((NodeValue) next, sw);
} catch (SAXException ex) {
LOG.error(ex.getMessage());
}
value = sw.toString();
// Get string value for other types
} else {
value = next.getStringValue();
}
// Write to log
LOG.info(label + " [" + position + "]: " + Type.getTypeName(type) + ": " + value);
}
// Add to result
result.add(next);
}
}
return result;
}
}
|
package org.ice4j.socket;
import java.net.*;
/**
* Implements a <tt>DatagramPacketFilter</tt> which only accepts
* <tt>DatagramPacket</tt>s which represent RTCP messages according to the rules
* described in RFC5761.
*
* @author Emil Ivov
* @author Boris Grozev
*/
public class RtcpDemuxPacketFilter
implements DatagramPacketFilter
{
public boolean accept(DatagramPacket p)
{
int len = p.getLength();
if (len >= 4) //minimum RTCP message length
{
byte[] data = p.getData();
int off = p.getOffset();
if (((data[off + 0] & 0xc0) >> 6) == 2) //RTP/RTCP version field
{
int pt = data[off + 1] & 0xff;
return (200 <= pt && pt <= 211);
}
}
return false;
}
}
|
package Models;
import Helpers.*;
import Models.Actions.*;
import java.util.*;
import java.util.Stack;
import Models.Actions.MActions.MAction;
// This enum declaration might need to be moved, not sure how accessible it is right now
// (needs to be accessible by GameModel and the Controller). #JavaTroubles
enum GameState {
ReplayMode, PlanningMode, NormalMode
}
public class GameModel implements Serializable<GameModel> {
// VARIABLES
private BoardModel gameBoard;
private JavaPlayer[] players;
private int indexOfCurrentPlayer;
private boolean isFinalRound;
public MAction selectedAction;
private Stack<Action> actionHistory; // This holds a history of the actions
// taken up to the currently held
// state.
private Stack<Action> actionReplays; // This holds currently undone actions
// for the purposes of Replay Mode
private GameState gameState;
private int actionIDCounter; // Provides unique actionIDs to every action
// created. To be incremented after each
// action instantiation.
public GameModel(int numberPlayers){
this.isFinalRound = false;
this.indexOfCurrentPlayer = 0;
this.gameBoard = new BoardModel();
this.players = new JavaPlayer[numberPlayers];
actionHistory = new Stack<Action>();
actionReplays = new Stack<Action>();
}
// This method is to be used by the controller to determine which buttons
// are visible/enabled in the view (and other visual components). For
// example, if the gameState is PlanningMode, the undo button and exit
// planning mode buttons will be enabled/shown, as well as a Label or
// something.
public GameState getGameState() {
return gameState;
}
public void changeFamePoints(int playerIndex, int modifier) {
players[playerIndex].changeFamePoints(modifier);
}
public Developer getDeveloperOnCell(Cell c)
{
for(int i = 0; i < players.length; i++)
{
for(Developer d:players[i].getDevelopersOnBoard())
{
if(d.getLocation() == c)
return d;
}
}
return null;
}
//Returns an array of players in order from highest to lowest of ranks of players
//valid on a palace/city
public ArrayList<Player> getPalaceRanks(JavaCell palace)
{
ArrayList<JavaCell> city = gameBoard.getCityFromRootCell(palace);
HashMap<Player, Integer> scores = new HashMap<Player, Integer>();
for(JavaCell c : city)
{
if(getDeveloperOnCell(c) != null)
{
Developer d = getDeveloperOnCell(c);
Player p = d.getOwner();
int rank = c.getElevation();
if(!scores.containsKey(p))
{
scores.put(p, rank);
}
else
{
int newRank = c.getElevation();
if(newRank > rank)
scores.put(p, newRank);
}
}
}
//we now have each player mapped to their rank or not mapped if they don't have a developer
//on the city.
ArrayList<Integer> values = new ArrayList<Integer>();
for(Integer i:scores.values())
values.add(i);
Collections.sort(values);
ArrayList<Player> players = new ArrayList<Player>();
for(Integer i:values)
{
for(Player p : scores.keySet())
{
if(scores.get(p) == i)
players.add(p);
}
}
return players;
}
public ArrayList<Player> getIrrigationRanks(JavaCell cell)
{
int x = cell.getX();
int y = cell.getY();
HashMap<Player, Integer> scores = new HashMap<Player, Integer>();
JavaCell[][] map = gameBoard.getMap();
if (y < 13 && getDeveloperOnCell(map[y + 1][x]) != null)
{
JavaCell c = map[y + 1][x];
Developer d = getDeveloperOnCell(map[y + 1][x]);
Player p = d.getOwner();
int rank = c.getElevation();
if(!scores.containsKey(p))
{
scores.put(p, rank);
}
else
{
int newRank = c.getElevation();
if(newRank > rank)
scores.put(p, newRank);
}
}
if (y > 0 && getDeveloperOnCell(map[y - 1][x]) != null)
{
JavaCell c = map[y - 1][x];
Developer d = getDeveloperOnCell(map[y - 1][x]);
Player p = d.getOwner();
int rank = cell.getElevation();
if(!scores.containsKey(p))
{
scores.put(p, rank);
}
else
{
int newRank = c.getElevation();
if(newRank > rank)
scores.put(p, newRank);
}
}
if (x < 14 && getDeveloperOnCell(map[y][x + 1]) != null)
{
JavaCell c = map[y][x+1];
Developer d = getDeveloperOnCell(map[y][x + 1]);
Player p = d.getOwner();
int rank = c.getElevation();
if(!scores.containsKey(p))
{
scores.put(p, rank);
}
else
{
int newRank = c.getElevation();
if(newRank > rank)
scores.put(p, newRank);
}
}
if (x > 0 && getDeveloperOnCell(map[y][x - 1]) != null)
{
JavaCell c = map[y][x-1];
Developer d = getDeveloperOnCell(map[y][x - 1]);
Player p = d.getOwner();
int rank = cell.getElevation();
if(!scores.containsKey(p))
{
scores.put(p, rank);
}
else
{
int newRank = c.getElevation();
if(newRank > rank)
scores.put(p, newRank);
}
}
ArrayList<Integer> values = new ArrayList<Integer>();
for(Integer i:scores.values())
values.add(i);
Collections.sort(values);
ArrayList<Player> players = new ArrayList<Player>();
for(Integer i:values)
{
for(Player p : scores.keySet())
{
if(scores.get(p) == i)
players.add(p);
}
}
return players;
}
/**
* Backtracks GameModel state to end of current player's previous turn,
* storing all backtracked moves in actionReplays stack. Also changes
* gameState to ReplayMode.
*/
public void initializeReplayMode() {
gameState = GameState.ReplayMode;
while (actionHistory.peek().getPlayerIndex() == indexOfCurrentPlayer) {
actionReplays.add(actionHistory.peek());
actionHistory.peek().undo(this);
actionHistory.pop();
}
while (actionHistory.peek().getPlayerIndex() != indexOfCurrentPlayer) {
actionReplays.add(actionHistory.peek());
actionHistory.peek().undo(this);
actionHistory.pop();
}
}
/**
* Iterates forward one move during ReplayMode. If the move replayed is the
* last move to be replayed, changes gameState to NormalMode.
* <p>
* This method should only be accessible while the gameState is ReplayMode!
* I'm leaving this responsibility to the view and controller.
*/
public void replayMove() {
actionHistory.add(actionReplays.peek());
actionReplays.peek().redo(this);
actionReplays.pop();
if (actionReplays.isEmpty())
gameState = GameState.NormalMode;
}
public int getPlayerIndex() {
return this.indexOfCurrentPlayer;
}
public void pressSpace() {
selectedAction.pressSpace();
}
//Methods for MAction/selected action traversal that is needed by the controller
public int getSelectedActionX() {
return selectedAction.getX();
}
public int getSelectedActionY() {
// TODO Auto-generated method stub
return selectedAction.getY();
}
public String getSelectedActionImageKey() {
return selectedAction.getImageKey();
}
public MAction getSelectedAction() {
return selectedAction;
}
public void pressEsc() {
selectedAction = null;
}
public boolean pressLeft() {
if(selectedAction != null){
return selectedAction.pressArrow(-1,0);
}
return false;
}
public boolean pressUp() {
if(selectedAction != null){
return selectedAction.pressArrow(1,0);
}
return false;
}
public boolean pressRight() {
if(selectedAction != null){
return selectedAction.pressArrow(0,1);
}
return false;
}
public boolean pressDown() {
if(selectedAction != null){
return selectedAction.pressArrow(0,-1);
}
return false;
}
public boolean setSelectedAction(MAction selectedAction) {
if(selectedAction == null){
this.selectedAction = selectedAction;
return true;
}
return false;
}
@Override
public String serialize() {
return Json.jsonPair("GameModel", Json.jsonObject(Json.jsonMembers(
Json.jsonPair("gameBoard", gameBoard.serialize()),
Json.jsonPair("gameState", gameState.toString()),
Json.jsonPair("actionHistory", Json.serializeArray(actionHistory)),
Json.jsonPair("actionReplays", Json.serializeArray(actionReplays)),
Json.jsonPair("players", Json.serializeArray(players)),
Json.jsonPair("indexOfCurrentPlayer", Json.jsonValue(indexOfCurrentPlayer + "")),
Json.jsonPair("isFinalRound", Json.jsonValue(isFinalRound + "")),
Json.jsonPair("actionIDCounter", Json.jsonValue(actionIDCounter + ""))
)));
}
@Override
public GameModel loadObject(JsonObject json) {
// TODO Auto-generated method stub
return null;
}
}
|
package org.immopoly.appengine;
import java.net.URL;
import java.util.List;
import java.util.Map;
import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.immopoly.common.ImmopolyException;
import org.json.JSONObject;
public class ActionExposeAdd extends AbstractAction implements Action {
protected ActionExposeAdd(Map<String, Action> actions) {
super(actions);
}
@Override
public String getURI() {
return "portfolio/add";
}
@Override
public void execute(HttpServletRequest req, HttpServletResponse resp) throws ImmopolyException {
PersistenceManager pm = PMF.get().getPersistenceManager();
try {
String token = req.getParameter(TOKEN);
String exposeId = req.getParameter(EXPOSE);
if (null == token || token.length() == 0)
throw new ImmopolyException("missing token", 61);
User user = DBManager.getUserByToken(pm, token);
if (null == user)
throw new ImmopolyException("token not found " + token, 62);
History history = null;
// first check if already owned
Expose expose = DBManager.getExpose(pm, exposeId);
if (null != expose) {
if (expose.getUserId() == user.getId()) {
throw new ImmopolyException("gehört dir schon du penner", 201);
} else {
// history eintrag
// other user
User otherUser = DBManager.getUser(pm, expose.getUserId());
// minus 30tel
double fine = 2 * expose.getRent() / 30.0;
user.setBalance(user.getBalance() - fine);
if (null != otherUser)
otherUser.setBalance(otherUser.getBalance() + fine);
history = new History(History.TYPE_EXPOSE_MONOPOLY_NEGATIVE, user.getId(), System.currentTimeMillis(), "Die Wohnung '"
+ expose.getName() + "' gehört schon '" + otherUser.getUserName() + "' Strafe "
+ History.MONEYFORMAT.format(fine), fine);
if (null != otherUser) {
History otherHistory = new History(History.TYPE_EXPOSE_MONOPOLY_POSITIVE, otherUser.getId(), System
.currentTimeMillis(), "Jemand wollte deine Wohnung '" + expose.getName() + "' übernehmen: Belohung "
+ History.MONEYFORMAT.format(fine), fine);
pm.makePersistent(otherHistory);
}
pm.makePersistent(history);
pm.makePersistent(user);
if (null != otherUser)
pm.makePersistent(otherUser);
}
} else {
URL url = new URL(OAuthData.SERVER + OAuthData.SEARCH_PREFIX + "expose/" + exposeId + ".json");
JSONObject obj = WebHelper.getHttpData(url);
if (obj.has("expose.expose")) {
expose = new Expose(user.getId(), obj);
// nur wohnungen mit rent
if (expose.getRent() == 0.0)
throw new ImmopolyException("Expose hat keinen Wert für Kaltmiete, sie kann nicht übernommen werden", 302);
if(!checkDistance(pm,expose))
throw new ImmopolyException("SPOOFING ALERT", 441);
pm.makePersistent(expose);
double fine = 2 * expose.getRent() / 30.0;
history = new History(History.TYPE_EXPOSE_ADDED, user.getId(), System.currentTimeMillis(), "Du hast die Wohnung '"
+ expose.getName() + "' gemietet für " + History.MONEYFORMAT.format(expose.getRent())
+ " im Monat. Übernahmekosten: " + History.MONEYFORMAT.format(fine), fine);
user.setBalance(user.getBalance() - fine);
pm.makePersistent(user);
pm.makePersistent(history);
} else if (obj.toString().contains("ERROR_RESOURCE_NOT_FOUND"))
throw new ImmopolyException("expose jibs nich", 301);
}
// history eintrag
resp.getOutputStream().write(history.toJSON().toString().getBytes("UTF-8"));
} catch (ImmopolyException e) {
throw e;
} catch (Exception e) {
throw new ImmopolyException("could not add expose ", 101, e);
} finally {
pm.close();
}
}
private boolean checkDistance(PersistenceManager pm, Expose expose) {
//get last x entries
List<Expose> lastExposes = DBManager.getLastExposes(pm, expose.getUserId(),System.currentTimeMillis()-(60*60*1000));
LOG.info("lastExposes "+lastExposes.size() + " userId: " +expose.getUserId()+" "+(System.currentTimeMillis()-(60*60*1000)));
for (Expose e : lastExposes) {
//wenn e weiter weg ist als MAX_SPOOFING_METER_PER_SECOND per return false
double distance = calcDistance(expose.getLatitude(),expose.getLongitude(),e.getLatitude(),e.getLongitude());
double distancePerSecond=distance/((System.currentTimeMillis()-e.getTime())/1000);
LOG.info("distance "+distance+" distancePerSecond "+distancePerSecond+" max "+Const.MAX_SPOOFING_METER_PER_SECOND);
if(distancePerSecond>Const.MAX_SPOOFING_METER_PER_SECOND){
LOG.severe("distance "+distance+" distancePerSecond "+distancePerSecond+" max "+Const.MAX_SPOOFING_METER_PER_SECOND);
return false;
}
}
return true;
}
public static double calcDistance(double lat1, double lng1, double lat2, double lng2) {
double earthRadius = 3958.75;
double dLat = Math.toRadians(lat2-lat1);
double dLng = Math.toRadians(lng2-lng1);
double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
Math.sin(dLng/2) * Math.sin(dLng/2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
double dist = earthRadius * c;
int meterConversion = 1609;
return new Double(dist * meterConversion).doubleValue();
}
}
|
package app.musicplayer.view;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.ResourceBundle;
import app.musicplayer.model.Album;
import app.musicplayer.model.Library;
import app.musicplayer.model.Song;
import app.musicplayer.util.ClippedTableCell;
import app.musicplayer.util.PlayingTableCell;
import app.musicplayer.util.Refreshable;
import javafx.animation.Animation;
import javafx.animation.Transition;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.Label;
import javafx.scene.control.OverrunStyle;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.image.ImageView;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.VBox;
import javafx.util.Duration;
/**
*
* @version 0.9
*
*/
public class AlbumsController implements Initializable, Refreshable {
private boolean isAlbumDetailCollapsed = true;
@FXML private FlowPane grid;
@FXML private VBox songBox;
@FXML private TableView<Song> songTable;
@FXML private TableColumn<Song, Boolean> playingColumn;
@FXML private TableColumn<Song, String> titleColumn;
@FXML private TableColumn<Song, String> lengthColumn;
@FXML private TableColumn<Song, Integer> playsColumn;
private double expandedHeight = 50;
private double collapsedHeight = 0;
private Animation songTableLoadAnimation = new Transition() {
{
setCycleDuration(Duration.millis(1000));
}
protected void interpolate(double frac) {
double curHeight = collapsedHeight + (expandedHeight - collapsedHeight) * (frac);
if (frac < 0.25) {
songTable.setTranslateY(expandedHeight - curHeight * 4);
} else {
songTable.setTranslateY(collapsedHeight);
}
songTable.setOpacity(frac);
}
};
@Override
public void initialize(URL location, ResourceBundle resources) {
ObservableList<Album> albums = FXCollections.observableArrayList(Library.getAlbums());
Collections.sort(albums);
int limit = (albums.size() < 25) ? albums.size() : 25;
for (int i = 0; i < limit; i++) {
Album album = albums.get(i);
grid.getChildren().add(createCell(album, i));
}
int rows = (albums.size() % 5 == 0) ? albums.size() / 5 : albums.size() / 5 + 1;
grid.prefHeightProperty().bind(grid.widthProperty().divide(5).add(16).multiply(rows));
new Thread(() -> {
ArrayList<VBox> cells = new ArrayList<VBox>();
for (int j = 25; j < albums.size(); j++) {
Album album = albums.get(j);
cells.add(createCell(album, j));
}
Platform.runLater(() -> {
grid.getChildren().addAll(cells);
});
}).start();
// Sets preferred column width.
titleColumn.prefWidthProperty().bind(songTable.widthProperty().subtract(50).multiply(0.5));
lengthColumn.prefWidthProperty().bind(songTable.widthProperty().subtract(50).multiply(0.25));
playsColumn.prefWidthProperty().bind(songTable.widthProperty().subtract(50).multiply(0.25));
// Sets the song table to be invisible when the view is initialized.
songBox.setVisible(false);
}
@Override
public void refresh() {}
private VBox createCell(Album album, int index) {
VBox cell = new VBox();
Label title = new Label(album.getTitle());
ImageView image = new ImageView(album.getArtwork());
VBox imageBox = new VBox();
title.setTextOverrun(OverrunStyle.CLIP);
title.setWrapText(true);
title.setPadding(new Insets(10, 0, 10, 0));
title.setAlignment(Pos.TOP_LEFT);
title.setPrefHeight(66);
title.prefWidthProperty().bind(grid.widthProperty().divide(5).subtract(21));
image.fitWidthProperty().bind(grid.widthProperty().divide(5).subtract(21));
image.fitHeightProperty().bind(grid.widthProperty().divide(5).subtract(21));
image.setPreserveRatio(true);
image.setSmooth(true);
imageBox.prefWidthProperty().bind(grid.widthProperty().divide(5).subtract(21));
imageBox.prefHeightProperty().bind(grid.widthProperty().divide(5).subtract(21));
imageBox.setAlignment(Pos.CENTER);
imageBox.getChildren().add(image);
cell.getChildren().addAll(imageBox, title);
cell.setPadding(new Insets(10, 10, 10, 10));
cell.getStyleClass().add("artist-cell");
cell.setAlignment(Pos.CENTER);
cell.setOnMouseClicked(event -> {
// TODO: DEBUG
System.out.println("Cell clicked!");
// If the album detail is collapsed, expand it. Else collapse it.
if (isAlbumDetailCollapsed) {
expandAlbumDetail(cell, index);
populateSongTable(cell, album);
} else {
collapseAlbumDetail(cell);
}
});
return cell;
}
private void expandAlbumDetail(VBox cell, int index) {
// TODO: DEBUG
System.out.println("128: Expand Album Detail");
// Converts the index integer to a string.
String indexString = Integer.toString(index);
// Initializes index used to insert song table into flowpane.
int insertIndex = 0;
// Defines insertIndex based on the clicked cell index so that the song table
// is inserted in the row after the clicked row.
if (indexString.endsWith("0") || indexString.endsWith("5")) {
insertIndex = index + 5;
} else if (indexString.endsWith("1") || indexString.endsWith("6")) {
insertIndex = index + 4;
} else if (indexString.endsWith("2") || indexString.endsWith("7")) {
insertIndex = index + 3;
} else if (indexString.endsWith("3") || indexString.endsWith("8")) {
insertIndex = index + 2;
} else if (indexString.endsWith("4") || indexString.endsWith("9")) {
insertIndex = index + 1;
}
// Obtains the flowpane width and sets the song box width to that value.
songBox.setPrefWidth(grid.getWidth());;
// Adds the song box to the flow pane.
grid.getChildren().add(insertIndex, songBox);
isAlbumDetailCollapsed = false;
songBox.setVisible(true);
songTableLoadAnimation.play();
}
private void collapseAlbumDetail(VBox cell) {
// TODO: DEBUG
System.out.println("135: Collapse Album Detail");
// Removes the songBox from the flow pane.
grid.getChildren().remove(songBox);
isAlbumDetailCollapsed = true;
songBox.setVisible(false);
}
private void populateSongTable(VBox cell, Album selectedAlbum) {
// TODO: DEBUG
System.out.println("Populate Song Table");
System.out.println("Album Title: " + selectedAlbum.getTitle());
// Retrieves albums songs and stores them as an observable list.
ObservableList<Song> albumSongs = FXCollections.observableArrayList(selectedAlbum.getSongs());
System.out.println("Album First Song (OL): " + albumSongs.get(0).getTitle());
playingColumn.setCellFactory(x -> new PlayingTableCell<Song, Boolean>());
titleColumn.setCellFactory(x -> new ClippedTableCell<Song, String>());
lengthColumn.setCellFactory(x -> new ClippedTableCell<Song, String>());
playsColumn.setCellFactory(x -> new ClippedTableCell<Song, Integer>());
// Sets each column item.
playingColumn.setCellValueFactory(new PropertyValueFactory<Song, Boolean>("playing"));
titleColumn.setCellValueFactory(new PropertyValueFactory<Song, String>("title"));
lengthColumn.setCellValueFactory(new PropertyValueFactory<Song, String>("lengthAsString"));
playsColumn.setCellValueFactory(new PropertyValueFactory<Song, Integer>("playCount"));
// Adds songs to table.
songTable.setItems(albumSongs);
}
}
|
package org.jenetics;
import static java.lang.Math.max;
import static java.lang.Math.min;
import java.util.Random;
import org.jenetics.util.Array;
import org.jenetics.util.Probability;
import org.jenetics.util.RandomRegistry;
public class PartiallyMatchedCrossover<G extends Gene<?, G>> extends Crossover<G> {
private static final long serialVersionUID = 4100745364870900673L;
public PartiallyMatchedCrossover(final Alterer<G> component) {
super(component);
}
public PartiallyMatchedCrossover(
final Probability probability, final Alterer<G> component
) {
super(probability, component);
}
public PartiallyMatchedCrossover(final Probability probability) {
super(probability);
}
@Override
protected void crossover(final Array<G> that, final Array<G> other) {
final Random random = RandomRegistry.getRandom();
int index1 = random.nextInt(that.length());
int index2 = random.nextInt(other.length());
index1 = min(index1, index2);
index2 = max(index1, index2) + 1;
final Array<G> thatGenes = new Array<G>(index2 - index1);
final Array<G> otherGenes = new Array<G>(index2 - index1);
//Swap the gene range.
for (int i = index1; i < index2; ++i) {
final int index = i - index1;
thatGenes.set(index, that.get(i));
otherGenes.set(index, other.get(i));
that.set(i, otherGenes.get(index));
other.set(i, thatGenes.get(index));
}
//Repare the chromosomes.
for (int i = 0; i < (index2 - index1); ++i) {
int thatIndex = indexOf(that, index1, index2, otherGenes.get(i));
int otherIndex = indexOf(other, index1, index2, thatGenes.get(i));
that.set(thatIndex, thatGenes.get(i));
other.set(otherIndex, otherGenes.get(i));
}
}
private static <A> int indexOf(
final Array<A> genes, final int idx1, final int idx2, final A gene
) {
int index = -1;
for (int i = 0; index == -1 && i < idx1; ++i) {
if (genes.get(i) == gene) {
index = i;
}
}
for (int i = idx2; index == -1 && i < genes.length(); ++i) {
if (genes.get(i) == gene) {
index = i;
}
}
for (int i = idx1; index == -1 && i < idx2; ++i) {
if (genes.get(i) == gene) {
index = i;
}
}
return index;
}
}
|
package com.github.podd.impl;
import info.aduna.iteration.Iterations;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import org.openrdf.OpenRDFException;
import org.openrdf.model.Literal;
import org.openrdf.model.Model;
import org.openrdf.model.Namespace;
import org.openrdf.model.Resource;
import org.openrdf.model.Statement;
import org.openrdf.model.URI;
import org.openrdf.model.Value;
import org.openrdf.model.impl.LinkedHashModel;
import org.openrdf.model.impl.ValueFactoryImpl;
import org.openrdf.model.util.Namespaces;
import org.openrdf.model.vocabulary.OWL;
import org.openrdf.model.vocabulary.RDF;
import org.openrdf.repository.Repository;
import org.openrdf.repository.RepositoryConnection;
import org.openrdf.repository.RepositoryException;
import org.openrdf.repository.RepositoryResult;
import org.openrdf.rio.RDFFormat;
import org.openrdf.rio.Rio;
import org.semanticweb.owlapi.model.IRI;
import org.semanticweb.owlapi.model.OWLException;
import org.semanticweb.owlapi.model.OWLOntology;
import org.semanticweb.owlapi.model.OWLOntologyID;
import org.semanticweb.owlapi.profiles.OWLProfileReport;
import org.semanticweb.owlapi.profiles.OWLProfileViolation;
import org.semanticweb.owlapi.reasoner.OWLReasoner;
import org.semanticweb.owlapi.rio.RioMemoryTripleSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.podd.api.DanglingObjectPolicy;
import com.github.podd.api.DataReferenceVerificationPolicy;
import com.github.podd.api.MetadataPolicy;
import com.github.podd.api.PoddArtifactManager;
import com.github.podd.api.PoddOWLManager;
import com.github.podd.api.PoddRepositoryManager;
import com.github.podd.api.PoddSchemaManager;
import com.github.podd.api.PoddSesameManager;
import com.github.podd.api.UpdatePolicy;
import com.github.podd.api.file.DataReference;
import com.github.podd.api.file.DataReferenceManager;
import com.github.podd.api.file.PoddDataRepositoryManager;
import com.github.podd.api.purl.PoddPurlManager;
import com.github.podd.api.purl.PoddPurlReference;
import com.github.podd.exception.ArtifactModifyException;
import com.github.podd.exception.DeleteArtifactException;
import com.github.podd.exception.DisconnectedObjectException;
import com.github.podd.exception.DuplicateArtifactIRIException;
import com.github.podd.exception.EmptyOntologyException;
import com.github.podd.exception.FileReferenceVerificationFailureException;
import com.github.podd.exception.InconsistentOntologyException;
import com.github.podd.exception.OntologyNotInProfileException;
import com.github.podd.exception.PoddException;
import com.github.podd.exception.PoddRuntimeException;
import com.github.podd.exception.PublishArtifactException;
import com.github.podd.exception.PublishedArtifactModifyException;
import com.github.podd.exception.PurlProcessorNotHandledException;
import com.github.podd.exception.UnmanagedArtifactIRIException;
import com.github.podd.exception.UnmanagedArtifactVersionException;
import com.github.podd.exception.UnmanagedSchemaIRIException;
import com.github.podd.utils.InferredOWLOntologyID;
import com.github.podd.utils.OntologyUtils;
import com.github.podd.utils.PoddObjectLabel;
import com.github.podd.utils.PoddRdfConstants;
import com.github.podd.utils.RdfUtility;
/**
* Implementation of the PODD Artifact Manager API, to manage the lifecycle for PODD Artifacts.
*
* @author Peter Ansell p_ansell@yahoo.com
*
*/
public class PoddArtifactManagerImpl implements PoddArtifactManager
{
private final Logger log = LoggerFactory.getLogger(this.getClass());
private DataReferenceManager dataReferenceManager;
private PoddDataRepositoryManager dataRepositoryManager;
private PoddOWLManager owlManager;
private PoddPurlManager purlManager;
private PoddSchemaManager schemaManager;
private PoddRepositoryManager repositoryManager;
private PoddSesameManager sesameManager;
public PoddArtifactManagerImpl()
{
}
@Override
public InferredOWLOntologyID attachDataReference(final InferredOWLOntologyID artifactId, final URI objectUri,
final DataReference dataReference, final DataReferenceVerificationPolicy dataReferenceVerificationPolicy)
throws OpenRDFException, PoddException, IOException, OWLException
{
return this.attachDataReferences(artifactId, dataReference.toRDF(), dataReferenceVerificationPolicy);
}
@Override
public InferredOWLOntologyID attachDataReferences(final InferredOWLOntologyID ontologyId, final Model model,
final DataReferenceVerificationPolicy dataReferenceVerificationPolicy) throws OpenRDFException,
IOException, OWLException, PoddException
{
model.removeAll(model.filter(null, PoddRdfConstants.PODD_BASE_INFERRED_VERSION, null));
final Set<Resource> fileReferences =
model.filter(null, RDF.TYPE, PoddRdfConstants.PODD_BASE_DATA_REFERENCE_TYPE).subjects();
final Collection<URI> fileReferenceObjects = new ArrayList<URI>(fileReferences.size());
for(final Resource nextFileReference : fileReferences)
{
if(nextFileReference instanceof URI)
{
fileReferenceObjects.add((URI)nextFileReference);
}
else
{
this.log.warn("Will not be updating file reference for blank node reference, will instead be creating a new file reference for it.");
}
}
final Model exportArtifact = this.exportArtifact(ontologyId, false);
exportArtifact.addAll(model);
final Model resultModel =
this.updateArtifact(ontologyId.getOntologyIRI().toOpenRDFURI(), ontologyId.getVersionIRI()
.toOpenRDFURI(), fileReferenceObjects, model, UpdatePolicy.MERGE_WITH_EXISTING,
DanglingObjectPolicy.REPORT, dataReferenceVerificationPolicy);
return OntologyUtils.modelToOntologyIDs(resultModel).get(0);
}
@Override
public boolean deleteArtifact(final InferredOWLOntologyID artifactId) throws PoddException
{
if(artifactId.getOntologyIRI() == null)
{
throw new PoddRuntimeException("Ontology IRI cannot be null");
}
RepositoryConnection connection = null;
try
{
if(this.isPublished(artifactId))
{
throw new DeleteArtifactException("Published Artifacts cannot be deleted", artifactId);
}
final Collection<OWLOntologyID> schemaImports = this.getSchemaImports(artifactId);
connection = this.getRepositoryManager().getPermanentRepository(schemaImports).getConnection();
connection.begin();
List<InferredOWLOntologyID> requestedArtifactIds =
this.getSesameManager().getAllOntologyVersions(artifactId.getOntologyIRI(), connection,
this.getRepositoryManager().getArtifactManagementGraph());
if(artifactId.getVersionIRI() != null)
{
final IRI requestedVersionIRI = artifactId.getVersionIRI();
for(final InferredOWLOntologyID nextVersion : new ArrayList<InferredOWLOntologyID>(requestedArtifactIds))
{
if(requestedVersionIRI.equals(nextVersion.getVersionIRI()))
{
requestedArtifactIds = Arrays.asList(nextVersion);
}
}
}
this.getSesameManager().deleteOntologies(requestedArtifactIds, connection,
this.getRepositoryManager().getArtifactManagementGraph());
connection.commit();
// - ensure deleted ontologies are removed from the OWLOntologyManager's cache
for(final InferredOWLOntologyID deletedOntologyId : requestedArtifactIds)
{
this.getOWLManager().removeCache(deletedOntologyId.getBaseOWLOntologyID());
this.getOWLManager().removeCache(deletedOntologyId.getInferredOWLOntologyID());
}
return !requestedArtifactIds.isEmpty();
}
catch(final OpenRDFException | OWLException e)
{
try
{
if(connection != null && connection.isActive())
{
connection.rollback();
}
}
catch(final RepositoryException e1)
{
this.log.error("Found error rolling back repository connection", e1);
}
throw new DeleteArtifactException("Repository exception occurred", e, artifactId);
}
finally
{
try
{
if(connection != null && connection.isOpen())
{
connection.close();
}
}
catch(final RepositoryException e)
{
throw new DeleteArtifactException("Repository exception occurred", e, artifactId);
}
}
}
@Override
public InferredOWLOntologyID deleteObject(final String artifactUri, final String versionUri,
final String objectUri, final boolean cascade) throws PoddException, OpenRDFException, IOException,
OWLException
{
// check if the specified artifact URI refers to a managed artifact
InferredOWLOntologyID artifactID = null;
try
{
artifactID = this.getArtifact(IRI.create(artifactUri));
}
catch(final UnmanagedArtifactIRIException e)
{
this.log.error("This artifact is unmanaged. [{}]", artifactUri);
throw e;
}
if(this.isPublished(artifactID))
{
throw new PublishedArtifactModifyException("Attempting to modify a Published Artifact", artifactID);
}
this.log.debug("deleteObject ({}) from artifact {} with cascade={}", objectUri, artifactUri, cascade);
final URI objectToDelete = PoddRdfConstants.VF.createURI(objectUri);
final Collection<URI> objectsToUpdate = new ArrayList<URI>();
objectsToUpdate.add(objectToDelete);
final Model fragments = new LinkedHashModel();
final Model artifactModel = this.exportArtifact(artifactID, false);
// - find the objectToDelete's parent and remove parent-child link
final Model parentDetails = this.getParentDetails(artifactID, objectToDelete);
if(parentDetails.subjects().size() != 1)
{
this.log.error("Object {} cannot be deleted. (No parent)", objectUri, artifactUri);
throw new ArtifactModifyException("Object cannot be deleted. (No parent)", artifactID, objectToDelete);
}
final Resource parent = parentDetails.subjects().iterator().next();
fragments.addAll(artifactModel.filter(parent, null, null));
fragments.remove(parent, null, objectToDelete);
objectsToUpdate.add((URI)parent);
// - remove any refersToLinks
final Model referenceLinks = this.getReferenceLinks(artifactID, objectToDelete);
final Set<Resource> referrers = referenceLinks.subjects();
for(final Resource referrer : referrers)
{
final Model referrerStatements = artifactModel.filter(referrer, null, null);
referrerStatements.remove(referrer, null, objectToDelete);
fragments.addAll(referrerStatements);
objectsToUpdate.add((URI)referrer);
}
DanglingObjectPolicy danglingObjectPolicy = DanglingObjectPolicy.REPORT;
if(cascade)
{
danglingObjectPolicy = DanglingObjectPolicy.FORCE_CLEAN;
}
this.updateArtifact(artifactID.getOntologyIRI().toOpenRDFURI(), artifactID.getVersionIRI().toOpenRDFURI(),
objectsToUpdate, fragments, UpdatePolicy.REPLACE_EXISTING, danglingObjectPolicy,
DataReferenceVerificationPolicy.DO_NOT_VERIFY);
return this.getArtifact(artifactID.getOntologyIRI());
}
@Override
public Model exportArtifact(final InferredOWLOntologyID ontologyId, final boolean includeInferred)
throws OpenRDFException, PoddException, IOException
{
if(ontologyId.getOntologyIRI() == null || ontologyId.getVersionIRI() == null)
{
throw new PoddRuntimeException("Ontology IRI and Version IRI cannot be null");
}
if(includeInferred && ontologyId.getInferredOntologyIRI() == null)
{
throw new PoddRuntimeException("Inferred Ontology IRI cannot be null");
}
List<URI> contexts;
if(includeInferred)
{
contexts =
Arrays.asList(ontologyId.getVersionIRI().toOpenRDFURI(), ontologyId.getInferredOntologyIRI()
.toOpenRDFURI());
}
else
{
contexts = Arrays.asList(ontologyId.getVersionIRI().toOpenRDFURI());
}
RepositoryConnection conn = null;
try
{
final Collection<OWLOntologyID> schemaImports = this.getSchemaImports(ontologyId);
conn = this.getRepositoryManager().getPermanentRepository(schemaImports).getConnection();
final RepositoryResult<Statement> statements =
conn.getStatements(null, null, null, includeInferred, contexts.toArray(new Resource[] {}));
final Model model = new LinkedHashModel(Iterations.asList(statements));
final RepositoryResult<Namespace> namespaces = conn.getNamespaces();
for(final Namespace nextNs : Iterations.asSet(namespaces))
{
model.setNamespace(nextNs);
}
return model;
}
finally
{
if(conn != null)
{
conn.close();
}
}
}
@Override
public void exportArtifact(final InferredOWLOntologyID ontologyId, final OutputStream outputStream,
final RDFFormat format, final boolean includeInferred) throws OpenRDFException, PoddException, IOException
{
final Model model = this.exportArtifact(ontologyId, includeInferred);
Rio.write(model, outputStream, format);
}
@Override
public void exportObjectMetadata(final URI objectType, final OutputStream outputStream, final RDFFormat format,
final boolean includeDoNotDisplayProperties, final MetadataPolicy containsPropertyPolicy,
final InferredOWLOntologyID artifactID) throws OpenRDFException, PoddException, IOException
{
RepositoryConnection conn = null;
try
{
final Collection<OWLOntologyID> schemaImports = this.getSchemaImports(artifactID);
conn = this.getRepositoryManager().getPermanentRepository(schemaImports).getConnection();
final URI[] contexts =
this.sesameManager.versionAndSchemaContexts(artifactID, conn,
this.repositoryManager.getSchemaManagementGraph());
Model model;
if(containsPropertyPolicy == MetadataPolicy.ONLY_CONTAINS)
{
model = this.sesameManager.getObjectTypeContainsMetadata(objectType, conn, contexts);
}
else
{
model =
this.sesameManager.getObjectTypeMetadata(objectType, includeDoNotDisplayProperties,
containsPropertyPolicy, conn, contexts);
}
Rio.write(model, outputStream, format);
}
finally
{
if(conn != null)
{
conn.close();
}
}
}
@Override
public Model fillMissingData(final InferredOWLOntologyID ontologyID, final Model inputModel)
throws OpenRDFException
{
RepositoryConnection conn = null;
try
{
final Collection<OWLOntologyID> schemaImports = this.getSchemaImports(ontologyID);
conn = this.getRepositoryManager().getPermanentRepository(schemaImports).getConnection();
final URI[] contexts =
this.getSesameManager().versionAndSchemaContexts(ontologyID, conn,
this.getRepositoryManager().getSchemaManagementGraph());
return this.getSesameManager().fillMissingLabels(inputModel, conn, contexts);
}
catch(final OpenRDFException e)
{
try
{
if(conn != null && conn.isActive())
{
conn.rollback();
}
}
catch(final RepositoryException e1)
{
this.log.error("Found error rolling back repository connection", e1);
}
throw e;
}
finally
{
try
{
if(conn != null && conn.isOpen())
{
conn.close();
}
}
catch(final RepositoryException e)
{
throw e;
}
}
}
@Override
public InferredOWLOntologyID getArtifact(final IRI artifactIRI) throws UnmanagedArtifactIRIException
{
try
{
return this.getArtifact(artifactIRI, null);
}
catch(final UnmanagedArtifactVersionException e)
{
this.log.error("Null artifact version not recognised, this should not happen");
return null;
}
}
@Override
public InferredOWLOntologyID getArtifact(final IRI artifactIRI, final IRI versionIRI)
throws UnmanagedArtifactIRIException, UnmanagedArtifactVersionException
{
RepositoryConnection repositoryConnection = null;
try
{
final Collection<OWLOntologyID> schemaImports =
this.getSchemaImports(new InferredOWLOntologyID(artifactIRI, versionIRI, null));
repositoryConnection = this.getRepositoryManager().getPermanentRepository(schemaImports).getConnection();
InferredOWLOntologyID result = null;
if(versionIRI != null)
{
result =
this.getSesameManager().getOntologyVersion(versionIRI, repositoryConnection,
this.getRepositoryManager().getArtifactManagementGraph());
}
if(result == null)
{
result =
this.getSesameManager().getCurrentArtifactVersion(artifactIRI, repositoryConnection,
this.getRepositoryManager().getArtifactManagementGraph());
}
if(result != null)
{
// If the result that was returned contained a different artifact IRI then throw an
// exception early instead of returning inconsistent results
if(versionIRI != null && !result.getVersionIRI().equals(versionIRI))
{
throw new UnmanagedArtifactVersionException(artifactIRI, result.getVersionIRI(), versionIRI,
"Artifact IRI and Version IRI combination did not match");
}
}
return result;
}
catch(final OpenRDFException e)
{
throw new UnmanagedArtifactIRIException(artifactIRI, e);
}
finally
{
if(repositoryConnection != null)
{
try
{
repositoryConnection.close();
}
catch(final RepositoryException e)
{
this.log.error("Failed to close repository connection", e);
}
}
}
}
/*
* (non-Javadoc)
*
* Wraps PoddSesameManager.getChildObjects()
*
* @see com.github.podd.api.PoddArtifactManager#getChildObjects()
*/
@Override
public Set<URI> getChildObjects(final InferredOWLOntologyID ontologyID, final URI objectUri)
throws OpenRDFException
{
RepositoryConnection conn = null;
try
{
final Collection<OWLOntologyID> schemaImports = this.getSchemaImports(ontologyID);
conn = this.getRepositoryManager().getPermanentRepository(schemaImports).getConnection();
final URI[] contexts =
this.getSesameManager().versionAndSchemaContexts(ontologyID, conn,
this.getRepositoryManager().getSchemaManagementGraph());
return this.getSesameManager().getChildObjects(objectUri, conn, contexts);
}
finally
{
conn.close();
}
}
/*
* (non-Javadoc)
*
* @see com.github.podd.api.PoddArtifactManager#getFileReferenceManager()
*/
@Override
public DataReferenceManager getFileReferenceManager()
{
return this.dataReferenceManager;
}
@Override
public Set<DataReference> getFileReferences(final InferredOWLOntologyID artifactId)
{
// TODO Auto-generated method stub
return null;
}
@Override
public Set<DataReference> getFileReferences(final InferredOWLOntologyID artifactId, final String alias)
{
// TODO Auto-generated method stub
return null;
}
@Override
public Set<DataReference> getFileReferences(final InferredOWLOntologyID artifactId, final URI objectUri)
{
// TODO Auto-generated method stub
return null;
}
/*
* (non-Javadoc)
*
* @see com.github.podd.api.PoddArtifactManager#getFileRepositoryManager()
*/
@Override
public PoddDataRepositoryManager getFileRepositoryManager()
{
return this.dataRepositoryManager;
}
/*
* (non-Javadoc)
*
* Wraps PoddSesameManager.getObjectDetailsForDisplay()
*
* @see com.github.podd.api.PoddArtifactManager#getObjectDetailsForDisplay()
*/
@Override
public Model getObjectDetailsForDisplay(final InferredOWLOntologyID ontologyID, final URI objectUri)
throws OpenRDFException
{
RepositoryConnection conn = null;
try
{
final Collection<OWLOntologyID> schemaImports = this.getSchemaImports(ontologyID);
conn = this.getRepositoryManager().getPermanentRepository(schemaImports).getConnection();
return this.getSesameManager().getObjectDetailsForDisplay(ontologyID, objectUri, conn);
}
finally
{
conn.close();
}
}
@Override
public PoddObjectLabel getObjectLabel(final InferredOWLOntologyID ontologyID, final URI objectUri)
throws OpenRDFException
{
RepositoryConnection conn = null;
try
{
final Collection<OWLOntologyID> schemaImports = this.getSchemaImports(ontologyID);
conn = this.getRepositoryManager().getPermanentRepository(schemaImports).getConnection();
return this.getSesameManager().getObjectLabel(ontologyID, objectUri, conn);
}
finally
{
conn.close();
}
}
/*
* (non-Javadoc)
*
* @see com.github.podd.api.PoddArtifactManager#getObjectTypes(com.github.podd.utils.
* InferredOWLOntologyID, org.openrdf.model.URI)
*/
@Override
public List<PoddObjectLabel> getObjectTypes(final InferredOWLOntologyID artifactId, final URI objectUri)
throws OpenRDFException
{
final List<PoddObjectLabel> results = new ArrayList<PoddObjectLabel>();
RepositoryConnection conn = null;
try
{
final Collection<OWLOntologyID> schemaImports = this.getSchemaImports(artifactId);
conn = this.getRepositoryManager().getPermanentRepository(schemaImports).getConnection();
final List<URI> typesList = this.getSesameManager().getObjectTypes(artifactId, objectUri, conn);
for(final URI objectType : typesList)
{
results.add(this.getSesameManager().getObjectLabel(artifactId, objectType, conn));
}
}
finally
{
conn.close();
}
return results;
}
/*
* (non-Javadoc)
*
* Wraps PoddSesameManager.getOrderedProperties()
*
* @see com.github.podd.api.PoddArtifactManager#getOrderedProperties()
*/
@Override
public List<URI> getOrderedProperties(final InferredOWLOntologyID ontologyID, final URI objectUri,
final boolean excludeContainsProperties) throws OpenRDFException
{
RepositoryConnection conn = null;
try
{
final Collection<OWLOntologyID> schemaImports = this.getSchemaImports(ontologyID);
conn = this.getRepositoryManager().getPermanentRepository(schemaImports).getConnection();
final URI[] contexts =
this.getSesameManager().versionAndSchemaContexts(ontologyID, conn,
this.getRepositoryManager().getSchemaManagementGraph());
return this.getSesameManager().getWeightedProperties(objectUri, excludeContainsProperties, conn, contexts);
}
finally
{
conn.close();
}
}
/*
* (non-Javadoc)
*
* @see com.github.podd.api.PoddArtifactManager#getOWLManager()
*/
@Override
public PoddOWLManager getOWLManager()
{
return this.owlManager;
}
/*
* (non-Javadoc)
*
* @see com.github.podd.api.PoddArtifactManager#getParentDetails(com.github.podd.utils.
* InferredOWLOntologyID, org.openrdf.model.URI)
*/
@Override
public Model getParentDetails(final InferredOWLOntologyID ontologyID, final URI objectUri) throws OpenRDFException
{
RepositoryConnection conn = null;
try
{
final Collection<OWLOntologyID> schemaImports = this.getSchemaImports(ontologyID);
conn = this.getRepositoryManager().getPermanentRepository(schemaImports).getConnection();
final URI[] contexts =
this.getSesameManager().versionAndSchemaContexts(ontologyID, conn,
this.getRepositoryManager().getSchemaManagementGraph());
return this.getSesameManager().getParentDetails(objectUri, conn, contexts);
}
catch(final OpenRDFException e)
{
try
{
if(conn != null && conn.isActive())
{
conn.rollback();
}
}
catch(final RepositoryException e1)
{
this.log.error("Found error rolling back repository connection", e1);
}
throw e;
}
finally
{
try
{
if(conn != null && conn.isOpen())
{
conn.close();
}
}
catch(final RepositoryException e)
{
throw e;
}
}
}
/*
* (non-Javadoc)
*
* @see com.github.podd.api.PoddArtifactManager#getPurlManager()
*/
@Override
public PoddPurlManager getPurlManager()
{
return this.purlManager;
}
public Model getReferenceLinks(final InferredOWLOntologyID ontologyID, final URI objectUri) throws OpenRDFException
{
RepositoryConnection conn = null;
try
{
final Collection<OWLOntologyID> schemaImports = this.getSchemaImports(ontologyID);
conn = this.getRepositoryManager().getPermanentRepository(schemaImports).getConnection();
final URI[] contexts =
this.getSesameManager().versionAndSchemaContexts(ontologyID, conn,
this.getRepositoryManager().getSchemaManagementGraph());
return this.getSesameManager().getReferringObjectDetails(objectUri, conn, contexts);
}
finally
{
try
{
if(conn != null && conn.isOpen())
{
conn.close();
}
}
catch(final RepositoryException e)
{
throw e;
}
}
}
@Override
public PoddRepositoryManager getRepositoryManager()
{
return this.repositoryManager;
}
@Override
public Collection<OWLOntologyID> getSchemaImports(final InferredOWLOntologyID artifactID)
{
// FIXME: Implement me!
return null;
}
@Override
public PoddSchemaManager getSchemaManager()
{
return this.schemaManager;
}
@Override
public PoddSesameManager getSesameManager()
{
return this.sesameManager;
}
@Override
public List<PoddObjectLabel> getTopObjectLabels(final List<InferredOWLOntologyID> artifacts)
throws OpenRDFException
{
final List<PoddObjectLabel> results = new ArrayList<PoddObjectLabel>();
RepositoryConnection conn = null;
try
{
for(final InferredOWLOntologyID artifactId : artifacts)
{
final Collection<OWLOntologyID> schemaImports = this.getSchemaImports(artifactId);
conn = this.getRepositoryManager().getPermanentRepository(schemaImports).getConnection();
final URI objectIRI = this.getSesameManager().getTopObjectIRI(artifactId, conn);
results.add(this.getSesameManager().getObjectLabel(artifactId, objectIRI, conn));
}
}
finally
{
conn.close();
}
return results;
}
/**
* Helper method to cache schema ontologies in memory before loading statements into OWLAPI
*/
private void handleCacheSchemasInMemory(final RepositoryConnection permanentRepositoryConnection,
final RepositoryConnection tempRepositoryConnection, final URI tempContext) throws OpenRDFException,
OWLException, IOException, PoddException
{
final Set<IRI> importedSchemas =
this.getSesameManager().getDirectImports(tempRepositoryConnection, tempContext);
for(final IRI importedSchemaIRI : importedSchemas)
{
final InferredOWLOntologyID ontologyVersion =
this.getSesameManager().getSchemaVersion(importedSchemaIRI, permanentRepositoryConnection,
this.getRepositoryManager().getSchemaManagementGraph());
this.getOWLManager().cacheSchemaOntology(ontologyVersion, permanentRepositoryConnection,
this.getRepositoryManager().getSchemaManagementGraph());
}
}
/**
* Checks for dangling objects that are not linked to the artifact and deletes them if
* <i>force</i> is true.
*
* @param artifactID
* @param repositoryConnection
* @param context
* @param force
* If true, deletes any dangling objects. If false, throws a
* DisconnectedObjectException if any dangling objects are found.
* @throws RepositoryException
* @throws DisconnectedObjectException
*/
private void handleDanglingObjects(final IRI artifactID, final RepositoryConnection repositoryConnection,
final URI context, final DanglingObjectPolicy policy) throws RepositoryException,
DisconnectedObjectException
{
final Set<URI> danglingObjects =
RdfUtility.findDisconnectedNodes(artifactID.toOpenRDFURI(), repositoryConnection, context);
if(!danglingObjects.isEmpty())
{
if(policy.equals(DanglingObjectPolicy.REPORT))
{
this.log.error("Found {} dangling object(s) (reporting). \n {}", danglingObjects.size(),
danglingObjects);
throw new DisconnectedObjectException(danglingObjects, "Update leads to disconnected PODD objects");
}
else if(policy.equals(DanglingObjectPolicy.FORCE_CLEAN))
{
this.log.info("Found {} dangling object(s) (force cleaning). \n {}", danglingObjects.size(),
danglingObjects);
for(final URI danglingObject : danglingObjects)
{
repositoryConnection.remove(danglingObject, null, null, context);
repositoryConnection.remove(null, null, (Value)danglingObject, context);
}
}
}
}
/**
* Helper method to handle File References in a newly loaded/updated set of statements.
*
* TODO: Optionally remove invalid file references or mark them as invalid using RDF
* statements/OWL Classes
*
* @param repositoryConnection
* @param context
* @param policy
* If true, verifies that DataReference objects are accessible from their respective
* remote File Repositories
*
* @throws OpenRDFException
* @throws PoddException
*/
private void handleFileReferences(final RepositoryConnection repositoryConnection,
final DataReferenceVerificationPolicy policy, final URI... contexts) throws OpenRDFException, PoddException
{
if(this.getFileReferenceManager() == null)
{
return;
}
if(DataReferenceVerificationPolicy.VERIFY.equals(policy))
{
final Set<DataReference> fileReferenceResults =
this.getFileReferenceManager().extractDataReferences(repositoryConnection, contexts);
this.log.debug("Handling File reference validation");
try
{
this.dataRepositoryManager.verifyDataReferences(fileReferenceResults);
}
catch(final FileReferenceVerificationFailureException e)
{
this.log.warn("From " + fileReferenceResults.size() + " file references, "
+ e.getValidationFailures().size() + " failed validation.");
throw e;
}
}
}
/**
* Helper method to handle File References in a newly loaded/updated set of statements
*/
private Set<PoddPurlReference> handlePurls(final RepositoryConnection repositoryConnection, final URI context)
throws PurlProcessorNotHandledException, OpenRDFException
{
if(this.getPurlManager() == null)
{
return Collections.emptySet();
}
this.log.debug("Handling Purl generation");
final Set<PoddPurlReference> purlResults =
this.getPurlManager().extractPurlReferences(repositoryConnection, context);
this.getPurlManager().convertTemporaryUris(purlResults, repositoryConnection, context);
return purlResults;
}
/**
* Helper method to check schema ontology imports and update use of ontology IRIs to version
* IRIs.
*/
private void handleSchemaImports(final IRI ontologyIRI, final RepositoryConnection permanentRepositoryConnection,
final RepositoryConnection tempRepositoryConnection, final URI tempContext) throws OpenRDFException,
UnmanagedSchemaIRIException
{
final Set<IRI> importedSchemas =
this.getSesameManager().getDirectImports(tempRepositoryConnection, tempContext);
for(final IRI importedSchemaIRI : importedSchemas)
{
final InferredOWLOntologyID schemaOntologyID =
this.getSesameManager().getSchemaVersion(importedSchemaIRI, permanentRepositoryConnection,
this.getRepositoryManager().getSchemaManagementGraph());
if(!importedSchemaIRI.equals(schemaOntologyID.getVersionIRI()))
{
// modify import to be a specific version of the schema
this.log.debug("Updating import to version <{}>", schemaOntologyID.getVersionIRI());
tempRepositoryConnection.remove(ontologyIRI.toOpenRDFURI(), OWL.IMPORTS,
importedSchemaIRI.toOpenRDFURI(), tempContext);
tempRepositoryConnection.add(ontologyIRI.toOpenRDFURI(), OWL.IMPORTS, schemaOntologyID.getVersionIRI()
.toOpenRDFURI(), tempContext);
}
}
}
/**
* This helper method checks for statements with the given property and having a date-time value
* with the year 1970 and updates their date-time with the given {@link Value}.
*
* @param repositoryConnection
* @param propertyUri
* @param newTimestamp
* @param context
* @throws OpenRDFException
*/
private void handleTimestamps(final RepositoryConnection repositoryConnection, final URI propertyUri,
final Value newTimestamp, final URI context) throws OpenRDFException
{
final List<Statement> statements =
Iterations.asList(repositoryConnection.getStatements(null, propertyUri, null, false, context));
for(final Statement s : statements)
{
final Value object = s.getObject();
if(object instanceof Literal)
{
final int year = ((Literal)object).calendarValue().getYear();
if(year == 1970)
{
repositoryConnection.remove(s, context);
repositoryConnection.add(s.getSubject(), s.getPredicate(), newTimestamp, context);
}
}
}
}
public String incrementVersion(final String oldVersion)
{
final char versionSeparatorChar = ':';
final int positionVersionSeparator = oldVersion.lastIndexOf(versionSeparatorChar);
if(positionVersionSeparator > 1)
{
final String prefix = oldVersion.substring(0, positionVersionSeparator);
final String version = oldVersion.substring(positionVersionSeparator + 1);
try
{
int versionInt = Integer.parseInt(version);
versionInt++;
return prefix + versionSeparatorChar + versionInt;
}
catch(final NumberFormatException e)
{
return oldVersion.concat("1");
}
}
return oldVersion.concat("1");
}
@Override
public boolean isPublished(final InferredOWLOntologyID ontologyId) throws OpenRDFException
{
RepositoryConnection conn = null;
try
{
conn = this.repositoryManager.getManagementRepository().getConnection();
return this.getSesameManager().isPublished(ontologyId, conn,
this.getRepositoryManager().getArtifactManagementGraph());
}
finally
{
if(conn != null && conn.isOpen())
{
conn.close();
}
}
}
private List<InferredOWLOntologyID> listArtifacts(final boolean published, final boolean unpublished)
throws OpenRDFException
{
if(!published && !unpublished)
{
throw new IllegalArgumentException("Cannot choose to exclude both published and unpublished artifacts");
}
final List<InferredOWLOntologyID> results = new ArrayList<InferredOWLOntologyID>();
RepositoryConnection conn = null;
try
{
conn = this.getRepositoryManager().getManagementRepository().getConnection();
final Collection<InferredOWLOntologyID> ontologies =
this.getSesameManager().getOntologies(true, conn,
this.getRepositoryManager().getArtifactManagementGraph());
for(final InferredOWLOntologyID nextOntology : ontologies)
{
final boolean isPublished =
this.getSesameManager().isPublished(nextOntology, conn,
this.getRepositoryManager().getArtifactManagementGraph());
if(isPublished)
{
if(published)
{
results.add(nextOntology);
}
}
else if(unpublished)
{
results.add(nextOntology);
}
}
}
finally
{
if(conn != null && conn.isOpen())
{
conn.close();
}
}
return results;
}
@Override
public List<InferredOWLOntologyID> listPublishedArtifacts() throws OpenRDFException
{
return this.listArtifacts(true, false);
}
@Override
public List<InferredOWLOntologyID> listUnpublishedArtifacts() throws OpenRDFException
{
return this.listArtifacts(false, true);
}
@Override
public InferredOWLOntologyID loadArtifact(final InputStream inputStream, final RDFFormat format)
throws OpenRDFException, PoddException, IOException, OWLException
{
return this.loadArtifact(inputStream, format, DanglingObjectPolicy.REPORT,
DataReferenceVerificationPolicy.DO_NOT_VERIFY);
}
/*
* (non-Javadoc)
*
* @see com.github.podd.api.PoddArtifactManager#loadArtifact(java.io.InputStream,
* org.openrdf.rio.RDFFormat)
*/
@Override
public InferredOWLOntologyID loadArtifact(final InputStream inputStream, RDFFormat format,
final DanglingObjectPolicy danglingObjectPolicy,
final DataReferenceVerificationPolicy dataReferenceVerificationPolicy) throws OpenRDFException,
PoddException, IOException, OWLException
{
if(inputStream == null)
{
throw new NullPointerException("Input stream must not be null");
}
if(format == null)
{
format = RDFFormat.RDFXML;
}
final URI randomContext = ValueFactoryImpl.getInstance().createURI("urn:uuid:" + UUID.randomUUID().toString());
final Model model = Rio.parse(inputStream, "", format, randomContext);
final List<InferredOWLOntologyID> ontologyIDs = OntologyUtils.modelToOntologyIDs(model);
if(ontologyIDs.isEmpty())
{
throw new EmptyOntologyException(null, "Loaded ontology is empty");
}
else if(ontologyIDs.size() > 1)
{
this.log.warn("Found multiple ontologies when we were only expecting a single ontology: {}", ontologyIDs);
}
// FIXME: This method only works if the imports are already in a repository somewhere, need
// to fix the Sesame manager to look for imports in Models also
final Collection<OWLOntologyID> schemaImports = this.getSchemaImports(ontologyIDs.get(0));
// connection to the temporary repository that the artifact RDF triples will be stored while
// they are initially parsed by OWLAPI.
final Repository tempRepository = this.repositoryManager.getNewTemporaryRepository(schemaImports);
RepositoryConnection temporaryRepositoryConnection = null;
RepositoryConnection permanentRepositoryConnection = null;
InferredOWLOntologyID inferredOWLOntologyID = null;
try
{
temporaryRepositoryConnection = tempRepository.getConnection();
// Load the artifact RDF triples into a random context in the temp repository, which may
// be shared between different uploads
temporaryRepositoryConnection.add(model, randomContext);
// Remove any assertions that the user has made about publication status, as this
// information is a privileged operation that must be done through the designated API
// method
temporaryRepositoryConnection.remove((Resource)null, PoddRdfConstants.PODD_BASE_HAS_PUBLICATION_STATUS,
(Resource)null, randomContext);
this.handlePurls(temporaryRepositoryConnection, randomContext);
final Repository permanentRepository = this.getRepositoryManager().getPermanentRepository(schemaImports);
permanentRepositoryConnection = permanentRepository.getConnection();
permanentRepositoryConnection.begin();
// Set a Version IRI for this artifact
/*
* Version information need not be available in uploaded artifacts (any existing values
* are ignored).
*
* For a new artifact, a Version IRI is created based on the Ontology IRI while for a
* new version of a managed artifact, the most recent version is incremented.
*/
final IRI ontologyIRI =
this.getSesameManager().getOntologyIRI(temporaryRepositoryConnection, randomContext);
if(ontologyIRI == null)
{
throw new EmptyOntologyException(null, "Loaded ontology is empty");
}
// check for managed version from artifact graph
OWLOntologyID currentManagedArtifactID = null;
try
{
currentManagedArtifactID =
this.getSesameManager().getCurrentArtifactVersion(ontologyIRI, permanentRepositoryConnection,
this.getRepositoryManager().getArtifactManagementGraph());
if(currentManagedArtifactID != null)
{
throw new DuplicateArtifactIRIException(ontologyIRI, "This artifact is already managed");
}
}
catch(final UnmanagedArtifactIRIException e)
{
// ignore. indicates a new artifact is being uploaded
this.log.info("This is an unmanaged artifact IRI {}", ontologyIRI);
}
IRI newVersionIRI = null;
if(currentManagedArtifactID == null || currentManagedArtifactID.getVersionIRI() == null)
{
newVersionIRI = IRI.create(ontologyIRI.toString() + ":version:1");
}
// set version IRI in temporary repository
this.log.info("Setting version IRI to <{}>", newVersionIRI);
temporaryRepositoryConnection.remove(ontologyIRI.toOpenRDFURI(), PoddRdfConstants.OWL_VERSION_IRI, null,
randomContext);
temporaryRepositoryConnection.add(ontologyIRI.toOpenRDFURI(), PoddRdfConstants.OWL_VERSION_IRI,
newVersionIRI.toOpenRDFURI(), randomContext);
// check and update statements with default timestamp values
final Value now = PoddRdfConstants.VF.createLiteral(new Date());
this.handleTimestamps(temporaryRepositoryConnection, PoddRdfConstants.PODD_BASE_CREATED_AT, now,
randomContext);
this.handleTimestamps(temporaryRepositoryConnection, PoddRdfConstants.PODD_BASE_LAST_MODIFIED, now,
randomContext);
this.handleDanglingObjects(ontologyIRI, temporaryRepositoryConnection, randomContext, danglingObjectPolicy);
// check and ensure schema ontology imports are for version IRIs
this.handleSchemaImports(ontologyIRI, permanentRepositoryConnection, temporaryRepositoryConnection,
randomContext);
// ensure schema ontologies are cached in memory before loading statements into OWLAPI
this.handleCacheSchemasInMemory(permanentRepositoryConnection, temporaryRepositoryConnection, randomContext);
// TODO: This web service could be used accidentally to insert invalid file references
inferredOWLOntologyID =
this.loadInferStoreArtifact(temporaryRepositoryConnection, permanentRepositoryConnection,
randomContext, dataReferenceVerificationPolicy);
permanentRepositoryConnection.commit();
return inferredOWLOntologyID;
}
catch(final Exception e)
{
if(temporaryRepositoryConnection != null && temporaryRepositoryConnection.isActive())
{
temporaryRepositoryConnection.rollback();
}
if(permanentRepositoryConnection != null && permanentRepositoryConnection.isActive())
{
permanentRepositoryConnection.rollback();
}
throw e;
}
finally
{
try
{
// release resources
if(inferredOWLOntologyID != null)
{
try
{
this.getOWLManager().removeCache(inferredOWLOntologyID.getBaseOWLOntologyID());
}
finally
{
this.getOWLManager().removeCache(inferredOWLOntologyID.getInferredOWLOntologyID());
}
}
}
finally
{
try
{
if(permanentRepositoryConnection != null && permanentRepositoryConnection.isOpen())
{
permanentRepositoryConnection.close();
}
}
catch(final RepositoryException e)
{
this.log.error("Found exception closing repository connection", e);
}
finally
{
try
{
if(temporaryRepositoryConnection != null && temporaryRepositoryConnection.isOpen())
{
temporaryRepositoryConnection.close();
}
}
catch(final RepositoryException e)
{
this.log.error("Found exception closing repository connection", e);
}
finally
{
tempRepository.shutDown();
}
}
}
}
}
/**
* Helper method to load the artifact into OWLAPI from a temporary location, perform reasoning
* and store in permanent repository.
*
* @param fileReferencePolicy
*/
private InferredOWLOntologyID loadInferStoreArtifact(final RepositoryConnection tempRepositoryConnection,
final RepositoryConnection permanentRepositoryConnection, final URI tempContext,
final DataReferenceVerificationPolicy fileReferencePolicy) throws OpenRDFException, OWLException,
IOException, PoddException, OntologyNotInProfileException, InconsistentOntologyException
{
// load into OWLAPI
this.log.debug("Loading podd artifact from temp repository: {}", tempContext);
final List<Statement> statements =
Iterations.asList(tempRepositoryConnection.getStatements(null, null, null, true, tempContext));
final RioMemoryTripleSource owlSource =
new RioMemoryTripleSource(statements.iterator(), Namespaces.asMap(Iterations
.asSet(tempRepositoryConnection.getNamespaces())));
final OWLOntology nextOntology = this.getOWLManager().loadOntology(owlSource);
// Check the OWLAPI OWLOntology against an OWLProfile to make sure it is in profile
final OWLProfileReport profileReport = this.getOWLManager().getReasonerProfile().checkOntology(nextOntology);
if(!profileReport.isInProfile())
{
this.getOWLManager().removeCache(nextOntology.getOntologyID());
if(this.log.isInfoEnabled())
{
for(final OWLProfileViolation violation : profileReport.getViolations())
{
this.log.info(violation.toString());
}
}
throw new OntologyNotInProfileException(nextOntology, profileReport,
"Ontology is not in required OWL Profile");
}
// Use the OWLManager to create a reasoner over the ontology
final OWLReasoner nextReasoner = this.getOWLManager().createReasoner(nextOntology);
// Test that the ontology was consistent with this reasoner
// This ensures in the case of Pellet that it is in the OWL2-DL profile
if(!nextReasoner.isConsistent())
{
this.getOWLManager().removeCache(nextOntology.getOntologyID());
throw new InconsistentOntologyException(nextReasoner, "Ontology is inconsistent");
}
// Copy the statements to permanentRepositoryConnection
this.getOWLManager().dumpOntologyToRepository(nextOntology, permanentRepositoryConnection,
nextOntology.getOntologyID().getVersionIRI().toOpenRDFURI());
// NOTE: At this stage, a client could be notified, and the artifact could be streamed
// back to them from permanentRepositoryConnection
// Use an OWLAPI InferredAxiomGenerator together with the reasoner to create inferred
// axioms to store in the database.
// Serialise the inferred statements back to a different context in the permanent
// repository connection.
// The contexts to use within the permanent repository connection are all encapsulated
// in the InferredOWLOntologyID object.
final InferredOWLOntologyID inferredOWLOntologyID =
this.getOWLManager().inferStatements(nextOntology, permanentRepositoryConnection);
// Check file references after inferencing to accurately identify the parent object
this.handleFileReferences(permanentRepositoryConnection, fileReferencePolicy, inferredOWLOntologyID
.getVersionIRI().toOpenRDFURI(), inferredOWLOntologyID.getInferredOntologyIRI().toOpenRDFURI());
this.getSesameManager().updateManagedPoddArtifactVersion(inferredOWLOntologyID, true,
permanentRepositoryConnection, this.getRepositoryManager().getArtifactManagementGraph());
return inferredOWLOntologyID;
}
/*
* (non-Javadoc)
*
* @see com.github.podd.api.PoddArtifactManager#publishArtifact(org.semanticweb.owlapi.model.
* OWLOntologyID)
*/
@Override
public InferredOWLOntologyID publishArtifact(final InferredOWLOntologyID ontologyId) throws OpenRDFException,
PublishArtifactException, UnmanagedArtifactIRIException
{
final IRI ontologyIRI = ontologyId.getOntologyIRI();
final IRI versionIRI = ontologyId.getVersionIRI();
if(versionIRI == null)
{
throw new PublishArtifactException("Could not publish artifact as version was not specified.", ontologyId);
}
Repository repository = null;
RepositoryConnection repositoryConnection = null;
try
{
final Collection<OWLOntologyID> currentSchemaImports = this.getSchemaImports(ontologyId);
repository = this.getRepositoryManager().getPermanentRepository(currentSchemaImports);
repositoryConnection = repository.getConnection();
repositoryConnection.begin();
if(this.getSesameManager().isPublished(ontologyId, repositoryConnection,
this.getRepositoryManager().getArtifactManagementGraph()))
{
// Cannot publish multiple versions of a single artifact
throw new PublishArtifactException("Could not publish artifact as a version was already published",
ontologyId);
}
final InferredOWLOntologyID currentVersion =
this.getSesameManager().getCurrentArtifactVersion(ontologyIRI, repositoryConnection,
this.getRepositoryManager().getArtifactManagementGraph());
if(!currentVersion.getVersionIRI().equals(versionIRI))
{
// User must make the given artifact version the current version manually before
// publishing, to ensure that work from the current version is not lost accidentally
throw new PublishArtifactException(
"Could not publish artifact as it was not the most current version.", ontologyId);
}
final InferredOWLOntologyID published =
this.getSesameManager().setPublished(true, currentVersion, repositoryConnection,
this.getRepositoryManager().getArtifactManagementGraph());
repositoryConnection.commit();
return published;
}
catch(final OpenRDFException | PublishArtifactException | UnmanagedArtifactIRIException e)
{
if(repositoryConnection != null && repositoryConnection.isActive())
{
repositoryConnection.rollback();
}
throw e;
}
finally
{
// release resources
try
{
if(repositoryConnection != null && repositoryConnection.isOpen())
{
repositoryConnection.close();
}
}
catch(final RepositoryException e)
{
this.log.error("Found exception closing repository connection", e);
}
}
}
/*
* (non-Javadoc)
*
* @see
* com.github.podd.api.PoddArtifactManager#searchForOntologyLabels(org.semanticweb.owlapi.model.
* OWLOntologyID, java.lang.String, org.openrdf.model.URI[])
*/
@Override
public Model searchForOntologyLabels(final InferredOWLOntologyID ontologyID, final String searchTerm,
final URI[] searchTypes) throws OpenRDFException
{
RepositoryConnection conn = null;
try
{
final Collection<OWLOntologyID> currentSchemaImports = this.getSchemaImports(ontologyID);
conn = this.getRepositoryManager().getPermanentRepository(currentSchemaImports).getConnection();
// FIXME: Cannot use contexts like this for a federated method
final URI[] contexts =
this.getSesameManager().versionAndSchemaContexts(ontologyID, conn,
this.getRepositoryManager().getSchemaManagementGraph());
return this.getSesameManager().searchOntologyLabels(searchTerm, searchTypes, 1000, 0, conn, contexts);
}
catch(final OpenRDFException e)
{
try
{
if(conn != null && conn.isActive())
{
conn.rollback();
}
}
catch(final RepositoryException e1)
{
this.log.error("Found error rolling back repository connection", e1);
}
throw e;
}
finally
{
try
{
if(conn != null && conn.isOpen())
{
conn.close();
}
}
catch(final RepositoryException e)
{
throw e;
}
}
}
/*
* (non-Javadoc)
*
* @see
* com.github.podd.api.PoddArtifactManager#setFileReferenceManager(com.github.podd.api.file.
* PoddFileReferenceManager)
*/
@Override
public void setDataReferenceManager(final DataReferenceManager fileManager)
{
this.dataReferenceManager = fileManager;
}
/*
* (non-Javadoc)
*
* @see
* com.github.podd.api.PoddArtifactManager#setFileRepositoryManager(com.github.podd.api.file
* .PoddFileRepositoryManager)
*/
@Override
public void setDataRepositoryManager(final PoddDataRepositoryManager dataRepositoryManager)
{
this.dataRepositoryManager = dataRepositoryManager;
}
/*
* (non-Javadoc)
*
* @see
* com.github.podd.api.PoddArtifactManager#setOwlManager(com.github.podd.api.PoddOWLManager)
*/
@Override
public void setOwlManager(final PoddOWLManager owlManager)
{
this.owlManager = owlManager;
}
/*
* (non-Javadoc)
*
* @see
* com.github.podd.api.PoddArtifactManager#setPurlManager(com.github.podd.api.purl.PoddPurlManager
* )
*/
@Override
public void setPurlManager(final PoddPurlManager purlManager)
{
this.purlManager = purlManager;
}
@Override
public void setRepositoryManager(final PoddRepositoryManager repositoryManager)
{
this.repositoryManager = repositoryManager;
}
@Override
public void setSchemaManager(final PoddSchemaManager schemaManager)
{
this.schemaManager = schemaManager;
}
@Override
public void setSesameManager(final PoddSesameManager sesameManager)
{
this.sesameManager = sesameManager;
}
/*
* (non-Javadoc)
*
* @see com.github.podd.api.PoddArtifactManager#updateArtifact(org.openrdf.model.URI,
* java.io.InputStream, org.openrdf.rio.RDFFormat)
*/
@Override
public Model updateArtifact(final URI artifactUri, final URI versionUri, final Collection<URI> objectUris,
final InputStream inputStream, RDFFormat format, final UpdatePolicy updatePolicy,
final DanglingObjectPolicy danglingObjectAction, final DataReferenceVerificationPolicy fileReferenceAction)
throws OpenRDFException, IOException, OWLException, PoddException
{
if(inputStream == null)
{
throw new NullPointerException("Input stream must not be null");
}
if(format == null)
{
format = RDFFormat.RDFXML;
}
final Model model = Rio.parse(inputStream, "", format);
return this.updateArtifact(artifactUri, versionUri, objectUris, model, updatePolicy, danglingObjectAction,
fileReferenceAction);
}
/**
* Internal updateArtifact() method which takes a {@link Model} containing the modified triples
* instead of an InputStream.
*/
protected Model updateArtifact(final URI artifactUri, final URI versionUri, final Collection<URI> objectUris,
final Model model, final UpdatePolicy updatePolicy, final DanglingObjectPolicy danglingObjectAction,
final DataReferenceVerificationPolicy fileReferenceAction) throws OpenRDFException, IOException,
OWLException, PoddException
{
if(model == null)
{
throw new NullPointerException("Input Model must not be null");
}
// check if the specified artifact URI refers to a managed artifact
InferredOWLOntologyID artifactID = null;
try
{
artifactID = this.getArtifact(IRI.create(artifactUri));
}
catch(final UnmanagedArtifactIRIException e)
{
this.log.error("This artifact is unmanaged. [{}]", artifactUri);
throw e;
}
// check if updating from the most current version of the artifact
try
{
artifactID = this.getArtifact(IRI.create(versionUri));
}
catch(final UnmanagedArtifactIRIException e)
{
// if the version IRI is not the most current, it is unmanaged
final String message =
"Attempting to update from an invalid version of an artifact [" + versionUri
+ "]. The current version is [" + artifactID.getVersionIRI().toString() + "]";
this.log.error(message);
// TODO: UpdatePolicy.MERGE_WITH_EXISTING and UpdatePolicy.REPLACE_ALL should be fine to
// go on in most cases
throw new UnmanagedArtifactVersionException(artifactID.getOntologyIRI(), artifactID.getVersionIRI(),
IRI.create(versionUri), message, e);
// FIXME - handle this conflict intelligently instead of rejecting the update.
}
final Collection<OWLOntologyID> currentSchemaImports = this.getSchemaImports(artifactID);
final Repository tempRepository = this.getRepositoryManager().getNewTemporaryRepository(currentSchemaImports);
RepositoryConnection tempRepositoryConnection = null;
RepositoryConnection permanentRepositoryConnection = null;
InferredOWLOntologyID inferredOWLOntologyID = null;
try
{
// create a temporary in-memory repository
tempRepositoryConnection = tempRepository.getConnection();
tempRepositoryConnection.begin();
permanentRepositoryConnection =
this.getRepositoryManager().getPermanentRepository(currentSchemaImports).getConnection();
permanentRepositoryConnection.begin();
// load and copy the artifact's concrete statements to the temporary store
final RepositoryResult<Statement> repoResult =
permanentRepositoryConnection.getStatements(null, null, null, false, artifactID.getVersionIRI()
.toOpenRDFURI());
final URI tempContext = artifactID.getVersionIRI().toOpenRDFURI();
tempRepositoryConnection.add(repoResult, tempContext);
// update the artifact statements
if(UpdatePolicy.REPLACE_EXISTING.equals(updatePolicy))
{
// create an intermediate context and add "edit" statements to it
final URI intContext = PoddRdfConstants.VF.createURI("urn:intermediate:", UUID.randomUUID().toString());
tempRepositoryConnection.add(model, intContext);
final Collection<URI> replaceableObjects = new ArrayList<URI>(objectUris);
// If they did not send a list, we create one ourselves.
if(replaceableObjects.isEmpty())
{
// get all Subjects in "edit" statements
final RepositoryResult<Statement> statements =
tempRepositoryConnection.getStatements(null, null, null, false, intContext);
final List<Statement> allEditStatements = Iterations.addAll(statements, new ArrayList<Statement>());
// remove all references to these Subjects in "main" context
for(final Statement statement : allEditStatements)
{
if(statement.getSubject() instanceof URI)
{
replaceableObjects.add((URI)statement.getSubject());
}
else
{
// We do not support replacing objects that are not referenced using
// URIs, so they must stay for REPLACE_EXISTING
// To remove blank node subject statements, replace the entire object
// using REPLACE_ALL
}
}
}
for(final URI nextReplaceableObject : replaceableObjects)
{
tempRepositoryConnection.remove(nextReplaceableObject, null, null, tempContext);
}
// copy the "edit" statements from intermediate context into our "main" context
tempRepositoryConnection.add(
tempRepositoryConnection.getStatements(null, null, null, false, intContext), tempContext);
}
else
{
tempRepositoryConnection.add(model, tempContext);
}
// check and update statements with default timestamp values
final Value now = PoddRdfConstants.VF.createLiteral(new Date());
this.handleTimestamps(tempRepositoryConnection, PoddRdfConstants.PODD_BASE_CREATED_AT, now, tempContext);
this.handleTimestamps(tempRepositoryConnection, PoddRdfConstants.PODD_BASE_LAST_MODIFIED, now, tempContext);
this.handleDanglingObjects(artifactID.getOntologyIRI(), tempRepositoryConnection, tempContext,
danglingObjectAction);
// Remove any assertions that the user has made about publication status, as this
// information is a privileged operation that must be done through the designated API
// method
tempRepositoryConnection.remove((Resource)null, PoddRdfConstants.PODD_BASE_HAS_PUBLICATION_STATUS,
(Resource)null, tempContext);
final Set<PoddPurlReference> purls = this.handlePurls(tempRepositoryConnection, tempContext);
final Model resultsModel = new LinkedHashModel();
// add (temp-object-URI :hasPurl PURL) statements to Model
// NOTE: Using nested loops is rather inefficient, but these collections are not
// expected
// to have more than a handful of elements
for(final URI objectUri : objectUris)
{
for(final PoddPurlReference purl : purls)
{
final URI tempUri = purl.getTemporaryURI();
if(objectUri.equals(tempUri))
{
resultsModel.add(objectUri, PoddRdfConstants.PODD_REPLACED_TEMP_URI_WITH, purl.getPurlURI());
break; // out of inner loop
}
}
}
// this.handleFileReferences(tempRepositoryConnection, tempContext,
// fileReferenceAction);
// increment the version
final OWLOntologyID currentManagedArtifactID =
this.getSesameManager().getCurrentArtifactVersion(IRI.create(artifactUri),
permanentRepositoryConnection, this.getRepositoryManager().getArtifactManagementGraph());
final IRI newVersionIRI =
IRI.create(this.incrementVersion(currentManagedArtifactID.getVersionIRI().toString()));
// set version IRI in temporary repository
this.log.info("Setting version IRI to <{}>", newVersionIRI);
tempRepositoryConnection.remove(artifactID.getOntologyIRI().toOpenRDFURI(),
PoddRdfConstants.OWL_VERSION_IRI, null, tempContext);
tempRepositoryConnection.add(artifactID.getOntologyIRI().toOpenRDFURI(), PoddRdfConstants.OWL_VERSION_IRI,
newVersionIRI.toOpenRDFURI(), tempContext);
// check and ensure schema ontology imports are for version IRIs
this.handleSchemaImports(artifactID.getOntologyIRI(), permanentRepositoryConnection,
tempRepositoryConnection, tempContext);
// ensure schema ontologies are cached in memory before loading statements into OWLAPI
this.handleCacheSchemasInMemory(permanentRepositoryConnection, tempRepositoryConnection, tempContext);
inferredOWLOntologyID =
this.loadInferStoreArtifact(tempRepositoryConnection, permanentRepositoryConnection, tempContext,
fileReferenceAction);
permanentRepositoryConnection.commit();
tempRepositoryConnection.rollback();
return OntologyUtils.ontologyIDsToModel(Arrays.asList(inferredOWLOntologyID), resultsModel);
}
catch(final Exception e)
{
if(tempRepositoryConnection != null && tempRepositoryConnection.isActive())
{
tempRepositoryConnection.rollback();
}
if(permanentRepositoryConnection != null && permanentRepositoryConnection.isActive())
{
permanentRepositoryConnection.rollback();
}
throw e;
}
finally
{
if(permanentRepositoryConnection != null && permanentRepositoryConnection.isOpen())
{
try
{
permanentRepositoryConnection.close();
}
catch(final RepositoryException e)
{
this.log.error("Found exception closing repository connection", e);
}
}
// release resources
if(inferredOWLOntologyID != null)
{
this.getOWLManager().removeCache(inferredOWLOntologyID.getBaseOWLOntologyID());
this.getOWLManager().removeCache(inferredOWLOntologyID.getInferredOWLOntologyID());
}
if(tempRepositoryConnection != null && tempRepositoryConnection.isOpen())
{
try
{
tempRepositoryConnection.close();
}
catch(final RepositoryException e)
{
this.log.error("Found exception closing repository connection", e);
}
}
tempRepository.shutDown();
}
}
@Override
public InferredOWLOntologyID updateSchemaImports(final InferredOWLOntologyID artifactId,
final Set<OWLOntologyID> oldSchemaOntologyIds, final Set<OWLOntologyID> newSchemaOntologyIds)
throws OpenRDFException, PoddException, IOException, OWLException
{
if(artifactId == null)
{
throw new IllegalArgumentException("Artifact was null");
}
RepositoryConnection permanentRepositoryConnection = null;
RepositoryConnection tempRepositoryConnection = null;
Repository tempRepository = null;
try
{
permanentRepositoryConnection =
this.repositoryManager.getPermanentRepository(newSchemaOntologyIds).getConnection();
permanentRepositoryConnection.begin();
final InferredOWLOntologyID artifactVersion =
this.sesameManager.getCurrentArtifactVersion(artifactId.getOntologyIRI(),
permanentRepositoryConnection, this.repositoryManager.getArtifactManagementGraph());
if(!artifactVersion.getVersionIRI().equals(artifactId.getVersionIRI()))
{
throw new UnmanagedArtifactVersionException(artifactId.getOntologyIRI(),
artifactVersion.getVersionIRI(), artifactId.getVersionIRI(),
"Cannot update schema imports for artifact as the specified version was not found.");
}
// Export the artifact without including the old inferred triples, and they will be
// regenerated using the new schema ontologies
final Model model = this.exportArtifact(artifactVersion, false);
tempRepository = this.repositoryManager.getNewTemporaryRepository(newSchemaOntologyIds);
tempRepositoryConnection = tempRepository.getConnection();
tempRepositoryConnection.begin();
// Bump the version identifier to a new value
final IRI newVersionIRI = IRI.create(this.incrementVersion(artifactVersion.getVersionIRI().toString()));
tempRepositoryConnection.add(model, newVersionIRI.toOpenRDFURI());
tempRepositoryConnection.remove(artifactVersion.getOntologyIRI().toOpenRDFURI(), OWL.VERSIONIRI, null);
tempRepositoryConnection.add(artifactVersion.getOntologyIRI().toOpenRDFURI(), OWL.VERSIONIRI,
newVersionIRI.toOpenRDFURI(), newVersionIRI.toOpenRDFURI());
for(final OWLOntologyID nextOldSchemaOntologyID : oldSchemaOntologyIds)
{
// Remove both a generic import and a version specific import, so this method can be
// used to bump generic imports to version specific imports after they are imported,
// if necessary.
tempRepositoryConnection.remove(artifactVersion.getOntologyIRI().toOpenRDFURI(), OWL.IMPORTS,
nextOldSchemaOntologyID.getOntologyIRI().toOpenRDFURI());
tempRepositoryConnection.remove(artifactVersion.getOntologyIRI().toOpenRDFURI(), OWL.IMPORTS,
nextOldSchemaOntologyID.getVersionIRI().toOpenRDFURI());
}
// Even if the old version of the artifact did not import this schema, we include it now
// as it may be required by the others
for(final OWLOntologyID nextNewSchemaOntologyID : newSchemaOntologyIds)
{
// Add import to the specific version
tempRepositoryConnection.add(artifactVersion.getOntologyIRI().toOpenRDFURI(), OWL.IMPORTS,
nextNewSchemaOntologyID.getVersionIRI().toOpenRDFURI(), newVersionIRI.toOpenRDFURI());
}
tempRepositoryConnection.commit();
final InferredOWLOntologyID result =
this.loadInferStoreArtifact(tempRepositoryConnection, permanentRepositoryConnection,
newVersionIRI.toOpenRDFURI(), DataReferenceVerificationPolicy.DO_NOT_VERIFY);
permanentRepositoryConnection.commit();
return result;
}
catch(final Throwable e)
{
if(permanentRepositoryConnection != null)
{
permanentRepositoryConnection.rollback();
}
if(tempRepositoryConnection != null)
{
tempRepositoryConnection.rollback();
}
throw e;
}
finally
{
if(permanentRepositoryConnection != null)
{
permanentRepositoryConnection.close();
}
if(tempRepositoryConnection != null)
{
tempRepositoryConnection.close();
}
if(tempRepository != null)
{
tempRepository.shutDown();
}
}
}
}
|
package org.lwjgl.opengl;
import java.nio.IntBuffer;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL;
import org.lwjgl.opengl.WGL;
import org.lwjgl.opengl.WGLARBCreateContext;
import org.lwjgl.opengl.WGLARBCreateContextProfile;
import org.lwjgl.opengl.WGLARBMultisample;
import org.lwjgl.opengl.WGLARBPixelFormat;
import org.lwjgl.system.APIBuffer;
import org.lwjgl.system.APIUtil;
import org.lwjgl.system.JNI;
import org.lwjgl.system.MemoryUtil;
import org.lwjgl.system.windows.GDI32;
import org.lwjgl.system.windows.PIXELFORMATDESCRIPTOR;
import org.lwjgl.system.windows.User32;
/**
* Windows implementation of {@link ContextFunctions}.
*
* @author Kai Burjack
*/
public class Win32ContextFunctions implements ContextFunctions {
private static final WGL wgl;
static {
// Cache the WGL instance
wgl = new WGL(GL.getFunctionProvider());
}
private static boolean atLeast32(int major, int minor) {
return major == 3 && minor >= 2 || major > 3;
}
private static boolean atLeast30(int major, int minor) {
return major == 3 && minor >= 0 || major > 3;
}
private static boolean validVersion(int major, int minor) {
return (major == 0 && minor == 0) ||
(major >= 1 && minor >= 0) &&
(major != 1 || minor <= 5) &&
(major != 2 || minor <= 1) &&
(major != 3 || minor <= 3) &&
(major != 4 || minor <= 5);
}
/**
* Validate the given {@link GLContextAttributes} and throw an exception on validation error.
*
* @param attribs
* the {@link GLContextAttributes} to validate
*/
public static void validateAttributes(GLContextAttributes attribs) {
if (attribs.alphaSize < 0) {
throw new IllegalArgumentException("Alpha bits cannot be less than 0");
}
if (attribs.redSize < 0) {
throw new IllegalArgumentException("Red bits cannot be less than 0");
}
if (attribs.greenSize < 0) {
throw new IllegalArgumentException("Green bits cannot be less than 0");
}
if (attribs.blueSize < 0) {
throw new IllegalArgumentException("Blue bits cannot be less than 0");
}
if (attribs.stencilSize < 0) {
throw new IllegalArgumentException("Stencil bits cannot be less than 0");
}
if (attribs.depthSize < 0) {
throw new IllegalArgumentException("Depth bits cannot be less than 0");
}
if (attribs.forwardCompatible && !atLeast30(attribs.majorVersion, attribs.minorVersion)) {
throw new IllegalArgumentException("Forward-compatibility is only defined for OpenGL version 3.0 and above");
}
if (attribs.profile != 0
&& (attribs.profile < GLContextAttributes.OPENGL_CORE_PROFILE ||
attribs.profile > GLContextAttributes.OPENGL_COMPATIBILITY_PROFILE)) {
throw new IllegalArgumentException("Invalid profile.");
}
if (attribs.samples < 0) {
throw new IllegalArgumentException("Invalid samples count");
}
if (attribs.profile > 0 && !atLeast32(attribs.majorVersion, attribs.minorVersion)) {
throw new IllegalArgumentException("Context profiles are only defined for OpenGL version 3.2 and above");
}
if (!validVersion(attribs.majorVersion, attribs.minorVersion)) {
throw new IllegalArgumentException("Invalid OpenGL version");
}
if (attribs.contextReleaseBehavior != 0 &&
(attribs.contextReleaseBehavior < GLContextAttributes.CONTEXT_RELEASE_BEHAVIOR_NONE ||
attribs.contextReleaseBehavior > GLContextAttributes.CONTEXT_RELEASE_BEHAVIOR_FLUSH)) {
throw new IllegalArgumentException("Invalid context release behavior");
}
if (!attribs.doubleBuffer && attribs.swapInterval != null) {
throw new IllegalArgumentException("Swap interval set but not using double buffering");
}
if (attribs.colorSamplesNV < 0) {
throw new IllegalArgumentException("Invalid color samples count");
}
if (attribs.colorSamplesNV > attribs.samples) {
throw new IllegalArgumentException("Color samples greater than number of (coverage) samples");
}
if (attribs.swapGroupNV < 0) {
throw new IllegalArgumentException("Invalid swap group");
}
if (attribs.swapBarrierNV < 0) {
throw new IllegalArgumentException("Invalid swap barrier");
}
if (attribs.swapGroupNV > 0 && attribs.swapBarrierNV == 0) {
throw new IllegalArgumentException("Swap group requested but no valid swap barrier set");
}
}
/**
* Encode the pixel format attributes stored in the given {@link GLContextAttributes} into the given {@link IntBuffer} for wglChoosePixelFormatARB to
* consume.
*/
private void encodePixelFormatAttribs(IntBuffer ib, GLContextAttributes attribs) {
ib.put(WGLARBPixelFormat.WGL_DRAW_TO_WINDOW_ARB).put(1);
ib.put(WGLARBPixelFormat.WGL_SUPPORT_OPENGL_ARB).put(1);
ib.put(WGLARBPixelFormat.WGL_ACCELERATION_ARB).put(WGLARBPixelFormat.WGL_FULL_ACCELERATION_ARB);
if (attribs.doubleBuffer)
ib.put(WGLARBPixelFormat.WGL_DOUBLE_BUFFER_ARB).put(1);
if (attribs.floatPixelFormat)
ib.put(WGLARBPixelFormat.WGL_PIXEL_TYPE_ARB).put(WGLARBPixelFormatFloat.WGL_TYPE_RGBA_FLOAT_ARB);
else
ib.put(WGLARBPixelFormat.WGL_PIXEL_TYPE_ARB).put(WGLARBPixelFormat.WGL_TYPE_RGBA_ARB);
if (attribs.redSize > 0)
ib.put(WGLARBPixelFormat.WGL_RED_BITS_ARB).put(attribs.redSize);
if (attribs.greenSize > 0)
ib.put(WGLARBPixelFormat.WGL_GREEN_BITS_ARB).put(attribs.greenSize);
if (attribs.blueSize > 0)
ib.put(WGLARBPixelFormat.WGL_BLUE_BITS_ARB).put(attribs.blueSize);
if (attribs.alphaSize > 0)
ib.put(WGLARBPixelFormat.WGL_ALPHA_BITS_ARB).put(attribs.alphaSize);
if (attribs.depthSize > 0)
ib.put(WGLARBPixelFormat.WGL_DEPTH_BITS_ARB).put(attribs.depthSize);
if (attribs.stencilSize > 0)
ib.put(WGLARBPixelFormat.WGL_STENCIL_BITS_ARB).put(attribs.stencilSize);
if (attribs.accumRedSize > 0)
ib.put(WGLARBPixelFormat.WGL_ACCUM_RED_BITS_ARB).put(attribs.accumRedSize);
if (attribs.accumGreenSize > 0)
ib.put(WGLARBPixelFormat.WGL_ACCUM_GREEN_BITS_ARB).put(attribs.accumGreenSize);
if (attribs.accumBlueSize > 0)
ib.put(WGLARBPixelFormat.WGL_ACCUM_BLUE_BITS_ARB).put(attribs.accumBlueSize);
if (attribs.accumAlphaSize > 0)
ib.put(WGLARBPixelFormat.WGL_ACCUM_ALPHA_BITS_ARB).put(attribs.accumAlphaSize);
if (attribs.accumRedSize > 0 || attribs.accumGreenSize > 0 || attribs.accumBlueSize > 0 || attribs.accumAlphaSize > 0)
ib.put(WGLARBPixelFormat.WGL_ACCUM_BITS_ARB).put(attribs.accumRedSize + attribs.accumGreenSize + attribs.accumBlueSize + attribs.accumAlphaSize);
if (attribs.sRGB)
ib.put(WGLEXTFramebufferSRGB.WGL_FRAMEBUFFER_SRGB_CAPABLE_EXT).put(1);
if (attribs.samples > 0) {
ib.put(WGLARBMultisample.WGL_SAMPLE_BUFFERS_ARB).put(1);
ib.put(WGLARBMultisample.WGL_SAMPLES_ARB).put(attribs.samples);
if (attribs.colorSamplesNV > 0) {
ib.put(WGLNVMultisampleCoverage.WGL_COLOR_SAMPLES_NV).put(attribs.colorSamplesNV);
}
}
ib.put(0);
}
/**
* Create a GL context using WGL and return the opaque handle to be used by other methods such as {@link #makeCurrent(long, long)}, {@link #isCurrent(long)}
* or {@link #deleteContext(long)}.
*
* @see #makeCurrent(long, long)
* @see #isCurrent(long)
* @see #deleteContext(long)
*
* @param windowHandle
* the window handle
* @param dummyWindowHandle
* used to query supported pixel formats
* @param attribs
* the {@link GLContextAttributes}
* @return the opaque handle of the new context
* @throws OpenGLContextException
*/
public long create(long windowHandle, long dummyWindowHandle, GLContextAttributes attribs) throws OpenGLContextException {
// Validate context attributes
validateAttributes(attribs);
// Find this exact pixel format, though for now without multisampling. This comes later!
PIXELFORMATDESCRIPTOR pfd = PIXELFORMATDESCRIPTOR.create();
pfd.nSize((short) PIXELFORMATDESCRIPTOR.SIZEOF);
pfd.nVersion((short) 1); // this should always be 1
pfd.dwLayerMask(GDI32.PFD_MAIN_PLANE);
pfd.iPixelType((byte) GDI32.PFD_TYPE_RGBA);
int flags = GDI32.PFD_DRAW_TO_WINDOW | GDI32.PFD_SUPPORT_OPENGL;
if (attribs.doubleBuffer)
flags |= GDI32.PFD_DOUBLEBUFFER;
if (attribs.stereo)
flags |= GDI32.PFD_STEREO;
pfd.dwFlags(flags);
pfd.cRedBits((byte) attribs.redSize);
pfd.cGreenBits((byte) attribs.greenSize);
pfd.cBlueBits((byte) attribs.blueSize);
pfd.cAlphaBits((byte) attribs.alphaSize);
pfd.cDepthBits((byte) attribs.depthSize);
pfd.cStencilBits((byte) attribs.stencilSize);
pfd.cAccumRedBits((byte) attribs.accumRedSize);
pfd.cAccumGreenBits((byte) attribs.accumGreenSize);
pfd.cAccumBlueBits((byte) attribs.accumBlueSize);
pfd.cAccumAlphaBits((byte) attribs.accumAlphaSize);
pfd.cAccumBits((byte) (attribs.accumRedSize + attribs.accumGreenSize + attribs.accumBlueSize + attribs.accumAlphaSize));
long hDCdummy = User32.GetDC(dummyWindowHandle);
int pixelFormat = GDI32.ChoosePixelFormat(hDCdummy, pfd);
if (pixelFormat == 0 || GDI32.SetPixelFormat(hDCdummy, pixelFormat, pfd) == 0) {
// Pixel format unsupported
User32.ReleaseDC(dummyWindowHandle, hDCdummy);
throw new OpenGLContextException("Unsupported pixel format");
}
/*
* Next, create a dummy context using Opengl32.lib's wglCreateContext. This should ALWAYS work, but won't give us a "new"/"core" context if we requested
* that and also does not support multisampling. But we use this "dummy" context then to request the required WGL function pointers to create a new
* OpenGL >= 3.0 context and with optional multisampling.
*/
long dummyContext = JNI.callPP(wgl.CreateContext, hDCdummy);
if (dummyContext == 0L) {
User32.ReleaseDC(dummyWindowHandle, hDCdummy);
throw new OpenGLContextException("Failed to create OpenGL context");
}
APIBuffer buffer = APIUtil.apiBuffer();
long bufferAddr = buffer.address();
// Save current context to restore it later
long currentContext = JNI.callP(wgl.GetCurrentContext);
long currentDc = JNI.callP(wgl.GetCurrentDC);
// Make the new dummy context current
int success = JNI.callPPI(wgl.MakeCurrent, hDCdummy, dummyContext);
if (success == 0) {
User32.ReleaseDC(dummyWindowHandle, hDCdummy);
JNI.callPI(wgl.DeleteContext, dummyContext);
throw new OpenGLContextException("Failed to make OpenGL context current");
}
// Query supported WGL extensions
String wglExtensions = null;
int procEncoded = buffer.stringParamASCII("wglGetExtensionsStringARB", true);
long adr = buffer.address(procEncoded);
long wglGetExtensionsStringARBAddr = JNI.callPP(wgl.GetProcAddress, adr);
if (wglGetExtensionsStringARBAddr != 0L) {
long str = JNI.callPP(wglGetExtensionsStringARBAddr, hDCdummy);
if (str != 0L) {
wglExtensions = MemoryUtil.memDecodeASCII(str);
} else {
wglExtensions = "";
}
} else {
// Try the EXT extension
procEncoded = buffer.stringParamASCII("wglGetExtensionsStringEXT", true);
adr = buffer.address(procEncoded);
long wglGetExtensionsStringEXTAddr = JNI.callPP(wgl.GetProcAddress, adr);
if (wglGetExtensionsStringEXTAddr != 0L) {
long str = JNI.callP(wglGetExtensionsStringEXTAddr);
if (str != 0L) {
wglExtensions = MemoryUtil.memDecodeASCII(str);
} else {
wglExtensions = "";
}
} else {
wglExtensions = "";
}
}
success = User32.ReleaseDC(dummyWindowHandle, hDCdummy);
if (success == 0) {
JNI.callPI(wgl.DeleteContext, dummyContext);
JNI.callPPI(wgl.MakeCurrent, currentDc, currentContext);
throw new OpenGLContextException("Could not release dummy DC");
}
// For some constellations of context attributes, we can stop right here.
if (!atLeast30(attribs.majorVersion, attribs.minorVersion) && attribs.samples == 0 && !attribs.sRGB && !attribs.floatPixelFormat
&& attribs.contextReleaseBehavior == 0) {
/* Finally, create the real context on the real window */
long hDC = User32.GetDC(windowHandle);
GDI32.SetPixelFormat(hDC, pixelFormat, pfd);
success = JNI.callPI(wgl.DeleteContext, dummyContext);
if (success == 0) {
JNI.callPPI(wgl.MakeCurrent, currentDc, currentContext);
throw new OpenGLContextException("Could not delete dummy GL context");
}
long context = JNI.callPP(wgl.CreateContext, hDC);
if (attribs.swapInterval != null) {
boolean has_WGL_EXT_swap_control = wglExtensions.contains("WGL_EXT_swap_control");
if (!has_WGL_EXT_swap_control) {
User32.ReleaseDC(windowHandle, hDC);
JNI.callPPI(wgl.MakeCurrent, currentDc, currentContext);
throw new OpenGLContextException("Swap interval requested but WGL_EXT_swap_control is unavailable");
}
if (attribs.swapInterval < 0) {
// Only allowed if WGL_EXT_swap_control_tear is available
boolean has_WGL_EXT_swap_control_tear = wglExtensions.contains("WGL_EXT_swap_control_tear");
if (!has_WGL_EXT_swap_control_tear) {
User32.ReleaseDC(windowHandle, hDC);
JNI.callPPI(wgl.MakeCurrent, currentDc, currentContext);
throw new OpenGLContextException("Negative swap interval requested but WGL_EXT_swap_control_tear is unavailable");
}
}
// Make context current to set the swap interval
success = JNI.callPPI(wgl.MakeCurrent, hDC, context);
if (success == 0) {
User32.ReleaseDC(windowHandle, hDC);
JNI.callPPI(wgl.MakeCurrent, currentDc, currentContext);
throw new OpenGLContextException("Could not make GL context current");
}
procEncoded = buffer.stringParamASCII("wglSwapIntervalEXT", true);
adr = buffer.address(procEncoded);
long wglSwapIntervalEXTAddr = JNI.callPP(wgl.GetProcAddress, adr);
if (wglSwapIntervalEXTAddr != 0L) {
JNI.callII(wglSwapIntervalEXTAddr, attribs.swapInterval);
}
}
if (attribs.swapGroupNV > 0 && attribs.swapBarrierNV > 0) {
// Only allowed if WGL_NV_swap_group is available
boolean has_WGL_NV_swap_group = wglExtensions.contains("WGL_NV_swap_group");
if (!has_WGL_NV_swap_group) {
User32.ReleaseDC(windowHandle, hDC);
JNI.callPPI(wgl.MakeCurrent, currentDc, currentContext);
throw new OpenGLContextException("Swap group requested but WGL_NV_swap_group is unavailable");
}
success = JNI.callPPI(wgl.MakeCurrent, hDC, context);
try {
wglNvSwapGroup(windowHandle, attribs, buffer, hDC);
} catch (OpenGLContextException e) {
User32.ReleaseDC(windowHandle, hDC);
JNI.callPPI(wgl.MakeCurrent, currentDc, currentContext);
throw e;
}
}
success = User32.ReleaseDC(windowHandle, hDC);
if (success == 0) {
JNI.callPPI(wgl.MakeCurrent, currentDc, currentContext);
JNI.callPI(wgl.DeleteContext, context);
throw new OpenGLContextException("Could not release DC");
}
/* Check if we want to share context */
if (attribs.shareContext != 0L) {
int succ = JNI.callPPI(wgl.ShareLists, context, attribs.shareContext);
if (succ == 0) {
JNI.callPPI(wgl.MakeCurrent, currentDc, currentContext);
JNI.callPI(wgl.DeleteContext, context);
throw new OpenGLContextException("Failed while configuring context sharing.");
}
}
// Restore old context
JNI.callPPI(wgl.MakeCurrent, currentDc, currentContext);
return context;
}
// Obtain wglCreateContextAttribsARB function pointer
procEncoded = buffer.stringParamASCII("wglCreateContextAttribsARB", true);
adr = buffer.address(procEncoded);
long wglCreateContextAttribsARBAddr = JNI.callPP(wgl.GetProcAddress, adr);
if (wglCreateContextAttribsARBAddr == 0L) {
JNI.callPI(wgl.DeleteContext, dummyContext);
JNI.callPPI(wgl.MakeCurrent, currentDc, currentContext);
throw new OpenGLContextException("No support for wglCreateContextAttribsARB. Cannot create OpenGL context.");
}
IntBuffer attribList = BufferUtils.createIntBuffer(64);
long attribListAddr = MemoryUtil.memAddress(attribList);
long hDC = User32.GetDC(windowHandle);
// Obtain wglChoosePixelFormatARB if multisampling or sRGB or floating point pixel format is requested
if (attribs.samples > 0 || attribs.sRGB || attribs.floatPixelFormat) {
procEncoded = buffer.stringParamASCII("wglChoosePixelFormatARB", true);
adr = buffer.address(procEncoded);
long wglChoosePixelFormatAddr = JNI.callPP(wgl.GetProcAddress, adr);
if (wglChoosePixelFormatAddr == 0L) {
// Try EXT function (the WGL constants are the same in both extensions)
procEncoded = buffer.stringParamASCII("wglChoosePixelFormatEXT", true);
adr = buffer.address(procEncoded);
wglChoosePixelFormatAddr = JNI.callPP(wgl.GetProcAddress, adr);
if (wglChoosePixelFormatAddr == 0L) {
User32.ReleaseDC(windowHandle, hDC);
JNI.callPI(wgl.DeleteContext, dummyContext);
JNI.callPPI(wgl.MakeCurrent, currentDc, currentContext);
throw new OpenGLContextException("No support for wglChoosePixelFormatARB/EXT. Cannot query supported pixel formats.");
}
}
if (attribs.samples > 0) {
// Check for ARB or EXT extension (their WGL constants have the same value)
boolean has_WGL_ARB_multisample = wglExtensions.contains("WGL_ARB_multisample");
boolean has_WGL_EXT_multisample = wglExtensions.contains("WGL_EXT_multisample");
if (!has_WGL_ARB_multisample && !has_WGL_EXT_multisample) {
User32.ReleaseDC(windowHandle, hDC);
JNI.callPI(wgl.DeleteContext, dummyContext);
JNI.callPPI(wgl.MakeCurrent, currentDc, currentContext);
throw new OpenGLContextException("Multisampling requested but WGL_ARB_multisample is unavailable");
}
if (attribs.colorSamplesNV > 0) {
boolean has_WGL_NV_multisample_coverage = wglExtensions.contains("WGL_NV_multisample_coverage");
if (!has_WGL_NV_multisample_coverage) {
User32.ReleaseDC(windowHandle, hDC);
JNI.callPI(wgl.DeleteContext, dummyContext);
JNI.callPPI(wgl.MakeCurrent, currentDc, currentContext);
throw new OpenGLContextException("Color samples requested but WGL_NV_multisample_coverage is unavailable");
}
}
}
if (attribs.sRGB) {
// Check for WGL_EXT_framebuffer_sRGB
boolean has_WGL_EXT_framebuffer_sRGB = wglExtensions.contains("WGL_EXT_framebuffer_sRGB");
if (!has_WGL_EXT_framebuffer_sRGB) {
User32.ReleaseDC(windowHandle, hDC);
JNI.callPI(wgl.DeleteContext, dummyContext);
JNI.callPPI(wgl.MakeCurrent, currentDc, currentContext);
throw new OpenGLContextException("sRGB color space requested but WGL_EXT_framebuffer_sRGB is unavailable");
}
}
if (attribs.floatPixelFormat) {
// Check for WGL_ARB_pixel_format_float
boolean has_WGL_ARB_pixel_format_float = wglExtensions.contains("WGL_ARB_pixel_format_float");
if (!has_WGL_ARB_pixel_format_float) {
User32.ReleaseDC(windowHandle, hDC);
JNI.callPI(wgl.DeleteContext, dummyContext);
JNI.callPPI(wgl.MakeCurrent, currentDc, currentContext);
throw new OpenGLContextException("Floating-point format requested but WGL_ARB_pixel_format_float is unavailable");
}
}
// Query matching pixel formats
encodePixelFormatAttribs(attribList, attribs);
int succ = JNI.callPPPIPPI(wglChoosePixelFormatAddr, hDC, attribListAddr, 0L, 1, bufferAddr + 4, bufferAddr);
int numFormats = buffer.buffer().getInt(0);
if (succ == 0 || numFormats == 0) {
User32.ReleaseDC(windowHandle, hDC);
JNI.callPI(wgl.DeleteContext, dummyContext);
JNI.callPPI(wgl.MakeCurrent, currentDc, currentContext);
throw new OpenGLContextException("No supported pixel format found.");
}
pixelFormat = buffer.buffer().getInt(4);
// Describe pixel format for the PIXELFORMATDESCRIPTOR to match the chosen format
int pixFmtIndex = GDI32.DescribePixelFormat(hDC, pixelFormat, pfd);
if (pixFmtIndex == 0) {
User32.ReleaseDC(windowHandle, hDC);
JNI.callPI(wgl.DeleteContext, dummyContext);
JNI.callPPI(wgl.MakeCurrent, currentDc, currentContext);
throw new OpenGLContextException("Failed to validate supported pixel format.");
}
}
// Compose the attributes list
attribList.rewind();
if (atLeast30(attribs.majorVersion, attribs.minorVersion)) {
attribList.put(WGLARBCreateContext.WGL_CONTEXT_MAJOR_VERSION_ARB).put(attribs.majorVersion);
attribList.put(WGLARBCreateContext.WGL_CONTEXT_MINOR_VERSION_ARB).put(attribs.minorVersion);
}
int profile = 0;
if (attribs.profile == GLContextAttributes.OPENGL_COMPATIBILITY_PROFILE) {
profile = WGLARBCreateContextProfile.WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB;
} else if (attribs.profile == GLContextAttributes.OPENGL_CORE_PROFILE) {
profile = WGLARBCreateContextProfile.WGL_CONTEXT_CORE_PROFILE_BIT_ARB;
}
if (profile > 0) {
boolean has_WGL_ARB_create_context_profile = wglExtensions.contains("WGL_ARB_create_context_profile");
if (!has_WGL_ARB_create_context_profile) {
User32.ReleaseDC(windowHandle, hDC);
JNI.callPI(wgl.DeleteContext, dummyContext);
JNI.callPPI(wgl.MakeCurrent, currentDc, currentContext);
throw new OpenGLContextException("OpenGL profile requested but WGL_ARB_create_context_profile is unavailable");
}
attribList.put(WGLARBCreateContextProfile.WGL_CONTEXT_PROFILE_MASK_ARB).put(profile);
}
int contextFlags = 0;
if (attribs.debug) {
contextFlags |= WGLARBCreateContext.WGL_CONTEXT_DEBUG_BIT_ARB;
}
if (attribs.forwardCompatible) {
contextFlags |= WGLARBCreateContext.WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB;
}
if (contextFlags > 0)
attribList.put(WGLARBCreateContext.WGL_CONTEXT_FLAGS_ARB).put(contextFlags);
if (attribs.contextReleaseBehavior > 0) {
boolean has_WGL_ARB_context_flush_control = wglExtensions.contains("WGL_ARB_context_flush_control");
if (!has_WGL_ARB_context_flush_control) {
User32.ReleaseDC(windowHandle, hDC);
JNI.callPI(wgl.DeleteContext, dummyContext);
JNI.callPPI(wgl.MakeCurrent, currentDc, currentContext);
throw new OpenGLContextException("Context release behavior requested but WGL_ARB_context_flush_control is unavailable");
}
if (attribs.contextReleaseBehavior == GLContextAttributes.CONTEXT_RELEASE_BEHAVIOR_NONE)
attribList.put(WGLARBContextFlushControl.WGL_CONTEXT_RELEASE_BEHAVIOR_ARB).put(WGLARBContextFlushControl.WGL_CONTEXT_RELEASE_BEHAVIOR_NONE_ARB);
else if (attribs.contextReleaseBehavior == GLContextAttributes.CONTEXT_RELEASE_BEHAVIOR_FLUSH)
attribList.put(WGLARBContextFlushControl.WGL_CONTEXT_RELEASE_BEHAVIOR_ARB)
.put(WGLARBContextFlushControl.WGL_CONTEXT_RELEASE_BEHAVIOR_FLUSH_ARB);
}
attribList.put(0).put(0);
// Set pixelformat
int succ = GDI32.SetPixelFormat(hDC, pixelFormat, pfd);
if (succ == 0) {
User32.ReleaseDC(windowHandle, hDC);
JNI.callPI(wgl.DeleteContext, dummyContext);
JNI.callPPI(wgl.MakeCurrent, currentDc, currentContext);
throw new OpenGLContextException("Failed to set pixel format.");
}
// And create new context with it
long newCtx = JNI.callPPPP(wglCreateContextAttribsARBAddr, hDC, attribs.shareContext, attribListAddr);
JNI.callPI(wgl.DeleteContext, dummyContext);
if (newCtx == 0L) {
User32.ReleaseDC(windowHandle, hDC);
JNI.callPPI(wgl.MakeCurrent, currentDc, currentContext);
throw new OpenGLContextException("Failed to create OpenGL context.");
}
if (attribs.swapInterval != null) {
boolean has_WGL_EXT_swap_control = wglExtensions.contains("WGL_EXT_swap_control");
if (!has_WGL_EXT_swap_control) {
User32.ReleaseDC(windowHandle, hDC);
JNI.callPPI(wgl.MakeCurrent, currentDc, currentContext);
throw new OpenGLContextException("Swap interval requested but WGL_EXT_swap_control is unavailable");
}
if (attribs.swapInterval < 0) {
// Only allowed if WGL_EXT_swap_control_tear is available
boolean has_WGL_EXT_swap_control_tear = wglExtensions.contains("WGL_EXT_swap_control_tear");
if (!has_WGL_EXT_swap_control_tear) {
User32.ReleaseDC(windowHandle, hDC);
JNI.callPPI(wgl.MakeCurrent, currentDc, currentContext);
throw new OpenGLContextException("Negative swap interval requested but WGL_EXT_swap_control_tear is unavailable");
}
}
// Make context current to set the swap interval
JNI.callPPI(wgl.MakeCurrent, hDC, newCtx);
procEncoded = buffer.stringParamASCII("wglSwapIntervalEXT", true);
adr = buffer.address(procEncoded);
long wglSwapIntervalEXTAddr = JNI.callPP(wgl.GetProcAddress, adr);
if (wglSwapIntervalEXTAddr != 0L) {
JNI.callII(wglSwapIntervalEXTAddr, attribs.swapInterval);
}
}
if (attribs.swapGroupNV > 0 && attribs.swapBarrierNV > 0) {
// Only allowed if WGL_NV_swap_group is available
boolean has_WGL_NV_swap_group = wglExtensions.contains("WGL_NV_swap_group");
if (!has_WGL_NV_swap_group) {
User32.ReleaseDC(windowHandle, hDC);
JNI.callPPI(wgl.MakeCurrent, currentDc, currentContext);
throw new OpenGLContextException("Swap group requested but WGL_NV_swap_group is unavailable");
}
// Make context current to join swap group
success = JNI.callPPI(wgl.MakeCurrent, hDC, newCtx);
try {
wglNvSwapGroup(windowHandle, attribs, buffer, hDC);
} catch (OpenGLContextException e) {
User32.ReleaseDC(windowHandle, hDC);
JNI.callPPI(wgl.MakeCurrent, currentDc, currentContext);
throw e;
}
}
User32.ReleaseDC(windowHandle, hDC);
// Restore old context
JNI.callPPI(wgl.MakeCurrent, currentDc, currentContext);
return newCtx;
}
private void wglNvSwapGroup(long windowHandle, GLContextAttributes attribs, APIBuffer buffer, long hDC) throws OpenGLContextException {
int success;
int procEncoded;
long adr;
procEncoded = buffer.stringParamASCII("wglJoinSwapGroupNV", true);
adr = buffer.address(procEncoded);
long wglJoinSwapGroupNVAddr = JNI.callPP(wgl.GetProcAddress, adr);
procEncoded = buffer.stringParamASCII("wglBindSwapBarrierNV", true);
adr = buffer.address(procEncoded);
long wglBindSwapBarrierNVAddr = JNI.callPP(wgl.GetProcAddress, adr);
procEncoded = buffer.stringParamASCII("wglQueryMaxSwapGroupsNV", true);
adr = buffer.address(procEncoded);
long wglQueryMaxSwapGroupsNVAddr = JNI.callPP(wgl.GetProcAddress, adr);
IntBuffer maxGroups = BufferUtils.createIntBuffer(2);
success = JNI.callPPPI(wglQueryMaxSwapGroupsNVAddr, hDC, MemoryUtil.memAddress(maxGroups), MemoryUtil.memAddress(maxGroups) + 4);
if (maxGroups.get(0) > attribs.swapGroupNV) {
throw new OpenGLContextException("Swap group exceeds maximum group index");
}
if (maxGroups.get(1) > attribs.swapBarrierNV) {
throw new OpenGLContextException("Swap barrier exceeds maximum group index");
}
success = JNI.callPII(wglJoinSwapGroupNVAddr, hDC, attribs.swapGroupNV);
if (success == 0) {
throw new OpenGLContextException("Failed to join swap group");
}
success = JNI.callIII(wglBindSwapBarrierNVAddr, attribs.swapGroupNV, attribs.swapBarrierNV);
if (success == 0) {
JNI.callPII(wglJoinSwapGroupNVAddr, hDC, 0);
throw new OpenGLContextException("Failed to bind swap barrier. Probably no G-Sync card installed.");
}
}
public boolean isCurrent(long context) {
long ret = JNI.callP(wgl.GetCurrentContext);
return ret == context;
}
public boolean makeCurrent(long windowHandle, long context) {
long hDC = User32.GetDC(windowHandle);
int ret = JNI.callPPI(wgl.MakeCurrent, hDC, context);
User32.ReleaseDC(windowHandle, hDC);
return ret == 1;
}
public boolean deleteContext(long context) {
int ret = JNI.callPI(wgl.DeleteContext, context);
return ret == 1;
}
public boolean swapBuffers(long windowHandle) {
long hDC = User32.GetDC(windowHandle);
int ret = GDI32.SwapBuffers(hDC);
User32.ReleaseDC(windowHandle, hDC);
return ret == 1;
}
}
|
package won.node.rest;
import com.hp.hpl.jena.rdf.model.Model;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import won.protocol.exception.NoSuchConnectionException;
import won.protocol.exception.NoSuchNeedException;
import won.protocol.service.LinkedDataService;
import won.protocol.util.HTTP;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import java.net.URI;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
@Path("/") //the servlet-mapping defines where this root path is published externally
public class LinkedDataRestService {
final Logger logger = LoggerFactory.getLogger(getClass());
//prefix of a need resource
private String needResourceURIPrefix;
//prefix of a connection resource
private String connectionResourceURIPrefix;
//prefix for URISs of RDF data
private String dataURIPrefix;
//prefix for URIs referring to real-world things
private String resourceURIPrefix;
//prefix for human readable pages
private String pageURIPrefix;
//date format for Expires header (rfc 1123)
private static final String DATE_FORMAT_RFC_1123 = "EEE, dd MMM yyyy HH:mm:ss z";
@Autowired
private LinkedDataService linkedDataService;
@GET
@Path("/resource/{whatever:.*}")
@Produces("application/rdf+xml,application/x-turtle,text/turtle,text/rdf+n3,application/json")
public Response redirectToData(
@Context UriInfo uriInfo,
@PathParam("identifier") String identifier) {
URI resourceUriPrefix = URI.create(this.resourceURIPrefix);
URI dataUri = URI.create(this.dataURIPrefix);
String requestUri = uriInfo.getRequestUri().toString();
String redirectToURI = requestUri.replaceFirst(resourceUriPrefix.getPath(), dataUri.getPath());
//TODO: actually the expiry information should be the same as that of the resource that is redirected to
return markAsNeverExpires(Response.seeOther(URI.create(redirectToURI))).build();
}
@GET
@Path("/resource/{whatever:.*}")
@Produces("text/html")
public Response redirectToPage(
@Context UriInfo uriInfo,
@PathParam("identifier") String identifier) {
URI resourceUriPrefix = URI.create(this.resourceURIPrefix);
URI pageUriPrefix = URI.create(this.pageURIPrefix);
String requestUri = uriInfo.getRequestUri().toString();
String redirectToURI = requestUri.replaceFirst(resourceUriPrefix.getPath(), pageUriPrefix.getPath());
//TODO: actually the expiry information should be the same as that of the resource that is redirected to
return markAsNeverExpires(Response.seeOther(URI.create(redirectToURI))).build();
}
@GET
@Path("/data/need")
@Produces("application/rdf+xml,application/x-turtle,text/turtle,text/rdf+n3,application/json")
public Response listNeedURIs(
@Context UriInfo uriInfo,
@DefaultValue("-1") @QueryParam("page") int page) {
logger.debug("listNeedURIs() called");
Model model = linkedDataService.listNeedURIs(page);
return markAsAlreadyExpired(addLocationHeaderIfNecessary(Response.ok(model), uriInfo.getRequestUri(), URI.create(this.needResourceURIPrefix))) .build();
}
@GET
@Path("/data/connection")
@Produces("application/rdf+xml,application/x-turtle,text/turtle,text/rdf+n3,application/json")
public Response listConnectionURIs(
@Context UriInfo uriInfo,
@DefaultValue("-1") @QueryParam("page") int page) {
logger.debug("listNeedURIs() called");
Model model = linkedDataService.listConnectionURIs(page);
return markAsAlreadyExpired(addLocationHeaderIfNecessary(Response.ok(model),uriInfo.getRequestUri(), URI.create(this.connectionResourceURIPrefix))).build();
}
@GET
@Path("/data/need/{identifier}")
@Produces("application/rdf+xml,application/x-turtle,text/turtle,text/rdf+n3,application/json")
public Response readNeed(
@Context UriInfo uriInfo,
@PathParam("identifier") String identifier) {
logger.debug("readNeed() called");
URI needUri = URI.create(this.needResourceURIPrefix + "/" + identifier);
try {
Model model = linkedDataService.getNeedModel(needUri);
//TODO: need information does change over time. The immutable need information should never expire, the mutable should
return markAsNeverExpires(addLocationHeaderIfNecessary(Response.ok(model), uriInfo.getRequestUri(), needUri)).build();
} catch (NoSuchNeedException e) {
return Response.status(Response.Status.NOT_FOUND).build();
}
}
@GET
@Path("/data/connection/{identifier}")
@Produces("application/rdf+xml,application/x-turtle,text/turtle,text/rdf+n3,application/json")
public Response readConnection(
@Context UriInfo uriInfo,
@PathParam("identifier") String identifier) {
logger.debug("readConnection() called");
URI connectionUri = URI.create(this.connectionResourceURIPrefix + "/" + identifier);
try {
Model model = linkedDataService.getConnectionModel(connectionUri);
//TODO: connection information does change over time. The immutable connection information should never expire, the mutable should
return markAsNeverExpires(addLocationHeaderIfNecessary(Response.ok(model),uriInfo.getRequestUri(), connectionUri)).build();
} catch (NoSuchConnectionException e) {
return Response.status(Response.Status.NOT_FOUND).build();
}
}
@GET
@Path("/data/need/{identifier}/connections")
@Produces("application/rdf+xml,application/x-turtle,text/turtle,text/rdf+n3,application/json")
public Response readConnectionsOfNeed(
@Context UriInfo uriInfo,
@PathParam("identifier") String identifier,
@DefaultValue("-1") @QueryParam("page") int page) {
logger.debug("readConnectionsOfNeed() called");
URI needUri = URI.create(this.needResourceURIPrefix + "/" + identifier);
try {
Model model = linkedDataService.listConnectionURIs(page, needUri);
return markAsAlreadyExpired(addLocationHeaderIfNecessary(Response.ok(model),uriInfo.getRequestUri(), needUri)).build();
} catch (NoSuchNeedException e) {
return Response.status(Response.Status.NOT_FOUND).build();
}
}
public void setNeedResourceURIPrefix(String needResourceURIPrefix) {
this.needResourceURIPrefix = needResourceURIPrefix;
}
public void setConnectionResourceURIPrefix(String connectionResourceURIPrefix) {
this.connectionResourceURIPrefix = connectionResourceURIPrefix;
}
public void setDataURIPrefix(String dataURIPrefix) {
this.dataURIPrefix = dataURIPrefix;
}
public void setResourceURIPrefix(final String resourceURIPrefix) {
this.resourceURIPrefix = resourceURIPrefix;
}
public void setLinkedDataService(final LinkedDataService linkedDataService) {
this.linkedDataService = linkedDataService;
}
public void setPageURIPrefix(final String pageURIPrefix) {
this.pageURIPrefix = pageURIPrefix;
}
/**
* Checks if the actual URI is the same as the canonical URI; if not, adds a Location header to the response builder
* indicating the canonical URI.
* @param builder
* @param actualURI
* @param canonicalURI
* @return
*/
private Response.ResponseBuilder addLocationHeaderIfNecessary(Response.ResponseBuilder builder, URI actualURI, URI canonicalURI){
if(!canonicalURI.resolve(actualURI).equals(canonicalURI)) {
//the request URI is the canonical URI, it may be a DNS alias or relative
//according to http://www.w3.org/TR/ldp/#general we have to include
//the canonical URI in the lcoation header here
return builder.header(HTTP.HEADER_LOCATION, canonicalURI.toString());
}
return builder;
}
/**
* Sets the Date and Expires header fields such that the response will be treated as 'never expires'
* (and will therefore be cached forever)
* @param res
* @return
*/
private Response.ResponseBuilder markAsNeverExpires(Response.ResponseBuilder res){
SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT_RFC_1123);
return res
.header(HTTP.HEADER_EXPIRES, dateFormat.format(getNeverExpiresDate()))
.header(HTTP.HEADER_DATE, dateFormat.format(new Date()))
;
}
/**
* Sets the Date and Expires header fields such that the response will be treated as 'already expired'
* (and will therefore not be cached)
* @param res
* @return
*/
private Response.ResponseBuilder markAsAlreadyExpired(Response.ResponseBuilder res){
Date headerDate = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT_RFC_1123);
String formattedDate = dateFormat.format(headerDate);
return res
.header(HTTP.HEADER_EXPIRES, formattedDate)
.header(HTTP.HEADER_DATE, formattedDate)
;
}
//Calculates a date that, according to http spec, means 'never expires'
private Date getNeverExpiresDate(){
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
cal.set(Calendar.YEAR,cal.get(Calendar.YEAR)+1);
return cal.getTime();
}
}
|
package org.innovateuk.ifs.application.review.controller;
import org.innovateuk.ifs.application.forms.form.ApplicationReopenForm;
import org.innovateuk.ifs.application.forms.form.ApplicationSubmitForm;
import org.innovateuk.ifs.application.resource.ApplicationResource;
import org.innovateuk.ifs.application.review.populator.ReviewAndSubmitViewModelPopulator;
import org.innovateuk.ifs.application.review.viewmodel.TrackViewModel;
import org.innovateuk.ifs.application.service.ApplicationRestService;
import org.innovateuk.ifs.application.service.QuestionStatusRestService;
import org.innovateuk.ifs.assessment.service.AssessmentRestService;
import org.innovateuk.ifs.async.annotations.AsyncMethod;
import org.innovateuk.ifs.commons.error.ValidationMessages;
import org.innovateuk.ifs.commons.rest.RestResult;
import org.innovateuk.ifs.commons.security.SecuredBySpring;
import org.innovateuk.ifs.competition.resource.CompetitionResource;
import org.innovateuk.ifs.competition.resource.CompetitionStatus;
import org.innovateuk.ifs.competition.resource.CovidType;
import org.innovateuk.ifs.competition.service.CompetitionRestService;
import org.innovateuk.ifs.controller.ValidationHandler;
import org.innovateuk.ifs.filter.CookieFlashMessageFilter;
import org.innovateuk.ifs.user.resource.ProcessRoleResource;
import org.innovateuk.ifs.user.resource.UserResource;
import org.innovateuk.ifs.user.service.ProcessRoleRestService;
import org.innovateuk.ifs.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.function.Supplier;
import static java.lang.Boolean.TRUE;
import static java.lang.String.format;
import static org.innovateuk.ifs.application.resource.ApplicationState.SUBMITTED;
@Controller
@RequestMapping("/application")
public class ReviewAndSubmitController {
public static final String FORM_ATTR_NAME = "form";
@Autowired
private ReviewAndSubmitViewModelPopulator reviewAndSubmitViewModelPopulator;
@Autowired
private ApplicationRestService applicationRestService;
@Autowired
private CompetitionRestService competitionRestService;
@Autowired
private UserService userService;
@Autowired
private CookieFlashMessageFilter cookieFlashMessageFilter;
@Autowired
private QuestionStatusRestService questionStatusRestService;
@Autowired
private ProcessRoleRestService processRoleRestService;
@Value("${ifs.early.metrics.url}")
private String earlyMetricsUrl;
@SecuredBySpring(value = "READ", description = "Applicants can review and submit their applications")
@PreAuthorize("hasAnyAuthority('applicant')")
@GetMapping("/{applicationId}/review-and-submit")
@AsyncMethod
public String reviewAndSubmit(@ModelAttribute(value = FORM_ATTR_NAME, binding = false) ApplicationSubmitForm form,
BindingResult bindingResult,
@PathVariable long applicationId,
Model model,
UserResource user) {
model.addAttribute("model", reviewAndSubmitViewModelPopulator.populate(applicationId, user));
return "application/review-and-submit";
}
@SecuredBySpring(value = "APPLICATION_SUBMIT", description = "Applicants can submit their applications.")
@PreAuthorize("hasAuthority('applicant')")
@PostMapping("/{applicationId}/review-and-submit")
public String submitApplication(@PathVariable long applicationId,
@ModelAttribute(FORM_ATTR_NAME) ApplicationSubmitForm form,
BindingResult bindingResult,
UserResource user,
HttpServletResponse response) {
ApplicationResource application = applicationRestService.getApplicationById(applicationId).getSuccess();
if (!ableToSubmitApplication(user, application)) {
cookieFlashMessageFilter.setFlashMessage(response, "cannotSubmit");
return format("redirect:/application/%d", applicationId);
}
return format("redirect:/application/%d/confirm-submit?termsAgreed=true", applicationId);
}
@SecuredBySpring(value = "APPLICATION_REVIEW_AND_SUBMIT_RETURN_AND_EDIT",
description = "Applicants can return to edit questions from the review and submit page")
@PreAuthorize("hasAuthority('applicant')")
@PostMapping(value = "/{applicationId}/review-and-submit", params = "edit")
public String editQuestion(@PathVariable long applicationId,
@RequestParam("edit") long questionId) {
return redirectToQuestion(applicationId, questionId);
}
@SecuredBySpring(value = "APPLICATION_REVIEW_AND_SUBMIT_MARK_AS_COMPLETE",
description = "Applicants can mark questions as complete from the review and submit page")
@PreAuthorize("hasAuthority('applicant')")
@PostMapping(value = "/{applicationId}/review-and-submit", params = "complete")
public String completeQuestion(@PathVariable long applicationId,
@RequestParam("complete") long questionId,
UserResource user) {
ProcessRoleResource processRole = processRoleRestService.findProcessRole(user.getId(), applicationId).getSuccess();
List<ValidationMessages> messages = questionStatusRestService.markAsComplete(questionId, applicationId, processRole.getId()).getSuccess();
if (messages.isEmpty()) {
return redirectToReview(applicationId);
} else {
return handleMarkAsCompleteFailure(applicationId, questionId, processRole);
}
}
@SecuredBySpring(value = "APPLICATION_REVIEW_AND_SUBMIT_ASSIGN",
description = "Applicants can assign questions from the review and submit page")
@PreAuthorize("hasAuthority('applicant')")
@PostMapping(value = "/{applicationId}/review-and-submit", params = "assign")
public String assignQuestionToLead(@PathVariable long applicationId,
@RequestParam("assign") long questionId,
UserResource user) {
ProcessRoleResource assignTo = userService.getLeadApplicantProcessRole(applicationId);
ProcessRoleResource assignFrom = processRoleRestService.findProcessRole(user.getId(), applicationId).getSuccess();
questionStatusRestService.assign(questionId, applicationId, assignTo.getId(), assignFrom.getId()).getSuccess();
return redirectToReview(applicationId);
}
@SecuredBySpring(value = "APPLICATION_REVIEW_AND_SUBMIT_MARK_AS_INCOMPLETE",
description = "Applicants can mark questions as incomplete from the review and submit page")
@PreAuthorize("hasAuthority('applicant')")
@PostMapping(value = "/{applicationId}/review-and-submit", params = "incomplete")
public String incompleteQuestion(@PathVariable long applicationId,
@RequestParam("incomplete") long questionId,
UserResource user) {
ProcessRoleResource processRole = processRoleRestService.findProcessRole(user.getId(), applicationId).getSuccess();
questionStatusRestService.markAsInComplete(questionId, applicationId, processRole.getId());
return redirectToQuestion(applicationId, questionId);
}
private String redirectToQuestion(long applicationId, long questionId) {
return format("redirect:/application/%d/form/question/%d", applicationId, questionId);
}
private String redirectToReview(long applicationId) {
return format("redirect:/application/%d/review-and-submit", applicationId);
}
@SecuredBySpring(value = "APPLICANT_CONFIRM_SUBMIT", description = "Applicants can confirm they wish to submit their applications")
@PreAuthorize("hasAuthority('applicant')")
@GetMapping("/{applicationId}/confirm-submit")
public String applicationConfirmSubmit(@PathVariable long applicationId,
@ModelAttribute("termsAgreed") Boolean termsAgreed,
@ModelAttribute(FORM_ATTR_NAME) ApplicationSubmitForm form,
Model model) {
if (!TRUE.equals(termsAgreed)) {
return format("redirect:/application/%d/summary", applicationId);
}
model.addAttribute("termsAgreed", termsAgreed);
model.addAttribute("applicationId", applicationId);
return "application-confirm-submit";
}
@SecuredBySpring(value = "APPLICANT_CONFIRM_SUBMIT", description = "Applicants can confirm they wish to submit their applications")
@PreAuthorize("hasAuthority('applicant')")
@PostMapping("/{applicationId}/confirm-submit")
public String applicationSubmit(Model model,
@ModelAttribute(FORM_ATTR_NAME) ApplicationSubmitForm form,
@SuppressWarnings("UnusedParameters") BindingResult bindingResult,
ValidationHandler validationHandler,
@PathVariable("applicationId") long applicationId,
UserResource user,
HttpServletResponse response) {
ApplicationResource application = applicationRestService.getApplicationById(applicationId).getSuccess();
if (!ableToSubmitApplication(user, application)) {
cookieFlashMessageFilter.setFlashMessage(response, "cannotSubmit");
return format("redirect:/application/%d", applicationId);
}
RestResult<Void> updateResult = applicationRestService.updateApplicationState(applicationId, SUBMITTED);
Supplier<String> failureView = () -> applicationConfirmSubmit(applicationId, true, form, model);
return validationHandler.addAnyErrors(updateResult)
.failNowOrSucceedWith(failureView, () -> format("redirect:/application/%d/track", applicationId));
}
@SecuredBySpring(value = "APPLICANT_REOPEN", description = "Applicants can confirm they wish to reopen their applications")
@PreAuthorize("hasAuthority('applicant')")
@GetMapping("/{applicationId}/confirm-reopen")
public String applicationConfirmReopen(@PathVariable long applicationId,
@ModelAttribute(FORM_ATTR_NAME) ApplicationReopenForm form,
Model model,
UserResource userResource) {
ApplicationResource applicationResource = applicationRestService.getApplicationById(applicationId).getSuccess();
CompetitionResource competitionResource = competitionRestService.getCompetitionById(applicationResource.getCompetition()).getSuccess();
if (!canReopenApplication(applicationResource, userResource, competitionResource.isAlwaysOpen(), competitionResource.isHesta())) {
return "redirect:/application/" + applicationId + "/track";
}
model.addAttribute("applicationId", applicationResource.getId());
model.addAttribute("applicationName", applicationResource.getName());
model.addAttribute("competitionName", applicationResource.getCompetitionName());
return "application-confirm-reopen";
}
private boolean canReopenApplication(ApplicationResource application, UserResource user, boolean alwaysOpen, boolean isHesta) {
return !alwaysOpen || isHesta
&& CompetitionStatus.OPEN.equals(application.getCompetitionStatus())
&& application.canBeReopened()
&& userService.isLeadApplicant(user.getId(), application);
}
@SecuredBySpring(value = "APPLICANT_REOPEN", description = "Applicants can reopen their applications")
@PreAuthorize("hasAuthority('applicant')")
@PostMapping("/{applicationId}/confirm-reopen")
public String applicationReopen(Model model,
@ModelAttribute(FORM_ATTR_NAME) ApplicationReopenForm form,
@SuppressWarnings("UnusedParameters") BindingResult bindingResult,
ValidationHandler validationHandler,
@PathVariable("applicationId") long applicationId) {
RestResult<Void> updateResult = applicationRestService.reopenApplication(applicationId);
Supplier<String> failureView = () -> applicationReopen(model, form, bindingResult, validationHandler, applicationId);
Supplier<String> successView = () -> format("redirect:/application/%d", applicationId);
return validationHandler.addAnyErrors(updateResult)
.failNowOrSucceedWith(failureView, successView);
}
@SecuredBySpring(value = "APPLICANT_TRACK", description = "Applicants and kta can track their application after submitting.")
@PreAuthorize("hasAnyAuthority('applicant', 'knowledge_transfer_adviser')")
@GetMapping("/{applicationId}/track")
public String applicationTrack(Model model,
@PathVariable long applicationId,
UserResource user) {
ApplicationResource application = applicationRestService.getApplicationById(applicationId).getSuccess();
if (!application.isSubmitted()) {
return "redirect:/application/" + applicationId;
}
CompetitionResource competition = competitionRestService.getCompetitionById(application.getCompetition()).getSuccess();
model.addAttribute("model", new TrackViewModel(
competition,
application,
earlyMetricsUrl,
application.getCompletion(),
canReopenApplication(application, user, competition.isAlwaysOpen(), competition.isHesta())
));
return getTrackingPage(competition);
}
private String getTrackingPage(CompetitionResource competition) {
if (CovidType.ADDITIONAL_FUNDING.equals(competition.getCovidType())) {
return "covid-additional-funding-application-track";
} else if (competition.isHesta()) {
return "hesta-application-track";
} else if (competition.isAlwaysOpen()) {
return "always-open-track";
} else if (competition.isH2020()) {
return "h2020-grant-transfer-track";
} else if (competition.isLoan()) {
return "loan-application-track";
} else {
return "application-track";
}
}
private boolean ableToSubmitApplication(UserResource user, ApplicationResource application) {
return userService.isLeadApplicant(user.getId(), application) && application.isSubmittable();
}
private String handleMarkAsCompleteFailure(long applicationId, long questionId, ProcessRoleResource processRole) {
questionStatusRestService.markAsInComplete(questionId, applicationId, processRole.getId());
return "redirect:/application/" + applicationId + "/form/question/edit/" + questionId + "?show-errors=true";
}
}
|
package org.nutz.aop;
import java.lang.reflect.Method;
/**
*
* @author wendal(wendal1985@gmail.com)
* @see org.nutz.aop.MethodInterceptor
*/
public abstract class AbstractMethodInterceptor implements MethodInterceptor {
public Object afterInvoke(Object obj, Object returnObj, Method method, Object... args) {
return returnObj;
}
public boolean beforeInvoke(Object obj, Method method, Object... args) {
return true;
}
public boolean whenError(Throwable e, Object obj, Method method, Object... args) {
return true;
}
public boolean whenException(Exception e, Object obj, Method method, Object... args) {
return true;
}
}
|
package org.u_compare.gui.component;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import org.u_compare.gui.control.ComponentController;
import org.u_compare.gui.model.Component;
@SuppressWarnings("serial")
public class TitlePanel extends JPanel {
private static final int TITLE_SIZE_LIMIT = 30;
private final ComponentController controller;
private final Component component;
protected String title;
private JLabel titleLabel;
private JTextField titleTextField;
private ActionListener titleListener;
private FocusListener titleFocusListener;
public TitlePanel(ComponentController controller, Component component,
boolean whiteBackground) {
super();
this.controller = controller;
this.component = component;
titleListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
setTitle(titleTextField.getText());
titleTextField.setVisible(false);
titleLabel.setVisible(true);
}
};
// add a title panel
setLayout(new CardLayout());
title = component.getName();
titleLabel = new JLabel(title);
titleLabel.setText(title);
titleTextField = new JTextField(title);
titleTextField.setText(title);
titleTextField.setDocument(new JTextFieldLimit(TITLE_SIZE_LIMIT));
titleLabel.setFont(new Font("sansserif", Font.BOLD, 12));
titleTextField.setFont(new Font("sansserif", Font.BOLD, 12));
titleTextField.setVisible(false);
add(titleLabel, BorderLayout.LINE_START);
add(titleTextField, BorderLayout.LINE_START);
if (whiteBackground)
setBackground(Color.WHITE);
// start editing
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
// JPanel target = (JPanel) e.getSource();
if (!TitlePanel.this.component.getLockedStatus()) {
titleTextField.requestFocusInWindow();
titleTextField.setVisible(false);
titleTextField.setVisible(true);
titleTextField.requestFocus(); // this is one of the
// nastiest tricks I've
// seen in swing. viva
// swing.
setTitle(titleLabel.getText());
titleLabel.setVisible(false);
titleTextField.setVisible(true);
}
}
}
});
titleFocusListener = new FocusListener() {
public void focusGained(FocusEvent e) {
titleTextField.grabFocus();
}
public void focusLost(FocusEvent e) {
setTitle(titleLabel.getText());
System.out.println("FOCUS LOST \ntitlelabel "
+ titleLabel.getText());
System.out.println("title " + title);
System.out.println("titletextfield " + titleTextField.getText()
+ "<-- nothing ?");
titleTextField.setVisible(false);
titleLabel.setVisible(true);
}
};
// the title JTextField has listeners
titleTextField.addActionListener(titleListener);
titleTextField.addFocusListener(titleFocusListener);
}
// TODO this might be set directly by the controller
protected void setTitle(String title) {
this.title = title;
this.titleLabel.setText(title);
this.titleTextField.setText(title);
this.controller.setTitle(title);
}
}
|
package org.opendaylight.controller.cluster.access.client;
import akka.actor.ActorRef;
import com.google.common.base.Preconditions;
import javax.annotation.Nonnull;
import org.opendaylight.yangtools.concepts.Mutable;
/**
* Common, externally-invisible superclass of contexts associated with a {@link AbstractClientActor}. End users pass this
* object via opaque {@link ClientActorContext}.
*
* @author Robert Varga
*/
abstract class AbstractClientActorContext implements Mutable {
private final String persistenceId;
private final ActorRef self;
AbstractClientActorContext(final @Nonnull ActorRef self, final @Nonnull String persistenceId) {
this.persistenceId = Preconditions.checkNotNull(persistenceId);
this.self = Preconditions.checkNotNull(self);
}
final @Nonnull String persistenceId() {
return persistenceId;
}
public final @Nonnull ActorRef self() {
return self;
}
}
|
package org.usfirst.frc.team236.robot;
import standard.LogitechF310;
/**
* The RobotMap is a mapping from the ports sensors and actuators are wired into
* to a variable name. This provides flexibility changing wiring, makes checking
* the wiring easier and significantly reduces the number of magic numbers
* floating around.
*/
public class RobotMap {
// For example to map the left and right motors, you could define the
// following variables to use with your drivetrain subsystem.
// public static int leftMotor = 1;
// public static int rightMotor = 2;
// If you are using multiple modules, make sure to define both the port
// number and the module. For example you with a rangefinder:
// public static int rangefinderPort = 1;
// public static int rangefinderModule = 1;
public static final String MID_CAMERA_NAME = "cam3";
public static final String INTAKE_CAMERA_NAME = "cam4";
public class DriveMap {
public static final int PWM_LEFT_FRONT = 0;
public static final int PWM_LEFT_BACK = 1;
public static final int PWM_RIGHT_FRONT = 2;
public static final int PWM_RIGHT_BACK = 3;
public static final int DIO_ENCODER_LEFT_A = 0;
public static final int DIO_ENCODER_LEFT_B = 1;
public static final int DIO_ENCODER_RIGHT_A = 2;
public static final int DIO_ENCODER_RIGHT_B = 3;
public static final int SOL_FORWARD = 0;
public static final int SOL_REVERSE = 1;
public static final boolean INV_LEFT_FRONT = true;
public static final boolean INV_LEFT_BACK = true;
public static final boolean INV_RIGHT_FRONT = false;
public static final boolean INV_RIGHT_BACK = false;
public static final boolean INV_ENCODER_LEFT = false;
public static final boolean INV_ENCODER_RIGHT = false;
// Circumference of Drive Wheel may need tweaking
public static final double CIRCUMFERENCE = 28;
// Gear ratio is 3:1, and raw encoder count is 512 per full revolution
public static final double DISTANCE_PER_PULSE = CIRCUMFERENCE / (3 * 512);
}
public class IntakeMap {
public static final int PWM_MOTOR = 4;
public static final boolean INV_MOTOR = false;
public static final int DIO_LIMIT = 8;
}
public static class ArmMap {
public static final int FLASHLIGHT_RELAY = 0;
public static final int PWM_MOTOR = 5;
public static final boolean INV_MOTOR = false;
public static final int PWM_MOTOR_RIGHT = 6;
public static final boolean INV_MOTOR_RIGHT = false;
public static final int DIO_ENCODER_A = 4;
public static final int DIO_ENCODER_B = 5;
public static final int DIO_LIMIT_TOP = 6;
public static final int DIO_LIMIT_BOTTOM = 7;
public static final double MIN_ANGLE = -10.5; // Lowest angle of arm
public static final double MAX_ANGLE = 83; // TODO Highest angle of arm
public static final double BATTER_HIGH_SHOT_ANGLE = 74.0;
public static final double DEFENSE_HIGH_SHOT_ANGLE = 37.948;
// TODO Trig numbers
// Numbers to find actuator side length
public static final boolean INV_ENCODER = false;
public static final double ACTUATOR_MIN_LENGTH = 10;
public static final double INCHES_PER_THREAD = (1 / 2);
public static final double ROTATIONS_PER_PULSE = (1 / 512);
public static final double SCALE_FACTOR = (36 / 34);
public static final double DISTANCE_PER_PULSE = SCALE_FACTOR * ROTATIONS_PER_PULSE * INCHES_PER_THREAD;
// Axle to pivot side length
public static final double AXLE_ACTUATOR_DISTANCE = 4.75;
// Axle to anchor side length
public static final double AXLE_ANCHOR_MID_DISTANCE = 10;
public static final double MID_ANCHOR_DISTANCE = 4;
public static final double MID_ANCHOR_ANGLE = Math.atan(MID_ANCHOR_DISTANCE / AXLE_ANCHOR_MID_DISTANCE);
public static final double AXLE_ANCHOR_DISTANCE = Math
.sqrt(Math.pow(AXLE_ANCHOR_MID_DISTANCE, 2) + Math.pow(MID_ANCHOR_DISTANCE, 2));
public class PID {
public static final double kP = .05;
public static final double kI = 0;
public static final double kD = 0;
}
}
public class ControlMap {
// USB
public static final int PORT_STICK_LEFT = 0;
public static final int PORT_STICK_RIGHT = 1;
public static final int PORT_CONTROLLER = 2;
// Left stick
public static final int BUTTON_SHOOT = 1;
public static final int BUTTON_EJECT = 2;
public static final int BUTTON_INTAKE = 3;
public static final int BUTTON_COCK = 4;
public static final int BUTTON_INTAKE_OVERRIDE = 5;
// Right stick
public static final int BUTTON_SHIFT_DOWN = 2;
public static final int BUTTON_SHIFT_UP = 3;
public static final int BUTTON_INVERT_DRIVE = 4;
public static final int BUTTON_NORMAL_DRIVE = 5;
// Controller
public static final int BUTTON_ARM_BOTTOM = LogitechF310.A;
public static final int BUTTON_ARM_HIGH_SHOT_BATTER = LogitechF310.Y;
public static final int BUTTON_ARM_WITH_POV = LogitechF310.LB;
public static final int BUTTON_SHOOT_CONTROLLER = LogitechF310.RB;
public static final int BUTTON_ARM_JOYSTICK = LogitechF310.LEFT_PRESS;
public static final int BUTTON_ARM_HIGH_SHOT_DEFENSE = LogitechF310.X;
public static final int AXIS_ARM = LogitechF310.Axes.LEFT_Y;
public static final int BUTTON_FLASHLIGHT = LogitechF310.LB;
}
public class ShooterMap {
public static final int PWM_MOTOR = 7;
public static final boolean INV_MOTOR = false;
public static final int SOL_FORWARD = 2;
public static final int SOL_REVERSE = 3;
}
}
|
package se.citerus.cqrs.bookstore.ordercontext.client.productcatalog;
import com.sun.jersey.api.client.Client;
public class ProductCatalogClient {
private final Client client;
private final String serviceUrl;
private ProductCatalogClient(Client client, String serviceUrl) {
this.client = client;
this.serviceUrl = serviceUrl;
}
public static ProductCatalogClient create(Client client, String serviceUrl) {
return new ProductCatalogClient(client, serviceUrl);
}
public ProductDto getProduct(String productId) {
return client.resource(serviceUrl + productId).get(ProductDto.class);
}
}
|
package org.usfirst.frc.team236.robot;
/**
* The RobotMap is a mapping from the ports sensors and actuators are wired into
* to a variable name. This provides flexibility changing wiring, makes checking
* the wiring easier and significantly reduces the number of magic numbers
* floating around.
*/
public class RobotMap {
// For example to map the left and right motors, you could define the
// following variables to use with your drivetrain subsystem.
// public static int leftMotor = 1;
// public static int rightMotor = 2;
// If you are using multiple modules, make sure to define both the port
// number and the module. For example you with a rangefinder:
// public static int rangefinderPort = 1;
// public static int rangefinderModule = 1;
public static final String CAMERA_NAME = "cam0";
public class DriveMap {
public static final int PWM_LEFT_FRONT = 0;
public static final int PWM_LEFT_BACK = 1;
public static final int PWM_RIGHT_FRONT = 2;
public static final int PWM_RIGHT_BACK = 3;
public static final int DIO_ENCODER_LEFT_A = 0;
public static final int DIO_ENCODER_LEFT_B = 1;
public static final int DIO_ENCODER_RIGHT_A = 2;
public static final int DIO_ENCODER_RIGHT_B = 3;
public static final int SOL_FORWARD = 0;
public static final int SOL_REVERSE = 1;
public static final boolean INV_LEFT_FRONT = false;
public static final boolean INV_LEFT_MID = false;
public static final boolean INV_LEFT_BACK = false;
public static final boolean INV_RIGHT_FRONT = false;
public static final boolean INV_RIGHT_MID = false;
public static final boolean INV_RIGHT_BACK = false;
public static final boolean INV_ENCODER_LEFT = false;
public static final boolean INV_ENCODER_RIGHT = false;
public static final double DISTANCE_PER_PULSE = 1; // TODO get distance
}
public class IntakeMap {
public static final int PWM_MOTOR = 4;
public static final boolean INV_MOTOR = false;
}
public class ArmMap {
public static final int PWM_MOTOR = 5;
public static final boolean INV_MOTOR = false;
public static final int DIO_ENCODER_A = 4;
public static final int DIO_ENCODER_B = 5;
public static final double DEGREES_PER_PULSE = 1; // TODO get degrees
public static final boolean INV_ENCODER = false;
public static final int DIO_LIMITSWITCH_TOP = 6;
public static final int DIO_LIMITSWITCH_BOTTOM = 7;
public static final int MAN_INCREMENT = 1; // TODO test, get arm speed
public class PID {
// TODO tune PID
public static final double kP = 1;
public static final double kI = .5;
public static final double kD = 17;
}
}
public class ControlMap {
// USB
public static final int PORT_STICK_LEFT = 0;
public static final int PORT_STICK_RIGHT = 1;
public static final int PORT_CONTROLLER = 2;
// Right stick
public static final int BUTTON_EJECT = 1;
public static final int BUTTON_SHIFT_DOWN = 2;
public static final int BUTTON_SHIFT_UP = 3;
// Left stick
public static final int BUTTON_INTAKE = 1;
public static final int BUTTON_INVERT_DRIVE = 2;
public static final int BUTTON_COCK = 4;
public static final int BUTTON_SHOOT = 5;
// Controller
public static final int BUTTON_ARM_DOWN = 2;
public static final int BUTTON_ARM_UP = 4;
}
public class ShooterMap {
public static final int PWM_MOTOR_LEFT = 6;
public static final boolean INV_MOTOR_LEFT = false;
public static final int PWM_MOTOR_RIGHT = 7;
public static final boolean INV_MOTOR_RIGHT = false;
public static final int DIO_ENCODER_A = 6;
public static final int DIO_ENCODER_B = 7;
public static final double DISTANCE_PER_PULSE = 1; // TODO get distance
public static final boolean INV_ENCODER = false;
public static final int SOL_FORWARD = 2;
public static final int SOL_REVERSE = 3;
}
}
|
package com.redhat.ceylon.eclipse.debug.ui.launchConfigurations;
import static com.redhat.ceylon.eclipse.imp.proposals.CeylonContentProposer.getDescriptionFor;
import static com.redhat.ceylon.eclipse.imp.proposals.CeylonContentProposer.getStyledDescriptionFor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchConfigurationType;
import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
import org.eclipse.debug.core.ILaunchManager;
import org.eclipse.debug.ui.DebugUITools;
import org.eclipse.debug.ui.IDebugModelPresentation;
import org.eclipse.debug.ui.ILaunchShortcut;
import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.DelegatingStyledCellLabelProvider;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StyledCellLabelProvider;
import org.eclipse.jface.viewers.StyledString;
import org.eclipse.jface.viewers.ViewerCell;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.dialogs.ElementListSelectionDialog;
import org.eclipse.ui.dialogs.FilteredItemsSelectionDialog;
import com.redhat.ceylon.compiler.typechecker.TypeChecker;
import com.redhat.ceylon.compiler.typechecker.context.PhasedUnit;
import com.redhat.ceylon.compiler.typechecker.model.Class;
import com.redhat.ceylon.compiler.typechecker.model.Declaration;
import com.redhat.ceylon.compiler.typechecker.model.Method;
import com.redhat.ceylon.eclipse.imp.builder.CeylonBuilder;
import com.redhat.ceylon.eclipse.imp.editor.Util;
import com.redhat.ceylon.eclipse.imp.outline.CeylonLabelProvider;
import com.redhat.ceylon.eclipse.launching.ICeylonLaunchConfigurationConstants;
import com.redhat.ceylon.eclipse.ui.CeylonPlugin;
import com.redhat.ceylon.eclipse.vfs.ResourceVirtualFile;
public class CeylonApplicationLaunchShortcut implements ILaunchShortcut {
@Override
public void launch(ISelection selection, String mode) {
if (! (selection instanceof IStructuredSelection)) {
return;
}
IStructuredSelection structuredSelection = (IStructuredSelection) selection;
List<IFile> files = new LinkedList<IFile>();
for (Object object : structuredSelection.toList()) {
if (object instanceof IAdaptable) {
IResource resource = (IResource) ((IAdaptable)object).getAdapter(IResource.class);
if (resource != null) {
addFiles(files, resource);
}
}
}
searchAndLaunch(files, mode);
}
public void addFiles(List<IFile> files, IResource resource) {
switch (resource.getType()) {
case IResource.FILE:
IFile file = (IFile) resource;
IPath path = file.getFullPath(); //getProjectRelativePath();
if (path!=null && CeylonBuilder.LANGUAGE.hasExtension(path.getFileExtension())) {
files.add(file);
}
break;
case IResource.FOLDER:
case IResource.PROJECT:
IContainer folder = (IContainer) resource;
try {
for (IResource child: folder.members()) {
addFiles(files, child);
}
}
catch (CoreException e) {
e.printStackTrace();
}
break;
}
}
@Override
public void launch(IEditorPart editor, String mode) {
IEditorInput input = editor.getEditorInput();
List<IFile> files = Arrays.asList(Util.getFile(input));
searchAndLaunch(files, mode);
}
private void searchAndLaunch(List<IFile> files, String mode) {
List<Declaration> topLevelDeclarations = new LinkedList<Declaration>();
List<IFile> correspondingfiles = new LinkedList<IFile>();
for (IFile file : files) {
IProject project = file.getProject();
TypeChecker typeChecker = CeylonBuilder.getProjectTypeChecker(project);
PhasedUnit phasedUnit = typeChecker.getPhasedUnits().getPhasedUnit(ResourceVirtualFile.createResourceVirtualFile(file));
if (phasedUnit!=null) {
List<Declaration> declarations = phasedUnit.getUnit().getDeclarations();
for (Declaration d : declarations) {
boolean candidateDeclaration = true;
if (! d.isToplevel() || ! d.isShared()) {
candidateDeclaration = false;
}
if (d instanceof Method) {
Method methodDecl = (Method) d;
if (!methodDecl.getParameterLists().isEmpty() &&
!methodDecl.getParameterLists().get(0).getParameters().isEmpty()) {
candidateDeclaration = false;
}
}
if (d instanceof Class) {
Class classDecl = (Class) d;
if (!classDecl.getParameterList().getParameters().isEmpty()) {
candidateDeclaration = false;
}
}
if (candidateDeclaration) {
topLevelDeclarations.add(d);
correspondingfiles.add(file);
}
}
}
}
Declaration declarationToRun = null;
IFile fileToRun = null;
if (topLevelDeclarations.size() == 0) {
MessageDialog.openError(CeylonBuilder.getShell(), "Ceylon Launcher", "No ceylon runnable element");
}
else if (topLevelDeclarations.size() > 1) {
declarationToRun = chooseDeclaration(topLevelDeclarations);
if (declarationToRun!=null) {
fileToRun = correspondingfiles.get(topLevelDeclarations.indexOf(declarationToRun));
}
}
else {
declarationToRun = topLevelDeclarations.get(0);
fileToRun = correspondingfiles.get(0);
}
if (declarationToRun != null) {
launch(declarationToRun, fileToRun, mode);
}
}
private static final String SETTINGS_ID = CeylonPlugin.PLUGIN_ID + ".TOPLEVEL_DECLARATION_SELECTION_DIALOG";
protected Declaration chooseDeclaration(final List<Declaration> declarations) {
FilteredItemsSelectionDialog sd = new FilteredItemsSelectionDialog(CeylonBuilder.getShell())
{
{
setTitle("Ceylon Launcher");
setMessage("Select the toplevel method or class to launch:");
setListLabelProvider(new LabelProvider());
setDetailsLabelProvider(new LabelProvider());
}
@Override
protected Control createExtendedContentArea(Composite parent) {
return null;
}
@Override
protected IDialogSettings getDialogSettings() {
IDialogSettings settings = CeylonPlugin.getInstance().getDialogSettings();
IDialogSettings section = settings.getSection(SETTINGS_ID);
if (section == null) {
section = settings.addNewSection(SETTINGS_ID);
}
return section;
}
@Override
protected IStatus validateItem(Object item) {
return Status.OK_STATUS;
}
@Override
protected ItemsFilter createFilter() {
return new ItemsFilter() {
@Override
public boolean matchItem(Object item) {
return matchesRawNamePattern(item);
}
@Override
public boolean isConsistentItem(Object item) {
return true;
}
@Override
public String getPattern() {
String pattern = super.getPattern();
return pattern.isEmpty() ? "**" : pattern;
}
};
}
@Override
protected Comparator getItemsComparator() {
Comparator comp = new Comparator() {
public int compare(Object o1, Object o2) {
if(o1 instanceof Declaration && o2 instanceof Declaration) {
return ((Declaration)o1).getName().compareTo(((Declaration)o2).getName());
}
return -1;
}
};
return comp;
}
@Override
protected void fillContentProvider(
AbstractContentProvider contentProvider,
ItemsFilter itemsFilter, IProgressMonitor progressMonitor)
throws CoreException {
if(declarations != null) {
for(Declaration d : declarations) {
if(itemsFilter.isConsistentItem(d)) {
contentProvider.add(d, itemsFilter);
}
}
}
}
@Override
public String getElementName(Object item) {
return ((Declaration) item).getName();
}
};
if (sd.open() == Window.OK) {
return (Declaration)sd.getResult()[0];
}
return null;
}
class LabelProvider extends StyledCellLabelProvider
implements DelegatingStyledCellLabelProvider.IStyledLabelProvider, ILabelProvider {
@Override
public void addListener(ILabelProviderListener listener) {}
@Override
public void dispose() {}
@Override
public boolean isLabelProperty(Object element, String property) {
return false;
}
@Override
public void removeListener(ILabelProviderListener listener) {}
@Override
public Image getImage(Object element) {
Declaration d = (Declaration) element;
return d==null ? null : CeylonLabelProvider.getImage(d);
}
@Override
public String getText(Object element) {
Declaration d = (Declaration) element;
return d==null ? null : getDescriptionFor(d);
}
@Override
public StyledString getStyledText(Object element) {
if (element==null) {
return new StyledString();
}
else {
Declaration d = (Declaration) element;
return getStyledDescriptionFor(d);
}
}
@Override
public void update(ViewerCell cell) {
Object element = cell.getElement();
if (element!=null) {
StyledString styledText = getStyledText(element);
cell.setText(styledText.toString());
cell.setStyleRanges(styledText.getStyleRanges());
cell.setImage(getImage(element));
super.update(cell);
}
}
}
private void launch(Declaration declarationToRun, IFile fileToRun, String mode) {
ILaunchConfiguration config = findLaunchConfiguration(declarationToRun, fileToRun, getConfigurationType());
if (config == null) {
config = createConfiguration(declarationToRun, fileToRun);
}
if (config != null) {
DebugUITools.launch(config, mode);
}
}
protected ILaunchConfigurationType getConfigurationType() {
return getLaunchManager().getLaunchConfigurationType(ICeylonLaunchConfigurationConstants.ID_CEYLON_APPLICATION);
}
private ILaunchManager getLaunchManager() {
return DebugPlugin.getDefault().getLaunchManager();
}
/**
* Finds and returns an <b>existing</b> configuration to re-launch for the given type,
* or <code>null</code> if there is no existing configuration.
*
* @return a configuration to use for launching the given type or <code>null</code> if none
*/
protected ILaunchConfiguration findLaunchConfiguration(Declaration declaration, IFile file, ILaunchConfigurationType configType) {
List candidateConfigs = Collections.EMPTY_LIST;
try {
ILaunchConfiguration[] configs = DebugPlugin.getDefault().getLaunchManager().getLaunchConfigurations(configType);
candidateConfigs = new ArrayList(configs.length);
for (int i = 0; i < configs.length; i++) {
ILaunchConfiguration config = configs[i];
if (config.getAttribute(IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME, "").equals(declaration.getQualifiedNameString())) {
if (config.getAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, "").equals(file.getProject().getName())) {
candidateConfigs.add(config);
}
}
}
} catch (CoreException e) {
e.printStackTrace(); // TODO : Use a logger
}
int candidateCount = candidateConfigs.size();
if (candidateCount == 1) {
return (ILaunchConfiguration) candidateConfigs.get(0);
} else if (candidateCount > 1) {
return chooseConfiguration(candidateConfigs);
}
return null;
}
/**
* Returns a configuration from the given collection of configurations that should be launched,
* or <code>null</code> to cancel. Default implementation opens a selection dialog that allows
* the user to choose one of the specified launch configurations. Returns the chosen configuration,
* or <code>null</code> if the user cancels.
*
* @param configList list of configurations to choose from
* @return configuration to launch or <code>null</code> to cancel
*/
protected ILaunchConfiguration chooseConfiguration(List configList) {
IDebugModelPresentation labelProvider = DebugUITools.newDebugModelPresentation();
ElementListSelectionDialog dialog= new ElementListSelectionDialog(CeylonBuilder.getShell(), labelProvider);
dialog.setElements(configList.toArray());
dialog.setTitle("Ceylon Launcher");
dialog.setMessage("Please choose a configuration to start the Ceylon application");
dialog.setMultipleSelection(false);
int result = dialog.open();
labelProvider.dispose();
if (result == Window.OK) {
return (ILaunchConfiguration) dialog.getFirstResult();
}
return null;
}
protected ILaunchConfiguration createConfiguration(Declaration declarationToRun, IFile file) {
ILaunchConfiguration config = null;
ILaunchConfigurationWorkingCopy wc = null;
try {
ILaunchConfigurationType configType = getConfigurationType();
wc = configType.newInstance(null, getLaunchManager().generateLaunchConfigurationName(declarationToRun.getQualifiedNameString()));
wc.setAttribute(IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME, declarationToRun.getQualifiedNameString());
wc.setAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, file.getProject().getName());
wc.setMappedResources(new IResource[] {file});
config = wc.doSave();
} catch (CoreException exception) {
MessageDialog.openError(CeylonBuilder.getShell(), "Ceylon Launcher Error", exception.getStatus().getMessage());
}
return config;
}
}
|
package org.eclipse.che.ide.extension.machine.client;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import com.google.web.bindery.event.shared.EventBus;
import org.eclipse.che.api.machine.gwt.client.events.WsAgentStateEvent;
import org.eclipse.che.api.machine.gwt.client.events.WsAgentStateHandler;
import org.eclipse.che.ide.actions.CreateSnapshotAction;
import org.eclipse.che.ide.actions.StopMachineAction;
import org.eclipse.che.ide.actions.StopWorkspaceAction;
import org.eclipse.che.ide.api.action.ActionManager;
import org.eclipse.che.ide.api.action.DefaultActionGroup;
import org.eclipse.che.ide.api.action.IdeActions;
import org.eclipse.che.ide.api.constraints.Constraints;
import org.eclipse.che.ide.api.extension.Extension;
import org.eclipse.che.ide.api.icon.Icon;
import org.eclipse.che.ide.api.icon.IconRegistry;
import org.eclipse.che.ide.api.keybinding.KeyBindingAgent;
import org.eclipse.che.ide.api.keybinding.KeyBuilder;
import org.eclipse.che.ide.api.parts.PartStackType;
import org.eclipse.che.ide.api.parts.PerspectiveManager;
import org.eclipse.che.ide.api.parts.WorkspaceAgent;
import org.eclipse.che.ide.extension.machine.client.actions.CreateMachineAction;
import org.eclipse.che.ide.extension.machine.client.actions.DestroyMachineAction;
import org.eclipse.che.ide.extension.machine.client.actions.EditCommandsAction;
import org.eclipse.che.ide.extension.machine.client.actions.ExecuteSelectedCommandAction;
import org.eclipse.che.ide.extension.machine.client.actions.NewTerminalAction;
import org.eclipse.che.ide.extension.machine.client.actions.RestartMachineAction;
import org.eclipse.che.ide.extension.machine.client.actions.RunCommandAction;
import org.eclipse.che.ide.extension.machine.client.actions.SelectCommandComboBoxReady;
import org.eclipse.che.ide.extension.machine.client.actions.SwitchPerspectiveAction;
import org.eclipse.che.ide.extension.machine.client.command.custom.CustomCommandType;
import org.eclipse.che.ide.extension.machine.client.command.valueproviders.ServerPortProvider;
import org.eclipse.che.ide.extension.machine.client.machine.console.ClearConsoleAction;
import org.eclipse.che.ide.extension.machine.client.machine.console.MachineConsoleToolbar;
import org.eclipse.che.ide.extension.machine.client.outputspanel.OutputsContainerPresenter;
import org.eclipse.che.ide.extension.machine.client.processes.ConsolesPanelPresenter;
import org.eclipse.che.ide.ui.toolbar.ToolbarPresenter;
import org.eclipse.che.ide.util.input.KeyCodeMap;
import static org.eclipse.che.ide.api.action.IdeActions.GROUP_CENTER_TOOLBAR;
import static org.eclipse.che.ide.api.action.IdeActions.GROUP_MAIN_MENU;
import static org.eclipse.che.ide.api.action.IdeActions.GROUP_RIGHT_TOOLBAR;
import static org.eclipse.che.ide.api.action.IdeActions.GROUP_RUN;
import static org.eclipse.che.ide.api.action.IdeActions.GROUP_WORKSPACE;
import static org.eclipse.che.ide.api.constraints.Anchor.AFTER;
import static org.eclipse.che.ide.api.constraints.Constraints.FIRST;
import static org.eclipse.che.ide.workspace.perspectives.project.ProjectPerspective.PROJECT_PERSPECTIVE_ID;
/**
* Machine extension entry point.
*
* @author Artem Zatsarynnyi
* @author Dmitry Shnurenko
*/
@Singleton
@Extension(title = "Machine", version = "1.0.0")
public class MachineExtension {
public static final String GROUP_MACHINE_CONSOLE_TOOLBAR = "MachineConsoleToolbar";
public static final String GROUP_MACHINE_TOOLBAR = "MachineGroupToolbar";
public static final String GROUP_COMMANDS_LIST = "CommandsListGroup";
public static final String GROUP_COMMANDS_LIST_DISPLAY_NAME = "Run";
@Inject
public MachineExtension(MachineResources machineResources,
final EventBus eventBus,
final WorkspaceAgent workspaceAgent,
final ConsolesPanelPresenter consolesPanelPresenter,
final Provider<ServerPortProvider> machinePortProvider,
final OutputsContainerPresenter outputsContainerPresenter,
final PerspectiveManager perspectiveManager,
IconRegistry iconRegistry,
CustomCommandType arbitraryCommandType) {
machineResources.getCss().ensureInjected();
eventBus.addHandler(WsAgentStateEvent.TYPE, new WsAgentStateHandler() {
@Override
public void onWsAgentStarted(WsAgentStateEvent event) {
machinePortProvider.get();
perspectiveManager.setPerspectiveId(PROJECT_PERSPECTIVE_ID);
workspaceAgent.openPart(outputsContainerPresenter, PartStackType.INFORMATION);
workspaceAgent.openPart(consolesPanelPresenter, PartStackType.INFORMATION);
}
@Override
public void onWsAgentStopped(WsAgentStateEvent event) {
}
});
iconRegistry.registerIcon(new Icon(arbitraryCommandType.getId() + ".commands.category.icon", machineResources.customCommandType()));
}
@Inject
private void prepareActions(MachineLocalizationConstant localizationConstant,
ActionManager actionManager,
KeyBindingAgent keyBinding,
NewTerminalAction newTerminalAction,
ExecuteSelectedCommandAction executeSelectedCommandAction,
SelectCommandComboBoxReady selectCommandAction,
EditCommandsAction editCommandsAction,
CreateMachineAction createMachine,
RestartMachineAction restartMachine,
DestroyMachineAction destroyMachineAction,
StopWorkspaceAction stopWorkspaceAction,
StopMachineAction stopMachineAction,
SwitchPerspectiveAction switchPerspectiveAction,
CreateSnapshotAction createSnapshotAction,
RunCommandAction runCommandAction) {
final DefaultActionGroup mainMenu = (DefaultActionGroup)actionManager.getAction(GROUP_MAIN_MENU);
final DefaultActionGroup workspaceMenu = (DefaultActionGroup)actionManager.getAction(GROUP_WORKSPACE);
final DefaultActionGroup runMenu = (DefaultActionGroup)actionManager.getAction(GROUP_RUN);
// register actions
actionManager.registerAction("editCommands", editCommandsAction);
actionManager.registerAction("selectCommandAction", selectCommandAction);
actionManager.registerAction("executeSelectedCommand", executeSelectedCommandAction);
// add actions in main menu
runMenu.add(editCommandsAction);
//add actions in machine menu
final DefaultActionGroup machineMenu = new DefaultActionGroup(localizationConstant.mainMenuMachine(), true, actionManager);
actionManager.registerAction("machine", machineMenu);
actionManager.registerAction("createMachine", createMachine);
actionManager.registerAction("destroyMachine", destroyMachineAction);
actionManager.registerAction("restartMachine", restartMachine);
actionManager.registerAction("stopWorkspace", stopWorkspaceAction);
actionManager.registerAction("stopMachine", stopMachineAction);
actionManager.registerAction("createSnapshot", createSnapshotAction);
actionManager.registerAction("runCommand", runCommandAction);
actionManager.registerAction("newTerminal", newTerminalAction);
workspaceMenu.add(stopWorkspaceAction);
mainMenu.add(machineMenu, new Constraints(AFTER, IdeActions.GROUP_PROJECT));
machineMenu.add(createMachine);
machineMenu.add(restartMachine);
machineMenu.add(destroyMachineAction);
machineMenu.add(stopMachineAction);
machineMenu.add(createSnapshotAction);
// add actions on center part of toolbar
final DefaultActionGroup centerToolbarGroup = (DefaultActionGroup)actionManager.getAction(GROUP_CENTER_TOOLBAR);
final DefaultActionGroup machineToolbarGroup = new DefaultActionGroup(GROUP_MACHINE_TOOLBAR, false, actionManager);
actionManager.registerAction(GROUP_MACHINE_TOOLBAR, machineToolbarGroup);
centerToolbarGroup.add(machineToolbarGroup);
machineToolbarGroup.add(selectCommandAction);
final DefaultActionGroup executeToolbarGroup = new DefaultActionGroup(actionManager);
executeToolbarGroup.add(executeSelectedCommandAction);
machineToolbarGroup.add(executeToolbarGroup);
// add actions on right part of toolbar
final DefaultActionGroup rightToolbarGroup = (DefaultActionGroup)actionManager.getAction(GROUP_RIGHT_TOOLBAR);
rightToolbarGroup.add(switchPerspectiveAction);
// add group for command list
final DefaultActionGroup commandList = new DefaultActionGroup(GROUP_COMMANDS_LIST_DISPLAY_NAME, true, actionManager);
actionManager.registerAction(GROUP_COMMANDS_LIST, commandList);
commandList.add(editCommandsAction, FIRST);
final DefaultActionGroup runContextGroup = (DefaultActionGroup)actionManager.getAction(IdeActions.GROUP_RUN_CONTEXT_MENU);
runContextGroup.add(commandList);
runContextGroup.addSeparator();
// Define hot-keys
keyBinding.getGlobal().addKey(new KeyBuilder().alt().charCode(KeyCodeMap.F12).build(), "newTerminal");
}
@Inject
private void setUpMachineConsole(ActionManager actionManager,
ClearConsoleAction clearConsoleAction,
@MachineConsoleToolbar ToolbarPresenter machineConsoleToolbar) {
// add toolbar to Machine console
final DefaultActionGroup consoleToolbarActionGroup = new DefaultActionGroup(GROUP_MACHINE_CONSOLE_TOOLBAR, false, actionManager);
consoleToolbarActionGroup.add(clearConsoleAction);
consoleToolbarActionGroup.addSeparator();
machineConsoleToolbar.bindMainGroup(consoleToolbarActionGroup);
}
}
|
package org.wikipedia.servlets;
import java.io.*;
import java.util.*;
import javax.swing.JOptionPane;
import javax.servlet.*;
import javax.servlet.http.*;
import org.wikipedia.Wiki;
/**
* A crude replacement for Eagle's cross-wiki linksearch tool.
* @author MER-C
* @version 0.02
*/
public class XWikiLinksearch extends HttpServlet
{
// wiki groups
public static final Wiki[] top20wikis, top40wikis, importantwikis;
/**
* Initializes wiki groups.
*/
static
{
// top 20 Wikipedias
String[] temp = { "en", "de", "fr", "nl", "it", "pl", "es", "ru", "ja", "pt",
"zh", "sv", "vi", "uk", "ca", "no", "fi", "cs", "hu", "fa" };
top20wikis = new Wiki[20];
for (int i = 0; i < temp.length; i++)
{
top20wikis[i] = new Wiki(temp[i] + ".wikipedia.org");
top20wikis[i].setUsingCompressedRequests(false); // This is Google's fault.
top20wikis[i].setMaxLag(-1);
}
// top 40 Wikipedias
top40wikis = new Wiki[40];
System.arraycopy(top20wikis, 0, top40wikis, 0, 20);
temp = new String[] { "ro", "ko", "ar", "tr", "id", "sk", "eo", "da", "sr", "kk",
"lt", "ms", "he", "bg", "eu", "sl", "vo", "hr", "war", "hi" };
for (int i = 20; i < temp.length; i++)
{
top40wikis[i] = new Wiki(temp[i - 20] + ".wikipedia.org");
top40wikis[i].setUsingCompressedRequests(false); // This is Google's fault.
top40wikis[i].setMaxLag(-1);
}
// a collection of important wikis
temp = new String[] { "en", "de", "fr" };
importantwikis = new Wiki[17];
for (int i = 0; i < temp.length; i++)
{
importantwikis[5 * i ] = new Wiki(temp[i] + ".wikipedia.org");
importantwikis[5 * i + 1] = new Wiki(temp[i] + ".wiktionary.org");
importantwikis[5 * i + 2] = new Wiki(temp[i] + ".wikibooks.org");
importantwikis[5 * i + 3] = new Wiki(temp[i] + ".wikiquote.org");
importantwikis[5 * i + 4] = new Wiki(temp[i] + ".wikivoyage.org");
}
// not a typo, fr.wikivoyage does not exist yet
importantwikis[14] = new Wiki("meta.wikimedia.org");
importantwikis[15] = new Wiki("commons.wikimedia.org");
importantwikis[16] = new Wiki("mediawiki.org");
for (int i = 0; i < importantwikis.length; i++)
{
importantwikis[i].setUsingCompressedRequests(false);
importantwikis[i].setMaxLag(-1);
}
}
/**
* Main for testing/offline stuff. The results are found in results.html,
* which is in either the current or home directory.
*/
public static void main(String[] args) throws IOException
{
OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream("results.html"), "UTF-8");
String domain = JOptionPane.showInputDialog(null, "Enter domain to search");
if (domain == null)
System.exit(0);
StringBuilder builder = new StringBuilder(10000);
linksearch(domain, builder, top40wikis);
linksearch(domain, builder, importantwikis);
out.write(builder.toString());
out.close();
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html; charset=UTF-8");
PrintWriter out = response.getWriter();
StringBuilder buffer = new StringBuilder(10000);
// header
buffer.append("<!doctype html>\n<html>\n<head>\n<title>Cross-wiki linksearch</title>");
buffer.append("\n</head>\n\n<body>\n<p>This tool searches various Wikimedia projects for a ");
buffer.append("specific link. Enter a domain name (example.com, not *.example.com or ");
buffer.append("http://example.com) below. This process takes up to 20 seconds.\n");
String domain = request.getParameter("link");
String set = request.getParameter("set");
buffer.append("<form action=\"./linksearch.jsp\" method=GET>\n");
// wiki set combo box
buffer.append("<table>");
buffer.append("<tr><td>Wikis to search:\n<td>");
LinkedHashMap<String, String> options = new LinkedHashMap<String, String>(10);
options.put("top20", "Top 20 Wikipedias");
options.put("top40", "Top 40 Wikipedias");
options.put("major", "Major Wikimedia projects");
buffer.append(ServletUtils.generateComboBox("set", options, set));
// domain name text box
buffer.append("<tr><td>Domain to search: <td><input type=text name=link");
if (domain != null)
{
buffer.append(" value=\"");
buffer.append(ServletUtils.sanitize(domain));
buffer.append("\"");
}
buffer.append(">\n</table>\n<input type=submit value=\"Search\">\n</form>\n");
if (domain != null)
{
try
{
if (set == null || set.equals("top20"))
linksearch(domain, buffer, top20wikis);
else if (set.equals("top40"))
linksearch(domain, buffer, top40wikis);
else if (set.equals("major"))
linksearch(domain, buffer, importantwikis);
else
buffer.append("ERROR: Invalid wiki set.");
}
catch (IOException ex)
{
buffer.append(ex.toString());
}
}
// put a footer
buffer.append("<br><br>");
buffer.append(ServletUtils.generateFooter("Cross-wiki linksearch tool"));
out.write(buffer.toString());
out.close();
}
public static void linksearch(String domain, StringBuilder buffer, Wiki[] wikis) throws IOException
{
buffer.append("<hr>\n<h2>Searching for links to ");
buffer.append(ServletUtils.sanitize(domain));
buffer.append(".\n");
for (Wiki wiki : wikis)
{
ArrayList[] temp = wiki.linksearch("*." + domain, "http");
// silly api designs aplenty here!
ArrayList[] temp2 = wiki.linksearch("*." + domain, "https");
temp[0].addAll(temp2[0]);
temp[1].addAll(temp2[1]);
buffer.append("<h3>Results for ");
buffer.append(wiki.getDomain());
buffer.append(":</h3>\n<p><ol>\n");
for (int j = 0; j < temp[0].size(); j++)
{
buffer.append("<li><a href=\"
buffer.append(wiki.getDomain());
buffer.append("/wiki/");
buffer.append((String)temp[0].get(j));
buffer.append("\">");
buffer.append((String)temp[0].get(j));
buffer.append("</a> uses link <a href=\"");
buffer.append(temp[1].get(j).toString());
buffer.append("\">");
buffer.append(temp[1].get(j).toString());
buffer.append("</a>\n");
}
buffer.append("</ol>\n<p>");
buffer.append(temp[0].size());
buffer.append(" links found. (<a href=\"
buffer.append(wiki.getDomain());
|
package com.speedment.runtime.connector.sqlite.internal;
import com.speedment.runtime.config.Column;
import com.speedment.runtime.core.db.DbmsColumnHandler;
import java.util.function.Predicate;
/**
* Implementation of {@link DbmsColumnHandler} for SQLite databases.
*
* @author Emil Forslund
* @since 3.1.10
*/
public final class SqliteColumnHandler implements DbmsColumnHandler {
@Override
public Predicate<Column> excludedInInsertStatement() {
return col -> false;
}
@Override
public Predicate<Column> excludedInUpdateStatement() {
return col -> false;
}
}
|
package org.eclipse.birt.report.designer.internal.ui.editors.schematic.editparts;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.birt.report.designer.core.DesignerConstants;
import org.eclipse.birt.report.designer.core.commands.DeleteColumnCommand;
import org.eclipse.birt.report.designer.core.commands.DeleteRowCommand;
import org.eclipse.birt.report.designer.core.model.ITableAdapterHelper;
import org.eclipse.birt.report.designer.core.model.SessionHandleAdapter;
import org.eclipse.birt.report.designer.core.model.schematic.ColumnHandleAdapter;
import org.eclipse.birt.report.designer.core.model.schematic.HandleAdapterFactory;
import org.eclipse.birt.report.designer.core.model.schematic.RowHandleAdapter;
import org.eclipse.birt.report.designer.core.model.schematic.TableHandleAdapter;
import org.eclipse.birt.report.designer.core.util.mediator.request.ReportRequest;
import org.eclipse.birt.report.designer.internal.ui.editors.parts.DeferredGraphicalViewer;
import org.eclipse.birt.report.designer.internal.ui.editors.schematic.actions.EditGroupAction;
import org.eclipse.birt.report.designer.internal.ui.editors.schematic.border.BaseBorder;
import org.eclipse.birt.report.designer.internal.ui.editors.schematic.border.SectionBorder;
import org.eclipse.birt.report.designer.internal.ui.editors.schematic.editpolicies.ReportComponentEditPolicy;
import org.eclipse.birt.report.designer.internal.ui.editors.schematic.editpolicies.ReportContainerEditPolicy;
import org.eclipse.birt.report.designer.internal.ui.editors.schematic.editpolicies.TableXYLayoutEditPolicy;
import org.eclipse.birt.report.designer.internal.ui.editors.schematic.figures.TableFigure;
import org.eclipse.birt.report.designer.internal.ui.editors.schematic.handles.AbstractGuideHandle;
import org.eclipse.birt.report.designer.internal.ui.editors.schematic.handles.TableGuideHandle;
import org.eclipse.birt.report.designer.internal.ui.editors.schematic.layer.TableBorderLayer;
import org.eclipse.birt.report.designer.internal.ui.editors.schematic.layer.TableGridLayer;
import org.eclipse.birt.report.designer.internal.ui.layout.TableLayout;
import org.eclipse.birt.report.designer.internal.ui.util.ExceptionHandler;
import org.eclipse.birt.report.designer.internal.ui.util.UIUtil;
import org.eclipse.birt.report.designer.nls.Messages;
import org.eclipse.birt.report.designer.ui.IReportGraphicConstants;
import org.eclipse.birt.report.designer.ui.ReportPlatformUIImages;
import org.eclipse.birt.report.designer.ui.ReportPlugin;
import org.eclipse.birt.report.model.api.CellHandle;
import org.eclipse.birt.report.model.api.ColumnHandle;
import org.eclipse.birt.report.model.api.DesignElementHandle;
import org.eclipse.birt.report.model.api.ListingHandle;
import org.eclipse.birt.report.model.api.ReportItemHandle;
import org.eclipse.birt.report.model.api.RowHandle;
import org.eclipse.birt.report.model.api.StyleHandle;
import org.eclipse.birt.report.model.api.TableGroupHandle;
import org.eclipse.birt.report.model.api.TableHandle;
import org.eclipse.birt.report.model.api.activity.NotificationEvent;
import org.eclipse.birt.report.model.api.activity.SemanticException;
import org.eclipse.birt.report.model.api.command.ContentEvent;
import org.eclipse.birt.report.model.api.command.ContentException;
import org.eclipse.birt.report.model.api.command.NameException;
import org.eclipse.birt.report.model.api.command.PropertyEvent;
import org.eclipse.draw2d.FreeformLayer;
import org.eclipse.draw2d.FreeformLayeredPane;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.LayeredPane;
import org.eclipse.draw2d.XYLayout;
import org.eclipse.draw2d.geometry.Dimension;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.EditPolicy;
import org.eclipse.gef.LayerConstants;
import org.eclipse.gef.Request;
import org.eclipse.gef.RequestConstants;
import org.eclipse.gef.editparts.GridLayer;
import org.eclipse.gef.editparts.GuideLayer;
import org.eclipse.gef.editparts.LayerManager;
import org.eclipse.gef.requests.GroupRequest;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.widgets.Display;
/**
* <p>
* Table EditPart,control the UI & model of table
* </p>
*
*/
public class TableEditPart extends ReportElementEditPart implements
LayerConstants,
ITableAdapterHelper
{
public static final String BORDER_LAYER = "Table Border layer"; //$NON-NLS-1$
private static final String RESIZE_COLUMN_TRANS_LABEL = Messages.getString( "TableEditPart.Label.ResizeColumn" ); //$NON-NLS-1$
private static final String MERGE_TRANS_LABEL = Messages.getString( "TableEditPart.Label.Merge" ); //$NON-NLS-1$
private static final String GUIDEHANDLE_TEXT = Messages.getString( "TableEditPart.GUIDEHANDLE_TEXT" ); //$NON-NLS-1$
protected FreeformLayeredPane innerLayers;
protected LayeredPane printableLayers;
private Rectangle selectRowAndColumnRect = null;
/**
* Constructor
*
* @param obj
*/
public TableEditPart( Object obj )
{
super( obj );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.designer.internal.ui.editors.schematic.editparts.ReportElementEditPart#createGuideHandle()
*/
protected AbstractGuideHandle createGuideHandle( )
{
TableGuideHandle handle = new TableGuideHandle( this );
handle.setIndicatorLabel( GUIDEHANDLE_TEXT );
handle.setIndicatorIcon( ReportPlatformUIImages.getImage( IReportGraphicConstants.ICON_ELEMENT_TABLE ) );
return handle;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.gef.EditPart#activate()
*/
public void activate( )
{
super.activate( );
addListenerToChildren( );
}
/*
* s (non-Javadoc)
*
* @see org.eclipse.gef.EditPart#deactivate()
*/
public void deactivate( )
{
super.deactivate( );
removeRowListener( );
removeColumnListener( );
removeGroupListener();
}
private void removeGroupListener( )
{
if(getModel() instanceof ListingHandle)
{
for ( Iterator it = ( (ListingHandle) getModel( ) ).getGroups( )
.iterator( ); it.hasNext( ); )
{
( (DesignElementHandle) it.next( ) ).removeListener( this );
}
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.gef.editparts.AbstractGraphicalEditPart#createFigure()
*/
protected IFigure createFigure( )
{
TableFigure viewport = new TableFigure( );
viewport.setOpaque( false );
innerLayers = new FreeformLayeredPane( );
createLayers( innerLayers );
viewport.setContents( innerLayers );
return viewport;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.gef.editparts.AbstractEditPart#createEditPolicies()
*/
protected void createEditPolicies( )
{
installEditPolicy( EditPolicy.COMPONENT_ROLE,
new ReportComponentEditPolicy( ) );
installEditPolicy( EditPolicy.CONTAINER_ROLE,
new ReportContainerEditPolicy( ) );
//should add highlight policy
//installEditPolicy(EditPolicy.SELECTION_FEEDBACK_ROLE, new
// ContainerHighlightEditPolicy());
installEditPolicy( EditPolicy.LAYOUT_ROLE,
new TableXYLayoutEditPolicy( (XYLayout) getContentPane( ).getLayoutManager( ) ) );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.gef.editparts.AbstractEditPart#getModelChildren()
*/
protected List getModelChildren( )
{
return getTableAdapter( ).getChildren( );
}
protected void addRowListener( )
{
List list = getRows( );
int size = list.size( );
for ( int i = 0; i < size; i++ )
{
RowHandle hanlde = (RowHandle) list.get( i );
hanlde.addListener( this );
}
}
protected void addColumnListener( )
{
List list = getColumns( );
int size = list.size( );
for ( int i = 0; i < size; i++ )
{
( (ColumnHandle) list.get( i ) ).addListener( this );
}
}
protected void removeColumnListener( )
{
List list = getColumns( );
int size = list.size( );
for ( int i = 0; i < size; i++ )
{
( (ColumnHandle) list.get( i ) ).removeListener( this );
}
}
protected void removeRowListener( )
{
List list = getRows( );
int size = list.size( );
for ( int i = 0; i < size; i++ )
{
( (RowHandle) list.get( i ) ).removeListener( this );
}
}
public void elementChanged( DesignElementHandle focus, NotificationEvent ev )
{
if ( !isActive( ) )
{
return;
}
switch ( ev.getEventType( ) )
{
case NotificationEvent.CONTENT_EVENT :
{
markDirty( true );
if ( focus instanceof TableHandle
|| focus instanceof TableGroupHandle )
{
addListenerToChildren( );
}
refreshChildren( );
refreshVisuals( );
if ( ( (ContentEvent) ev ).getAction( ) == ContentEvent.REMOVE )
{
//this.getViewer( ).select( this );
reselectTable();
}
break;
}
case NotificationEvent.PROPERTY_EVENT :
{
markDirty( true );
reLayout( );
PropertyEvent event = (PropertyEvent) ev;
if ( event.getPropertyName( ).startsWith( "border" ) )//$NON-NLS-1$
{
refreshVisuals( );
}
if ( event.getPropertyName( ).equals( StyleHandle.PADDING_TOP_PROP )
|| event.getPropertyName( )
.equals( StyleHandle.PADDING_BOTTOM_PROP )
|| event.getPropertyName( )
.equals( StyleHandle.PADDING_LEFT_PROP )
|| event.getPropertyName( )
.equals( StyleHandle.PADDING_RIGHT_PROP ) )
{
invalidParent( );
}
if ( event.getPropertyName( ).equals( ReportItemHandle.WIDTH_PROP )
|| event.getPropertyName( )
.equals( ReportItemHandle.HEIGHT_PROP ) )
{
invalidParent( );
}
refresh( );
break;
}
case NotificationEvent.ELEMENT_DELETE_EVENT :
case NotificationEvent.LAYOUT_CHANGED_EVENT :
{
markDirty( true );
refresh( );
break;
}
case NotificationEvent.STYLE_EVENT :
{
markDirty( true );
invalidParent( );
refresh( );
}
default :
break;
}
}
private void reselectTable()
{
if (isDelete())
{
return;
}
ReportRequest request = new ReportRequest( this );
List list = new ArrayList( );
list.add(this);
request.setSelectionObject( list );
request.setType( ReportRequest.SELECTION );
request.setRequestConvert( new DeferredGraphicalViewer.EditorReportRequestConvert( ) );
// SessionHandleAdapter.getInstance().getMediator().pushState();
SessionHandleAdapter.getInstance( )
.getMediator( )
.notifyRequest( request );
}
/**
* Re-layouts table.
*/
public void reLayout( )
{
getFigure( ).invalidateTree( );
getFigure( ).getUpdateManager( ).addInvalidFigure( getFigure( ) );
}
protected void invalidParent( )
{
getFigure( ).getParent( ).revalidate( );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.gef.editparts.AbstractEditPart#refreshChildren()
*/
protected void refreshChildren( )
{
super.refreshChildren( );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.gef.EditPart#performRequest(org.eclipse.gef.Request)
*/
public void performRequest( Request request )
{
if ( RequestConstants.REQ_OPEN.equals( request.getType( ) ) )
{
Object obj = request.getExtendedData( )
.get( DesignerConstants.TABLE_ROW_NUMBER );
if ( obj != null )
{
int rowNum = ( (Integer) obj ).intValue( );
RowHandle row = (RowHandle) getRow( rowNum );
if ( row.getContainer( ) instanceof TableGroupHandle )
{
IAction action = new EditGroupAction( null,
(TableGroupHandle) row.getContainer( ) );
if ( action.isEnabled( ) )
{
action.run( );
}
}
}
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.designer.internal.ui.editors.schematic.editparts.AbstractReportEditPart#refreshFigure()
*/
public void refreshFigure( )
{
refreshBorder( getTableAdapter( ).getHandle( ),
(BaseBorder) getFigure( ).getBorder( ) );
( (SectionBorder) ( getFigure( ).getBorder( ) ) ).setPaddingInsets( getTableAdapter( ).getPadding( getFigure( ).getInsets( ) ) );
refreshBackground( (DesignElementHandle) getModel( ) );
refreshMargin( );
for ( Iterator itr = getChildren( ).iterator( ); itr.hasNext( ); )
{
TableCellEditPart fg = (TableCellEditPart) itr.next( );
fg.updateBlankString( );
}
}
/**
* Gets the top, left, right, bottom of edit part.
*
* @param parts
* @return cell edit parts.
*/
public TableCellEditPart[] getMinAndMaxNumber( TableCellEditPart[] parts )
{
if ( parts == null || parts.length == 0 )
{
return null;
}
int size = parts.length;
TableCellEditPart leftTopPart = parts[0];
TableCellEditPart leftBottomPart = parts[0];
TableCellEditPart rightBottomPart = parts[0];
TableCellEditPart rightTopPart = parts[0];
for ( int i = 1; i < size; i++ )
{
TableCellEditPart part = parts[i];
if ( part == null )
{
continue;
}
if ( part.getRowNumber( ) <= leftTopPart.getRowNumber( )
&& part.getColumnNumber( ) <= leftTopPart.getColumnNumber( ) )
{
leftTopPart = part;
}
if ( part.getRowNumber( ) <= rightTopPart.getRowNumber( )
&& part.getColumnNumber( ) + part.getColSpan( ) - 1 >= leftTopPart.getColumnNumber( ) )
{
rightTopPart = part;
}
if ( part.getColumnNumber( ) <= leftBottomPart.getColumnNumber( )
&& part.getRowNumber( ) + part.getRowSpan( ) - 1 >= leftBottomPart.getRowNumber( ) )
{
leftBottomPart = part;
}
if ( part.getRowNumber( ) + part.getRowSpan( ) - 1 >= rightBottomPart.getRowNumber( )
&& part.getColumnNumber( ) + part.getColSpan( ) - 1 >= rightBottomPart.getColumnNumber( ) )
{
rightBottomPart = part;
}
}
return new TableCellEditPart[]{
leftTopPart, rightTopPart, leftBottomPart, rightBottomPart
};
}
/**
* Returns the layer indicated by the key. Searches all layered panes.
*
* @see LayerManager#getLayer(Object)
*/
public IFigure getLayer( Object key )
{
if ( innerLayers == null )
return null;
IFigure layer = innerLayers.getLayer( key );
if ( layer != null )
return layer;
if ( printableLayers == null )
return null;
return printableLayers.getLayer( key );
}
/**
* Creates the top-most set of layers on the given layered pane.
*
* @param layeredPane
* the parent for the created layers
*/
protected void createLayers( LayeredPane layeredPane )
{
layeredPane.add( createGridLayer( ), GRID_LAYER );
layeredPane.add( getPrintableLayers( ), PRINTABLE_LAYERS );
layeredPane.add( new FreeformLayer( ), HANDLE_LAYER );
layeredPane.add( new GuideLayer( ), GUIDE_LAYER );
}
/**
* Creates a {@link GridLayer grid}. Sub-classes can override this method
* to customize the appearance of the grid. The grid layer should be the
* first layer (i.e., beneath the primary layer) if it is not to cover up
* parts on the primary layer. In that case, the primary layer should be
* transparent so that the grid is visible.
*
* @return the newly created GridLayer
*/
protected GridLayer createGridLayer( )
{
GridLayer grid = new TableGridLayer( this );
grid.setOpaque( false );
return grid;
}
/**
* Creates a layered pane and the layers that should be printed.
*
* @see org.eclipse.gef.print.PrintGraphicalViewerOperation
* @return a new LayeredPane containing the printable layers
*/
protected LayeredPane createPrintableLayers( )
{
FreeformLayeredPane layeredPane = new FreeformLayeredPane( );
FreeformLayer layer = new FreeformLayer( );
layer.setLayoutManager( new TableLayout( this ) );
layeredPane.add( layer, PRIMARY_LAYER );
layeredPane.add( new TableBorderLayer( this ), BORDER_LAYER );
return layeredPane;
}
/**
* this layer may be a un-useful layer.
*
* @return the layered pane containing all printable content
*/
protected LayeredPane getPrintableLayers( )
{
if ( printableLayers == null )
printableLayers = createPrintableLayers( );
return printableLayers;
}
/**
* Resets size of column.
*
* @param start
* @param end
* @param value
*/
public void resizeColumn( int start, int end, int value )
{
Object startColumn = getColumn( start );
ColumnHandleAdapter startAdapt = HandleAdapterFactory.getInstance( )
.getColumnHandleAdapter( startColumn );
Object endColumn = getColumn( end );
ColumnHandleAdapter endAdapt = HandleAdapterFactory.getInstance( )
.getColumnHandleAdapter( endColumn );
int startWidth = 0;
int endWidth = 0;
startWidth = TableUtil.caleVisualWidth( this, startColumn );
endWidth = TableUtil.caleVisualWidth( this, endColumn );
try
{
getTableAdapter( ).transStar( RESIZE_COLUMN_TRANS_LABEL ); //$NON-NLS-1$
startAdapt.setWidth( startWidth + value );
endAdapt.setWidth( endWidth - value );
getTableAdapter( ).transEnd( );
}
catch ( SemanticException e )
{
ExceptionHandler.handle( e );
}
}
/**
* Selects the columns
*
* @param numbers
*/
public void selectColumn( int[] numbers )
{
if ( numbers == null || numbers.length == 0 )
{
return;
}
ArrayList list = new ArrayList( );
int size = numbers.length;
int width = 0;
int minColumnnumber = numbers[0];
for ( int i = 0; i < size; i++ )
{
if ( minColumnnumber > numbers[i] )
{
minColumnnumber = numbers[i];
}
width = width
+ TableUtil.caleVisualWidth( this, getColumn( numbers[i] ) );
list.add( new DummyColumnEditPart( getColumn( numbers[i] ) ) );
}
for ( int i = 0; i < size; i++ )
{
int rowNumber = getTableAdapter( ).getRowCount( );
for ( int j = 0; j < rowNumber; j++ )
{
TableCellEditPart part = getCell( j + 1, numbers[i] );
if ( part != null )
{
list.add( part );
}
}
}
int x = TableUtil.caleX( this, minColumnnumber );
Rectangle rect = new Rectangle( x,
0,
width,
TableUtil.getTableContentsHeight(this) );
setSelectRowAndColumnRect( rect );
getViewer( ).setSelection( new StructuredSelection( list ) );
setSelectRowAndColumnRect( null );
}
/**
* Resize the row.
*
* @param start
* @param end
* @param value
*/
public void resizeRow( int start, int end, int value )
{
Object row = getRow( start );
RowHandleAdapter adapt = HandleAdapterFactory.getInstance( )
.getRowHandleAdapter( row );
int rowHeight = 0;
if ( adapt.isCustomHeight( ) )
{
rowHeight = adapt.getHeight( );
}
else
{
rowHeight = TableUtil.caleVisualHeight( this, row );
}
try
{
adapt.setHeight( rowHeight + value );
}
catch ( SemanticException e )
{
ExceptionHandler.handle( e );
}
}
/**
* Selects rows
*
* @param numbers
*/
public void selectRow( int[] numbers )
{
if ( numbers == null || numbers.length == 0 )
{
return;
}
ArrayList list = new ArrayList( );
int size = numbers.length;
int height = 0;
int minRownumber = numbers[0];
//add row object in the list first
for ( int i = 0; i < size; i++ )
{
if ( minRownumber > numbers[i] )
{
minRownumber = numbers[i];
}
height = height
+ TableUtil.caleVisualHeight( this, getRow( numbers[i] ) );
list.add( new DummyRowEditPart( getRow( numbers[i] ) ) );
}
for ( int i = 0; i < size; i++ )
{
int columnNumber = getTableAdapter( ).getColumnCount( );
for ( int j = 0; j < columnNumber; j++ )
{
TableCellEditPart part = getCell( numbers[i], j + 1 );
if ( part != null )
{
list.add( part );
}
}
}
int y = TableUtil.caleY( this, minRownumber );
Rectangle rect = new Rectangle( 0,
y,
TableUtil.getTableContentsWidth(this),
height) ;
setSelectRowAndColumnRect( rect );
getViewer( ).setSelection( new StructuredSelection( list ) );
setSelectRowAndColumnRect( null );
}
/**
* Get mini height of row.
*
* @param rowNumber
* @return the minimum height of row.
*/
public int getMinHeight( int rowNumber )
{
return Math.max( TableUtil.getMinHeight( this, rowNumber ),
getTableAdapter( ).getMinHeight( rowNumber ) );
}
/**
* Get mini width of column.
*
* @param columnNumber
* @return the minimum height of column.
*/
public int getMinWidth( int columnNumber )
{
return Math.max( TableUtil.getMinWidth( this, columnNumber ),
getTableAdapter( ).getMinWidth( columnNumber ) );
}
/**
* The contents' Figure will be added to the PRIMARY_LAYER.
*
* @see org.eclipse.gef.GraphicalEditPart#getContentPane()
*/
public IFigure getContentPane( )
{
return getLayer( PRIMARY_LAYER );
}
/**
* @return the table adapter
*/
protected TableHandleAdapter getTableAdapter( )
{
return (TableHandleAdapter) getModelAdapter( );
}
/**
* Get all rows list
*
* @return all rows list.
*/
public List getRows( )
{
return getTableAdapter( ).getRows( );
}
/**
* @param number
* a row position
* @return a specific row.
*/
public Object getRow( int number )
{
return getTableAdapter( ).getRow( number );
}
/**
* @param number
* a column position
* @return a specific column.
*/
public Object getColumn( int number )
{
return getTableAdapter( ).getColumn( number );
}
/**
* Gets all columns list
*
* @return all columns list.
*/
public List getColumns( )
{
return getTableAdapter( ).getColumns( );
}
/**
* Gets the rows count
*
* @return row count
*/
public int getRowCount( )
{
return getTableAdapter( ).getRowCount( );
}
/**
* Gets the columns count
*
* @return column count
*/
public int getColumnCount( )
{
return getTableAdapter( ).getColumnCount( );
}
/**
* @return select bounds
*/
public Rectangle getSelectBounds( )
{
if ( getSelectRowAndColumnRect( ) != null )
{
return getSelectRowAndColumnRect( );
}
List list = TableUtil.getSelectionCells( this );
int size = list.size( );
TableCellEditPart[] parts = new TableCellEditPart[size];
list.toArray( parts );
TableCellEditPart[] caleNumber = getMinAndMaxNumber( parts );
TableCellEditPart minRow = caleNumber[0];
TableCellEditPart maxColumn = caleNumber[3];
Rectangle min = minRow.getBounds( ).getCopy( );
Rectangle max = maxColumn.getBounds( ).getCopy( );
return min.union( max );
}
/**
* @return selected row and column area
*/
public Rectangle getSelectRowAndColumnRect( )
{
return selectRowAndColumnRect;
}
/**
* Set selected row and column area.
*
* @param selectRowAndColumnRect
*/
public void setSelectRowAndColumnRect( Rectangle selectRowAndColumnRect )
{
this.selectRowAndColumnRect = selectRowAndColumnRect;
}
/**
* Gets data set, which is biding on table.
*
*/
public Object getDataSet( )
{
return getTableAdapter( ).getDataSet( );
}
/**
* Get the cell on give position.
*
* @param rowNumber
* @param columnNumber
*/
public TableCellEditPart getCell( int rowNumber, int columnNumber )
{
Object cell = getTableAdapter( ).getCell( rowNumber, columnNumber );
return (TableCellEditPart) getViewer( ).getEditPartRegistry( )
.get( cell );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.gef.editparts.AbstractEditPart#removeChild(org.eclipse.gef.EditPart)
*/
protected void removeChild( EditPart child )
{
super.removeChild( child );
}
/**
* Delete specified row.
*
* @param numbers
*/
public void deleteRow( int[] numbers )
{
try
{
getTableAdapter( ).deleteRow( numbers );
}
catch ( SemanticException e )
{
ExceptionHandler.handle( e );
}
}
/**
* Delete specified column
*
* @param numbers
*/
public void deleteColumn( int[] numbers )
{
try
{
getTableAdapter( ).deleteColumn( numbers );
}
catch ( SemanticException e )
{
ExceptionHandler.handle( e );
}
}
/**
* inserts a row after the row number
*
* @param rowNumber
*/
public void insertRow( int rowNumber )
{
insertRow( -1, rowNumber );
}
/**
* Inserts a single row at give position.
*
* @param relativePos
* The relative position to insert the new row.
* @param originRowNumber
* The row number of the original row.
*/
public void insertRow( final int relativePos, final int originRowNumber )
{
final RowHandleAdapter adapter = HandleAdapterFactory.getInstance( )
.getRowHandleAdapter( getRow( originRowNumber ) );
try
{
getTableAdapter( ).insertRow( relativePos, originRowNumber );
}
catch ( SemanticException e )
{
ExceptionHandler.handle( e );
}
Display.getCurrent( ).asyncExec( new Runnable( ) {
public void run( )
{
//reLayout();
selectRow( new int[]{
adapter.getRowNumber( )
} );
}
} );
}
/**
* Inserts multi rows( or a single row ) at give position.
*
* @author Liu sanyong
*
* @version 1.0 2005.4.22
*
* @param relativePos
* The direction to indicate inserting rows above or below.
* @param rowNumbers
* The row numbers of the origin selected rows.
*/
public void insertRows( final int relativePos, final int[] rowNumbers )
{
int rowCount = rowNumbers.length;
try
{
if ( relativePos < 0 )
{ // insert above.
getTableAdapter( ).insertRows( -rowCount, rowNumbers[0] );
}
else
{// insert below.
getTableAdapter( ).insertRows( rowCount,
rowNumbers[rowCount - 1] );
}
}
catch ( SemanticException e )
{
ExceptionHandler.handle( e );
}
// no need to relayout.
}
/**
* Inserts a row after the row number
*
* @param columnNumber
*/
public void insertColumn( int columnNumber )
{
insertColumn( -1, columnNumber );
}
/**
* Inserts a single column at give position.
*
* @param relativePos
* The relative position to insert the new column.
* @param originColNumber
* The column number of the original column.
*/
public void insertColumn( final int relativePos, final int originColNumber )
{
final ColumnHandleAdapter adapter = HandleAdapterFactory.getInstance( )
.getColumnHandleAdapter( getColumn( originColNumber ) );
try
{
getTableAdapter( ).insertColumn( relativePos, originColNumber );
}
catch ( SemanticException e )
{
ExceptionHandler.handle( e );
}
Display.getCurrent( ).asyncExec( new Runnable( ) {
public void run( )
{
//reLayout();
selectColumn( new int[]{
adapter.getColumnNumber( )
} );
}
} );
}
/**
* Inserts multi columns( or a single column ) at give position.
*
* @author Liu sanyong
*
* @version 1.0 2005.4.22
*
* @param relativePos
* The direction to indicate inserting rows above or below.
* @param colNumbers
* The column numbers of the origin selected column(s).
*/
//TODO move the logic to tableHandle adapt
public void insertColumns( final int relativePos, final int[] colNumbers )
{
int colCount = colNumbers.length;
try
{
if ( relativePos < 0 )
{ // insert left.
getTableAdapter( ).insertColumns( -colCount, colNumbers[0] );
}
else
{// insert right.
getTableAdapter( ).insertColumns( colCount,
colNumbers[colCount - 1] );
}
}
catch ( SemanticException e )
{
ExceptionHandler.handle( e );
}
// no need to relayout.
}
/**
* merge the selection cell
*/
public void merge( )
{
List selections = TableUtil.getSelectionCells( this );
if ( selections.size( ) == 1 )
{
return;
}
int size = selections.size( );
TableCellEditPart[] parts = new TableCellEditPart[size];
selections.toArray( parts );
TableCellEditPart[] caleNumber = getMinAndMaxNumber( parts );
TableCellEditPart minRow = caleNumber[0];
TableCellEditPart maxRow = caleNumber[2];
TableCellEditPart maxColumn = caleNumber[3];
TableCellEditPart cellPart = caleNumber[0];
ArrayList list = new ArrayList( );
//first is the contain cell(minrow, minColumn)
for ( int i = 0; i < size; i++ )
{
if ( selections.get( i ) != cellPart )
{
list.add( selections.get( i ) );
}
}
int rowSpan = maxRow.getRowNumber( )
- minRow.getRowNumber( )
+ maxRow.getRowSpan( );
int colSpan = maxColumn.getColumnNumber( )
- maxRow.getColumnNumber( )
+ maxColumn.getColSpan( );
getTableAdapter( ).transStar( MERGE_TRANS_LABEL );
try
{
MergeContent(cellPart, list);
}
catch(ContentException e)
{
ExceptionHandler.handle( e );
}
cellPart.setRowSpan( rowSpan );
cellPart.setColumnSpan( colSpan );
removeMergeList( list );
getTableAdapter( ).transEnd( );
getViewer( ).setSelection( new StructuredSelection( cellPart ) );
getTableAdapter( ).reload( );
}
//TODO move logic to adapt
private void MergeContent(TableCellEditPart cellPart, List list) throws ContentException
{
CellHandle cellHandle = (CellHandle)cellPart.getModel();
int size = list.size();
for (int i=0; i<size; i++)
{
CellHandle handle = (CellHandle)(((TableCellEditPart)list.get(i)).getModel());
List chList = handle.getSlot(CellHandle.CONTENT_SLOT).getContents();
for (int j=0; j<chList.size(); j++)
{
DesignElementHandle contentHandle = (DesignElementHandle)chList.get(j);
handle.getSlot(CellHandle.CONTENT_SLOT).move(contentHandle, cellHandle, CellHandle.CONTENT_SLOT);
}
}
}
/**
* not use?
*
* @param list
*/
private void removeMergeList( ArrayList list )
{
int size = list.size( );
for ( int i = 0; i < size; i++ )
{
remove( (TableCellEditPart) list.get( i ) );
}
}
/**
* not use?
*
* @param cellPart
*/
public void remove( TableCellEditPart cellPart )
{
try
{
getTableAdapter( ).removeChild( cellPart.getModel( ) );
}
catch ( SemanticException e )
{
ExceptionHandler.handle( e );
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.designer.core.model.IModelAdaptHelper#getPreferredSize()
*/
public Dimension getPreferredSize( )
{
Dimension retValue = getFigure( ).getParent( )
.getClientArea( )
.getSize( );
Rectangle rect = getBounds( );
if ( rect.width > 0 )
{
retValue.width = rect.width;
}
if ( rect.height > 0 )
{
retValue.height = rect.height;
}
return retValue;
}
protected void notifyChildrenDirty( boolean bool )
{
super.notifyChildrenDirty( bool );
if ( bool )
{
reLayout( );
( (TableLayout) getContentPane( ).getLayoutManager( ) ).markDirty( );
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.designer.internal.ui.editors.schematic.editparts.ReportElementEditPart#markDirty(boolean)
*/
public void markDirty( boolean bool, boolean notifyParent )
{
super.markDirty( bool, notifyParent );
if ( bool )
{
( (TableLayout) getContentPane( ).getLayoutManager( ) ).markDirty( );
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.designer.core.facade.ITableAdaptHelper#caleVisualWidth(int)
*/
public int caleVisualWidth( int columnNumber )
{
assert columnNumber > 0;
return TableUtil.caleVisualWidth( this, getColumn( columnNumber ) );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.designer.core.facade.ITableAdaptHelper#caleVisualHeight(int)
*/
public int caleVisualHeight( int rowNumber )
{
return TableUtil.caleVisualHeight( this, getRow( rowNumber ) );
}
/**
* Determines if selected cells can be merged.
*
* @return true if merge success, else false.
*/
public boolean canMerge( )
{
if ( !isActive() || isDelete( ) || getParent( ) == null )
{
return false;
}
List list = TableUtil.getSelectionCells( this );
int size = list.size( );
List temp = new ArrayList( );
for ( int i = 0; i < size; i++ )
{
ReportElementEditPart part = (ReportElementEditPart) list.get( i );
if ( part.isDelete( ) )
{
return false;
}
temp.add( part.getModel( ) );
}
boolean rt = getTableAdapter( ).canMerge( temp );
if ( rt )
{
TableUtil.calculateNewSelection( TableUtil.getUnionBounds( list ),
list,
getChildren( ) );
return list.size( ) == size;
}
return rt;
}
/**
* Split merged cells
*
* @param part
*/
public void splitCell( TableCellEditPart part )
{
try
{
getTableAdapter( ).splitCell( part.getModel( ) );
}
catch ( ContentException e )
{
ExceptionHandler.handle( e );
}
catch ( NameException e )
{
ExceptionHandler.handle( e );
}
catch ( SemanticException e )
{
ExceptionHandler.handle( e );
}
}
/**
* @param bool
* @param id
*/
public void includeSlotHandle( boolean bool, int id )
{
try
{
if ( bool )
{
getTableAdapter( ).insertRowInSlotHandle( id );
}
else
{
getTableAdapter( ).deleteRowInSlotHandle( id );
}
}
catch ( SemanticException e )
{
ExceptionHandler.handle( e );
}
}
/**
* Inserts group in table.
*/
public boolean insertGroup( )
{
return UIUtil.createGroup( getTableAdapter( ).getHandle( ) );
}
/**
* Inserts group in table.
*
* @param position
* insert position
*/
public boolean insertGroup( int position )
{
return UIUtil.createGroup( getTableAdapter( ).getHandle( ), position );
}
/**
* Removes group in table
*
* @param group
*/
public void removeGroup( Object group )
{
try
{
( (TableHandleAdapter) getModelAdapter( ) ).removeGroup( group );
}
catch ( Exception e )
{
ExceptionHandler.handle( e );
}
}
protected void addListenerToChildren( )
{
addGroupListener( );
addRowListener( );
addColumnListener( );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.designer.core.model.ITableAdaptHelper#getClientAreaSize()
*/
public Dimension getClientAreaSize( )
{
return getFigure( ).getParent( ).getClientArea( ).getSize( );
}
protected void addGroupListener( )
{
for ( Iterator it = ( (TableHandle) getModel( ) ).getGroups( )
.iterator( ); it.hasNext( ); )
{
( (DesignElementHandle) it.next( ) ).addListener( this );
}
}
public void showTargetFeedback( Request request )
{
if ( this.getSelected( ) == 0
&& isActive( )
&& request.getType( ) == RequestConstants.REQ_SELECTION )
{
if ( isFigureLeft( request ) )
{
this.getViewer( ).setCursor( ReportPlugin.getDefault( )
.getLeftCellCursor( ) );
}
else
{
this.getViewer( ).setCursor( ReportPlugin.getDefault( )
.getRightCellCursor( ) );
}
}
super.showTargetFeedback( request );
}
public void eraseTargetFeedback( Request request )
{
if ( isActive( ) )
{
this.getViewer( ).setCursor( null );
}
super.eraseTargetFeedback( request );
}
protected void addChildVisual( EditPart part, int index )
{
// make sure we don't keep a select cell cursor after new contents
// are added
this.getViewer( ).setCursor( null );
super.addChildVisual( part, index );
}
/**
* The class use for select row in table.
*
*/
public static class DummyColumnEditPart extends DummyEditpart
{
/**
* @param model
*/
public DummyColumnEditPart( Object model )
{
super( model );
createEditPolicies( );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.designer.internal.ui.editors.schematic.editparts.DummyEditpart#createEditPolicies()
*/
protected void createEditPolicies( )
{
ReportComponentEditPolicy policy = new ReportComponentEditPolicy( ) {
protected org.eclipse.gef.commands.Command createDeleteCommand(
GroupRequest deleteRequest )
{
DeleteColumnCommand command = new DeleteColumnCommand( getModel( ) );
return command;
}
};
installEditPolicy( EditPolicy.COMPONENT_ROLE, policy );
}
public int getColumnNumber( )
{
return HandleAdapterFactory.getInstance( )
.getColumnHandleAdapter( getModel( ) )
.getColumnNumber( );
}
}
/**
* The class use for select row in table.
*
*/
public static class DummyRowEditPart extends DummyEditpart
{
/**
* @param model
*/
public DummyRowEditPart( Object model )
{
super( model );
createEditPolicies( );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.designer.internal.ui.editors.schematic.editparts.DummyEditpart#createEditPolicies()
*/
protected void createEditPolicies( )
{
ReportComponentEditPolicy policy = new ReportComponentEditPolicy( ) {
protected org.eclipse.gef.commands.Command createDeleteCommand(
GroupRequest deleteRequest )
{
DeleteRowCommand command = new DeleteRowCommand( getModel( ) );
return command;
}
};
installEditPolicy( EditPolicy.COMPONENT_ROLE, policy );
}
public int getRowNumber( )
{
return HandleAdapterFactory.getInstance( )
.getRowHandleAdapter( getModel( ) )
.getRowNumber( );
}
}
}
|
package edu.northwestern.bioinformatics.studycalendar.security.plugin.cas;
import edu.northwestern.bioinformatics.studycalendar.security.plugin.AbstractAuthenticationSystem;
import edu.northwestern.bioinformatics.studycalendar.security.plugin.AuthenticationSystemTools;
import edu.northwestern.bioinformatics.studycalendar.security.plugin.cas.direct.CasDirectUsernamePasswordAuthenticationToken;
import edu.northwestern.bioinformatics.studycalendar.tools.spring.SpringBeanConfigurationTools;
import gov.nih.nci.cabig.ctms.tools.configuration.ConfigurationProperties;
import gov.nih.nci.cabig.ctms.tools.configuration.ConfigurationProperty;
import gov.nih.nci.cabig.ctms.tools.configuration.DefaultConfigurationProperties;
import gov.nih.nci.cabig.ctms.tools.configuration.DefaultConfigurationProperty;
import org.acegisecurity.Authentication;
import org.acegisecurity.AuthenticationManager;
import org.acegisecurity.providers.AuthenticationProvider;
import org.acegisecurity.providers.UsernamePasswordAuthenticationToken;
import org.acegisecurity.ui.AuthenticationEntryPoint;
import org.acegisecurity.ui.cas.CasProcessingFilter;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.Filter;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Properties;
import java.util.ArrayList;
/**
* @author Rhett Sutphin
*/
public class CasAuthenticationSystem extends AbstractAuthenticationSystem {
private final Logger log = LoggerFactory.getLogger(getClass());
private static final DefaultConfigurationProperties PROPERTIES
= new DefaultConfigurationProperties(
new ClassPathResource(absoluteClasspathResourceNameFor("cas-details.properties" , CasAuthenticationSystem.class), CasAuthenticationSystem.class));
public static final ConfigurationProperty<String> SERVICE_URL
= PROPERTIES.add(new DefaultConfigurationProperty.Text("cas.serviceUrl"));
public static final ConfigurationProperty<String> TRUST_STORE
= PROPERTIES.add(new DefaultConfigurationProperty.Text("cas.trustStore"));
public static final ConfigurationProperty<String> APPLICATION_URL
= PROPERTIES.add(new DefaultConfigurationProperty.Text(PSC_URL_CONFIGURATION_PROPERTY_NAME));
public static final ConfigurationProperty<Boolean> ALLOW_DIRECT_CAS
= PROPERTIES.add(new DefaultConfigurationProperty.Bool("cas.direct.enable"));
private static final String CAS_FILTER_PATH = "/auth/cas_security_check";
private ApplicationContext casContext;
public ConfigurationProperties configurationProperties() {
return PROPERTIES;
}
@Override
public String name() {
return "CAS";
}
public String behaviorDescription() {
return "delegates authentication decisions to an enterprise-wide CAS server";
}
@Override
protected Collection<ConfigurationProperty<?>> requiredConfigurationProperties() {
return Arrays.asList((ConfigurationProperty<?>) SERVICE_URL, APPLICATION_URL);
}
@Override
protected void initBeforeCreate() {
ApplicationContext configParametersContext
= AuthenticationSystemTools.createApplicationContextWithPropertiesBean(
getApplicationContext(), "casConfiguration",
createContextProperties(), getClass().getClassLoader());
casContext = loadClassRelativeXmlApplicationContext(
configParametersContext, applicationContextResourceNames());
}
protected String[] applicationContextResourceNames() {
return new String[] { absoluteClasspathResourceNameFor("cas-authentication-beans.xml" , CasAuthenticationSystem.class) };
}
protected Properties createContextProperties() {
Properties template = new Properties();
nullSafeSetProperty(template, "cas.server.trustStore", getConfiguration().get(TRUST_STORE));
nullSafeSetProperty(template, "cas.server.url.base", getConfiguration().get(SERVICE_URL));
nullSafeSetProperty(template, "cas.server.url.validate",
urlJoin(getConfiguration().get(SERVICE_URL), "proxyValidate"));
nullSafeSetProperty(template, "cas.server.url.login",
urlJoin(getConfiguration().get(SERVICE_URL), "login"));
nullSafeSetProperty(template, "cas.server.url.logout",
urlJoin(getConfiguration().get(SERVICE_URL), "logout"));
nullSafeSetProperty(template, "cas.local.filterPath", urlJoin("", CAS_FILTER_PATH));
nullSafeSetProperty(template, "cas.local.url",
urlJoin(getConfiguration().get(APPLICATION_URL), CAS_FILTER_PATH));
nullSafeSetProperty(template, "psc.defaultTarget", DEFAULT_TARGET_PATH);
nullSafeSetProperty(template, "populatorBeanName", getPopulatorBeanName());
nullSafeSetProperty(template, "ticketValidatorBeanName", getTicketValidatorBeanName());
return template;
}
protected void nullSafeSetProperty(Properties template, String key, String value) {
template.setProperty(key, value == null ? "" : value);
}
private String urlJoin(String left, String right) {
StringBuilder sb = new StringBuilder(left);
if (left.endsWith("/") && right.startsWith("/")) {
sb.deleteCharAt(sb.length() - 1);
} else if (!left.endsWith("/") && !right.startsWith("/")) {
sb.append('/');
}
sb.append(right);
return sb.toString();
}
@Override
protected AuthenticationManager createAuthenticationManager() {
List<AuthenticationProvider> providers = new ArrayList<AuthenticationProvider>(2);
if (getConfiguration().get(ALLOW_DIRECT_CAS)) {
log.debug("Initializing CAS plugin with direct CAS support");
providers.add((AuthenticationProvider) casContext.getBean("casDirectAuthenticationProvider"));
}
providers.add((AuthenticationProvider) casContext.getBean("casAuthenticationProvider"));
return AuthenticationSystemTools.createProviderManager(getApplicationContext(), providers);
}
@Override
protected AuthenticationEntryPoint createEntryPoint() {
return (AuthenticationEntryPoint) casContext.getBean("casEntryPoint");
}
@Override
protected Filter createFilter() {
// filter needs a reference to the authentication manager, so it can't go in the XML
CasProcessingFilter filter = new CasProcessingFilter();
filter.setAuthenticationManager(authenticationManager());
filter.setDefaultTargetUrl(DEFAULT_TARGET_PATH);
filter.setFilterProcessesUrl(CAS_FILTER_PATH);
filter.setAuthenticationFailureUrl("/accessDenied.jsp");
return SpringBeanConfigurationTools.prepareBean(casContext, filter);
}
@Override
public Filter logoutFilter() {
return (Filter) casContext.getBean("casLogoutFilter");
}
public Authentication createUsernamePasswordAuthenticationRequest(String username, String password) {
if (getConfiguration().get(ALLOW_DIRECT_CAS)) {
return new CasDirectUsernamePasswordAuthenticationToken(username, password);
} else {
return null;
}
}
public Authentication createTokenAuthenticationRequest(String token) {
return new UsernamePasswordAuthenticationToken(CasProcessingFilter.CAS_STATELESS_IDENTIFIER, token);
}
protected String getPopulatorBeanName() {
return "casAuthoritiesPopulator";
}
protected String getTicketValidatorBeanName() {
return "casProxyTicketValidator";
}
protected static String absoluteClasspathResourceNameFor(String relative , Class root) {
return "/" + root.getName().
replaceAll(root.getSimpleName(), "").
replaceAll("\\.", "/") + relative;
}
}
|
package be.ibridge.kettle.core;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
/**
* This class is a container for "Local" enrvironment variables.
* This is a singleton. We are going to launch jobs using a customer classloader.
* This will make the variables inside it local.
*
* @author Matt
*/
public class LocalVariables
{
ThreadLocal local;
private static LocalVariables localVariables;
private Map map;
/**
* Create a new KettleVariables variable map in the local variables map for the specified thread.
* @param localThread The local thread to attach to
* @param parentThread The parent thread, null if there is no parent thread. The initial value of the variables will be taken from the variables that are attached to this thread.
* @param sameNamespace true if you want to use the same namespace as the parent (if any) or false if you want to use a new namespace, create a new KettleVariables object.
*/
public synchronized KettleVariables createKettleVariables(String localThread, String parentThread, boolean sameNamespace)
{
if (parentThread!=null && parentThread.equals(localThread))
{
throw new RuntimeException("local thread can't be the same as the parent thread!");
}
LogWriter.getInstance().logDebug("LocalVariables", "---> Create new KettleVariables for thread ["+localThread+"] for parent thread ["+parentThread+"], same namespace? ["+sameNamespace+"]");
// See if the thread already has an entry in the map
KettleVariables vars = new KettleVariables(localThread, parentThread);
// Copy the initial values from the parent thread if it is specified
if (parentThread!=null)
{
KettleVariables initialValue = getKettleVariables(parentThread);
if (initialValue!=null)
{
if (sameNamespace)
{
vars = new KettleVariables(localThread, parentThread);
vars.setProperties(initialValue.getProperties());
}
else
{
vars.putAll(initialValue.getProperties());
}
}
else
{
throw new RuntimeException("No parent Kettle Variables found for thread ["+parentThread+"], local thread is ["+localThread+"]");
}
}
// Before we add this, for debugging, just see if we're not overwriting anything.
// Overwriting is a big No-No
KettleVariables checkVars = (KettleVariables) map.get(localThread);
if (checkVars!=null)
{
// throw new RuntimeException("There are already variables in the local variables map for ["+localThread+"]");
}
// Put this one in the map, attached to the local thread
map.put(localThread, vars);
return vars;
}
public LocalVariables()
{
map = new Hashtable();
}
public static final LocalVariables getInstance()
{
if (localVariables==null) // Not the first time we call this, see if we have properties for this thread
{
// System.out.println("Init of new local variables object");
localVariables = new LocalVariables();
}
return localVariables;
}
public Map getMap()
{
return map;
}
public static final KettleVariables getKettleVariables()
{
return getInstance().getVariables(Thread.currentThread().getName());
}
public static final KettleVariables getKettleVariables(String thread)
{
return getInstance().getVariables(thread);
}
/**
* Find the KettleVariables in the map, attached to the specified Thread.
* This is not singleton stuff, we return null in case we don't have anything attached to the current thread.
* That makes it easier to find the "missing links"
* @param localThread The thread to look for
* @return The KettleVariables attached to the specified thread.
*/
private KettleVariables getVariables(String localThread)
{
KettleVariables kettleVariables = (KettleVariables) map.get(localThread);
return kettleVariables;
}
public void removeKettleVariables(String thread)
{
if (thread==null) return;
removeKettleVariables(thread, 1);
}
/**
* Remove all KettleVariables objects in the map, including the one for this thread, but also the ones with this thread as parent, etc.
* @param thread the grand-parent thread to look for to remove
*/
private void removeKettleVariables(String thread, int level)
{
LogWriter log = LogWriter.getInstance();
List children = getKettleVariablesWithParent(thread);
for (int i=0;i<children.size();i++)
{
String child = (String)children.get(i);
removeKettleVariables(child, level+1);
}
// See if it was in there in the first place...
if (map.get(thread)==null)
{
// We should not ever arrive here...
log.logError("LocalVariables!!!!!!!", "The variables you are trying to remove, do not exist for thread ["+thread+"]");
log.logError("LocalVariables!!!!!!!", "Please report this error to the Kettle developers.");
}
else
{
map.remove(thread);
}
}
private List getKettleVariablesWithParent(String parentThread)
{
List children = new ArrayList();
List values;
synchronized (map) {
values = new ArrayList(map.values());
}
for (int i=0;i<values.size();i++)
{
KettleVariables kv = (KettleVariables)values.get(i);
if ( ( kv.getParentThread()==null && parentThread==null) ||
( kv.getParentThread()!=null && parentThread!=null && kv.getParentThread().equals(parentThread) )
)
{
if (kv.getLocalThread().equals(parentThread))
{
System.out.println("---> !!!! This should not happen! Thread ["+parentThread+"] is linked to itself!");
}
else
{
children.add(kv.getLocalThread());
}
}
}
return children;
}
}
|
package chunk;
import org.junit.Assert;
import org.junit.Test;
import org.mwdb.Constants;
import org.mwdb.KType;
import org.mwdb.chunk.*;
import org.mwdb.chunk.heap.HeapStateChunk;
import org.mwdb.utility.PrimitiveHelper;
public class StateChunkTest implements KChunkListener {
private int nbCount = 0;
@Test
public void heapStateChunkTest() {
saveLoadTest(new HeapStateChunk(Constants.NULL_LONG, Constants.NULL_LONG, Constants.NULL_LONG, this), new HeapStateChunk(Constants.NULL_LONG, Constants.NULL_LONG, Constants.NULL_LONG, this));
protectionTest(new HeapStateChunk(Constants.NULL_LONG, Constants.NULL_LONG, Constants.NULL_LONG, this));
}
private void saveLoadTest(KStateChunk chunk, KStateChunk chunk2) {
//reset nb count
nbCount = 0;
//init chunk with primitives
chunk.set(0, KType.BOOL, true);
chunk.set(1, KType.STRING, "hello");
chunk.set(2, KType.DOUBLE, 1.0);
chunk.set(3, KType.LONG, 1000l);//TODO check for solution for long cast
chunk.set(4, KType.INT, 100);
String savedChunk = chunk.save();
chunk2.load(savedChunk);
String savedChunk2 = chunk2.save();
Assert.assertTrue(PrimitiveHelper.equals(savedChunk, savedChunk2));
for (int i = 0; i < 5; i++) {
if (i == 1) {
Assert.assertTrue(PrimitiveHelper.equals(chunk.get(i).toString(), chunk2.get(i).toString()));
} else {
Assert.assertTrue(chunk.get(i).equals(chunk2.get(i)));
}
}
//init chunk with arrays
chunk.set(5, KType.LONG_ARRAY, new long[]{0, 1, 2, 3, 4});
chunk.set(6, KType.DOUBLE_ARRAY, new double[]{0.1, 1.1, 2.1, 3.1, 4.1});
chunk.set(7, KType.INT_ARRAY, new int[]{0, 1, 2, 3, 4});
savedChunk = chunk.save();
chunk2.load(savedChunk);
savedChunk2 = chunk2.save();
Assert.assertTrue(PrimitiveHelper.equals(savedChunk, savedChunk2));
//init chunk with some maps
KLongLongMap long2longMap = (KLongLongMap) chunk.getOrCreate(8, KType.LONG_LONG_MAP);
long2longMap.put(1, 1);
long2longMap.put(Constants.END_OF_TIME, Constants.END_OF_TIME);
long2longMap.put(Constants.BEGINNING_OF_TIME, Constants.BEGINNING_OF_TIME);
KStringLongMap string2longMap = (KStringLongMap) chunk.getOrCreate(9, KType.STRING_LONG_MAP);
string2longMap.put("1", 1);
string2longMap.put(Constants.END_OF_TIME + "", Constants.END_OF_TIME);
string2longMap.put(Constants.BEGINNING_OF_TIME + "", Constants.BEGINNING_OF_TIME);
savedChunk = chunk.save();
chunk2.load(savedChunk);
savedChunk2 = chunk2.save();
//System.out.println(savedChunk);
//System.out.println(savedChunk2);
//System.out.println(nbCount);
Assert.assertTrue(PrimitiveHelper.equals(savedChunk, savedChunk2));
Assert.assertTrue(1 == nbCount);
//force reHash
for (int i = 0; i < 10; i++) {
chunk.set(1000 + i, KType.INT, i);
}
for (int i = 0; i < 10; i++) {
Assert.assertTrue(chunk.get(1000 + i).equals(i));
}
}
private void protectionTest(KStateChunk chunk) {
//boolean protection test
protectionMethod(chunk, KType.BOOL, null, true);
protectionMethod(chunk, KType.BOOL, true, false);
protectionMethod(chunk, KType.BOOL, "Hello", true);
protectionMethod(chunk, KType.DOUBLE, null, true);
protectionMethod(chunk, KType.DOUBLE, 0.5d, false);
protectionMethod(chunk, KType.DOUBLE, "Hello", true);
protectionMethod(chunk, KType.LONG, null, true);
protectionMethod(chunk, KType.LONG, 100000000l, false);
protectionMethod(chunk, KType.LONG, "Hello", true);
protectionMethod(chunk, KType.INT, null, true);
protectionMethod(chunk, KType.INT, 10, false);
protectionMethod(chunk, KType.INT, "Hello", true);
protectionMethod(chunk, KType.STRING, null, false);
protectionMethod(chunk, KType.STRING, "Hello", false);
protectionMethod(chunk, KType.STRING, true, true);
//arrays
protectionMethod(chunk, KType.DOUBLE_ARRAY, new double[]{0.1d, 0.2d, 0.3d}, false);
protectionMethod(chunk, KType.DOUBLE_ARRAY, "hello", true);
protectionMethod(chunk, KType.LONG_ARRAY, new long[]{10l, 100l, 1000l}, false);
protectionMethod(chunk, KType.LONG_ARRAY, "hello", true);
protectionMethod(chunk, KType.INT_ARRAY, new int[]{10, 100, 1000}, false);
protectionMethod(chunk, KType.INT_ARRAY, "hello", true);
//maps
protectionMethod(chunk, KType.STRING_LONG_MAP, "hello", true);
protectionMethod(chunk, KType.LONG_LONG_MAP, "hello", true);
//TODO
//protectionMethod(chunk, KType.LONG_LONG_ARRAY_MAP, "hello", true);
}
private void protectionMethod(KStateChunk chunk, int elemType, Object elem, boolean shouldCrash) {
boolean hasCrash = false;
try {
chunk.set(0, elemType, elem);
} catch (Throwable e) {
hasCrash = true;
}
Assert.assertTrue(hasCrash == shouldCrash);
}
@Override
public void declareDirty(KChunk chunk) {
nbCount++;
//simulate space management
chunk.setFlags(Constants.DIRTY_BIT, 0);
}
}
|
package be.ibridge.kettle.www;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.util.zip.GZIPOutputStream;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import be.ibridge.kettle.core.Const;
import be.ibridge.kettle.core.LogWriter;
import be.ibridge.kettle.core.XMLHandler;
import be.ibridge.kettle.trans.Trans;
import be.ibridge.kettle.trans.TransConfiguration;
import be.ibridge.kettle.trans.TransMeta;
public class AddTransServlet extends HttpServlet
{
private static final long serialVersionUID = -6850701762586992604L;
private static LogWriter log = LogWriter.getInstance();
public static final String CONTEXT_PATH = "/kettle/addTrans";
private TransformationMap transformationMap;
public AddTransServlet(TransformationMap transformationMap)
{
this.transformationMap = transformationMap;
}
public void init(ServletConfig servletConfig) throws ServletException
{
super.init(servletConfig);
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
if (!request.getServletPath().equals(CONTEXT_PATH)) return;
if (log.isDebug()) log.logDebug(toString(), "Addition of transformation requested");
boolean useXML = "Y".equalsIgnoreCase( request.getParameter("xml") );
PrintStream out;
GZIPOutputStream gzout=null;
if (useXML)
{
gzout = new GZIPOutputStream(response.getOutputStream());
out = new PrintStream(gzout);
}
else out = new PrintStream(response.getOutputStream());
InputStream is = request.getInputStream(); // read from the client
if (useXML)
{
response.setContentType("text/xml");
out.print(XMLHandler.getXMLHeader());
}
else
{
response.setContentType("text/html");
out.println("<HTML>");
out.println("<HEAD><TITLE>Add transformation</TITLE></HEAD>");
out.println("<BODY>");
}
try
{
// First read the complete transformation in memory from the inputStream
int c;
StringBuffer xml = new StringBuffer();
while ( (c=is.read())!=-1)
{
xml.append((char)c);
}
// Parse the XML, create a transformation configuration
TransConfiguration transConfiguration = TransConfiguration.fromXML(xml.toString());
TransMeta transMeta = transConfiguration.getTransMeta();
// Create the transformation and store in the list...
Trans trans = new Trans(log, transMeta);
Trans oldOne = transformationMap.getTransformation(trans.getName());
if ( oldOne!=null && !oldOne.isFinished())
{
if ( oldOne.isRunning() || oldOne.isPreparing() || oldOne.isInitializing() )
{
throw new Exception("A transformation with the same name exists and is not idle."+Const.CR+"Please stop the transformation first.");
}
}
transformationMap.addTransformation(transMeta.getName(), trans, transConfiguration);
String message;
if (oldOne!=null)
{
message = "Transformation '"+trans.getName()+"' was replaced in the list.";
}
else
{
message = "Transformation '"+trans.getName()+"' was added to the list.";
}
if (useXML)
{
out.println(new WebResult(WebResult.STRING_OK, message));
}
else
{
out.println("<H1>"+message+"</H1>");
out.println("<p><a href=\"/kettle/transStatus?name="+trans.getName()+"\">Go to the transformation status page</a><p>");
}
}
catch (Exception ex)
{
if (useXML)
{
out.println(new WebResult(WebResult.STRING_ERROR, Const.getStackTracker(ex)));
}
else
{
out.println("<p>");
out.println("<pre>");
ex.printStackTrace(out);
out.println("</pre>");
}
}
if (!useXML)
{
out.println("<p>");
out.println("</BODY>");
out.println("</HTML>");
}
out.flush();
if (useXML) gzout.flush();
// Request baseRequest = (request instanceof Request) ? (Request)request:HttpConnection.getCurrentConnection().getRequest();
// baseRequest.setHandled(true);
}
public String toString()
{
return "Add Transformation";
}
}
|
package beast.app.treeannotator;
import java.io.*;
import java.util.*;
import javax.swing.JFrame;
import beast.app.BEASTVersion;
import beast.app.beauti.BeautiDoc;
import beast.app.tools.LogCombiner;
import beast.app.util.Arguments;
import beast.app.util.Utils;
import beast.core.util.Log;
import beast.evolution.alignment.TaxonSet;
import beast.evolution.tree.Node;
import beast.evolution.tree.Tree;
import beast.evolution.tree.TreeUtils;
import beast.math.statistic.DiscreteStatistics;
import beast.util.CollectionUtils;
import beast.util.HeapSort;
import beast.util.NexusParser;
import beast.util.TreeParser;
import jam.console.ConsoleApplication;
//import org.rosuda.JRI.REXP;
//import org.rosuda.JRI.RVector;
//import org.rosuda.JRI.Rengine;
/**
* @author Alexei Drummond
* @author Andrew Rambaut
*
* TreeAnnotator ported from BEAST 1
*/
public class TreeAnnotator {
private final static BEASTVersion version = new BEASTVersion();
private final static boolean USE_R = false;
private static boolean forceIntegerToDiscrete = false;
private boolean SAmode = false;
abstract class TreeSet {
abstract boolean hasNext();
abstract Tree next() throws IOException;
abstract void reset() throws IOException;
String inputFileName;
int burninCount = 0;
int totalTrees = 0;
boolean isNexus = true;
/** determine number of trees in the file,
* and number of trees to skip as burnin
* @throws IOException
* @throws FileNotFoundException **/
void countTrees(int burninPercentage) throws IOException {
BufferedReader fin = new BufferedReader(new FileReader(new File(inputFileName)));
if (!fin.ready()) {
throw new IOException("File appears empty");
}
String str = fin.readLine();
if (!str.toUpperCase().trim().startsWith("#NEXUS")) {
// the file contains a list of Newick trees instead of a list in Nexus format
isNexus = false;
if (str.trim().length() > 0) {
totalTrees = 1;
}
}
while (fin.ready()) {
str = fin.readLine();
if (isNexus) {
if (str.trim().toLowerCase().startsWith("tree ")) {
totalTrees++;
}
} else if (str.trim().length() > 0) {
totalTrees++;
}
}
fin.close();
burninCount = Math.max(0, (burninPercentage * totalTrees)/100);
progressStream.println("Processing " + (totalTrees - burninCount) + " trees from file" +
(burninPercentage > 0 ? " after ignoring first " + burninPercentage + "% = " + burninCount + " trees." : "."));
}
}
class FastTreeSet extends TreeSet {
int current = 0;
Tree [] trees;
public FastTreeSet(String inputFileName, int burninPercentage) throws IOException {
this.inputFileName = inputFileName;
countTrees(burninPercentage);
List<Tree> parsedTrees;
if (isNexus) {
NexusParser nexusParser = new NexusParser();
nexusParser.parseFile(new File(inputFileName));
parsedTrees = nexusParser.trees;
} else {
BufferedReader fin = new BufferedReader(new FileReader(inputFileName));
parsedTrees = new ArrayList<>();
while (fin.ready()) {
String line = fin.readLine().trim();
Tree thisTree;
try {
thisTree = new TreeParser(null, line, 0, false);
} catch (ArrayIndexOutOfBoundsException e) {
thisTree = new TreeParser(null, line, 1, false);
}
parsedTrees.add(thisTree);
}
fin.close();
}
int treesToUse = parsedTrees.size() - burninCount;
trees = new Tree[treesToUse];
for (int i=burninCount; i<parsedTrees.size(); i++)
trees[i-burninCount] = parsedTrees.get(i);
}
@Override
boolean hasNext() {
return current < trees.length;
}
@Override
Tree next() {
return trees[current++];
}
@Override
void reset() {
current = 0;
}
}
class MemoryFriendlyTreeSet extends TreeSet {
// Tree [] trees;
int current = 0;
int lineNr;
public Map<String, String> translationMap = null;
public List<String> taxa;
// label count origin for NEXUS trees
int origin = -1;
BufferedReader fin;
MemoryFriendlyTreeSet(String inputFileName, int burninPercentage) throws IOException {
this.inputFileName = inputFileName;
countTrees(burninPercentage);
fin = new BufferedReader(new FileReader(inputFileName));
}
@Override
void reset() throws FileNotFoundException {
current = 0;
fin = new BufferedReader(new FileReader(new File(inputFileName)));
lineNr = 0;
try {
while (fin.ready()) {
final String str = nextLine();
if (str == null) {
return;
}
final String lower = str.toLowerCase();
if (lower.matches("^\\s*begin\\s+trees;\\s*$")) {
parseTreesBlock();
return;
}
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Around line " + lineNr + "\n" + e.getMessage());
}
} // parseFile
/**
* read next line from Nexus file that is not a comment and not empty
* @throws IOException *
*/
String nextLine() throws IOException {
String str = readLine();
if (str == null) {
return null;
}
if (str.contains("[")) {
final int start = str.indexOf('[');
int end = str.indexOf(']', start);
while (end < 0) {
str += readLine();
end = str.indexOf(']', start);
}
str = str.substring(0, start) + str.substring(end + 1);
if (str.matches("^\\s*$")) {
return nextLine();
}
}
if (str.matches("^\\s*$")) {
return nextLine();
}
return str;
}
/**
* read line from nexus file *
*/
String readLine() throws IOException {
if (!fin.ready()) {
return null;
}
lineNr++;
return fin.readLine();
}
private void parseTreesBlock() throws IOException {
// read to first non-empty line within trees block
String str = fin.readLine().trim();
while (str.equals("")) {
str = fin.readLine().trim();
}
// if first non-empty line is "translate" then parse translate block
if (str.toLowerCase().contains("translate")) {
translationMap = parseTranslateBlock();
origin = getIndexedTranslationMapOrigin(translationMap);
if (origin != -1) {
taxa = getIndexedTranslationMap(translationMap, origin);
}
}
// we got to the end of the translate block
// read bunrinCount trees
current = 0;
while (current < burninCount && fin.ready()) {
str = nextLine();
if (str.toLowerCase().startsWith("tree ")) {
current++;
}
}
}
private List<String> getIndexedTranslationMap(final Map<String, String> translationMap, final int origin) {
//System.out.println("translation map size = " + translationMap.size());
final String[] taxa = new String[translationMap.size()];
for (final String key : translationMap.keySet()) {
taxa[Integer.parseInt(key) - origin] = translationMap.get(key);
}
return Arrays.asList(taxa);
}
/**
* @param translationMap
* @return minimum key value if keys are a contiguous set of integers starting from zero or one, -1 otherwise
*/
private int getIndexedTranslationMapOrigin(final Map<String, String> translationMap) {
final SortedSet<Integer> indices = new java.util.TreeSet<>();
int count = 0;
for (final String key : translationMap.keySet()) {
final int index = Integer.parseInt(key);
indices.add(index);
count += 1;
}
if ((indices.last() - indices.first() == count - 1) && (indices.first() == 0 || indices.first() == 1)) {
return indices.first();
}
return -1;
}
/**
* @return a map of taxa translations, keys are generally integer node number starting from 1
* whereas values are generally descriptive strings.
* @throws IOException
*/
private Map<String, String> parseTranslateBlock() throws IOException {
final Map<String, String> translationMap = new HashMap<>();
String line = readLine();
final StringBuilder translateBlock = new StringBuilder();
while (line != null && !line.trim().toLowerCase().equals(";")) {
translateBlock.append(line.trim());
line = readLine();
}
final String[] taxaTranslations = translateBlock.toString().split(",");
for (final String taxaTranslation : taxaTranslations) {
final String[] translation = taxaTranslation.split("[\t ]+");
if (translation.length == 2) {
translationMap.put(translation[0], translation[1]);
// System.out.println(translation[0] + " -> " + translation[1]);
} else {
Log.err.println("Ignoring translation:" + Arrays.toString(translation));
}
}
return translationMap;
}
@Override
boolean hasNext() {
return current < totalTrees;
}
@Override
Tree next() throws IOException {
String str = nextLine();
if (!isNexus) {
TreeParser treeParser;
if (origin != -1) {
treeParser = new TreeParser(taxa, str, origin, false);
} else {
try {
treeParser = new TreeParser(taxa, str, 0, false);
} catch (ArrayIndexOutOfBoundsException e) {
treeParser = new TreeParser(taxa, str, 1, false);
}
}
return treeParser;
}
// read trees from NEXUS file
if (str.toLowerCase().startsWith("tree ")) {
current++;
final int i = str.indexOf('(');
if (i > 0) {
str = str.substring(i);
}
TreeParser treeParser;
if (origin != -1) {
treeParser = new TreeParser(taxa, str, origin, false);
} else {
try {
treeParser = new TreeParser(taxa, str, 0, false);
} catch (ArrayIndexOutOfBoundsException e) {
treeParser = new TreeParser(taxa, str, 1, false);
}
}
if (translationMap != null) treeParser.translateLeafIds(translationMap);
return treeParser;
}
return null;
}
}
TreeSet treeSet;
enum Target {
MAX_CLADE_CREDIBILITY("Maximum clade credibility tree"),
MAX_SUM_CLADE_CREDIBILITY("Maximum sum of clade credibilities"),
USER_TARGET_TREE("User target tree");
String desc;
Target(String s) {
desc = s;
}
@Override
public String toString() {
return desc;
}
}
enum HeightsSummary {
CA_HEIGHTS("Common Ancestor heights"),
MEDIAN_HEIGHTS("Median heights"),
MEAN_HEIGHTS("Mean heights"),
KEEP_HEIGHTS("Keep target heights");
String desc;
HeightsSummary(String s) {
desc = s;
}
@Override
public String toString() {
return desc;
}
}
// Messages to stderr, output to stdout
static PrintStream progressStream = Log.err;
// private final String location1Attribute = "longLat1";
// private final String location2Attribute = "longLat2";
// private final String locationOutputAttribute = "location";
public TreeAnnotator() { }
public TreeAnnotator(final int burninPercentage,
boolean lowMemory, // allowSingleChild was defunct (always set to false), now replaced by flag to say how much
HeightsSummary heightsOption,
double posteriorLimit,
double hpd2D,
Target targetOption,
String targetTreeFileName,
String inputFileName,
String outputFileName
) throws IOException {
this.posteriorLimit = posteriorLimit;
this.hpd2D = hpd2D;
attributeNames.add("height");
attributeNames.add("length");
CladeSystem cladeSystem = new CladeSystem();
totalTrees = 10000;
totalTreesUsed = 0;
try {
if (lowMemory) {
treeSet = new MemoryFriendlyTreeSet(inputFileName, burninPercentage);
} else {
treeSet = new FastTreeSet(inputFileName, burninPercentage);
}
} catch (Exception e) {
e.printStackTrace();
Log.err.println("Error Parsing Input Tree: " + e.getMessage());
return;
}
if (targetOption != Target.USER_TARGET_TREE) {
try {
treeSet.reset();
while (treeSet.hasNext()) {
Tree tree = treeSet.next();
tree.getLeafNodeCount();
if (tree.getDirectAncestorNodeCount() > 0 && !SAmode) {
SAmode = true;
Log.err.println("A tree with a sampled ancestor is found. Turning on\n the sampled ancestor " +
"summary analysis.");
if (heightsOption == HeightsSummary.CA_HEIGHTS) {
throw new RuntimeException("The common ancestor height is not \n available for trees with sampled " +
"ancestors. Please choose \n another height summary option");
}
}
cladeSystem.add(tree, false);
totalTreesUsed++;
}
totalTrees = totalTreesUsed * 100 / (100-Math.max(burninPercentage, 0));
} catch (Exception e) {
Log.err.println(e.getMessage());
return;
}
progressStream.println();
progressStream.println();
if (totalTrees < 1) {
Log.err.println("No trees");
return;
}
if (totalTreesUsed <= 1) {
if (burninPercentage > 0) {
Log.err.println("No trees to use: burnin too high");
return;
}
}
cladeSystem.calculateCladeCredibilities(totalTreesUsed);
progressStream.println("Total trees have " + totalTrees + ", where " + totalTreesUsed + " are used.");
progressStream.println("Total unique clades: " + cladeSystem.getCladeMap().keySet().size());
progressStream.println();
} else {
// even when a user specificed target tree is provided we still need to count the totalTreesUsed for subsequent steps.
treeSet.reset();
while (treeSet.hasNext()) {
Tree tree = treeSet.next();
tree.getLeafNodeCount();
if (tree.getDirectAncestorNodeCount() > 0 && !SAmode) {
SAmode = true;
Log.err.println("A tree with a sampled ancestor is found. Turning on\n the sampled ancestor " +
"summary analysis.");
if (heightsOption == HeightsSummary.CA_HEIGHTS) {
throw new RuntimeException("The common ancestor height is not \n available for trees with sampled " +
"ancestors. Please choose \n another height summary option");
}
}
totalTreesUsed++;
}
}
Tree targetTree = null;
switch (targetOption) {
case USER_TARGET_TREE: {
if (targetTreeFileName != null) {
progressStream.println("Reading user specified target tree, " + targetTreeFileName);
String tree = BeautiDoc.load(targetTreeFileName);
if (tree.startsWith("#NEXUS")) {
NexusParser parser2 = new NexusParser();
parser2.parseFile(new File(targetTreeFileName));
targetTree = parser2.trees.get(0);
} else {
try {
TreeParser parser2 = new TreeParser();
parser2.initByName("IsLabelledNewick", true, "newick", tree);
targetTree = parser2;
} catch (Exception e) {
Log.err.println("Error Parsing Target Tree: " + e.getMessage());
return;
}
}
} else {
Log.err.println("No user target tree specified.");
return;
}
break;
}
case MAX_CLADE_CREDIBILITY: {
progressStream.println("Finding maximum credibility tree...");
targetTree = summarizeTrees(cladeSystem, false).copy();
break;
}
case MAX_SUM_CLADE_CREDIBILITY: {
progressStream.println("Finding maximum sum clade credibility tree...");
targetTree = summarizeTrees(cladeSystem, true).copy();
break;
}
}
progressStream.println("Collecting node information...");
progressStream.println("0 25 50 75 100");
progressStream.println("|
int stepSize = Math.max(totalTreesUsed / 60, 1);
int reported = 0;
// this call increments the clade counts and it shouldn't
// this is remedied with removeClades call after while loop below
cladeSystem = new CladeSystem(targetTree);
int totalTreesUsedNew = 0;
try {
int counter = 0;
treeSet.reset();
while (treeSet.hasNext()) {
Tree tree = treeSet.next();
if (counter == 0) {
setupAttributes(tree);
}
cladeSystem.collectAttributes(tree, attributeNames);
if (counter > 0 && counter % stepSize == 0 && reported < 61) {
while (1000 * reported < 61000 * (counter + 1)/ this.totalTreesUsed) {
progressStream.print("*");
reported++;
}
progressStream.flush();
}
totalTreesUsedNew++;
counter++;
}
cladeSystem.removeClades(targetTree.getRoot(), true);
this.totalTreesUsed = totalTreesUsedNew;
cladeSystem.calculateCladeCredibilities(totalTreesUsedNew);
} catch (Exception e) {
Log.err.println("Error Parsing Input Tree: " + e.getMessage());
return;
}
progressStream.println();
progressStream.println();
progressStream.println("Annotating target tree...");
try {
annotateTree(cladeSystem, targetTree.getRoot(), null, heightsOption);
if( heightsOption == HeightsSummary.CA_HEIGHTS ) {
setTreeHeightsByCA(targetTree);
}
} catch (Exception e) {
e.printStackTrace();
Log.err.println("Error to annotate tree: " + e.getMessage() + "\nPlease check the tree log file format.");
return;
}
progressStream.println("Writing annotated tree....");
processMetaData(targetTree.getRoot());
try {
final PrintStream stream = outputFileName != null ?
new PrintStream(new FileOutputStream(outputFileName)) :
System.out;
targetTree.init(stream);
stream.println();
stream.print("tree TREE1 = ");
int[] dummy = new int[1];
String newick = targetTree.getRoot().toSortedNewick(dummy, true);
stream.print(newick);
stream.println(";");
// stream.println(targetTree.getRoot().toShortNewick(false));
// stream.println();
targetTree.close(stream);
stream.println();
} catch (Exception e) {
Log.err.println("Error to write annotated tree file: " + e.getMessage());
return;
}
}
private void processMetaData(Node node) {
for (Node child : node.getChildren()) {
processMetaData(child);
}
Set<String> metaDataNames = node.getMetaDataNames();
if (metaDataNames != null && !metaDataNames.isEmpty()) {
String metadata = "";
for (String name : metaDataNames) {
Object value = node.getMetaData(name);
metadata += name + "=";
if (value instanceof Object[]) {
Object [] values = (Object[]) value;
metadata += "{";
for (int i = 0; i < values.length; i++) {
metadata += values[i].toString();
if (i < values.length - 1) {
metadata += ",";
}
}
metadata += "}";
} else {
metadata += value.toString();
}
metadata += ",";
}
metadata = metadata.substring(0, metadata.length() - 1);
node.metaDataString = metadata;
}
}
private void setupAttributes(Tree tree) {
for (int i = 0; i < tree.getNodeCount(); i++) {
Node node = tree.getNode(i);
Set<String> iter = node.getMetaDataNames();
if (iter != null) {
for (String name : iter) {
attributeNames.add(name);
}
}
}
for (TreeAnnotationPlugin beastObject : beastObjects) {
Set<String> claimed = beastObject.setAttributeNames(attributeNames);
attributeNames.removeAll(claimed);
}
}
private Tree summarizeTrees(CladeSystem cladeSystem, boolean useSumCladeCredibility) throws IOException {
Tree bestTree = null;
double bestScore = Double.NEGATIVE_INFINITY;
progressStream.println("Analyzing " + totalTreesUsed + " trees...");
progressStream.println("0 25 50 75 100");
progressStream.println("|
int stepSize = Math.max(totalTreesUsed / 60, 1);
int reported = 0;
int counter = 0;
treeSet.reset();
while (treeSet.hasNext()) {
Tree tree = treeSet.next();
double score = scoreTree(tree, cladeSystem, useSumCladeCredibility);
if (score > bestScore) {
bestTree = tree;
bestScore = score;
}
if (counter % stepSize == 0 && reported < 61) {
while (1000*reported < 61000 * (counter + 1) / totalTreesUsed) {
progressStream.print("*");
reported++;
}
progressStream.flush();
}
counter++;
}
progressStream.println();
progressStream.println();
if (useSumCladeCredibility) {
progressStream.println("Highest Sum Clade Credibility: " + bestScore);
} else {
progressStream.println("Highest Log Clade Credibility: " + bestScore);
}
return bestTree;
}
public double scoreTree(Tree tree, CladeSystem cladeSystem, boolean useSumCladeCredibility) {
if (useSumCladeCredibility) {
return cladeSystem.getSumCladeCredibility(tree.getRoot(), null);
} else {
return cladeSystem.getLogCladeCredibility(tree.getRoot(), null);
}
}
private void annotateTree(CladeSystem cladeSystem, Node node, BitSet bits, HeightsSummary heightsOption) {
BitSet bits2 = new BitSet();
if (node.isLeaf()) {
int index = cladeSystem.getTaxonIndex(node);
bits2.set(2*index);
annotateNode(cladeSystem, node, bits2, true, heightsOption);
} else {
for (int i = 0; i < node.getChildCount(); i++) {
Node node1 = node.getChild(i);
annotateTree(cladeSystem, node1, bits2, heightsOption);
}
for (int i=1; i<bits2.length(); i=i+2) {
bits2.set(i, false);
}
if (node.isFake()) {
int index = cladeSystem.getTaxonIndex(node.getDirectAncestorChild());
bits2.set(2 * index + 1);
}
annotateNode(cladeSystem, node, bits2, false, heightsOption);
}
if (bits != null) {
bits.or(bits2);
}
}
private void annotateNode(CladeSystem cladeSystem, Node node, BitSet bits, boolean isTip, HeightsSummary heightsOption) {
CladeSystem.Clade clade = cladeSystem.cladeMap.get(bits);
assert clade != null : "Clade missing?";
boolean filter = false;
if (!isTip) {
final double posterior = clade.getCredibility();
node.setMetaData("posterior", posterior);
if (posterior < posteriorLimit) {
filter = true;
}
}
int i = 0;
for (String attributeName : attributeNames) {
if (clade.attributeValues != null && clade.attributeValues.size() > 0) {
double[] values = new double[clade.attributeValues.size()];
HashMap<Object, Integer> hashMap = new HashMap<>();
Object[] v = clade.attributeValues.get(0);
if (v[i] != null) {
final boolean isHeight = attributeName.equals("height");
boolean isBoolean = v[i] instanceof Boolean;
boolean isDiscrete = v[i] instanceof String;
if (forceIntegerToDiscrete && v[i] instanceof Integer) isDiscrete = true;
double minValue = Double.MAX_VALUE;
double maxValue = -Double.MAX_VALUE;
final boolean isArray = v[i] instanceof Object[];
boolean isDoubleArray = isArray && ((Object[]) v[i])[0] instanceof Double;
// This is Java, friends - first value type does not imply all.
if (isDoubleArray) {
for (Object n : (Object[]) v[i]) {
if (!(n instanceof Double)) {
isDoubleArray = false;
break;
}
}
}
// todo Handle other types of arrays
double[][] valuesArray = null;
double[] minValueArray = null;
double[] maxValueArray = null;
int lenArray = 0;
if (isDoubleArray) {
lenArray = ((Object[]) v[i]).length;
valuesArray = new double[lenArray][clade.attributeValues.size()];
minValueArray = new double[lenArray];
maxValueArray = new double[lenArray];
for (int k = 0; k < lenArray; k++) {
minValueArray[k] = Double.MAX_VALUE;
maxValueArray[k] = -Double.MAX_VALUE;
}
}
for (int j = 0; j < clade.attributeValues.size(); j++) {
Object value = clade.attributeValues.get(j)[i];
if (isDiscrete) {
final Object s = value;
if (hashMap.containsKey(s)) {
hashMap.put(s, hashMap.get(s) + 1);
} else {
hashMap.put(s, 1);
}
} else if (isBoolean) {
values[j] = (((Boolean) value) ? 1.0 : 0.0);
} else if (isDoubleArray) {
// Forcing to Double[] causes a cast exception. MAS
try {
Object[] array = (Object[]) value;
for (int k = 0; k < lenArray; k++) {
valuesArray[k][j] = ((Double) array[k]);
if (valuesArray[k][j] < minValueArray[k]) minValueArray[k] = valuesArray[k][j];
if (valuesArray[k][j] > maxValueArray[k]) maxValueArray[k] = valuesArray[k][j];
}
} catch (Exception e) {
// ignore
}
} else {
// Ignore other (unknown) types
if (value instanceof Number) {
values[j] = ((Number) value).doubleValue();
if (values[j] < minValue) minValue = values[j];
if (values[j] > maxValue) maxValue = values[j];
}
}
}
if (isHeight) {
if (heightsOption == HeightsSummary.MEAN_HEIGHTS) {
final double mean = DiscreteStatistics.mean(values);
if (node.isDirectAncestor()) {
node.getParent().setHeight(mean);
}
if (node.isFake()) {
node.getDirectAncestorChild().setHeight(mean);
}
node.setHeight(mean);
} else if (heightsOption == HeightsSummary.MEDIAN_HEIGHTS) {
final double median = DiscreteStatistics.median(values);
if (node.isDirectAncestor()) {
node.getParent().setHeight(median);
}
if (node.isFake()) {
node.getDirectAncestorChild().setHeight(median);
}
node.setHeight(median);
} else {
// keep the existing height
}
}
if (!filter) {
boolean processed = false;
for (TreeAnnotationPlugin beastObject : beastObjects) {
if (beastObject.handleAttribute(node, attributeName, values)) {
processed = true;
}
}
if (!processed) {
if (!isDiscrete) {
if (!isDoubleArray)
annotateMeanAttribute(node, attributeName, values);
else {
for (int k = 0; k < lenArray; k++) {
annotateMeanAttribute(node, attributeName + (k + 1), valuesArray[k]);
}
}
} else {
annotateModeAttribute(node, attributeName, hashMap);
annotateFrequencyAttribute(node, attributeName, hashMap);
}
if (!isBoolean && minValue < maxValue && !isDiscrete && !isDoubleArray) {
// Basically, if it is a boolean (0, 1) then we don't need the distribution information
// Likewise if it doesn't vary.
annotateMedianAttribute(node, attributeName + "_median", values);
annotateHPDAttribute(node, attributeName + "_95%_HPD", 0.95, values);
annotateRangeAttribute(node, attributeName + "_range", values);
}
if (isDoubleArray) {
String name = attributeName;
// todo
// if (name.equals(location1Attribute)) {
// name = locationOutputAttribute;
boolean want2d = processBivariateAttributes && lenArray == 2;
if (name.equals("dmv")) { // terrible hack
want2d = false;
}
for (int k = 0; k < lenArray; k++) {
if (minValueArray[k] < maxValueArray[k]) {
annotateMedianAttribute(node, name + (k + 1) + "_median", valuesArray[k]);
annotateRangeAttribute(node, name + (k + 1) + "_range", valuesArray[k]);
if (!want2d)
annotateHPDAttribute(node, name + (k + 1) + "_95%_HPD", 0.95, valuesArray[k]);
}
}
// 2D contours
if (want2d) {
boolean variationInFirst = (minValueArray[0] < maxValueArray[0]);
boolean variationInSecond = (minValueArray[1] < maxValueArray[1]);
if (variationInFirst && !variationInSecond)
annotateHPDAttribute(node, name + "1" + "_95%_HPD", 0.95, valuesArray[0]);
if (variationInSecond && !variationInFirst)
annotateHPDAttribute(node, name + "2" + "_95%_HPD", 0.95, valuesArray[1]);
if (variationInFirst && variationInSecond)
annotate2DHPDAttribute(node, name, "_" + (int) (100 * hpd2D) + "%HPD", hpd2D, valuesArray);
}
}
}
}
}
}
i++;
}
}
private void annotateMeanAttribute(Node node, String label, double[] values) {
double mean = DiscreteStatistics.mean(values);
node.setMetaData(label, mean);
}
private void annotateMedianAttribute(Node node, String label, double[] values) {
double median = DiscreteStatistics.median(values);
node.setMetaData(label, median);
}
private void annotateModeAttribute(Node node, String label, HashMap<Object, Integer> values) {
Object mode = null;
int maxCount = 0;
int totalCount = 0;
int countInMode = 1;
for (Object key : values.keySet()) {
int thisCount = values.get(key);
if (thisCount == maxCount) {
// I hope this is the intention
mode = mode.toString().concat("+" + key);
countInMode++;
} else if (thisCount > maxCount) {
mode = key;
maxCount = thisCount;
countInMode = 1;
}
totalCount += thisCount;
}
double freq = (double) maxCount / (double) totalCount * countInMode;
node.setMetaData(label, mode);
node.setMetaData(label + ".prob", freq);
}
private void annotateFrequencyAttribute(Node node, String label, HashMap<Object, Integer> values) {
double totalCount = 0;
Set<?> keySet = values.keySet();
int length = keySet.size();
String[] name = new String[length];
Double[] freq = new Double[length];
int index = 0;
for (Object key : values.keySet()) {
name[index] = key.toString();
freq[index] = new Double(values.get(key));
totalCount += freq[index];
index++;
}
for (int i = 0; i < length; i++)
freq[i] /= totalCount;
node.setMetaData(label + ".set", name);
node.setMetaData(label + ".set.prob", freq);
}
private void annotateRangeAttribute(Node node, String label, double[] values) {
double min = DiscreteStatistics.min(values);
double max = DiscreteStatistics.max(values);
node.setMetaData(label, new Object[]{min, max});
}
private void annotateHPDAttribute(Node node, String label, double hpd, double[] values) {
int[] indices = new int[values.length];
HeapSort.sort(values, indices);
double minRange = Double.MAX_VALUE;
int hpdIndex = 0;
int diff = (int) Math.round(hpd * values.length);
for (int i = 0; i <= (values.length - diff); i++) {
double minValue = values[indices[i]];
double maxValue = values[indices[i + diff - 1]];
double range = Math.abs(maxValue - minValue);
if (range < minRange) {
minRange = range;
hpdIndex = i;
}
}
double lower = values[indices[hpdIndex]];
double upper = values[indices[hpdIndex + diff - 1]];
node.setMetaData(label, new Object[]{lower, upper});
}
// todo Move rEngine to outer class; create once.
// Rengine rEngine = null;
// private final String[] rArgs = {"--no-save"};
// private final String[] rBootCommands = {
// "library(MASS)",
// "makeContour = function(var1, var2, prob=0.95, n=50, h=c(1,1)) {" +
// "post1 = kde2d(var1, var2, n = n, h=h); " + // This had h=h in argument
// "dx = diff(post1$x[1:2]); " +
// "dy = diff(post1$y[1:2]); " +
// "sz = sort(post1$z); " +
// "c1 = cumsum(sz) * dx * dy; " +
// "levels = sapply(prob, function(x) { approx(c1, sz, xout = 1 - x)$y }); " +
// "line = contourLines(post1$x, post1$y, post1$z, level = levels); " +
// "return(line) }"
// private String makeRString(double[] values) {
// StringBuffer sb = new StringBuffer("c(");
// sb.append(values[0]);
// for (int i = 1; i < values.length; i++) {
// sb.append(",");
// sb.append(values[i]);
// sb.append(")");
// return sb.toString();
public static final String CORDINATE = "cordinates";
// private String formattedLocation(double loc1, double loc2) {
// return formattedLocation(loc1) + "," + formattedLocation(loc2);
private String formattedLocation(double x) {
return String.format("%5.2f", x);
}
private void annotate2DHPDAttribute(Node node, String preLabel, String postLabel,
double hpd, double[][] values) {
if (USE_R) {
// Uses R-Java interface, and the HPD routines from 'emdbook' and 'coda'
// int N = 50;
// if (rEngine == null) {
// if (!Rengine.versionCheck()) {
// throw new RuntimeException("JRI library version mismatch");
// rEngine = new Rengine(rArgs, false, null);
// if (!rEngine.waitForR()) {
// throw new RuntimeException("Cannot load R");
// for (String command : rBootCommands) {
// rEngine.eval(command);
// // todo Need a good method to pick grid size
// REXP x = rEngine.eval("makeContour(" +
// makeRString(values[0]) + "," +
// makeRString(values[1]) + "," +
// hpd + "," +
// RVector contourList = x.asVector();
// int numberContours = contourList.size();
// if (numberContours > 1) {
// Log.err.println("Warning: a node has a disjoint " + 100 * hpd + "% HPD region. This may be an artifact!");
// Log.err.println("Try decreasing the enclosed mass or increasing the number of samples.");
// node.setMetaData(preLabel + postLabel + "_modality", numberContours);
// StringBuffer output = new StringBuffer();
// for (int i = 0; i < numberContours; i++) {
// output.append("\n<" + CORDINATE + ">\n");
// RVector oneContour = contourList.at(i).asVector();
// double[] xList = oneContour.at(1).asDoubleArray();
// double[] yList = oneContour.at(2).asDoubleArray();
// StringBuffer xString = new StringBuffer("{");
// StringBuffer yString = new StringBuffer("{");
// for (int k = 0; k < xList.length; k++) {
// xString.append(formattedLocation(xList[k])).append(",");
// yString.append(formattedLocation(yList[k])).append(",");
// xString.append(formattedLocation(xList[0])).append("}");
// yString.append(formattedLocation(yList[0])).append("}");
// node.setMetaData(preLabel + "1" + postLabel + "_" + (i + 1), xString);
// node.setMetaData(preLabel + "2" + postLabel + "_" + (i + 1), yString);
} else { // do not use R
// KernelDensityEstimator2D kde = new KernelDensityEstimator2D(values[0], values[1], N);
//ContourMaker kde = new ContourWithSynder(values[0], values[1], N);
boolean bandwidthLimit = false;
ContourMaker kde = new ContourWithSynder(values[0], values[1], bandwidthLimit);
ContourPath[] paths = kde.getContourPaths(hpd);
node.setMetaData(preLabel + postLabel + "_modality", paths.length);
if (paths.length > 1) {
Log.err.println("Warning: a node has a disjoint " + 100 * hpd + "% HPD region. This may be an artifact!");
Log.err.println("Try decreasing the enclosed mass or increasing the number of samples.");
}
StringBuffer output = new StringBuffer();
int i = 0;
for (ContourPath p : paths) {
output.append("\n<" + CORDINATE + ">\n");
double[] xList = p.getAllX();
double[] yList = p.getAllY();
StringBuffer xString = new StringBuffer("{");
StringBuffer yString = new StringBuffer("{");
for (int k = 0; k < xList.length; k++) {
xString.append(formattedLocation(xList[k])).append(",");
yString.append(formattedLocation(yList[k])).append(",");
}
xString.append(formattedLocation(xList[0])).append("}");
yString.append(formattedLocation(yList[0])).append("}");
node.setMetaData(preLabel + "1" + postLabel + "_" + (i + 1), xString);
node.setMetaData(preLabel + "2" + postLabel + "_" + (i + 1), yString);
i++;
}
}
}
int totalTrees = 0;
int totalTreesUsed = 0;
double posteriorLimit = 0.0;
double hpd2D = 0.80;
private final List<TreeAnnotationPlugin> beastObjects = new ArrayList<>();
Set<String> attributeNames = new HashSet<>();
TaxonSet taxa = null;
static boolean processBivariateAttributes = false;
// static {
// try {
// System.loadLibrary("jri");
// processBivariateAttributes = true;
// Log.err.println("JRI loaded. Will process bivariate attributes");
// } catch (UnsatisfiedLinkError e) {
// Log.err.print("JRI not available. ");
// if (!USE_R) {
// processBivariateAttributes = true;
// Log.err.println("Using Java bivariate attributes");
// } else {
// Log.err.println("Will not process bivariate attributes");
public static void printTitle() {
progressStream.println();
centreLine("TreeAnnotator " + version.getVersionString() + ", " + version.getDateString(), 60);
centreLine("MCMC Output analysis", 60);
centreLine("by", 60);
centreLine("Andrew Rambaut and Alexei J. Drummond", 60);
progressStream.println();
centreLine("Institute of Evolutionary Biology", 60);
centreLine("University of Edinburgh", 60);
centreLine("a.rambaut@ed.ac.uk", 60);
progressStream.println();
centreLine("Department of Computer Science", 60);
centreLine("University of Auckland", 60);
centreLine("alexei@cs.auckland.ac.nz", 60);
progressStream.println();
progressStream.println();
}
public static void centreLine(String line, int pageWidth) {
int n = pageWidth - line.length();
int n1 = n / 2;
for (int i = 0; i < n1; i++) {
progressStream.print(" ");
}
progressStream.println(line);
}
public static void printUsage(Arguments arguments) {
arguments.printUsage("treeannotator", "<input-file-name> [<output-file-name>]");
progressStream.println();
progressStream.println(" Example: treeannotator test.trees out.txt");
progressStream.println(" Example: treeannotator -burnin 10 -heights mean test.trees out.txt");
progressStream.println(" Example: treeannotator -burnin 20 -target map.tree test.trees out.txt");
progressStream.println();
}
//Main method
public static void main(String[] args) throws IOException {
// There is a major issue with languages that use the comma as a decimal separator.
// To ensure compatibility between programs in the package, enforce the US locale.
Locale.setDefault(Locale.US);
String targetTreeFileName = null;
String inputFileName = null;
String outputFileName = null;
if (args.length == 0) {
Utils.loadUIManager();
System.setProperty("com.apple.macos.useScreenMenuBar", "true");
System.setProperty("apple.laf.useScreenMenuBar", "true");
System.setProperty("apple.awt.showGrowBox", "true");
java.net.URL url = LogCombiner.class.getResource("/images/utility.png");
javax.swing.Icon icon = null;
if (url != null) {
icon = new javax.swing.ImageIcon(url);
}
final String versionString = version.getVersionString();
String nameString = "TreeAnnotator " + versionString;
String aboutString = "<html><center><p>" + versionString + ", " + version.getDateString() + "</p>" +
"<p>by<br>" +
"Andrew Rambaut and Alexei J. Drummond</p>" +
"<p>Institute of Evolutionary Biology, University of Edinburgh<br>" +
"<a href=\"mailto:a.rambaut@ed.ac.uk\">a.rambaut@ed.ac.uk</a></p>" +
"<p>Department of Computer Science, University of Auckland<br>" +
"<a href=\"mailto:alexei@cs.auckland.ac.nz\">alexei@cs.auckland.ac.nz</a></p>" +
"<p>Part of the BEAST package:<br>" +
"<a href=\"http:
"</center></html>";
new ConsoleApplication(nameString, aboutString, icon, true);
Log.info = System.out;
Log.err = System.err;
// The ConsoleApplication will have overridden System.out so set progressStream
// to capture the output to the window:
progressStream = System.out;
printTitle();
TreeAnnotatorDialog dialog = new TreeAnnotatorDialog(new JFrame());
if (!dialog.showDialog("TreeAnnotator " + versionString)) {
return;
}
int burninPercentage = dialog.getBurninPercentage();
if (burninPercentage < 0) {
Log.warning.println("burnin percentage is " + burninPercentage + " but should be non-negative. Setting it to zero");
burninPercentage = 0;
}
if (burninPercentage >= 100) {
Log.err.println("burnin percentage is " + burninPercentage + " but should be less than 100.");
return;
}
double posteriorLimit = dialog.getPosteriorLimit();
double hpd2D = 0.80;
Target targetOption = dialog.getTargetOption();
HeightsSummary heightsOption = dialog.getHeightsOption();
targetTreeFileName = dialog.getTargetFileName();
if (targetOption == Target.USER_TARGET_TREE && targetTreeFileName == null) {
Log.err.println("No target file specified");
return;
}
inputFileName = dialog.getInputFileName();
if (inputFileName == null) {
Log.err.println("No input file specified");
return;
}
outputFileName = dialog.getOutputFileName();
if (outputFileName == null) {
Log.err.println("No output file specified");
return;
}
boolean lowMem = dialog.useLowMem();
try {
new TreeAnnotator(burninPercentage,
lowMem,
heightsOption,
posteriorLimit,
hpd2D,
targetOption,
targetTreeFileName,
inputFileName,
outputFileName);
} catch (Exception ex) {
Log.err.println("Exception: " + ex.getMessage());
}
progressStream.println("Finished - Quit program to exit.");
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
printTitle();
Arguments arguments = new Arguments(
new Arguments.Option[]{
//new Arguments.StringOption("target", new String[] { "maxclade", "maxtree" }, false, "an option of 'maxclade' or 'maxtree'"),
new Arguments.StringOption("heights", new String[]{"keep", "median", "mean", "ca"}, false,
"an option of 'keep' (default), 'median', 'mean' or 'ca'"),
new Arguments.IntegerOption("burnin", 0, 99, "the percentage of states to be considered as 'burn-in'"),
// allow -b as burnin option, just like other apps
new Arguments.IntegerOption("b", 0, 99, "the percentage of states to be considered as 'burn-in'"),
new Arguments.RealOption("limit", "the minimum posterior probability for a node to be annotated"),
new Arguments.StringOption("target", "target_file_name", "specifies a user target tree to be annotated"),
new Arguments.Option("help", "option to print this message"),
new Arguments.Option("forceDiscrete", "forces integer traits to be treated as discrete traits."),
new Arguments.Option("lowMem", "use less memory, which is a bit slower."),
new Arguments.RealOption("hpd2D", "the HPD interval to be used for the bivariate traits")
});
try {
arguments.parseArguments(args);
} catch (Arguments.ArgumentException ae) {
progressStream.println(ae);
printUsage(arguments);
System.exit(1);
}
if (arguments.hasOption("forceDiscrete")) {
Log.info.println(" Forcing integer traits to be treated as discrete traits.");
forceIntegerToDiscrete = true;
}
if (arguments.hasOption("help")) {
printUsage(arguments);
System.exit(0);
}
boolean lowMem = false;
if (arguments.hasOption("lowMem")) {
lowMem = true;
}
HeightsSummary heights = HeightsSummary.CA_HEIGHTS;
if (arguments.hasOption("heights")) {
String value = arguments.getStringOption("heights");
if (value.equalsIgnoreCase("mean")) {
heights = HeightsSummary.MEAN_HEIGHTS;
} else if (value.equalsIgnoreCase("median")) {
heights = HeightsSummary.MEDIAN_HEIGHTS;
} else if (value.equalsIgnoreCase("ca")) {
heights = HeightsSummary.CA_HEIGHTS;
Log.info.println("Please cite: Heled and Bouckaert: Looking for trees in the forest:\n" +
"summary tree from posterior samples. BMC Evolutionary Biology 2013 13:221.");
}
}
int burnin = -1;
if (arguments.hasOption("burnin")) {
burnin = arguments.getIntegerOption("burnin");
} else if (arguments.hasOption("b")) {
burnin = arguments.getIntegerOption("b");
}
if (burnin >= 100) {
Log.err.println("burnin percentage is " + burnin + " but should be less than 100.");
System.exit(1);
}
double posteriorLimit = 0.0;
if (arguments.hasOption("limit")) {
posteriorLimit = arguments.getRealOption("limit");
}
double hpd2D = 0.80;
if (arguments.hasOption("hpd2D")) {
hpd2D = arguments.getRealOption("hpd2D");
if (hpd2D <= 0 || hpd2D >=1) {
Log.err.println("hpd2D is a fraction and should be in between 0.0 and 1.0.");
System.exit(1);
}
processBivariateAttributes = true;
}
Target target = Target.MAX_CLADE_CREDIBILITY;
if (arguments.hasOption("target")) {
target = Target.USER_TARGET_TREE;
targetTreeFileName = arguments.getStringOption("target");
}
final String[] args2 = arguments.getLeftoverArguments();
switch (args2.length) {
case 2:
outputFileName = args2[1];
// fall to
case 1:
inputFileName = args2[0];
break;
default: {
Log.err.println("Unknown option: " + args2[2]);
Log.err.println();
printUsage(arguments);
System.exit(1);
}
}
try {
new TreeAnnotator(burnin, lowMem, heights, posteriorLimit, hpd2D, target, targetTreeFileName, inputFileName, outputFileName);
} catch (IOException e) {
throw e;
} catch (Exception e) {
e.printStackTrace();
}
System.exit(0);
}
/**
* @author Andrew Rambaut
* @version $Id$
*/
//TODO code review: it seems not necessary
public static interface TreeAnnotationPlugin {
Set<String> setAttributeNames(Set<String> attributeNames);
boolean handleAttribute(Node node, String attributeName, double[] values);
}
boolean setTreeHeightsByCA(Tree targetTree) throws IOException
{
progressStream.println("Setting node heights...");
progressStream.println("0 25 50 75 100");
progressStream.println("|
int reportStepSize = totalTreesUsed / 60;
if (reportStepSize < 1) reportStepSize = 1;
int reported = 0;
// this call increments the clade counts and it shouldn't
// this is remedied with removeClades call after while loop below
CladeSystem cladeSystem = new CladeSystem(targetTree);
final int clades = cladeSystem.getCladeMap().size();
// allocate posterior tree nodes order once
int[] postOrderList = new int[clades];
BitSet[] ctarget = new BitSet[clades];
BitSet[] ctree = new BitSet[clades];
for (int k = 0; k < clades; ++k) {
ctarget[k] = new BitSet();
ctree[k] = new BitSet();
}
cladeSystem.getTreeCladeCodes(targetTree, ctarget);
// temp collecting heights inside loop allocated once
double[] hs = new double[clades];
// heights total sum from posterior trees
double[] ths = new double[clades];
int totalTreesUsed = 0;
int counter = 0;
treeSet.reset();
while (treeSet.hasNext()) {
Tree tree = treeSet.next();
TreeUtils.preOrderTraversalList(tree, postOrderList);
cladeSystem.getTreeCladeCodes(tree, ctree);
for (int k = 0; k < clades; ++k) {
int j = postOrderList[k];
for (int i = 0; i < clades; ++i) {
if( CollectionUtils.isSubSet(ctarget[i], ctree[j]) ) {
hs[i] = tree.getNode(j).getHeight();
}
}
}
for (int k = 0; k < clades; ++k) {
ths[k] += hs[k];
}
totalTreesUsed += 1;
if (counter > 0 && counter % reportStepSize == 0 && reported < 61) {
while (1000 * reported < 61000 * (counter + 1)/ this.totalTreesUsed) {
progressStream.print("*");
reported++;
}
progressStream.flush();
}
counter++;
}
targetTree.initAndValidate();
cladeSystem.removeClades(targetTree.getRoot(), true);
for (int k = 0; k < clades; ++k) {
ths[k] /= totalTreesUsed;
final Node node = targetTree.getNode(k);
node.setHeight(ths[k]);
}
assert (totalTreesUsed == this.totalTreesUsed);
this.totalTreesUsed = totalTreesUsed;
progressStream.println();
progressStream.println();
return true;
}
}
|
package br.unisinos.tokens.impl;
import br.unisinos.MultiLineStringReader;
import br.unisinos.tokens.Token;
import br.unisinos.tokens.TokenParser;
import br.unisinos.tokens.TokenType;
import java.util.Optional;
public abstract class OperatorToken extends Token {
OperatorToken(TokenType type, String value) {
super(type, value);
}
private static Optional<String> tryParse(TokenType type, MultiLineStringReader input) {
MultiLineStringReader.Point point = input.mark();
StringBuilder sb = new StringBuilder();
while (input.hasMoreCharsOnSameLine() && Character.isLetter(input.peek())) {
sb.append(input.nextChar());
}
String text = sb.toString();
if (text.length() == 0 || !type.asTokenName().equalsIgnoreCase(text)) {
input.moveTo(point);
return Optional.empty();
}
return Optional.of(text);
}
public static class ThenOperatorToken extends OperatorToken {
ThenOperatorToken(String value) {
super(TokenType.THEN_OP, value);
}
public static class Parser implements TokenParser<ThenOperatorToken> {
@Override
public Optional<ThenOperatorToken> tryParse(MultiLineStringReader input) {
return OperatorToken.tryParse(TokenType.THEN_OP, input).map(ThenOperatorToken::new);
}
}
}
public static class AfterOperatorToken extends OperatorToken {
AfterOperatorToken(String value) {
super(TokenType.AFTER_OP, value);
}
public static class Parser implements TokenParser<OperatorToken> {
@Override
public Optional<OperatorToken> tryParse(MultiLineStringReader input) {
return OperatorToken.tryParse(TokenType.AFTER_OP, input).map(AfterOperatorToken::new);
}
}
}
}
|
package info.puzz.a10000sentences.utils;
import android.content.Context;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.widget.Toast;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
import info.puzz.a10000sentences.Preferences;
import info.puzz.a10000sentences.R;
import info.puzz.a10000sentences.models.Language;
import lombok.Getter;
public class Speech {
private static final String TAG = Speech.class.getSimpleName();
private TextToSpeech tts;
private final Context context;
private final Locale locale;
private final boolean languageFound;
private final boolean enabled;
private final Set<Integer> toastMessagesShown = new HashSet<>();
@Getter
private boolean initialized = false;
public Speech(Context context, Language language) {
this.context = context;
this.locale = findLocale(language);
this.languageFound = locale != null;
this.enabled = Preferences.isUseTTS(context);
if (!this.enabled) {
return;
}
tts = new TextToSpeech(context, new TextToSpeech.OnInitListener() {
@Override
public void onInit(int i) {
Speech.this.initialized = true;
}
});
tts.setPitch(1);
tts.setSpeechRate(0.75F);
tts.setLanguage(locale);
}
private static Locale findLocale(Language language) {
return findLocale(language.languageId);
}
private static Locale findLocale(String languageID) {
for (Locale locale : Locale.getAvailableLocales()) {
if (org.apache.commons.lang3.StringUtils.isEmpty(locale.getCountry()) && StringUtils.equals(locale.getLanguage(), languageID)) {
return locale;
}
}
for (Locale locale : Locale.getAvailableLocales()) {
if (StringUtils.equals(locale.getLanguage(), languageID)) {
return locale;
}
}
return null;
}
public void speech(String speech) {
if (!enabled) {
return;
}
if (!languageFound) {
showToastOnce(R.string.tts_language_not_available);
return;
}
if (!initialized) {
showToastOnce(R.string.tts_not_inititialized);
return;
}
/* Bundle bundle = new Bundle();
bundle.putFloat(TextToSpeech.Engine.KEY_PARAM_VOLUME, 1F);
tts.speak(speech, TextToSpeech.QUEUE_FLUSH, bundle, null);*/
tts.setLanguage(locale);
tts.speak(speech, TextToSpeech.QUEUE_FLUSH, null);
}
private void showToastOnce(int resId) {
if (toastMessagesShown.contains(resId)) {
return;
}
toastMessagesShown.add(resId);
Toast.makeText(context, resId, Toast.LENGTH_SHORT).show();
}
public void shutdown() {
if (tts != null) {
tts.shutdown();
}
}
public static void main(String[] args) {
System.out.println(findLocale("de"));
}
}
|
package cluster.worker;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.zip.GZIPInputStream;
import bitManipulations.Encode;
import utils.FastaSequence;
import utils.Spearman;
import utils.Translate;
public class ConstrainKMersToRegion
{
public static HashMap<String, Float> parseDistanceFileIgnoringComparisonsToSame( File file) throws Exception
{
HashMap<String, Float> map = new HashMap<String, Float>();
BufferedReader reader = new BufferedReader( new InputStreamReader(new GZIPInputStream(new
FileInputStream(file))));
reader.readLine();
for(String s = reader.readLine(); s != null; s= reader.readLine())
{
String[] splits = s.split("\t");
if( splits.length != 3)
throw new Exception("Unexpected file format " + file.getAbsolutePath());
if( ! splits[0].equals(splits[1]) )
{
String key = getKey(splits[0], splits[1]);
if( map.containsKey(key))
throw new Exception("Duplicate key " + key + " " + file.getAbsolutePath());
map.put(key, Float.parseFloat(splits[2]));
}
}
reader.close();
return map;
}
private static String getKey(String a, String b) throws Exception
{
a = a.replace("_"+ MakeMatrixWithAllKmers.EXPECTED_SUFFIX, "");
b = b.replace("_" + MakeMatrixWithAllKmers.EXPECTED_SUFFIX, "");
if( a.equals(b))
throw new Exception("Comparing identical objects");
if( a.compareTo(b) >0 )
{
return a + "@" + b;
}
return b + "@" + a;
}
/*
* The outer key is the genome name.
* The inner key is a encoding of the k-mer (encoded with Encode.makeLong()
* The inner value is the # of times that k-mer was seen in the genome
*/
private static HashMap<String, HashMap<Long,Integer>> getBigMap(File kmerDir, String[] files,
HashSet<String> constrainingSet) throws Exception
{
HashMap<String, HashMap<Long,Integer>> bigMap = new HashMap<String, HashMap<Long,Integer>>();
for( int x=0; x < files.length; x++)
{
File xFile = new File( kmerDir.getAbsolutePath() + File.separator + files[x]);
if( xFile.getName().toLowerCase().endsWith( MakeMatrixWithAllKmers.EXPECTED_SUFFIX))
{
String key = xFile.getName().replace("_" + MakeMatrixWithAllKmers.EXPECTED_SUFFIX, "");
if( bigMap.containsKey(key))
throw new Exception("Duplicate key " + key);
HashMap<String, Integer> countMap = MakeMatrixWithAllKmers.getCounts(xFile, constrainingSet);
HashMap<Long, Integer> innerMap = new HashMap<Long,Integer>();
bigMap.put(key, innerMap);
for(String s : countMap.keySet())
{
long aVal = Encode.makeLong(s);
if( innerMap.containsKey(aVal))
throw new Exception("Duplicate long " + aVal + " " + s);
innerMap.put(aVal, countMap.get(s));
}
}
}
return bigMap;
}
static long getSumSquare(HashMap<Long, Integer> counts)
{
long sum =0;
for( Integer i : counts.values())
sum = sum + i * i;
return sum;
}
static float getDistance(HashMap<Long, Integer> aMap, HashMap<Long, Integer> bMap,
long sumASquared, int kmerSize) throws Exception
{
long sumBSquared = getSumSquare(bMap);
long topSum = 0;
for( Long aLong : aMap.keySet() )
{
if( bMap.containsKey(aLong))
{
topSum += aMap.get(aLong) * bMap.get(aLong);
}
else
{
String s = Encode.getKmer(aLong, kmerSize);
String reverse = Translate.reverseTranscribe(s);
Long bLong = Encode.makeLong(reverse);
if( bMap.containsKey( bLong))
{
topSum += aMap.get(aLong) * bMap.get(bLong);
}
}
}
return (float) (1- topSum / Math.sqrt(sumASquared * sumBSquared));
}
private static HashMap<String, Float> getResultsFromConstrained(
HashSet<String> constrainingSet, HashMap<String, HashMap<Long,Integer>> bigMap,
int kmerSize) throws Exception
{
HashMap<String, Float> resultsMap = new HashMap<String,Float>();
List<String> genomeNames = new ArrayList<>( bigMap.keySet());
for( int x=0; x < genomeNames.size()-1; x++)
{
HashMap<Long, Integer> xMap = bigMap.get(genomeNames.get(x));
long sumXSquared = getSumSquare(xMap);
for(int y=x+1; y < genomeNames.size(); y++)
{
HashMap<Long, Integer> yMap = bigMap.get(genomeNames.get(y));
String key = getKey(genomeNames.get(x), genomeNames.get(y));
if( resultsMap.containsKey(key))
throw new Exception("Duplciate key " + key);
resultsMap.put(key, getDistance(xMap, yMap, sumXSquared, kmerSize));
}
}
return resultsMap;
}
public static void main(String[] args) throws Exception
{
if( args.length != 8)
{
System.out.println("usage kmerLength referenceGenomeFilepath contig startPos endPos kmerDirectory allTreeFile resultsFile");
System.exit(1);
}
File allTreeFile = new File(args[6]);
if( ! allTreeFile.exists() || ! allTreeFile.getName().toLowerCase().endsWith("gz"))
throw new Exception("All tree file must be a zipped comparison file; see MakeMatrixWithAllKmers");
File kmerDir = new File(args[5]);
if( ! kmerDir.exists() || ! kmerDir.isDirectory())
throw new Exception(args[5] + " is not an exisiting directory");
String[] files = kmerDir.list();
String seq = getConstrainingString(args[1], args[2], Integer.parseInt(args[3]), Integer.parseInt(args[4]));
Integer kmerSize = null;
try
{
kmerSize = Integer.parseInt(args[0]);
}
catch(Exception ex)
{
ex.printStackTrace();
}
if( kmerSize == null || kmerSize <= 0 )
{
throw new Exception("kmer argument (argument 0) must be a postive integer");
}
HashSet<String> set = getConstrainingSet(seq, kmerSize);
HashMap<String, HashMap<Long,Integer>> bigMap =getBigMap(kmerDir, files, set);
HashMap<String, Float> resultsFromAllTree = parseDistanceFileIgnoringComparisonsToSame(allTreeFile);
HashMap<String, Float> resultsFromConstrainedSet = getResultsFromConstrained(set, bigMap, kmerSize);
writeResults(resultsFromConstrainedSet, resultsFromAllTree,
new File(args[7]), new File(args[1]), args[2], Integer.parseInt(args[3]),
Integer.parseInt(args[4]));
}
private static void writeResults( HashMap<String, Float> constrainedMap, HashMap<String, Float> allTree,
File outFile, File genomeFile, String contigName, int startPos, int endPos) throws Exception
{
BufferedWriter writer = new BufferedWriter(new FileWriter(outFile));
List<Float> list1 = new ArrayList<Float>();
List<Float> list2 = new ArrayList<Float>();
for( String s : constrainedMap.keySet())
{
if( allTree.containsKey(s) )
{
list1.add(constrainedMap.get(s));
list2.add(allTree.get(s));
}
}
Spearman s = Spearman.getSpear(list1, list2);
writer.write(" Spearman distance = " + s.getRs() + "\n");
writer.write(" Spearman p = " + s.getProbrs() + "\n");
writer.write(" Number of kmers in Spearman = " + list1.size() + "\n");
writer.write(" Number of kmers in all tree = " + allTree.size() + "\n");
writer.write(" reference genome = " + genomeFile.getAbsolutePath() + "\n");
writer.write(" contig = " + contigName + "\n");
writer.write(" start to stop = " + startPos + " " + endPos + "\n");
writer.flush(); writer.close();
}
private static String getConstrainingString(String filepath, String contig, int startPos, int endPos) throws Exception
{
List<FastaSequence> list =
FastaSequence.readFastaFile(
filepath);
String toFind = contig;
for(FastaSequence fs : list)
if(fs.getFirstTokenOfHeader().equals(toFind))
{
return fs.getSequence().substring(startPos, endPos).toUpperCase();
}
throw new Exception("No");
}
private static HashSet<String> getConstrainingSet(String seq, int kmerLength) throws Exception
{
HashMap<String, Integer> map = new HashMap<String,Integer>();
for( int x=0; x < seq.length()- kmerLength; x++)
{
String sub = seq.substring(x, x + kmerLength);
if( MakeKmers.isACGT(sub))
{
MakeKmers.addToMap(map, seq, kmerLength);
}
}
MakeKmers.checkForNoReverse(map);
return new HashSet<String>(map.keySet());
}
public static void addToMap(HashMap<String, Integer> map, String seq, int kmerLength) throws Exception
{
for( int x=0; x < seq.length()- kmerLength; x++)
{
String sub = seq.substring(x, x + kmerLength);
if( MakeKmers.isACGT(sub))
{
Integer count = map.get(sub);
if( count == null)
{
String reverse = Translate.reverseTranscribe(sub);
count = map.get(reverse);
if( count != null)
sub = reverse;
}
if( count == null)
count =0;
count++;
map.put(sub,count);
}
}
}
}
|
package codeu.chat.client.simplegui;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.Stage;
import javafx.scene.text.*;
import javafx.collections.*;
import codeu.chat.client.ClientContext;
import codeu.chat.client.Controller;
import codeu.chat.client.View;
import codeu.chat.util.Logger;
public final class ChatGuiFX extends Application {
private final static Logger.Log LOG = Logger.newLog(ChatGuiFX.class);
private static final double WINDOW_WIDTH = 1000;
private static final double WINDOW_HEIGHT = 500;
private Stage thestage; // Holds the scene that user is currently viewing
private Scene signInScene, mainScene; // Scenes to hold all the elements for each page
private Button signInButton;
private TextField userInput;
private PasswordField passInput; // Takes input for username and password
private ClientContext clientContext;
public void run(String [] args) {
try {
// launches gui
Application.launch(ChatGuiFX.class, args);
} catch (Exception ex) {
System.out.println("ERROR: Exception in ChatGuiFX.run. Check log for details.");
LOG.error(ex, "Exception in ChatGuiFX.run");
System.exit(1);
}
}
public void launch(Controller controller, View view) {
this.clientContext = new ClientContext(controller, view);
Application.launch(ChatGuiFX.class);
}
@Override
public void start(Stage primaryStage) throws Exception {
// Sign in page
this.thestage = primaryStage; // Initialize the main stage
BorderPane signInPane = new BorderPane(); // Initialize panes
FlowPane signInLabelPane = new FlowPane();
HBox inputMasterBox = new HBox();
inputMasterBox.setSpacing(5);
VBox inputVBox = new VBox();
HBox usernameHBox = new HBox();
HBox passHBox = new HBox();
// Set Pane alignments
signInLabelPane.setAlignment(Pos.BOTTOM_CENTER);
inputMasterBox.setAlignment(Pos.CENTER);
inputVBox.setAlignment(Pos.CENTER);
usernameHBox.setAlignment(Pos.CENTER);
passHBox.setAlignment(Pos.CENTER);
Label signInLabel = new Label("Sign-in screen"); // Title for sign-in page
Label userLabel = new Label("Username:");
Label passLabel = new Label("Password:");
signInLabel.setFont(Font.font(20)); // Set style
userLabel.setFont(Font.font(15));
passLabel.setFont(Font.font(15));
signInButton = new Button("Sign in"); // Initialize sign in button
signInButton.setOnAction((event)-> buttonClicked(event)); // Initialize its event handler
userInput = new TextField();
passInput = new PasswordField(); // Set up password fields
userInput.setPromptText("Username"); // TODO: figure out if have the prompt text is overkill
passInput.setPromptText("Password");
userInput.setAlignment(Pos.CENTER);
passInput.setAlignment(Pos.CENTER);
signInLabelPane.getChildren().add(signInLabel); // Add labels to their respective panes
usernameHBox.getChildren().add(userLabel);
usernameHBox.getChildren().add(userInput); // Set up HBoxes to hold username and password labels/inputs
passHBox.getChildren().add(passLabel);
passHBox.getChildren().add(passInput);
inputVBox.getChildren().add(usernameHBox);
inputVBox.getChildren().add(passHBox); // Add those HBoxes to a VBox to stack them on top of each other
inputMasterBox.getChildren().add(inputVBox);
inputMasterBox.getChildren().add(signInButton); // Add that VBox and the signInButton to the inputMasterBox
signInPane.setTop(signInLabelPane);
signInPane.setCenter(inputMasterBox); // Add label and input box to the pane
signInScene = new Scene(signInPane, WINDOW_WIDTH, WINDOW_HEIGHT);
// Main Page
HBox hboxClient = new HBox();
HBox hboxInput = new HBox();
VBox userVBox = new VBox();
VBox chatVBox = new VBox();
VBox convosVBox = new VBox();
BorderPane container = new BorderPane();
Button send = new Button("Send");
Button update = new Button("Update");
Button addConvo = new Button("Add Conversation");
Text userTitle = new Text("Users");
Text chatTitle = new Text("Conversation"); // changed based on name?
Text convosTitle = new Text("Conversations");
TextFlow userTf = new TextFlow(userTitle);
TextFlow chatTf = new TextFlow(chatTitle);
TextFlow convosTf = new TextFlow(convosTitle);
TextField input = new TextField();
// MenuBar menuBar = new MenuBar();
// Menu menuAdd = new Menu("Add Conversation");
// menuBar.getMenus().addAll(menuConvo);
ObservableList<String> usersList = FXCollections.observableArrayList(
"Julia", "Ian", "Sue", "Matthew", "Hannah", "Stephan", "Denise");
ListView<String> users = new ListView<String>(usersList);
ObservableList<String> convoList = FXCollections.observableArrayList(
"Julia", "Ian", "Sue", "Matthew", "Hannah", "Stephan", "Denise");
ListView<String> conversations = new ListView<String>(convoList);
ObservableList<String> messageList = FXCollections.observableArrayList(
"Julia", "Ian", "Sue", "Matthew", "Hannah", "Stephan", "Denise");
ListView<String> messages = new ListView<String>(messageList);
// userTf.setStyle("-fx-base: #b6e7c9;");
VBox.setVgrow(users, Priority.ALWAYS);
VBox.setVgrow(conversations, Priority.ALWAYS);
VBox.setVgrow(messages, Priority.ALWAYS);
HBox.setHgrow(input, Priority.ALWAYS);
HBox.setHgrow(userVBox, Priority.ALWAYS);
HBox.setHgrow(chatVBox, Priority.ALWAYS);
HBox.setHgrow(convosVBox, Priority.ALWAYS);
send.setMinHeight(40);
update.setMinHeight(40);
input.setMinHeight(40);
addConvo.setMinHeight(40);
addConvo.setMaxWidth(Double.MAX_VALUE);
userTf.setMaxWidth(Double.MAX_VALUE);
userTf.setMinHeight(30);
chatTf.setMaxWidth(Double.MAX_VALUE);
chatTf.setMinHeight(30);
convosTf.setMaxWidth(Double.MAX_VALUE);
convosTf.setMinHeight(30);
userVBox.setMaxWidth(150);
chatVBox.setMaxWidth(Double.MAX_VALUE);
convosVBox.setMaxWidth(150);
hboxInput.getChildren().addAll(input, send, update);
userVBox.getChildren().addAll(userTf, users);
chatVBox.getChildren().addAll(chatTf, messages, hboxInput);
convosVBox.getChildren().addAll(convosTf, conversations, addConvo);
hboxClient.getChildren().addAll(userVBox, chatVBox, convosVBox);
container.setCenter(hboxClient);
// container.setTop(menuBar);
mainScene = new Scene(container, WINDOW_WIDTH, WINDOW_HEIGHT);
thestage.setScene(signInScene);
thestage.show();
}
private void buttonClicked(ActionEvent e)
{
thestage.setScene(mainScene); // TODO: Call a controller function here instead
}
}
|
package news.caughtup.caughtup.ws.remote;
import android.os.AsyncTask;
import com.google.gson.Gson;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import news.caughtup.caughtup.R;
import news.caughtup.caughtup.entities.ResponseObject;
public class RestClient implements IRest {
private static final String SERVER_URL = "http://" + R.string.server_dns + ":8080/caughtup";
@Override
public void getCall(String endPoint, String jsonData, Callback callback) {
new RequestTask(callback).execute(endPoint, jsonData, "GET");
}
@Override
public void postCall(String endPoint, String jsonData, Callback callback) {
new RequestTask(callback).execute(endPoint, "POST");
}
@Override
public void putCall(String endPoint, String jsonData, Callback callback) {
new RequestTask(callback).execute(endPoint, "PUT");
}
@Override
public void deleteCall(String endPoint, String jsonData, Callback callback) {
new RequestTask(callback).execute(endPoint, "DELETE");
}
private class RequestTask extends AsyncTask<String, Void, ResponseObject> {
private Callback callback;
public RequestTask(Callback callback) {
this.callback = callback;
}
@Override
protected ResponseObject doInBackground(String... params) {
HttpURLConnection urlConnection = null;
try {
URL url = new URL(SERVER_URL + params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
switch (params[2]) {
case "POST": urlConnection.setRequestMethod("POST");
case "PUT": urlConnection.setRequestMethod("PUT");
case "DELETE": urlConnection.setRequestMethod("DELETE");
default: urlConnection.setRequestMethod("GET");
}
if (!params[2].equals("GET")) {
urlConnection.setChunkedStreamingMode(0);
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/json");
}
urlConnection.setDoInput(true);
OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
writeStream(out, params[1]);
BufferedReader in = new BufferedReader(
new InputStreamReader(urlConnection.getInputStream()));
return new ResponseObject(urlConnection.getResponseCode(), readStream(in));
} catch (MalformedURLException e) {
System.err.println("Wrong url format");
} catch (IOException e) {
System.err.println("Error while trying to open a stream on the HTTP response");
} finally {
urlConnection.disconnect();
}
return null;
}
@Override
protected void onPostExecute(ResponseObject o) {
callback.process(o);
}
private Object readStream(BufferedReader in) {
StringBuilder sb = new StringBuilder();
try {
String line;
while ((line = in.readLine()) != null) {
sb.append(line);
}
Gson gson = new Gson();
return gson.fromJson(sb.toString(), Object.class);
} catch (IOException e) {
System.err.println("Error while trying to read content of response");
}
return null;
}
private void writeStream(OutputStream out, String jsonData) {
try {
out.write(jsonData.getBytes(Charset.forName("UTF-8")));
out.flush();
out.close();
} catch (IOException e) {
System.err.println("Error while trying to write to output stream");
}
}
}
}
|
package org.opendaylight.controller.sal.dom.broker;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.annotations.VisibleForTesting;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import org.opendaylight.controller.sal.core.api.model.SchemaService;
import org.opendaylight.controller.sal.dom.broker.impl.SchemaContextProvider;
import org.opendaylight.yangtools.concepts.ListenerRegistration;
import org.opendaylight.yangtools.concepts.Registration;
import org.opendaylight.yangtools.concepts.util.ListenerRegistry;
import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.model.api.SchemaServiceListener;
import org.opendaylight.yangtools.yang.parser.impl.util.URLSchemaContextResolver;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleEvent;
import org.osgi.framework.ServiceReference;
import org.osgi.util.tracker.BundleTracker;
import org.osgi.util.tracker.BundleTrackerCustomizer;
import org.osgi.util.tracker.ServiceTracker;
import org.osgi.util.tracker.ServiceTrackerCustomizer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
public class GlobalBundleScanningSchemaServiceImpl implements SchemaContextProvider, SchemaService, ServiceTrackerCustomizer<SchemaServiceListener, SchemaServiceListener>, AutoCloseable {
private static final Logger LOG = LoggerFactory.getLogger(GlobalBundleScanningSchemaServiceImpl.class);
private final ListenerRegistry<SchemaServiceListener> listeners = new ListenerRegistry<>();
private final URLSchemaContextResolver contextResolver = new URLSchemaContextResolver();
private final BundleScanner scanner = new BundleScanner();
private final BundleContext context;
private ServiceTracker<SchemaServiceListener, SchemaServiceListener> listenerTracker;
private BundleTracker<Iterable<Registration<URL>>> bundleTracker;
private boolean starting = true;
private static GlobalBundleScanningSchemaServiceImpl instance;
private GlobalBundleScanningSchemaServiceImpl(final BundleContext context) {
this.context = Preconditions.checkNotNull(context);
}
public synchronized static GlobalBundleScanningSchemaServiceImpl createInstance(final BundleContext ctx) {
Preconditions.checkState(instance == null);
instance = new GlobalBundleScanningSchemaServiceImpl(ctx);
instance.start();
return instance;
}
public synchronized static GlobalBundleScanningSchemaServiceImpl getInstance() {
Preconditions.checkState(instance != null, "Global Instance was not instantiated");
return instance;
}
@VisibleForTesting
public static synchronized void destroyInstance() {
instance = null;
}
public BundleContext getContext() {
return context;
}
public void start() {
checkState(context != null);
listenerTracker = new ServiceTracker<>(context, SchemaServiceListener.class, GlobalBundleScanningSchemaServiceImpl.this);
bundleTracker = new BundleTracker<>(context, BundleEvent.RESOLVED | BundleEvent.UNRESOLVED, scanner);
bundleTracker.open();
listenerTracker.open();
starting = false;
tryToUpdateSchemaContext();
}
@Override
public SchemaContext getSchemaContext() {
return getGlobalContext();
}
@Override
public SchemaContext getGlobalContext() {
return contextResolver.getSchemaContext().orNull();
}
@Override
public void addModule(final Module module) {
throw new UnsupportedOperationException();
}
@Override
public SchemaContext getSessionContext() {
throw new UnsupportedOperationException();
}
@Override
public void removeModule(final Module module) {
throw new UnsupportedOperationException();
}
@Override
public synchronized ListenerRegistration<SchemaServiceListener> registerSchemaServiceListener(final SchemaServiceListener listener) {
Optional<SchemaContext> potentialCtx = contextResolver.getSchemaContext();
if(potentialCtx.isPresent()) {
listener.onGlobalContextUpdated(potentialCtx.get());
}
return listeners.register(listener);
}
@Override
public void close() throws Exception {
if (bundleTracker != null) {
bundleTracker.close();
}
if (listenerTracker != null) {
listenerTracker.close();
}
// FIXME: Add listeners.close();
}
private synchronized void updateContext(final SchemaContext snapshot) {
Object[] services = listenerTracker.getServices();
for (ListenerRegistration<SchemaServiceListener> listener : listeners) {
try {
listener.getInstance().onGlobalContextUpdated(snapshot);
} catch (Exception e) {
LOG.error("Exception occured during invoking listener", e);
}
}
if (services != null) {
for (Object rawListener : services) {
SchemaServiceListener listener = (SchemaServiceListener) rawListener;
try {
listener.onGlobalContextUpdated(snapshot);
} catch (Exception e) {
LOG.error("Exception occured during invoking listener {}", listener, e);
}
}
}
}
private class BundleScanner implements BundleTrackerCustomizer<Iterable<Registration<URL>>> {
@Override
public Iterable<Registration<URL>> addingBundle(final Bundle bundle, final BundleEvent event) {
if (bundle.getBundleId() == 0) {
return Collections.emptyList();
}
final Enumeration<URL> enumeration = bundle.findEntries("META-INF/yang", "*.yang", false);
if (enumeration == null) {
return Collections.emptyList();
}
final List<Registration<URL>> urls = new ArrayList<>();
while (enumeration.hasMoreElements()) {
final URL u = enumeration.nextElement();
try {
urls.add(contextResolver.registerSource(u));
LOG.debug("Registered {}", u);
} catch (Exception e) {
LOG.warn("Failed to register {}, ignoring it", e);
}
}
if (!urls.isEmpty()) {
LOG.debug("Loaded {} new URLs, rebuilding schema context", urls.size());
tryToUpdateSchemaContext();
}
return ImmutableList.copyOf(urls);
}
@Override
public void modifiedBundle(final Bundle bundle, final BundleEvent event, final Iterable<Registration<URL>> object) {
LOG.debug("Modified bundle {} {} {}", bundle, event, object);
}
/**
* If removing YANG files makes yang store inconsistent, method
* {@link #getYangStoreSnapshot()} will throw exception. There is no
* rollback.
*/
@Override
public synchronized void removedBundle(final Bundle bundle, final BundleEvent event, final Iterable<Registration<URL>> urls) {
for (Registration<URL> url : urls) {
try {
url.close();
} catch (Exception e) {
LOG.warn("Failed do unregister URL {}, proceeding", url, e);
}
}
tryToUpdateSchemaContext();
}
}
@Override
public synchronized SchemaServiceListener addingService(final ServiceReference<SchemaServiceListener> reference) {
SchemaServiceListener listener = context.getService(reference);
SchemaContext _ctxContext = getGlobalContext();
if (getContext() != null && _ctxContext != null) {
listener.onGlobalContextUpdated(_ctxContext);
}
return listener;
}
public synchronized void tryToUpdateSchemaContext() {
if (starting) {
return;
}
Optional<SchemaContext> schema = contextResolver.tryToUpdateSchemaContext();
if(schema.isPresent()) {
updateContext(schema.get());
}
}
@Override
public void modifiedService(final ServiceReference<SchemaServiceListener> reference, final SchemaServiceListener service) {
// NOOP
}
@Override
public void removedService(final ServiceReference<SchemaServiceListener> reference, final SchemaServiceListener service) {
context.ungetService(reference);
}
}
|
package org.openwms.tms.domain.comparator;
import java.io.Serializable;
import java.util.Comparator;
import org.openwms.tms.domain.order.TransportOrder;
/**
* A TransportStartComparator. I used to sort TransportOrders is a particular
* order. Unfortunately some fields of the TransportOrder class are defined as
* Enums for a better handling in business logic. Persisting these fields as
* Strings makes it impossible to do a proper sorting in the database with JPA.
* Hence we must do it with Comparators in the application layer.
*
* @author <a href="mailto:scherrer@openwms.org">Heiko Scherrer</a>
* @version $Revision$
* @since 0.1
* @see {@link org.openwms.tms.domain.values.PriorityLevel}
*/
public class TransportStartComparator implements Comparator<TransportOrder>, Serializable {
private static final long serialVersionUID = -5977273516346830448L;
/**
* First the priority or orders is compared, when both are equals the id is
* compared too.
*
* @param o1
* FirstOrder to compare
* @param o2
* Second order to compare
* @return a negative integer, zero, or a positive integer as the first
* argument is less than, equal to, or greater than the second.
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
*/
@Override
public int compare(TransportOrder o1, TransportOrder o2) {
if (o1.getPriority().getOrder() > o2.getPriority().getOrder()) {
return -1;
} else if (o1.getPriority().getOrder() < o2.getPriority().getOrder()) {
return 1;
}
if (o1.getId() < o2.getId()) {
return -1;
} else if (o1.getId() > o2.getId()) {
return 1;
}
return 0;
}
}
|
package com.bkahlert.nebula.utils;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import javax.swing.JEditorPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultEditorKit;
import javax.swing.text.Document;
import javax.swing.text.EditorKit;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.rtf.RTFEditorKit;
import org.eclipse.jface.viewers.StyledString;
public class StringUtils {
private static final Pattern BODY_PATTERN = Pattern.compile(
".*<body.*?>(.*)</body>.*", Pattern.CASE_INSENSITIVE
| Pattern.DOTALL);
public static interface IStringAdapter<T> {
public String getString(T object);
}
public static String join(List<String> strings, String separator) {
if (strings == null) {
return "";
}
StringBuffer sb = new StringBuffer();
for (int i = 0, m = strings.size(); i < m; i++) {
String string = strings.get(i);
if (string == null) {
string = "";
}
sb.append(string);
if (i + 1 < m) {
sb.append(separator);
}
}
return sb.toString();
}
public static StyledString join(ArrayList<StyledString> strings,
StyledString separator) {
StyledString string = new StyledString("");
for (int i = 0, m = strings.size(); i < m; i++) {
StyledString s = strings.get(i);
if (string == null) {
string = new StyledString("");
}
string.append(s);
if (i + 1 < m) {
string.append(separator);
}
}
return string;
}
public static String getLongestCommonPrefix(String string1, String string2) {
if (string1 == null || string2 == null) {
throw new IllegalArgumentException();
}
int minLength = Math.min(string1.length(), string2.length());
for (int i = 0; i < minLength; i++) {
if (string1.charAt(i) != string2.charAt(i)) {
return string1.substring(0, i);
}
}
return string1.substring(0, minLength);
}
public static <T> String getLongestCommonPrefix(
IStringAdapter<T> stringAdapter, T... objects) {
if (objects == null) {
throw new IllegalArgumentException();
}
List<String> strings = new ArrayList<String>();
for (T object : objects) {
if (object == null && stringAdapter == null) {
throw new IllegalArgumentException();
}
strings.add(stringAdapter != null ? stringAdapter.getString(object)
: object.toString());
}
if (strings.size() == 0) {
return "";
}
if (strings.size() == 1) {
return strings.get(0);
}
try {
Collections.sort(strings);
} catch (NullPointerException e) {
throw new IllegalArgumentException(e);
}
return getLongestCommonPrefix(strings.get(0),
strings.get(strings.size() - 1));
}
/**
* Returns all found common prefixes and their occurrences.
* <p>
* Prefixes that are not common and thus have occurrence one are not part of
* the result.<br/>
* Prefixes can only be of length 1 or greater.
* <p>
* e.g. given AAA, AAB, BBB returns prefix AA with number of occurrences 2.
*
* @param stringAdapter
* TODO
* @param objects
*
* @return
*/
public static <T> Map<String, Integer> getLongestCommonPrefix(
IStringAdapter<T> stringAdapter, int partitionLength, T... objects) {
if (objects == null) {
throw new IllegalArgumentException();
}
Map<String, List<String>> partitionedStrings = new HashMap<String, List<String>>();
for (T object : objects) {
if (object == null && stringAdapter == null) {
throw new IllegalArgumentException();
}
String string = stringAdapter != null ? stringAdapter
.getString(object) : object.toString();
if (string == null) {
throw new IllegalArgumentException();
}
if (string.length() < partitionLength) {
continue;
}
String key = string.substring(0, partitionLength);
if (!partitionedStrings.containsKey(key)) {
partitionedStrings.put(key, new ArrayList<String>());
}
partitionedStrings.get(key).add(string);
}
Map<String, Integer> rs = new HashMap<String, Integer>();
for (List<String> partition : partitionedStrings.values()) {
String longestPrefix = getLongestCommonPrefix(null,
partition.toArray());
rs.put(longestPrefix, partition.size());
}
return rs;
}
public static String rtfToBody(String rtf) throws IOException {
String html = rtfToHtml(new StringReader(rtf));
if (html.contains("<body")) {
html = BODY_PATTERN.matcher(html).replaceAll("$1");
}
return html;
}
public static String rtfToHtml(String rtf) throws IOException {
return rtfToHtml(new StringReader(rtf));
}
public static String rtfToPlain(String rtf) {
RTFEditorKit rtfParser = new RTFEditorKit();
Document document = rtfParser.createDefaultDocument();
try {
rtfParser.read(new ByteArrayInputStream(rtf.getBytes()), document,
0);
return document.getText(0, document.getLength());
} catch (Exception e) {
throw new RuntimeException("Error converting RTF to plain text", e);
}
}
public static String rtfToHtml(Reader rtf) throws IOException {
JEditorPane p = new JEditorPane();
p.setContentType("text/rtf");
EditorKit kitRtf = p.getEditorKitForContentType("text/rtf");
try {
kitRtf.read(rtf, p.getDocument(), 0);
kitRtf = null;
EditorKit kitHtml = p.getEditorKitForContentType("text/html");
Writer writer = new StringWriter();
kitHtml.write(writer, p.getDocument(), 0, p.getDocument()
.getLength());
return writer.toString();
} catch (BadLocationException e) {
e.printStackTrace();
}
return null;
}
public static String htmlToPlain(String html) {
HTMLEditorKit htmlParser = new HTMLEditorKit();
Document document = htmlParser.createDefaultDocument();
try {
htmlParser.read(new ByteArrayInputStream(html.getBytes()),
document, 0);
String plain = document.getText(0, document.getLength());
return plain;
} catch (Exception e) {
throw new RuntimeException("Error converting HTML to plain text", e);
}
}
public static String plainToHtml(String plain) {
DefaultEditorKit plainParser = new DefaultEditorKit();
Document document = plainParser.createDefaultDocument();
try {
plainParser.read(new ByteArrayInputStream(plain.getBytes()),
document, 0);
String html = document.getText(0, document.getLength());
return html;
} catch (Exception e) {
throw new RuntimeException("Error converting plain text to HTML", e);
}
}
public static String shorten(String script, int length) {
String shortened = script.length() > length ? script.substring(0,
length).intern()
+ "..." : script;
return shortened.replace("\n", " ").replace("\r", " ")
.replace("\t", " ");
}
public static String shorten(String script) {
return shorten(script, 100);
}
}
|
package com.cavariux.twitchirc.Core;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.ArrayList;
import com.cavariux.twitchirc.Chat.Channel;
import com.cavariux.twitchirc.Chat.User;
/**
* The main object to start making your bot
* @author Leonardo Mariscal
* @version 1.0-Beta
*/
public class TwitchBot {
private String whispers_ip = "";
private int whispers_port = 443;
private boolean wen = true;
private String user;
private String oauth_key;
private BufferedWriter writer;
private BufferedReader reader;
private ArrayList<String> channels = new ArrayList<String>();
private String version = "v1.0-Beta";
private boolean stopped = true;
private String commandTrigger = "!";
public TwitchBot(){}
/**
* Here you can connect without having to connect to a chat group
*/
public void connect() {
wen = false;
connect("irc.twitch.tv", 6667);
}
/**
* The connect method alouds you to connect to the IRC servers on twitch
* @param ip The ip of the Chat group
* @param port The port of the Chat group
*/
public void connect(String ip, int port)
{
if (isRunning()) return;
try{
if (user == null || user == "")
{
System.err.println("Please select a valid Username");
System.exit(1);
return;
}
if (oauth_key == null || oauth_key == "")
{
System.err.println("Please select a valid Oauth_Key");
System.exit(2);
return;
}
@SuppressWarnings("resource")
Socket socket = new Socket(ip, port);
this.writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
this.reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
this.writer.write("PASS " + oauth_key + "\r\n");
this.writer.write("NICK " + user + "\r\n");
this.writer.write("USER " + this.getVersion() + " \r\n");
this.writer.write("CAP REQ :twitch.tv/commands \r\n");
this.writer.write("CAP REQ :twitch.tv/membership \r\n");
this.writer.flush();
String line = "";
while ((line = this.reader.readLine()) != null)
{
if (line.indexOf("004") >= 0) {
System.out.println("Connected >> " + user + " ~ irc.twitch.tv");
break;
}else {
System.out.println(line);
}
}
} catch (IOException e)
{
e.printStackTrace();
}
}
protected void onSub(User user, Channel channel, String message)
{
}
public final void setUsername(String username)
{
this.user = username;
}
public final void setOauth_Key (String oauth_key)
{
this.oauth_key = oauth_key;
}
/**
* This method is called when a message is sent on the Twitch Chat.
* @param user The user is sent, if you put it on a String it will give you the user's nick
* @param channel The channel where the message was sent
* @param message The message
*/
protected void onMessage(User user, Channel channel, String message)
{
}
/**
* This method is called when a command is sent on the Twitch Chat.
* @param user The user is sent, if you put it on a String it will give you the user's nick
* @param channel The channel where the command was sent
* @param message The command
*/
protected void onCommand(User user, Channel channel, String command)
{
}
// /**
// * This method is used if you want to send a command to the IRC server, not commontly used
// * @param message the command you will sent
// */
// public void sendRawMessage(String message)
// try {
// this.writer.write(message + " \r\n");
// this.writer.flush();
// } catch (IOException e) {
// e.printStackTrace();
// System.out.println(message);
/**
* An int variation of the sendRawMessage(String)
* @param message the command you will sent
*/
public void sendRawMessage(Object message)
{
try {
this.writer.write(message + " \r\n");
this.writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(message);
}
/**
* Send a message to a channel on Twitch (Don't need to be on that channel)
* @param message The message that will be sent
* @param channel The channel where the message will be sent
*/
public void sendMessage(Object message, Channel channel)
{
try {
this.writer.write("PRIVMSG " + channel + " :" + message.toString() + "\r\n");
this.writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("> MSG " + channel + " : " + message.toString());
}
// /**
// * Send a message to a channel on Twitch (Don't need to be on that channel)
// * @param message The message that will be sent
// * @param channel The channel where the message will be sent
// */
// public void sendMessage(String message, Channel channel)
// try {
// this.writer.write("PRIVMSG " + channel + " :" + message + "\r\n");
// this.writer.flush();
// } catch (IOException e) {
// e.printStackTrace();
// System.out.println("> MSG " + channel + " : " + message);
// /**
// * A sendMessage variation with an int
// * @param message The message that will be sent
// * @param channel channel The channel where the message will be sent
// */
// public void sendMessage(int message, Channel channel)
// try {
// this.writer.write("PRIVMSG " + channel + " :" + message + "\r\n");
// this.writer.flush();
// } catch (IOException e) {
// e.printStackTrace();
// System.out.println("> MSG " + channel + " : " + message);
/**
* The method to join an IRC channel on Twitch
* @param channel The channel name
* @return You can get the channel you just created
*/
public final Channel joinChannel (String channel)
{
Channel cnl = Channel.getChannel(channel, this);
sendRawMessage("JOIN " + cnl + "\r\n");
this.channels.add(cnl.toString());
System.out.println("> JOIN " + cnl);
return cnl;
}
/**
* Leaves the channel you want
* @param channel The channel you want to leave
*/
public final void partChannel (String channel)
{
Channel cnl = Channel.getChannel(channel, this);
this.sendRawMessage("PART " + cnl);
this.channels.remove(cnl);
System.out.println("> PART " + channel);
}
/**
* No need to use this dev things
* @return a BufferedWrtier
*/
public final BufferedWriter getWriter ()
{
return this.writer;
}
/**
* Starts the full mechanism of the bot, this is the last method to be called
*/
public final void start()
{
if (isRunning()) return;
String line = "";
stopped = false;
try {
while ((line = this.reader.readLine( )) != null && !stopped) {
if (line.toLowerCase( ).startsWith("ping")) {
System.out.println("> PING");
System.out.println("< PONG " + line.substring(5));
this.writer.write("PONG " + line.substring(5) + "\r\n");
this.writer.flush();
} else if (line.contains("PRIVMSG"))
{
String str[];
str = line.split("!");
final User msg_user = User.getUser(str[0].substring(1, str[0].length()));
str = line.split(" ");
Channel msg_channel;
msg_channel = Channel.getChannel(str[2], this);
String msg_msg = line.substring((str[0].length() + str[1].length() + str[2].length() + 4), line.length());
System.out.println("> " + msg_channel + " | " + msg_user + " >> " + msg_msg);
if (msg_msg.startsWith(commandTrigger))
onCommand(msg_user, msg_channel, msg_msg.substring(1));
onMessage(msg_user, msg_channel, msg_msg);
} else if (line.contains(" JOIN ")) {
String[] p = line.split(" ");
String[] pd = line.split("!");
if (p[1].equals("JOIN"))
userJoins(User.getUser(pd[0].substring(1)), Channel.getChannel(p[2], this));
} else if (line.contains(" PART ")) {
String[] p = line.split(" ");
String[] pd = line.split("!");
if (p[1].equals("PART"))
userParts(User.getUser(pd[0].substring(1)), Channel.getChannel(p[2], this));
} else if (line.contains(" WHISPER ")) {
String[] parts = line.split(":");
final User wsp_user = User.getUser(parts[1].split("!")[0]);
String message = parts[2];
onWhisper(wsp_user, message);
} else if (line.startsWith(":tmi.twitch.tv ROOMSTATE")) {
} else if (line.startsWith(":tmi.twitch.tv NOTICE"))
{
String[] parts = line.split(" ");
if (line.contains("This room is now in slow mode. You may send messages every"))
{
System.out.println("> Chat is now in slow mode. You can send messages every " + parts[15] + " sec(s)!");
} else if (line.contains("subscribers-only mode")) {
if (line.contains("This room is no longer"))
System.out.println("> The room is no longer Subscribers Only!");
else
System.out.println("> The room has been set to Subscribers Only!");
} else {
System.out.println(line);
}
} else if (line.startsWith(":jtv MODE "))
{
String[] p = line.split(" ");
if (p[3].equals("+o")) {
System.out.println("> +o " + p[4]);
} else {
System.out.println("> -o " + p[4]);
}
}else if (line.toLowerCase().contains("disconnected"))
{
System.out.println(line);
this.connect();
} else
{
System.out.println("> " + line);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Simply stops the bot.
*/
public void stop() {
this.stopped = true;
this.sendRawMessage("Stopping"); //so that the bot has one message to process to actually stop
}
/**
* Stops the bot and sends a message to all channels the bot has joined
* @param message Message to send to all channels
*/
public void stopWithMessage(String message) {
this.stopped = true;
for (String cnl : channels) {
this.sendMessage(message, Channel.getChannel(cnl, this));
}
}
public boolean isRunning() {
return !stopped;
}
/**
* A user joins the channel
* @param user The user that has join
* @param channel The channel he joined
*/
protected void userJoins(User user, Channel channel)
{
}
/**
* A user leaves/parts the channel
* @param user The user that has left
* @param channel The channel he left
*/
protected void userParts(User user, Channel channel)
{
}
/**
* This will let you whisper to the specified user
* @param user The user to send the message
* @param message The messsage to send
*/
public void whisper(User user, String message)
{
if (!channels.isEmpty()) {
this.sendMessage(".w " + user + " " + message, Channel.getChannel(channels.get(0), this));
} else if (!wen) {
System.out.println("You have to be either connected to at least one channel or join another Server to be able to whisper!");
} else {
sendRawMessage("PRIVMSG #jtv :/w " + user + " " + message);
}
}
/**
* When overrided this method lets you check for whispers.
* @param user The user that sent it
* @param message The message he sent
*/
protected void onWhisper(User user, String message)
{
}
/**
* Sets the whispers ip (000.000.000.000:0000)
* @param ip The whole ip
*/
protected final void setWhispersIp(String ip)
{
if (!ip.contains(":")) {
System.out.println("Invaid ip!");
return;
}
String[] args = ip.split(":");
whispers_ip = args[0];
whispers_port = Integer.parseInt(args[1]);
}
/**
* Sets the whispers ip
* @param ip The ip to connect
* @param port The port to connect with
*/
protected final void setWhispersIp(String ip, int port)
{
whispers_ip = ip;
whispers_port = port;
}
/**
* Sets the string that will mark a message as command if it begins with it
* @param trigger string to mark a message as command
*/
public void setCommandTrigger(String trigger) {
this.commandTrigger = trigger;
}
/**
* Get the version of the TwitchIRC lib
* @return the version of the TwitchIRC lib
*/
public final String getVersion()
{
return "TwitchIRC "+version;
}
}
|
package com.stylepoints.habittracker.model;
import com.stylepoints.habittracker.repository.remote.Id;
import java.time.LocalDate;
/**
* The model class for a User. Implements the Id interface so that it can be
* serialized and uploaded to Elastic Search. This class is automatically serialized
* by gson into JSON when uploaded to the remote server
*
* In elastic search the users are keyed on the username field
*
* @author Niko Somos
*/
public class User implements Id {
private String username;
private LocalDate dateCreated;
/**
* Constructor
* @param username a unique username
*/
public User(String username){
this.username = username;
this.dateCreated = LocalDate.now();
}
/**
* @return the unique username of this user
*/
public String getUsername(){
return username;
}
/**
* @return the date this account was created
*/
public LocalDate getDateCreated(){
return dateCreated;
}
/**
* @param id the unique username of this user
*/
@Override
public void setElasticId(String id) {
this.username = id;
}
}
|
package org.unitime.timetable.webutil;
import java.util.Collection;
import java.util.Iterator;
import java.util.Vector;
import javax.servlet.http.HttpServletRequest;
import org.unitime.commons.Debug;
import org.unitime.commons.web.WebTable;
import org.unitime.localization.impl.Localization;
import org.unitime.localization.messages.CourseMessages;
import org.unitime.timetable.defaults.CommonValues;
import org.unitime.timetable.defaults.UserProperty;
import org.unitime.timetable.model.Department;
import org.unitime.timetable.model.ItypeDesc;
import org.unitime.timetable.model.SimpleItypeConfig;
import org.unitime.timetable.model.dao.DepartmentDAO;
import org.unitime.timetable.security.SessionContext;
import org.unitime.timetable.security.rights.Right;
import org.unitime.timetable.util.Constants;
/**
* Build Configuration Edit Tree
*
* @author Heston Fernandes
*/
public class SchedulingSubpartTableBuilder {
protected final static CourseMessages MSG = Localization.create(CourseMessages.class);
/**
* Reads the user defined config object and generates html code to display it
* @param request
* @param limit
* @param uid
* @param createAsNew
* @param unlimitedEnroll
* @return Html code for displaying user defined config
*/
public static String buildSubpartsTable(
HttpServletRequest request, SessionContext context, int limit, String uid, boolean createAsNew, boolean unlimitedEnroll) throws Exception {
// Check if variable limits is selected
boolean varLimits = "y".equals(request.getParameter("varLimits"));
// Read user defined config
Vector sp = (Vector) context.getAttribute(SimpleItypeConfig.CONFIGS_ATTR_NAME);
// Read setting for auto calculation
boolean autoCalc = true;
if (!CommonValues.Yes.eq(UserProperty.ConfigAutoCalc.get(context.getUser())))
autoCalc = false;
// Get external depts
Collection extDepts = (Collection) request.getAttribute(Department.EXTERNAL_DEPT_ATTR_NAME);
String extDeptsOption = "<OPTION value='-1'>Department</OPTION>";
for(Iterator it = extDepts.iterator(); it.hasNext();){
Department d = (Department) it.next();
extDeptsOption += "<OPTION value='" + d.getUniqueId().toString() + "'>" + d.getManagingDeptLabel() + "</OPTION>";
}
// Subparts exist
if(sp!=null && sp.size()>0) {
if (!varLimits) {
for(int i=0; i<sp.size(); i++) {
SimpleItypeConfig sic = (SimpleItypeConfig) sp.elementAt(i);
if ( hasVarLimitsInSubpart(request, sic) ) {
varLimits=true;
break;
}
}
}
// Create a table
WebTable tbl = new WebTable(9,
"",
new String[] { unlimitedEnroll
? ""
: "<<00>>",
" ",
!varLimits ? "<<1>>" : MSG.columnSubpartMinLimitPerClass(),
!varLimits ? "<<11>>" : MSG.columnSubpartMaxLimitPerClass(),
MSG.columnSubpartNumberOfClasses(),
MSG.columnSubpartMinutesPerWeek(),
MSG.columnSubpartNumberOfRooms(),
MSG.columnSubpartRoomRatio(),
MSG.columnSubpartManagingDepartment()},
new String[] { "left", "left", "center", "center", "center", "center", "center", "center", "center"},
null);
tbl.setSuppressRowHighlight(true);
// Loop through itypes
for(int i=0; i<sp.size(); i++) {
SimpleItypeConfig sic = (SimpleItypeConfig) sp.elementAt(i);
// Recursively process each itype config
setupSubpart(request, context, sic, 1, tbl, i, sp.size(),
-1, -1, limit, null, autoCalc, createAsNew, extDeptsOption, unlimitedEnroll, varLimits);
}
request.setAttribute("subpartsExist", "true");
String varLimitsCheckBox = "<input type='checkbox' name='varLimits' value='y' <<0>>" + (varLimits ? "checked":"") + " onClick=\"doClick('multipleLimits', 0);\"> <small>Allow variable limits</small>";
String tblStr = tbl.printTable();
if (request.getAttribute("varLimits")!=null) {
tblStr = tblStr.replaceAll("<<00>>", varLimitsCheckBox);
tblStr = tblStr.replaceAll("<<0>>", "checked");
tblStr = tblStr.replaceAll("<<1>>", MSG.columnSubpartMinLimitPerClass());
tblStr = tblStr.replaceAll("<<11>>", MSG.columnSubpartMaxLimitPerClass());
}
else {
if (CommonValues.Yes.eq(UserProperty.VariableClassLimits.get(context.getUser()))) {
tblStr = tblStr.replaceAll("<<00>>", varLimitsCheckBox);
tblStr = tblStr.replaceAll("<<0>>", " ");
}
else
tblStr = tblStr.replaceAll("<<00>>", " ");
tblStr = tblStr.replaceAll("<<1>>", " ");
tblStr = tblStr.replaceAll("<<11>>", MSG.columnSubpartLimitPerClass());
}
return (tblStr);
}
else {
request.setAttribute("subpartsExist", "false");
return "";
}
}
/**
* Checks if any subpart in the config has variable limits
* @param request Http Request object
* @param sic SimpleItypeConfig object
* @return true if var limits found, false otherwise
*/
private static boolean hasVarLimitsInSubpart(HttpServletRequest request, SimpleItypeConfig sic) {
if(request.getParameter("mnlpc" + sic.getId())!=null)
sic.setMinLimitPerClass(Constants.getPositiveInteger(request.getParameter("mnlpc" + sic.getId()), -1));
if(request.getParameter("mxlpc" + sic.getId())!=null)
sic.setMaxLimitPerClass(Constants.getPositiveInteger(request.getParameter("mxlpc" + sic.getId()), -1));
int mnlpc = sic.getMinLimitPerClass();
int mxlpc = sic.getMaxLimitPerClass();
if (mnlpc!=mxlpc)
return true;
Vector v = sic.getSubparts();
for(int i=0; i<v.size(); i++) {
SimpleItypeConfig sic1 = (SimpleItypeConfig) v.elementAt(i);
if (hasVarLimitsInSubpart(request, sic1))
return true;
}
return false;
}
/**
* Recursive function generates the html code for displaying the config
* @param request Http Request object
* @param sic SimpleItypeConfig object
* @param level Recurse Level
* @param tbl WebTable object
* @param rowNum Row Number (in config)
* @param maxRows Max elements in config
* @param spRowNum row number of subpart
* @param maxSp Max subparts
* @param limit
* @param parentSic
* @param autoCalc
*/
private static void setupSubpart(
HttpServletRequest request, SessionContext context, SimpleItypeConfig sic,
int level, WebTable tbl, int rowNum, int maxRows,
int spRowNum, int maxSp, int limit,
SimpleItypeConfig parentSic, boolean autoCalc,
boolean createAsNew, String extDepts, boolean unlimitedEnroll, boolean varLimits) throws Exception {
ItypeDesc itype = sic.getItype();
// Set attributes
if(request.getParameter("mnlpc" + sic.getId())!=null)
sic.setMinLimitPerClass(Constants.getPositiveInteger(request.getParameter("mnlpc" + sic.getId()), -1));
if(request.getParameter("mxlpc" + sic.getId())!=null)
sic.setMaxLimitPerClass(Constants.getPositiveInteger(request.getParameter("mxlpc" + sic.getId()), -1));
if(request.getParameter("mpw" + sic.getId())!=null)
sic.setMinPerWeek(Constants.getPositiveInteger(request.getParameter("mpw" + sic.getId()), -1));
if(request.getParameter("nc" + sic.getId())!=null)
sic.setNumClasses(Constants.getPositiveInteger(request.getParameter("nc" + sic.getId()), -1));
if(request.getParameter("nr" + sic.getId())!=null)
sic.setNumRooms(Constants.getPositiveInteger(request.getParameter("nr" + sic.getId()), -1));
if(request.getParameter("rr" + sic.getId())!=null)
sic.setRoomRatio(Constants.getPositiveFloat(request.getParameter("rr" + sic.getId()), 1.0f));
if(request.getParameter("md" + sic.getId())!=null)
sic.setManagingDeptId(Long.parseLong(request.getParameter("md" + sic.getId())));
if(request.getParameter("disabled" + sic.getId())!=null)
sic.setDisabled(new Boolean(request.getParameter("disabled" + sic.getId())).booleanValue());
// Read attributes
int mnlpc = sic.getMinLimitPerClass();
int mxlpc = sic.getMaxLimitPerClass();
int mpw = sic.getMinPerWeek();
int nc = sic.getNumClasses();
int nr = sic.getNumRooms();
float rr = sic.getRoomRatio();
long md = sic.getManagingDeptId();
long subpartId = -1L;
if (!createAsNew)
subpartId = sic.getSubpartId();
long sicId = sic.getId();
boolean disabled = sic.isDisabled();
boolean notOwned = sic.isNotOwned();
boolean hasError = sic.getHasError();
boolean uDisabled = unlimitedEnroll;
Vector v = sic.getSubparts();
// If status is not LLR Edit then do not show option to change to external manager
boolean mgrDisabled = false;
if (subpartId >= 0 && !context.hasPermission(subpartId, "SchedulingSubpart", Right.InstrOfferingConfigEditSubpart)) {
mgrDisabled = true;
if (createAsNew) {
md = -1;
}
}
if (unlimitedEnroll) {
mnlpc = -1;
mxlpc = -1;
nr = -1;
rr = -1;
}
Debug.debug("setting up subpart: " + itype.getAbbv() + ", Level: " + level);
// Generate Javascript
String onBlur1 = "";
String onBlur2 = "";
String maxClasses = "if ( document.forms[0].nc" + sicId + ".value > 999) { document.forms[0].nc" + sicId + ".value=0 } ";
if (autoCalc) {
onBlur1 = " onBlur=\"if (this.value!=0 && (document.forms[0].mxlpc" + sicId + ".value==''|| document.forms[0].mxlpc" + sicId + ".value==null) ) {" +
" document.forms[0].mxlpc" + sicId + ".value=this.value; }\"";
if (parentSic!=null) {
onBlur2 = " onBlur=\"if (this.value!=0) "
+ "{ document.forms[0].nc" + sicId
+ ".value=Math.ceil( (document.forms[0].mxlpc" + parentSic.getId()
+ ".value * document.forms[0].nc" + parentSic.getId()
+ ".value) / this.value ); " + maxClasses + " } ";
}
else {
onBlur2 = " onBlur=\"if (this.value!=0) { document.forms[0].nc" + sicId
+ ".value=Math.ceil(document.forms[0].limit.value/this.value); " + maxClasses + "} ";
}
}
if (!varLimits) {
if (onBlur2.length()==0)
onBlur2 = "onBlur=\"document.forms[0].mnlpc" + sicId + ".value=this.value; \"";
else
onBlur2 += "document.forms[0].mnlpc" + sicId + ".value=this.value; \"";
}
else {
onBlur2 += "\"";
}
// Generate indentation depending on recursive level
String indent = "";
for(int i=1; i<level; i++)
indent += "\n<IMG width=\"10\" align=\"absmiddle\" src=\"images/blank.gif\">";
if(indent.length()!=0)
indent += "\n<IMG align=\"absmiddle\" src=\"images/dot_line.gif\"> ";
if (!varLimits && mnlpc!=mxlpc) {
if (mnlpc==-1)
mnlpc=mxlpc;
else
request.setAttribute("varLimits", "1");
}
// Generate html row for itype config
tbl.addLine(
new String[] {
indent
+ "<span style='font-weight:bold;'>" + itype.getDesc() + "</span>"
+ (hasError ? " <IMG align=\"absmiddle\" src=\"images/Error16.jpg\">" : ""),
(!disabled)
? getIcons(sic, level, rowNum, maxRows, spRowNum, maxSp)
: (notOwned)
? "<img border=\"0\" src=\"images/lock.gif\">"
: "",
"\n\t <INPUT type=\"hidden\" name=\"subpartId" + sicId + "\" value=\"" + subpartId + "\">"
+ "\n\t <INPUT type=\"hidden\" name=\"disabled" + sicId + "\" value=\"" + disabled + "\">"
+ ( (disabled || uDisabled || (!varLimits && mnlpc==mxlpc))
? ( "\n\t<INPUT "
+ " name=\"mnlpc" + sicId
+ "\" type=\"hidden\" value=\""
+ (mnlpc>=0?""+mnlpc:"") + "\""
+ " >"
+ (( (disabled || uDisabled) && mnlpc>=0) || (!varLimits && mnlpc!=mxlpc)
?""+mnlpc
:"" ) )
: ( "\n\t<INPUT "
+ " name=\"mnlpc" + sicId
+ "\" type=\"text\" size=\"4\" maxlength=\"4\" value=\""
+ (mnlpc>=0?""+mnlpc:"") + "\""
+ onBlur1
+ " >" ) ),
((disabled || uDisabled)
? ( "\n\t<INPUT "
+ " name=\"mxlpc" + sicId
+ "\" type=\"hidden\" value=\""
+ (mxlpc>=0?""+mxlpc:"") + "\""
+ " >" + (mxlpc>=0?""+mxlpc:"") )
: ( "\n\t<INPUT "
+ " name=\"mxlpc" + sicId
+ "\" type=\"text\" size=\"4\" maxlength=\"4\" value=\""
+ (mxlpc>=0?""+mxlpc:"") + "\""
+ onBlur2
+ " >" ) ),
((disabled)
? ( "\n\t<INPUT "
+ " name=\"nc" + sicId
+ "\" type=\"hidden\" value=\""
+ (nc>=0?""+nc:"") + "\">" + (nc>=0?""+nc:"") )
: ( "\n\t<INPUT "
+ " name=\"nc" + sicId
+ "\" type=\"text\" size=\"3\" maxlength=\"3\" value=\""
+ (nc>=0?""+nc:"") + "\" onblur=\"if (!confirmNumClasses(this.value)) { this.value = 0 }\">" ) ),
((disabled)
? ( "\n\t<INPUT "
+ " name=\"mpw" + sicId
+ "\" type=\"hidden\" value=\""
+ (mpw>=0?""+mpw:"") + "\">" + (mpw>=0?""+mpw:"") )
: ( "\n\t<INPUT "
+ " name=\"mpw" + sicId
+ "\" type=\"text\" size=\"4\" maxlength=\"4\" value=\""
+ (mpw>=0?""+mpw:"") + "\">" ) ),
((disabled || uDisabled)
? ( "\n\t<INPUT "
+ " name=\"nr" + sicId
+ "\" type=\"hidden\" value=\""
+ (nr>=0?""+nr:"") + "\">" + (nr>=0?""+nr:"") )
: ( "\n\t<INPUT "
+ " name=\"nr" + sicId
+ "\" type=\"text\" size=\"4\" maxlength=\"2\" value=\""
+ (nr>=0?""+nr:"") + "\">" ) ),
((disabled || uDisabled)
? ( "\n\t<INPUT "
+ " name=\"rr" + sicId
+ "\" type=\"hidden\" value=\""
+ (rr>=0?""+rr:"") + "\">" + (rr>=0?""+rr:"") )
: ( "\n\t<INPUT "
+ " name=\"rr" + sicId
+ "\" type=\"text\" size=\"4\" maxlength=\"4\" value=\""
+ (rr>=0?""+rr:"") + "\">" ) ),
((disabled || mgrDisabled)
? ( "\n\t<INPUT "
+ " name=\"md" + sicId
+ "\" type=\"hidden\" value=\""
+ md + "\">" + getManagingDeptLabel(request, md) )
: ( "\n\t<SELECT "
+ " name=\"md" + sicId
+ "\">" + extDepts.replaceAll("'" + md + "'", "'" + md + "' selected") +
"</SELECT>" ) )
}, null);
// Loop through children sub-parts
for(int i=0; i<v.size(); i++) {
SimpleItypeConfig sic1 = (SimpleItypeConfig) v.elementAt(i);
setupSubpart(request, context, sic1, level+1, tbl, rowNum, maxRows,
i, v.size(), limit, sic, autoCalc, createAsNew, extDepts, unlimitedEnroll, varLimits);
}
}
/**
* @param md
* @return
*/
private static String getManagingDeptLabel(HttpServletRequest request, long md) {
if (md<0)
return "Department";
if (md==Constants.MANAGED_BY_MULTIPLE_DEPTS)
return "Multiple Departments";
Department d = new DepartmentDAO().get(new Long (md));
if (d!=null) {
if (d.isExternalManager().booleanValue())
return d.getExternalMgrLabel();
else
return "Department";
}
return "Not Found";
}
/**
* Generates icons for shifting and deleting operations on itype config elements
* @param sic SimpleItypeConfig object
* @param level Recurse Level
* @param rowNum Row Number (in config)
* @param maxRows Max elements in config
* @param uid Unique Id of course offering
* @param spRowNum row number of subpart
* @param maxSp Max subparts
* @return Html code for arrow images
*/
private static String getIcons(SimpleItypeConfig sic, int level, int rowNum, int maxRows, int spRowNum, int maxSp) {
String html = "";
// Right Arrow
if ( (level==1 && rowNum>0)
|| (level>1 && spRowNum>0) )
html += "<IMG border=\"0\" alt=\""+ MSG.titleMoveToChildLevel() + "\" title=\"" + MSG.titleMoveToChildLevel() + "\" align=\"top\" src=\"images/arrow_r.gif\" " +
"onClick=\"doClick('shiftRight', " + sic.getId() + ");\" onMouseOver=\"this.style.cursor='hand';this.style.cursor='pointer';\">";
else
html += "<IMG align=\"top\" src=\"images/blank.gif\">";
// Left Arrow
if (level>1)
html += "<IMG border=\"0\" alt=\""+ MSG.titleMoveToParentLevel()+"\" title=\""+MSG.titleMoveToParentLevel() +"\" align=\"top\" src=\"images/arrow_l.gif\" " +
"onClick=\"doClick('shiftLeft', " + sic.getId() + ");\" onMouseOver=\"this.style.cursor='hand';this.style.cursor='pointer';\">";
else
html += "<IMG align=\"top\" src=\"images/blank.gif\">";
// Up Arrow
if( (level==1 && rowNum>0 )
|| (level>1 && spRowNum>0) )
html += "<IMG border=\"0\" alt=\""+MSG.altMoveUp()+"\" align=\"absmiddle\" src=\"images/arrow_u.gif\" " +
"onClick=\"doClick('shiftUp', " + sic.getId() + ");\" onMouseOver=\"this.style.cursor='hand';this.style.cursor='pointer';\">";
else
html += "<IMG align=\"absmiddle\" src=\"images/blank.gif\">";
// Down Arrow
if ( (level==1 && (rowNum+1)<maxRows)
|| (level>1 && (spRowNum+1)<maxSp) )
html += "<IMG border=\"0\" alt=\""+MSG.altMoveDown()+"\" align=\"absmiddle\" src=\"images/arrow_d.gif\" " +
"onClick=\"doClick('shiftDown', " + sic.getId() + ");\" onMouseOver=\"this.style.cursor='hand';this.style.cursor='pointer';\">";
else
html += "<IMG align=\"absmiddle\" src=\"images/blank.gif\">";
// Delete
html += "<IMG border=\"0\" alt=\""+MSG.altDelete()+"\" title=\""+MSG.titleDeleteInstructionalType()+"\" align=\"top\" src=\"images/Delete16.gif\" " +
"onClick=\"doClick('delete', " + sic.getId() + ");\" onMouseOver=\"this.style.cursor='hand';this.style.cursor='pointer';\"> ";
html += " ";
return html;
}
}
|
package com.eddysystems.eddy;
import com.eddysystems.eddy.actions.EddyAction;
import com.eddysystems.eddy.engine.Eddy;
import com.intellij.codeInsight.hint.HintManager;
import com.intellij.codeInsight.hint.HintManagerImpl;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.event.CaretEvent;
import com.intellij.openapi.editor.event.CaretListener;
import com.intellij.openapi.editor.event.DocumentEvent;
import com.intellij.openapi.editor.event.DocumentListener;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileEditor.TextEditor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.ui.Hint;
import com.intellij.ui.LightweightHint;
import org.jetbrains.annotations.NotNull;
import static com.eddysystems.eddy.engine.Utility.log;
public class EddyFileListener implements CaretListener, DocumentListener {
private final @NotNull Project project;
private final @NotNull Editor editor;
private final @NotNull Document document;
private static final @NotNull Object active_lock = new Object();
// last editor that an eddy thread has run on
private static Editor active_editor = null;
// if the eddy instance in a file listener is associated with an active hint, this is it
private static EddyFileListener active_hint_instance = null;
// an action that shows up as an intention action (lives longer than the hint)
private static EddyFileListener active_instance = null;
private static EddyAction active_action = null;
private static LightweightHint active_hint = null;
private static int active_line = -1;
// to keymapped actions that should affect the file listener that showed the last hint
public static EddyFileListener activeHintInstance() {
return active_hint_instance;
}
public static EddyAction getActionFor(Editor editor) {
synchronized (active_lock) {
if (active_instance == null || editor != active_instance.editor ||
editor.getCaretModel().getCurrentCaret().getLogicalPosition().line != active_line)
return null;
return active_action;
}
}
private boolean inChange = false;
private int lastEditLocation = -1;
public EddyFileListener(@NotNull Project project, TextEditor editor) {
this.project = project;
this.editor = editor.getEditor();
this.document = this.editor.getDocument();
VirtualFile file = FileDocumentManager.getInstance().getFile(this.document);
if (file != null)
log("making eddy for editor for file " + file.getPresentableName());
else
log("making eddy for editor for file 'null'");
// moving the caret around
this.editor.getCaretModel().addCaretListener(this);
// subscribe to document events
this.editor.getDocument().addDocumentListener(this);
}
public void dispose() {
log("disposing editor listener for " + editor);
editor.getCaretModel().removeCaretListener(this);
editor.getDocument().removeDocumentListener(this);
}
protected boolean enabled() {
return editor.getCaretModel().getCaretCount() == 1 && EddyPlugin.getInstance(project).isInitialized();
}
protected void process() {
if (!enabled()) {
// check if we're not initialized, and if so, try to reinitialize
if (!EddyPlugin.getInstance(project).isInitialized()) {
EddyPlugin.getInstance(project).requestInit();
}
return;
}
PsiDocumentManager.getInstance(project).performForCommittedDocument(document, new Runnable() {
@Override
public void run() {
synchronized (active_lock) {
EddyThread.run(new EddyThread(project,editor,lastEditLocation, new Eddy.Take() {
@Override public boolean take(Eddy.Output output) {
showHint(output);
return output.results.size() >= 4;
}
}));
active_editor = editor;
}
}
});
}
private void showHint(final Eddy.Output output) {
if (output == null)
return; // Don't make a hint if there's no output
final int line = editor.getCaretModel().getLogicalPosition().line;
final EddyAction action = new EddyAction(output,editor);
synchronized (active_lock) {
active_instance = this;
active_line = line;
active_action = action;
active_hint_instance = null;
// show hint only if we found something really good
if (output.shouldShowHint()) {
final int offset = editor.getCaretModel().getOffset();
active_hint = EddyHintLabel.makeHint(output);
// we can only show hints from the UI thread, so schedule that
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
try {
// whoever showed the hint last is it
// the execution order of later-invoked things is the same as the call order, and it's on a single thread, so
// no synchronization is needed in here
active_hint_instance = EddyFileListener.this;
int use_offset = Math.min(offset, editor.getDocument().getTextLength());
HintManagerImpl.getInstanceImpl().showQuestionHint(editor, use_offset, use_offset, active_hint, action, HintManager.ABOVE);
} catch (NullPointerException e) {
// silence null pointer exceptions in HintUtil
}
}
}, new Condition() {
@Override
public boolean value(Object o) {
// do not synchronize this -- we're still in the sync block!
return action != active_action;
}
});
} else {
// if we shouldn't show a hint, make sure any old hint is hidden
final Hint current_hint = active_hint;
active_hint = null;
if (current_hint != null) {
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
if (current_hint.isVisible()) {
current_hint.hide();
}
}
});
}
}
}
}
public void nextResult() {
synchronized (active_lock) {
if ( active_hint_instance == this
&& active_action.getOutput().nextBestResult())
showHint(active_action.getOutput());
}
}
public void prevResult() {
synchronized (active_lock) {
if ( active_hint_instance == this
&& active_action.getOutput().prevBestResult())
showHint(active_action.getOutput());
}
}
@Override
public void caretPositionChanged(CaretEvent e) {
if (inChange)
return;
// TODO: only process if input changed (if we switched statements?)
if (active_editor != this.editor || // process if current thread is for a different editor
e.getNewPosition().line != e.getOldPosition().line) // process if we switched lines
process();
}
@Override
public void caretAdded(CaretEvent e) {
}
@Override
public void caretRemoved(CaretEvent e) {
}
@Override
public void beforeDocumentChange(DocumentEvent event) {
inChange = true;
}
@Override
public void documentChanged(DocumentEvent event) {
inChange = false;
lastEditLocation = event.getOffset();
process();
}
}
|
package com.edinarobotics.utils.pid;
/**
* This class is used to exchange PID configuration data with PIDTuningManager.
* It provides methods to get the latest P, I and D values set by the dashboard
* and to provide value and setpoint feedback to the dashboard.
*/
public class PIDConfig {
private String name;
boolean overrideDefault;
double p,i,d, value, setpoint;
protected PIDConfig(String name){
this.name = name;
overrideDefault = false;
}
/**
* Returns the name of this PIDConfig instance.
* @return The String name of this PIDConfig instance.
*/
public String getName(){
return name;
}
/**
* Returns the P value that should be used by the relevant PID controller.
* This method will return the value set by the dashboard if such a value
* exists or the default value.
* @param defaultP The default value of P that should be used if the
* tuning process has not set a new value.
* @return The value of P that should be used by the relevant PID controller.
*/
public double getP(double defaultP){
if(overrideDefault){
return p;
}
return defaultP;
}
/**
* Returns the I value that should be used by the relevant PID controller.
* This method will return the value set by the dashboard if such a value
* exists or the default value.
* @param defaultI The default value of I that should be used if the
* tuning process has not set a new value.
* @return The value of I that should be used by the relevant PID controller.
*/
public double getI(double defaultI){
if(overrideDefault){
return i;
}
return defaultI;
}
/**
* Returns the D value that should be used by the relevant PID controller.
* This method will return the value set by the dashboard if such a value
* exists or the default value.
* @param defaultD The default value of D that should be used if the
* tuning process has not set a new value.
* @return The value of D that should be used by the relevant PID controller.
*/
public double getD(double defaultD){
if(overrideDefault){
return d;
}
return defaultD;
}
/**
* Sets the value that should be sent as feedback to the dashboard
* during the PID tuning process. This value should be the value
* that is backing the PID controller. For example, it could be an
* encoder or potentiometer reading.
* @param value The value that should be sent as feedback to the dashboard.
*/
public void setValue(double value){
this.value = value;
}
/**
* Sets the setpoint value that should be sent as feedback to the dashboard
* during the PID tuning process. This value should be the current setpoint
* of the PID controller. For example, it could be a target encoder
* or potentiometer reading.
* @param setpoint The setpoint that should be sent to the dashboard.
*/
public void setSetpoint(double setpoint){
this.setpoint = setpoint;
}
/**
* Returns the last value set by {@link #setValue(double}.
* @return The last value set by setValue(double).
*/
public double getValue(){
return value;
}
/**
* Returns the last value set by {@link #setSetpoint(double)}.
* @return The last value set by setSetpoint(double).
*/
public double getSetpoint(){
return setpoint;
}
/**
* This method is used internally by PIDTuningManager to override
* the default P, I and D values used by a PID controller. This method
* will replace any default values passed to the getP, getI and getD methods.
* @param p The new value of P for the PID controller.
* @param i The new value of I for the PID controller.
* @param d The new value of D for the PID controller.
*/
protected void setPID(double p, double i, double d){
this.p = p;
this.i = i;
this.d = d;
overrideDefault = true;
}
/**
* Resets the P, I and D values of this PIDConfig to their default values.
* This method will undo any tuning performed by the dashboard.
*/
public void reset(){
overrideDefault = false;
}
/**
* Indicates whether some other object is equal to this one.
* Another object is equal to this PIDConfig if it is also a PIDConfig
* and if its {@link #getName()} method returns the same value
* as this objects getName() method.
* @param other The object to be compared for equality to this object.
* @return {@code true} if the {@code other} is equal to this object as
* described above, {@code false} otherwise.
*/
public boolean equals(Object other){
if(other instanceof PIDConfig){
return getName().equals(((PIDConfig)other).getName());
}
return false;
}
/**
* Returns a hash code value for this object.
* This value is equivalent to {@code getName().hashCode()}.
* @return A hash code value for this object.
*/
public int hashCode(){
return getName().hashCode();
}
/**
* Returns a String representation of this object.
* @return A String representation of this object.
*/
public String toString(){
return "<PIDConfig "+p+":"+i+":"+d+":"+overrideDefault+">";
}
}
|
package com.example.reader;
import ilearnrw.textadaptation.TextAnnotationModule;
import ilearnrw.textclassification.Word;
import ilearnrw.user.problems.ProblemDefinition;
import ilearnrw.user.problems.ProblemDefinitionIndex;
import ilearnrw.user.problems.ProblemDescription;
import ilearnrw.user.profile.UserProfile;
import java.io.File;
import java.util.ArrayList;
import com.example.reader.interfaces.ColorPickerListener;
import com.example.reader.interfaces.OnHttpListener;
import com.example.reader.interfaces.OnProfileFetched;
import com.example.reader.tasks.ProfileTask;
import com.example.reader.types.ColorPickerDialog;
import com.example.reader.types.BasicListAdapter;
import com.example.reader.utils.FileHelper;
import com.example.reader.utils.HttpHelper;
import com.google.gson.Gson;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Spinner;
public class PresentationModule
extends
Activity
implements
OnClickListener,
OnCheckedChangeListener,
OnHttpListener,
OnProfileFetched,
OnItemSelectedListener {
private LinearLayout colorLayout, container;
private Button btnOk, btnCancel;
private CheckBox chkSwitch;
private RadioGroup rulesGroup;
private RadioButton rbtnRule1, rbtnRule2, rbtnRule3, rbtnRule4;
private Spinner spCategories, spProblems;
private ImageView colorBox;
private File fileHtml = null;
private File fileJSON = null;
private String html, json;
private String name = "";
private Boolean showGUI = false;
private ArrayList<Word> trickyWords;
private SharedPreferences sp;
private String TAG;
private ProblemDefinition[] definitions;
private ProblemDescription[][] descriptions;
private ProblemDescription[] problemDescriptions;
private ArrayList<String> categories;
private ArrayList<String> problems;
private final int DEFAULT_COLOR = 0xffff0000;
private final int DEFAULT_RULE = 3;
private int currentColor;
private int currentRule;
private int currentCategoryPos;
private int currentProblemPos;
private TextAnnotationModule txModule;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TAG = getClass().getName();
Bundle bundle = getIntent().getExtras();
boolean loadFiles = true;
if(bundle.containsKey("loadFiles"))
loadFiles = bundle.getBoolean("loadFiles");
name = bundle.getString("title", "");
showGUI = bundle.getBoolean("showGUI", false);
trickyWords = new ArrayList<Word>();
if(loadFiles){
fileHtml = (File)bundle.get("file");
fileJSON = (File)bundle.get("json");
html = FileHelper.readFromFile(fileHtml);
json = FileHelper.readFromFile(fileJSON);
} else {
html = bundle.getString("html");
json = bundle.getString("json");
}
categories = new ArrayList<String>();
problems = new ArrayList<String>();
setContentView(R.layout.activity_presentation_module);
sp = PreferenceManager.getDefaultSharedPreferences(this);
sp.edit().putBoolean("showGUI", showGUI).commit();
int id = sp.getInt("id",-1);
String token = sp.getString("authToken", "");
if(id==-1 || token.isEmpty()) {
finished(); // If you don't have an id something is terribly wrong
throw new IllegalArgumentException("Missing id or token");
}
init();
}
private void init(){
container = (LinearLayout) findViewById(R.id.presentation_module_container);
if(showGUI)
container.setVisibility(View.VISIBLE);
else
container.setVisibility(View.GONE);
spCategories = (Spinner) findViewById(R.id.categories);
spProblems = (Spinner) findViewById(R.id.problems);
btnOk = (Button) findViewById(R.id.pm_btn_ok);
btnCancel = (Button) findViewById(R.id.pm_btn_cancel);
chkSwitch = (CheckBox) findViewById(R.id.pm_switch);
rulesGroup = (RadioGroup) findViewById(R.id.pm_rules);
rbtnRule1 = (RadioButton) findViewById(R.id.pm_rule1);
rbtnRule2 = (RadioButton) findViewById(R.id.pm_rule2);
rbtnRule3 = (RadioButton) findViewById(R.id.pm_rule3);
rbtnRule4 = (RadioButton) findViewById(R.id.pm_rule4);
colorLayout = (LinearLayout) findViewById(R.id.pm_color_layout);
colorBox = (ImageView) findViewById(R.id.pm_color);
btnCancel.setOnClickListener(this);
btnOk.setOnClickListener(this);
colorLayout.setOnClickListener(this);
rulesGroup.setOnCheckedChangeListener(this);
String userId = Integer.toString(sp.getInt("id", 0));
String token = sp.getString("authToken", "");
currentCategoryPos = 0;
currentProblemPos = 0;
updateColor(currentCategoryPos, currentProblemPos);
updateRule(currentCategoryPos, currentProblemPos);
spCategories.setOnItemSelectedListener(this);
spProblems.setOnItemSelectedListener(this);
chkSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
sp.edit().putBoolean("pm_enabled_" + currentCategoryPos + "_" + currentProblemPos, isChecked).commit();
}
});
String jsonProfile = sp.getString("json_profile", "");
if(jsonProfile.isEmpty())
new ProfileTask(this, this, this).run(userId, token);
else {
initProfile(jsonProfile);
}
}
private void initProfile(String json){
UserProfile profile = new Gson().fromJson(json, UserProfile.class);
trickyWords = (ArrayList<Word>) profile.getUserProblems().getTrickyWords();
txModule = new TextAnnotationModule(html);
if (profile != null){
txModule.initializePresentationModule(profile);
}
txModule.setJSONFile(json);
txModule.setInputHTMLFile(html);
txModule.annotateText();
if(!showGUI){
finished();
return;
}
ProblemDefinitionIndex index = profile.getUserProblems().getProblems();
definitions = index.getProblemsIndex();
descriptions = index.getProblems();
categories.clear();
for(int i=0; i<definitions.length;i++){
categories.add((i+1) + ". " + definitions[i].getUri());
}
currentCategoryPos = 0;
updateProblems(currentCategoryPos);
ArrayAdapter<String> categoryAdapter = new BasicListAdapter(this, R.layout.textview_item_multiline, categories, true);
spCategories.setAdapter(categoryAdapter);
}
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.pm_btn_ok:
for (int i = 0; i < definitions.length; i++)
{
int problemSize = descriptions[i].length;
for (int j = 0; j < problemSize; j++)
{
int color = sp.getInt("pm_color_"+i+"_"+j, DEFAULT_COLOR);
int rule = sp.getInt("pm_rule_"+i+"_"+j, DEFAULT_RULE);
this.txModule.getPresentationRulesModule().setPresentationRule(i, j, rule);
if (rbtnRule1.isChecked() || rbtnRule2.isChecked())
{
this.txModule.getPresentationRulesModule().setTextColor(i, j, color);
}
else if (rbtnRule3.isChecked() || rbtnRule4.isChecked())
{
this.txModule.getPresentationRulesModule().setHighlightingColor(i, j, color);
}
this.txModule.getPresentationRulesModule().setActivated(i, j, this.chkSwitch.isChecked());
}
}
finished();
break;
case R.id.pm_btn_cancel:
onBackPressed();
break;
case R.id.pm_color_layout:
int color = sp.getInt("pm_color_" + currentCategoryPos + "_" + currentProblemPos, DEFAULT_COLOR);
ColorPickerDialog dialog = new ColorPickerDialog(this, color, new ColorPickerListener() {
@Override
public void onOk(ColorPickerDialog dialog, int color) {
sp.edit().putInt("pm_color_" + currentCategoryPos + "_" + currentProblemPos, color).commit();
updateColor(currentCategoryPos, currentProblemPos);
}
@Override
public void onCancel(ColorPickerDialog dialog) {}
});
dialog.show();
break;
}
};
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (group.getId()) {
case R.id.pm_rules:
switch(group.getCheckedRadioButtonId()){
case R.id.pm_rule1:
currentRule = 1;
break;
case R.id.pm_rule2:
currentRule = 2;
break;
case R.id.pm_rule3:
currentRule = 3;
break;
case R.id.pm_rule4:
currentRule = 4;
break;
}
default:
break;
}
sp.edit().putInt("pm_rule_"+currentCategoryPos+"_"+currentProblemPos, currentRule).commit();
updateRule(currentCategoryPos, currentProblemPos);
}
@Override
public void onItemSelected(AdapterView<?> parent, View v, int pos, long id) {
switch(parent.getId()){
case R.id.categories:
currentCategoryPos = pos;
updateProblems(currentCategoryPos);
updateColor(currentCategoryPos, 0);
updateRule(currentCategoryPos, 0);
updateEnabled(currentCategoryPos, 0);
break;
case R.id.problems:
currentProblemPos = pos;
updateColor(currentCategoryPos, currentProblemPos);
updateRule(currentCategoryPos, currentProblemPos);
updateEnabled(currentCategoryPos, currentProblemPos);
break;
default:
break;
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {}
@Override
public void onBackPressed() {
Intent i = new Intent(this, LibraryActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(i);
finish();
}
private void finished(){
Intent intent = new Intent(PresentationModule.this, ReaderActivity.class);
intent.putExtra("html", html);
intent.putExtra("json", json);
intent.putExtra("title", name);
intent.putExtra("trickyWords", (ArrayList<Word>) trickyWords);
startActivity(intent);
}
private void updateColor(int category, int problem){
currentColor = sp.getInt("pm_color_"+category+"_"+problem, DEFAULT_COLOR);
colorBox.setBackgroundColor(currentColor);
}
private void updateRule(int category, int problem){
currentRule = sp.getInt("pm_rule_"+category+"_"+problem, DEFAULT_RULE);
switch(currentRule){
case 1:
rbtnRule1.setChecked(true);
break;
case 2:
rbtnRule2.setChecked(true);
break;
case 3:
rbtnRule3.setChecked(true);
break;
case 4:
rbtnRule4.setChecked(true);
break;
}
}
private void updateEnabled(int category, int problem){
boolean isChecked = sp.getBoolean("pm_enabled_"+category+"_"+problem, true);
chkSwitch.setChecked(isChecked);
}
private void updateProblems(int index){
problemDescriptions = descriptions[index];
currentProblemPos = 0;
problems.clear();
for(int i=0; i<problemDescriptions.length; i++){
String[] descriptions = problemDescriptions[i].getDescriptions();
String str = "";
for(int j=0; j<descriptions.length; j++){
if(j+1<descriptions.length)
str += descriptions[j] + " | ";
else
str += descriptions[j];
}
problems.add((i+1) + ". " + str);
}
ArrayAdapter<String> problemAdapter = new BasicListAdapter(this, R.layout.textview_item_multiline, problems, true);
problemAdapter.notifyDataSetChanged();
spProblems.setAdapter(problemAdapter);
}
@Override
public void onTokenExpired(final String... params) {
if(HttpHelper.refreshTokens(this)){
final String newToken = sp.getString("authToken", "");
runOnUiThread(new Runnable() {
@Override
public void run() {
new ProfileTask(PresentationModule.this, PresentationModule.this, PresentationModule.this).run(params[0], newToken);
Log.d(TAG, getString(R.string.token_error_retry));
Toast.makeText(PresentationModule.this, getString(R.string.token_error_retry), Toast.LENGTH_SHORT).show();
}
});
}
}
@Override
public void onProfileFetched(String result) {
initProfile(result);
}
}
|
package com.yahoo.vespa.hosted.athenz.instanceproviderservice;
import com.google.inject.Inject;
import com.yahoo.component.AbstractComponent;
import com.yahoo.config.provision.SystemName;
import com.yahoo.config.provision.Zone;
import com.yahoo.jdisc.http.SecretStore;
import com.yahoo.jdisc.http.ssl.SslKeyStoreConfigurator;
import com.yahoo.jdisc.http.ssl.SslKeyStoreContext;
import com.yahoo.log.LogLevel;
import com.yahoo.vespa.hosted.athenz.instanceproviderservice.config.AthenzProviderServiceConfig;
import com.yahoo.vespa.hosted.athenz.instanceproviderservice.impl.AthenzCertificateClient;
import com.yahoo.vespa.hosted.athenz.instanceproviderservice.impl.SecretStoreKeyProvider;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Logger;
import static com.yahoo.vespa.hosted.athenz.instanceproviderservice.impl.Utils.getZoneConfig;
/**
* @author bjorncs
*/
// TODO Cache certificate on disk
public class AthenzSslKeyStoreConfigurator extends AbstractComponent implements SslKeyStoreConfigurator {
private static final Logger log = Logger.getLogger(AthenzSslKeyStoreConfigurator.class.getName());
// TODO Make expiry and update frequency configurable parameters
private static final Duration CERTIFICATE_EXPIRY_TIME = Duration.ofDays(30);
private static final Duration CERTIFICATE_UPDATE_PERIOD = Duration.ofDays(7);
private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
private final AthenzCertificateClient certificateClient;
private final SecretStoreKeyProvider keyProvider;
private final AthenzProviderServiceConfig.Zones zoneConfig;
private final AtomicBoolean alreadyConfigured = new AtomicBoolean();
private final Zone zone;
@Inject
public AthenzSslKeyStoreConfigurator(SecretStore secretStore,
AthenzProviderServiceConfig config,
Zone zone) {
AthenzProviderServiceConfig.Zones zoneConfig = getZoneConfig(config, zone);
this.certificateClient = new AthenzCertificateClient(config, zoneConfig);
this.keyProvider = new SecretStoreKeyProvider(secretStore, zoneConfig.secretName());
this.zoneConfig = zoneConfig;
this.zone = zone;
}
@Override
public void configure(SslKeyStoreContext sslKeyStoreContext) {
// TODO Remove this when main is ready
if (zone.system() != SystemName.cd) {
return;
}
if (alreadyConfigured.getAndSet(true)) { // For debugging purpose of SslKeyStoreConfigurator interface
throw new IllegalStateException("Already configured. configure() can only be called once.");
}
AthenzCertificateUpdater updater = new AthenzCertificateUpdater(sslKeyStoreContext);
scheduler.scheduleAtFixedRate(updater, /*initialDelay*/0, CERTIFICATE_UPDATE_PERIOD.toMinutes(), TimeUnit.MINUTES);
}
@Override
public void deconstruct() {
try {
scheduler.shutdownNow();
scheduler.awaitTermination(30, TimeUnit.SECONDS);
} catch (InterruptedException e) {
throw new RuntimeException("Failed to shutdown Athenz certificate updater on time", e);
}
}
private class AthenzCertificateUpdater implements Runnable {
private final SslKeyStoreContext sslKeyStoreContext;
AthenzCertificateUpdater(SslKeyStoreContext sslKeyStoreContext) {
this.sslKeyStoreContext = sslKeyStoreContext;
}
@Override
public void run() {
try {
log.log(LogLevel.INFO, "Updating Athenz certificate from ZTS");
PrivateKey privateKey = keyProvider.getPrivateKey(zoneConfig.secretVersion());
X509Certificate certificate = certificateClient.updateCertificate(privateKey, CERTIFICATE_EXPIRY_TIME);
verifyActualExperiy(certificate);
String dummyPassword = "athenz";
KeyStore keyStore = KeyStore.getInstance("JKS");
keyStore.load(null);
keyStore.setKeyEntry("athenz", privateKey, dummyPassword.toCharArray(), new Certificate[]{certificate});
sslKeyStoreContext.updateKeyStore(keyStore, dummyPassword);
log.log(LogLevel.INFO, "Athenz certificate reload successfully completed");
} catch (Throwable e) {
log.log(LogLevel.ERROR, "Failed to update certificate from ZTS: " + e.getMessage(), e);
}
}
private void verifyActualExperiy(X509Certificate certificate) {
Instant notAfter = certificate.getNotAfter().toInstant();
Instant notBefore = certificate.getNotBefore().toInstant();
if (!notBefore.plus(CERTIFICATE_EXPIRY_TIME).equals(notAfter)) {
Duration actualExpiry = Duration.between(notBefore, notAfter);
log.log(LogLevel.WARNING,
String.format("Expected expiry %s, got %s", CERTIFICATE_EXPIRY_TIME, actualExpiry));
}
}
}
}
|
package com.jackwink.libsodium;
import com.jackwink.libsodium.jni.Sodium;
public class NaCl {
private static NaCl instance = null;
protected NaCl() {
// Exists to defeat instantiation and force the first created instance to call sodium_init
if (Sodium.sodium_init() == -1) {
throw new RuntimeException("Sodium could not be initialized.");
}
}
public static NaCl getInstance() {
if(instance == null) {
instance = new NaCl();
}
return instance;
}
public static String sodium_version_string() {
return Sodium.sodium_version_string();
}
public int sodium_init() {
return Sodium.sodium_init();
}
public static int crypto_sign_keypair(byte[] pk, byte[] sk) {
return Sodium.crypto_sign_keypair(pk, sk);
}
static {
System.loadLibrary("sodiumjni");
}
}
|
package org.openbmap.activity;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import org.mapsforge.core.graphics.Color;
import org.mapsforge.core.graphics.Paint;
import org.mapsforge.core.graphics.Style;
import org.mapsforge.core.model.BoundingBox;
import org.mapsforge.core.model.LatLong;
import org.mapsforge.map.android.AndroidPreferences;
import org.mapsforge.map.android.graphics.AndroidGraphicFactory;
import org.mapsforge.map.android.view.MapView;
import org.mapsforge.map.layer.Layer;
import org.mapsforge.map.layer.LayerManager;
import org.mapsforge.map.layer.Layers;
import org.mapsforge.map.layer.cache.TileCache;
import org.mapsforge.map.layer.overlay.Circle;
import org.mapsforge.map.layer.overlay.Polyline;
import org.mapsforge.map.model.MapViewPosition;
import org.mapsforge.map.model.common.Observer;
import org.mapsforge.map.util.MapPositionUtil;
import org.openbmap.Preferences;
import org.openbmap.R;
import org.openbmap.RadioBeacon;
import org.openbmap.db.DataHelper;
import org.openbmap.db.Schema;
import org.openbmap.db.model.WifiRecord;
import org.openbmap.utils.GpxMapObjectsLoader;
import org.openbmap.utils.GpxMapObjectsLoader.OnGpxLoadedListener;
import org.openbmap.utils.LatLongHelper;
import org.openbmap.utils.MapUtils;
import org.openbmap.utils.SessionLatLong;
import org.openbmap.utils.SessionMapObjectsLoader;
import org.openbmap.utils.SessionMapObjectsLoader.OnSessionLoadedListener;
import org.openbmap.utils.WifiCatalogMapObjectsLoader;
import org.openbmap.utils.WifiCatalogMapObjectsLoader.OnCatalogLoadedListener;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Matrix;
import android.location.Location;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.Spinner;
import android.widget.ToggleButton;
/**
* Activity for displaying session's GPX track and wifis
*/
public class MapViewActivity extends Activity implements
OnCatalogLoadedListener,
OnSessionLoadedListener,
OnGpxLoadedListener {
public enum LayersDisplayed { ALL, SESSION_ONLY, SESSION_AND_CATALOG};
private static final String TAG = MapViewActivity.class.getSimpleName();
/**
* If zoom level < MIN_OBJECT_ZOOM session wifis and wifi catalog objects won't be displayed for performance reasons
*/
private static final int MIN_OBJECT_ZOOM = 12;
private static final int ALPHA_WIFI_CATALOG_FILL = 90;
private static final int ALPHA_WIFI_CATALOG_STROKE = 100;
private static final int ALPHA_SESSION_FILL = 50;
private static final int ALPHA_OTHER_SESSIONS_FILL = 35;
/**
* Circle size current session objects
*/
private static final int CIRCLE_SESSION_WIDTH = 30;
private static final int CIRCLE_OTHER_SESSION_WIDTH = 15;
private static final int CIRCLE_WIFI_CATALOG_WIDTH = 15;
private static final int STROKE_GPX_WIDTH = 5;
/**
* Keeps the SharedPreferences.
*/
private SharedPreferences prefs = null;
/**
* Database helper for retrieving session wifi scan results.
*/
private DataHelper dbHelper;
/**
* Minimum time (in millis) between automatic overlay refresh
*/
protected static final float SESSION_REFRESH_INTERVAL = 2000;
/**
* Minimum distance (in meter) between automatic session overlay refresh
*/
protected static final float SESSION_REFRESH_DISTANCE = 10;
/**
* Minimum distance (in meter) between automatic catalog overlay refresh
* Please note: catalog objects are static, thus updates aren't necessary that often
*/
protected static final float CATALOG_REFRESH_DISTANCE = 200;
/**
* Minimum time (in millis) between automatic catalog refresh
* Please note: catalog objects are static, thus updates aren't necessary that often
*/
protected static final float CATALOG_REFRESH_INTERVAL = 5000;
/**
* Minimum time (in millis) between gpx position refresh
*/
protected static final float GPX_REFRESH_INTERVAL = 1000;
/**
* Load more than currently visible objects?
*/
private static final boolean PREFETCH_MAP_OBJECTS = true;
/**
* Session currently displayed
*/
private int mSessionId;
/**
* System time of last gpx refresh (in millis)
*/
private long gpxRefreshTime;
private byte lastZoom;
// [start] UI controls
/**
* MapView
*/
private MapView mapView;
/**
* When checked map view will automatically focus current location
*/
private ToggleButton btnSnapToLocation;
/**
* Zoom button
*/
private ImageButton btnZoom;
/**
* Un-zoom button
*/
private ImageButton btnUnzoom;
/**
* Spinner toggling displayed session objects (all or only current)
*/
private Spinner btnLayerSelection;
//[end]
// [start] Map styles
/**
* Baselayer cache
*/
private TileCache tileCache;
private Paint paintCatalogFill;
private Paint paintCatalogStroke;
/**
* Paint style for active sessions objects
*/
private Paint paintActiveSessionFill;
/**
* Paint style for objects from other sessions
*/
private Paint paintOtherSessionFill;
private ArrayList<Layer> catalogObjects;
private ArrayList<Layer> sessionObjects;
private Polyline gpxObjects;
//[end]
// [start] Dynamic map variables
/**
* Used for persisting zoom and position settings onPause / onDestroy
*/
private AndroidPreferences preferencesFacade;
/**
* Observes zoom and map movements (for triggering overlay updates)
*/
private Observer mapObserver;
/**
* Another wifi catalog overlay refresh is taking place
*/
private boolean mRefreshCatalogPending = false;
/**
* Another session overlay refresh is taking place
*/
private boolean mRefreshSessionPending = false;
/**
* Direction marker is currently updated
*/
private boolean mRefreshDirectionPending;
/**
* Another gpx overlay refresh is taking place
*/
private boolean mRefreshGpxPending;
/**
* System time of last session overlay refresh (in millis)
*/
private long sessionObjectsRefreshTime;
/**
* System time of last catalog overlay refresh (in millis)
*/
private long catalogObjectsRefreshTime;
/**
* Location of last session overlay refresh
*/
private Location sessionObjectsRefreshedAt = new Location("DUMMY");
/**
* Location of last session overlay refresh
*/
private Location catalogObjectsRefreshedAt = new Location("DUMMY");
// [end]
/**
* Receives GPS location updates.
*/
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(final Context context, final Intent intent) {
// handling GPS broadcasts
if (RadioBeacon.INTENT_BROADCAST_POSITION.equals(intent.getAction())) {
Location location = intent.getExtras().getParcelable("android.location.Location");
// if btnSnapToLocation is checked, move map
if (btnSnapToLocation.isChecked() && mapView != null) {
LatLong currentPos = new LatLong(location.getLatitude(), location.getLongitude());
mapView.getModel().mapViewPosition.setCenter(currentPos);
}
// update overlays
if (LatLongHelper.isValidLocation(location)) {
/*
* Update overlays if necessary, but only if
* 1.) current zoom level >= 12 (otherwise single points not visible, huge performance impact)
* 2.) overlay items haven't been refreshed for a while AND user has moved a bit
*/
if ((mapView.getModel().mapViewPosition.getZoomLevel() >= MIN_OBJECT_ZOOM) && (sessionLayerOutdated(location))) {
refreshSessionOverlays(location);
}
if ((mapView.getModel().mapViewPosition.getZoomLevel() >= MIN_OBJECT_ZOOM) &&
catalogLayerSelected() &&
catalogLayerOutdated(location)) {
refreshCatalogOverlay(location);
}
if (gpxLayerOutdated()) {
refreshGpxTrace(location);
}
// indicate bearing
refreshCompass(location);
} else {
Log.e(TAG, "Invalid positon! Cycle skipped");
}
location = null;
}
}
};
@Override
public final void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mapview);
// get shared preferences
prefs = PreferenceManager.getDefaultSharedPreferences(this);
// Register our gps broadcast mReceiver
registerReceiver();
initUi();
initMap();
catalogObjects = new ArrayList<Layer>();
sessionObjects = new ArrayList<Layer>();
gpxObjects = new Polyline(MapUtils.createPaint(AndroidGraphicFactory.INSTANCE.createColor(Color.BLACK), STROKE_GPX_WIDTH,
Style.STROKE), AndroidGraphicFactory.INSTANCE);
}
@Override
protected final void onResume() {
super.onResume();
initDb();
registerReceiver();
if (this.getIntent().hasExtra(Schema.COL_ID)) {
int focusWifi = this.getIntent().getExtras().getInt(Schema.COL_ID);
Log.d(TAG, "Zooming onto " + focusWifi);
if (focusWifi != 0) {
loadSingleObject(focusWifi);
}
}
}
@Override
protected final void onPause() {
//releaseMap();
unregisterReceiver();
super.onPause();
}
@Override
protected final void onDestroy() {
releaseMap();
super.onDestroy();
}
private void initDb() {
dbHelper = new DataHelper(this);
mSessionId = dbHelper.getActiveSessionId();
if (mSessionId != RadioBeacon.SESSION_NOT_TRACKING) {
Log.i(TAG, "Displaying session " + mSessionId);
} else {
Log.w(TAG, "No active session?");
}
}
/**
* Initializes map components
*/
private void initMap() {
SharedPreferences sharedPreferences = this.getSharedPreferences(getPersistableId(), MODE_PRIVATE);
preferencesFacade = new AndroidPreferences(sharedPreferences);
this.mapView = (MapView) findViewById(R.id.map);
this.mapView.getModel().init(preferencesFacade);
this.mapView.setClickable(true);
this.mapView.getMapScaleBar().setVisible(true);
this.tileCache = createTileCache();
// on first start zoom is set to very low value, so users won't see anything
// zoom to moderate zoomlevel..
if (this.mapView.getModel().mapViewPosition.getZoomLevel() < (byte) 10) {
this.mapView.getModel().mapViewPosition.setZoomLevel((byte) 15);
}
LayerManager layerManager = this.mapView.getLayerManager();
Layers layers = layerManager.getLayers();
// remove all layers including base layer
layers.clear();
layers.add(MapUtils.createTileRendererLayer(
this.tileCache,
this.mapView.getModel().mapViewPosition,
getMapFile()));
this.mapObserver = new Observer() {
@Override
public void onChange() {
byte zoom = mapView.getModel().mapViewPosition.getZoomLevel();
if (zoom != lastZoom && zoom >= MIN_OBJECT_ZOOM) {
// Zoom level changed
Log.i(TAG, "New zoom level " + zoom + ", reloading map objects");
Location mapCenter = new Location("DUMMY");
mapCenter.setLatitude(mapView.getModel().mapViewPosition.getCenter().latitude);
mapCenter.setLongitude(mapView.getModel().mapViewPosition.getCenter().longitude);
refreshSessionOverlays(mapCenter);
if (catalogLayerSelected()) {
refreshCatalogOverlay(mapCenter);
} else {
clearCatalogLayer();
}
lastZoom = zoom;
}
if (!btnSnapToLocation.isChecked()) {
// Free-move mode
LatLong tmp = mapView.getModel().mapViewPosition.getCenter();
Location position = new Location("DUMMY");
position.setLatitude(tmp.latitude);
position.setLongitude(tmp.longitude);
if (sessionLayerOutdated(position)) {
refreshSessionOverlays(position);
}
if (catalogLayerSelected() && catalogLayerOutdated(position)) {
refreshCatalogOverlay(position);
} else {
clearCatalogLayer();
}
}
}
};
mapView.getModel().mapViewPosition.addObserver(mapObserver);
}
/**
* Initializes UI componensts
*/
private void initUi() {
btnLayerSelection = (Spinner) findViewById(R.id.mapview_layers_selection);
btnLayerSelection.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(final AdapterView<?> parent, final View view, final int pos, final long id) {
Location mapCenter = new Location("DUMMY");
mapCenter.setLatitude(mapView.getModel().mapViewPosition.getCenter().latitude);
mapCenter.setLongitude(mapView.getModel().mapViewPosition.getCenter().longitude);
refreshSessionOverlays(mapCenter);
if (catalogLayerSelected()) {
refreshCatalogOverlay(mapCenter);
}
}
public void onNothingSelected(final AdapterView<?> parent) {
}
});
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.layers, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
btnLayerSelection.setAdapter(adapter);
btnSnapToLocation = (ToggleButton) findViewById(R.id.mapview_tb_snap_to_location);
btnZoom = (ImageButton) findViewById(R.id.btnZoom);
btnZoom.setOnClickListener(new OnClickListener() {
@Override
public void onClick(final View v) {
byte zoom = mapView.getModel().mapViewPosition.getZoomLevel();
if (zoom < mapView.getModel().mapViewPosition.getZoomLevelMax()) {
mapView.getModel().mapViewPosition.setZoomLevel((byte) (zoom + 1));
}
}
});
btnUnzoom = (ImageButton) findViewById(R.id.btnUnzoom);
btnUnzoom.setOnClickListener(new OnClickListener() {
@Override
public void onClick(final View v) {
byte zoom = mapView.getModel().mapViewPosition.getZoomLevel();
if (zoom > mapView.getModel().mapViewPosition.getZoomLevelMin()) {
mapView.getModel().mapViewPosition.setZoomLevel((byte) (zoom - 1));
}
}
});
paintCatalogFill = MapUtils.createPaint(AndroidGraphicFactory.INSTANCE.createColor(ALPHA_WIFI_CATALOG_FILL, 120, 150, 120), 2, Style.FILL);
paintCatalogStroke = MapUtils.createPaint(AndroidGraphicFactory.INSTANCE.createColor(ALPHA_WIFI_CATALOG_STROKE, 120, 150, 120), 2, Style.STROKE);
paintActiveSessionFill = MapUtils.createPaint(AndroidGraphicFactory.INSTANCE.createColor(ALPHA_SESSION_FILL, 0, 0, 255), 2, Style.FILL);
paintOtherSessionFill = MapUtils.createPaint(AndroidGraphicFactory.INSTANCE.createColor(ALPHA_OTHER_SESSIONS_FILL, 255, 0, 255), 2, Style.FILL);
}
private void registerReceiver() {
IntentFilter filter = new IntentFilter();
filter.addAction(RadioBeacon.INTENT_BROADCAST_POSITION);
registerReceiver(mReceiver, filter);
}
/**
* Unregisters receivers for GPS and wifi scan results.
*/
private void unregisterReceiver() {
try {
unregisterReceiver(mReceiver);
} catch (IllegalArgumentException e) {
return;
}
}
protected final void refreshCatalogOverlay(final Location location) {
if (!mRefreshCatalogPending) {
Log.d(TAG, "Updating wifi catalog overlay");
mRefreshCatalogPending = true;
proceedAfterCatalogLoaded();
catalogObjectsRefreshedAt = location;
catalogObjectsRefreshTime = System.currentTimeMillis();
} else {
Log.v(TAG, "Reference overlay refresh in progress. Skipping refresh..");
}
}
/**
* Is new location far enough from last refresh location?
* @return true if catalog overlay needs refresh
*/
private boolean catalogLayerOutdated(final Location current) {
if (current == null) {
// fail safe: draw if something went wrong
return true;
}
return (
(catalogObjectsRefreshedAt.distanceTo(current) > CATALOG_REFRESH_DISTANCE)
&& ((System.currentTimeMillis() - catalogObjectsRefreshTime) > CATALOG_REFRESH_INTERVAL)
);
}
/**
* Loads reference wifis around location from openbmap wifi catalog.
* Callback function, upon completion onCatalogLoaded is called for drawing
* @param center
* For performance reasons only wifis around specified location are displayed.
*/
private void proceedAfterCatalogLoaded() {
BoundingBox bbox = MapPositionUtil.getBoundingBox(
mapView.getModel().mapViewPosition.getMapPosition(),
mapView.getDimension());
double minLatitude = bbox.minLatitude;
double maxLatitude = bbox.maxLatitude;
double minLongitude = bbox.minLongitude;
double maxLongitude = bbox.maxLongitude;
// query more than visible objects for smoother data scrolling / less database queries?
if (PREFETCH_MAP_OBJECTS) {
double latSpan = maxLatitude - minLatitude;
double lonSpan = maxLongitude - minLongitude;
minLatitude -= latSpan * 0.5;
maxLatitude += latSpan * 0.5;
minLongitude -= lonSpan * 0.5;
maxLongitude += lonSpan * 0.5;
}
WifiCatalogMapObjectsLoader task = new WifiCatalogMapObjectsLoader(this);
task.execute(minLatitude, maxLatitude, minLongitude, maxLongitude);
}
/* (non-Javadoc)
* @see org.openbmap.utils.WifiCatalogMapObjectsLoader.OnCatalogLoadedListener#onComplete(java.util.ArrayList)
*/
@Override
public final void onCatalogLoaded(final ArrayList<LatLong> points) {
Log.d(TAG, "Loaded catalog objects");
Layers layers = this.mapView.getLayerManager().getLayers();
clearCatalogLayer();
// redraw
for (int i = 0; i < points.size(); i++) {
Circle circle = new Circle(points.get(i), CIRCLE_WIFI_CATALOG_WIDTH, paintCatalogFill, paintCatalogStroke);
catalogObjects.add(circle);
}
/**
* Draw stack (z-order):
* base map
* catalog objects
* session objects
*/
int insertAfter = -1;
if (layers.size() > 0) {
// base map
insertAfter = 1;
} else {
// no map
insertAfter = 0;
}
for (int i = 0; i < catalogObjects.size(); i++) {
layers.add(insertAfter + i, catalogObjects.get(i));
}
// enable next refresh
mRefreshCatalogPending = false;
Log.d(TAG, "Drawed catalog objects");
}
/**
* Clears catalog layer objects
*/
private void clearCatalogLayer() {
for (Iterator<Layer> iterator = catalogObjects.iterator(); iterator.hasNext();) {
Layer layer = (Layer) iterator.next();
this.mapView.getLayerManager().getLayers().remove(layer);
}
catalogObjects.clear();
}
/**
* Refreshes reference and session overlays.
* If another refresh is in progress, update is skipped.
* @param location
*/
protected final void refreshSessionOverlays(final Location location) {
if (!mRefreshSessionPending) {
Log.d(TAG, "Updating session overlay");
mRefreshSessionPending = true;
proceedAfterSessionObjectsLoaded(null);
sessionObjectsRefreshTime = System.currentTimeMillis();
sessionObjectsRefreshedAt = location;
} else {
Log.v(TAG, "Session overlay refresh in progress. Skipping refresh..");
}
}
/**
* Is new location far enough from last refresh location and is last refresh to old?
* @return true if session overlay needs refresh
*/
private boolean sessionLayerOutdated(final Location current) {
if (current == null) {
// fail safe: draw if something went wrong
return true;
}
return (
(sessionObjectsRefreshedAt.distanceTo(current) > SESSION_REFRESH_DISTANCE)
&& ((System.currentTimeMillis() - sessionObjectsRefreshTime) > SESSION_REFRESH_INTERVAL)
);
}
/**
* Loads session wifis in visible range.
* Will call onSessionLoaded callback upon completion
* @param highlight
* If highlight is specified only this wifi is displayed
*/
private void proceedAfterSessionObjectsLoaded(final WifiRecord highlight) {
BoundingBox bbox = MapPositionUtil.getBoundingBox(
mapView.getModel().mapViewPosition.getMapPosition(),
mapView.getDimension());
if (highlight == null) {
ArrayList<Integer> sessions = new ArrayList<Integer>();
if (allLayerSelected()) {
// load all session wifis
sessions = new DataHelper(this).getSessionList();
} else {
sessions.add(mSessionId);
}
double minLatitude = bbox.minLatitude;
double maxLatitude = bbox.maxLatitude;
double minLongitude = bbox.minLongitude;
double maxLongitude = bbox.maxLongitude;
// query more than visible objects for smoother data scrolling / less database queries
if (PREFETCH_MAP_OBJECTS) {
double latSpan = maxLatitude - minLatitude;
double lonSpan = maxLongitude - minLongitude;
minLatitude -= latSpan * 0.5;
maxLatitude += latSpan * 0.5;
minLongitude -= lonSpan * 0.5;
maxLongitude += lonSpan * 0.5;
}
SessionMapObjectsLoader task = new SessionMapObjectsLoader(this, sessions);
task.execute(minLatitude, maxLatitude, minLongitude, maxLatitude, null);
} else {
// draw specific wifi
ArrayList<Integer> sessions = new ArrayList<Integer>();
sessions.add(mSessionId);
SessionMapObjectsLoader task = new SessionMapObjectsLoader(this, sessions);
task.execute(bbox.minLatitude, bbox.maxLatitude, bbox.minLongitude, bbox.maxLatitude, highlight.getBssid());
}
}
/* (non-Javadoc)
* @see org.openbmap.utils.SessionMapObjectsLoader.OnSessionLoadedListener#onSessionLoaded(java.util.ArrayList)
*/
@Override
public final void onSessionLoaded(final ArrayList<SessionLatLong> points) {
Log.d(TAG, "Loaded session objects");
Layers layers = this.mapView.getLayerManager().getLayers();
// clear overlay
for (Iterator<Layer> iterator = sessionObjects.iterator(); iterator.hasNext();) {
Layer layer = (Layer) iterator.next();
layers.remove(layer);
}
sessionObjects.clear();
for (int i = 0; i < points.size(); i++) {
if (points.get(i).getSession() == mSessionId) {
// current session objects are larger
Circle circle = new Circle(points.get(i), CIRCLE_SESSION_WIDTH, paintActiveSessionFill, null);
sessionObjects.add(circle);
} else {
// other session objects are smaller and in other color
Circle circle = new Circle(points.get(i), CIRCLE_OTHER_SESSION_WIDTH, paintOtherSessionFill, null);
sessionObjects.add(circle);
}
}
/**
* Draw stack (z-order):
* base map
* catalog objects
* session objects
*/
int insertAfter = -1;
if (layers.size() > 0 && catalogObjects.size() > 0) {
// base map + catalog objects
insertAfter = layers.indexOf((Layer) catalogObjects.get(catalogObjects.size() - 1));
} else if (layers.size() > 0 && catalogObjects.size() == 0) {
// base map + no catalog objects
insertAfter = 1;
} else {
// no map + no catalog objects
insertAfter = 0;
}
for (int i = 0; i < sessionObjects.size(); i++) {
layers.add(insertAfter + i, sessionObjects.get(i));
}
// if we have just loaded on point, set map center
if (points.size() == 1) {
mapView.getModel().mapViewPosition.setCenter((LatLong) points.get(0));
}
// enable next refresh
mRefreshSessionPending = false;
Log.d(TAG, "Drawed catalog objects");
}
/**
* @param location
*/
private void refreshGpxTrace(final Location location) {
if (!mRefreshGpxPending) {
Log.d(TAG, "Updating gpx overlay");
mRefreshGpxPending = true;
proceedAfterGpxObjectsLoaded();
gpxRefreshTime = System.currentTimeMillis();
} else {
Log.v(TAG, "Gpx overlay refresh in progress. Skipping refresh..");
}
}
/**
* Is last gpx overlay update to old?
* @return true if overlay needs refresh
*/
private boolean gpxLayerOutdated() {
return ((System.currentTimeMillis() - gpxRefreshTime) > GPX_REFRESH_INTERVAL);
}
/*
* Loads gpx points in visible range.
*/
private void proceedAfterGpxObjectsLoaded() {
BoundingBox bbox = MapPositionUtil.getBoundingBox(
mapView.getModel().mapViewPosition.getMapPosition(),
mapView.getDimension());
GpxMapObjectsLoader task = new GpxMapObjectsLoader(this);
// query with some extra space
task.execute(mSessionId, bbox.minLatitude - 0.01, bbox.maxLatitude + 0.01, bbox.minLongitude - 0.15, bbox.maxLatitude + 0.15);
}
/**
* Callback function for loadGpxObjects()
*/
@Override
public final void onGpxLoaded(final ArrayList<LatLong> points) {
Log.d(TAG, "Loaded gpx objects");
// clear overlay
gpxObjects.getLatLongs().clear();
this.mapView.getLayerManager().getLayers().remove(gpxObjects);
for (int i = 0; i < points.size(); i++) {
gpxObjects.getLatLongs().add(points.get(i));
}
this.mapView.getLayerManager().getLayers().add(gpxObjects);
mRefreshGpxPending = false;
}
/**
* Highlights single wifi on map.
* @param id wifi id to highlight
*/
public final void loadSingleObject(final int id) {
Log.d(TAG, "Adding selected wifi to overlay: " + id);
WifiRecord wifi = dbHelper.loadWifiById(id);
if (wifi != null) {
proceedAfterSessionObjectsLoaded(wifi);
}
}
/**
* Draws arrow in direction of travel. If bearing is unavailable a generic position symbol is used.
* If another refresh is taking place, update is skipped
*/
private void refreshCompass(final Location location) {
// ensure that previous refresh has been finished
if (mRefreshDirectionPending) {
return;
}
mRefreshDirectionPending = true;
// determine which drawable we currently
ImageView iv = (ImageView) findViewById(R.id.position_marker);
Integer id = (Integer) iv.getTag() == null ? 0 : (Integer) iv.getTag();
if (location.hasBearing()) {
// determine which drawable we currently use
drawCompass(iv, id, location.getBearing());
} else {
// refresh only if needed
if (id != R.drawable.cross) {
iv.setImageResource(R.drawable.cross);
}
//Log.i(TAG, "Can't draw direction marker: no bearing provided");
}
mRefreshDirectionPending = false;
}
/**
* Draws compass
* @param iv image view used for compass
* @param ressourceId resource id compass needle
* @param bearing bearing (azimuth)
*/
private void drawCompass(final ImageView iv, final Integer ressourceId, final float bearing) {
// refresh only if needed
if (ressourceId != R.drawable.arrow) {
iv.setImageResource(R.drawable.arrow);
}
// rotate arrow
Matrix matrix = new Matrix();
iv.setScaleType(ScaleType.MATRIX); //required
matrix.postRotate(bearing, iv.getWidth() / 2f, iv.getHeight() / 2f);
iv.setImageMatrix(matrix);
}
/**
* Checks whether user wants to see catalog objects
* @return true if catalog objects need to be drawn
*/
private boolean catalogLayerSelected() {
return (btnLayerSelection.getSelectedItemPosition() == LayersDisplayed.ALL.ordinal()
|| btnLayerSelection.getSelectedItemPosition() == LayersDisplayed.SESSION_AND_CATALOG.ordinal());
}
/**
* Checks whether user wants to see all sessions' objects (i.e. not only active)
* @return true if all sessions need to be drawn
*/
private boolean allLayerSelected() {
return (btnLayerSelection.getSelectedItemPosition() == LayersDisplayed.ALL.ordinal());
}
/**
* Opens selected map file
* @return a map file
*/
protected final File getMapFile() {
File mapFile = new File(
Environment.getExternalStorageDirectory().getPath()
+ prefs.getString(Preferences.KEY_DATA_DIR, Preferences.VAL_DATA_DIR)
+ Preferences.MAPS_SUBDIR,
prefs.getString(Preferences.KEY_MAP_FILE, Preferences.VAL_MAP_FILE));
/*
if (mapFile.exists()) {
mMapView.setClickable(true);
//mMapView.setBuiltInZoomControls(true);
//mMapView.setMapFile(mapFile);
} else {
Log.i(TAG, "No map file found!");
Toast.makeText(this.getBaseContext(), R.string.please_select_map, Toast.LENGTH_LONG).show();
mMapView.setClickable(false);
//mMapView.setBuiltInZoomControls(false);
mMapView.setVisibility(View.GONE);
}
*/
return mapFile;
}
protected final void addLayers(final LayerManager layerManager, final TileCache tileCache, final MapViewPosition mapViewPosition) {
layerManager.getLayers().add(MapUtils.createTileRendererLayer(tileCache, mapViewPosition, getMapFile()));
}
/**
* Creates a tile cache for the baselayer
* @return
*/
protected final TileCache createTileCache() {
return MapUtils.createExternalStorageTileCache(this, getPersistableId());
}
/**
* @return the id that is used to save this mapview
*/
protected final String getPersistableId() {
return this.getClass().getSimpleName();
}
/**
* Sets map-related object to null to enable garbage collection.
*/
private void releaseMap() {
Log.i(TAG, "Releasing map components");
// save map settings
this.mapView.getModel().save(this.preferencesFacade);
this.preferencesFacade.save();
// release zoom / move observer for gc
this.mapObserver = null;
if (mapView != null) {
mapView.destroy();
}
}
/**
* Creates gpx overlay line
* @param points
* @return
*/
/*
private static Polyline createGpxSymbol(final ArrayList<LatLong> points) {
Paint paintStroke = new Paint(Paint.ANTI_ALIAS_FLAG);
paintStroke.setStyle(Paint.Style.STROKE);
paintStroke.setColor(Color.BLACK);
paintStroke.setAlpha(255);
paintStroke.setStrokeWidth(3);
paintStroke.setStrokeCap(Cap.ROUND);
paintStroke.setStrokeJoin(Paint.Join.ROUND);
Polygon chain = new Polygon(points);
Polyline line = new Polyline(chain, paintStroke);
return line;
}
*/
static Paint createPaint(final int color, final int strokeWidth, final Style style) {
Paint paint = AndroidGraphicFactory.INSTANCE.createPaint();
paint.setColor(color);
paint.setStrokeWidth(strokeWidth);
paint.setStyle(style);
return paint;
}
}
|
package com.marverenic.music;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.audiofx.AudioEffect;
import android.media.audiofx.Equalizer;
import android.net.Uri;
import android.os.PowerManager;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.v4.media.MediaMetadataCompat;
import android.support.v4.media.session.MediaSessionCompat;
import android.support.v4.media.session.PlaybackStateCompat;
import com.crashlytics.android.Crashlytics;
import com.marverenic.music.activity.NowPlayingActivity;
import com.marverenic.music.instances.Library;
import com.marverenic.music.instances.Song;
import com.marverenic.music.utils.ManagedMediaPlayer;
import com.marverenic.music.utils.Prefs;
import com.marverenic.music.utils.Util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import java.util.Random;
import java.util.Scanner;
public class Player implements MediaPlayer.OnCompletionListener, MediaPlayer.OnPreparedListener,
AudioManager.OnAudioFocusChangeListener {
// Sent to refresh views that use up-to-date player information
public static final String UPDATE_BROADCAST = "marverenic.jockey.player.REFRESH";
private static final String TAG = "Player";
private static final String QUEUE_FILE = ".queue";
public static final String PREFERENCE_SHUFFLE = "prefShuffle";
public static final String PREFERENCE_REPEAT = "prefRepeat";
// Instance variables
private ManagedMediaPlayer mediaPlayer;
private Equalizer equalizer;
private Context context;
private MediaSessionCompat mediaSession;
private HeadsetListener headphoneListener;
// Queue information
private List<Song> queue;
private List<Song> queueShuffled = new ArrayList<>();
private int queuePosition;
private int queuePositionShuffled;
// MediaFocus variables
// If we currently have audio focus
private boolean active = false;
// If we should play music when focus is returned
private boolean shouldResumeOnFocusGained = false;
// Shufle & Repeat options
private boolean shuffle; // Shuffle status
public static final short REPEAT_NONE = 0;
public static final short REPEAT_ALL = 1;
public static final short REPEAT_ONE = 2;
private short repeat; // Repeat status
private Bitmap art; // The art for the current song
/**
* A {@link Properties} object used as a hashtable for saving play and skip counts.
* See {@link Player#logPlayCount(long, boolean)}
*
* Keys are stored as strings in the form "song_id"
* Values are stored as strings in the form "play,skip,lastPlayDateAsUtcTimeStamp"
*/
private Properties playCountHashtable;
/**
* Create a new Player Object, which manages a {@link MediaPlayer}
* @param context A {@link Context} that will be held for the lifetime of the Player
*/
public Player(Context context) {
this.context = context;
// Initialize the media player
mediaPlayer = new ManagedMediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setWakeMode(context, PowerManager.PARTIAL_WAKE_LOCK);
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setOnCompletionListener(this);
// Initialize the queue
queue = new ArrayList<>();
queuePosition = 0;
// Load preferences
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
shuffle = prefs.getBoolean(PREFERENCE_SHUFFLE, false);
repeat = (short) prefs.getInt(PREFERENCE_REPEAT, REPEAT_NONE);
initMediaSession();
if (Util.hasEqualizer()) {
initEqualizer();
}
// Attach a HeadsetListener to respond to headphone events
headphoneListener = new HeadsetListener(this);
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_MEDIA_BUTTON);
filter.addAction(Intent.ACTION_HEADSET_PLUG);
context.registerReceiver(headphoneListener, filter);
}
/**
* Reload the last queue saved by the Player
*/
public void reload() {
try {
File save = new File(context.getExternalFilesDir(null), QUEUE_FILE);
Scanner scanner = new Scanner(save);
final int currentPosition = scanner.nextInt();
if (shuffle) {
queuePositionShuffled = scanner.nextInt();
} else {
queuePosition = scanner.nextInt();
}
int queueLength = scanner.nextInt();
int[] queueIDs = new int[queueLength];
for (int i = 0; i < queueLength; i++) {
queueIDs[i] = scanner.nextInt();
}
queue = Library.buildSongListFromIds(queueIDs, context);
int[] shuffleQueueIDs;
if (scanner.hasNextInt()) {
shuffleQueueIDs = new int[queueLength];
for (int i = 0; i < queueLength; i++) {
shuffleQueueIDs[i] = scanner.nextInt();
}
queueShuffled = Library.buildSongListFromIds(shuffleQueueIDs, context);
} else if (shuffle) {
queuePosition = queuePositionShuffled;
shuffleQueue();
}
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
mp.seekTo(currentPosition);
updateNowPlaying();
mp.setOnPreparedListener(Player.this);
}
});
art = Util.fetchFullArt(getNowPlaying());
mediaPlayer.setDataSource(getNowPlaying().getLocation());
mediaPlayer.prepareAsync();
} catch (Exception e) {
queuePosition = 0;
queuePositionShuffled = 0;
queue.clear();
queueShuffled.clear();
}
}
/**
* Reload all equalizer settings from SharedPreferences
*/
private void initEqualizer() {
SharedPreferences prefs = Prefs.getPrefs(context);
String eqSettings = prefs.getString(Prefs.EQ_SETTINGS, null);
boolean enabled = Prefs.getPrefs(context).getBoolean(Prefs.EQ_ENABLED, false);
equalizer = new Equalizer(0, mediaPlayer.getAudioSessionId());
if (eqSettings != null) {
try {
equalizer.setProperties(new Equalizer.Settings(eqSettings));
} catch (IllegalArgumentException | UnsupportedOperationException e) {
Crashlytics.logException(new RuntimeException(
"Failed to load equalizer settings: " + eqSettings, e));
}
}
equalizer.setEnabled(enabled);
// If the built in equalizer is off, bind to the system equalizer if one is available
if (!enabled) {
final Intent intent = new Intent(AudioEffect.ACTION_OPEN_AUDIO_EFFECT_CONTROL_SESSION);
intent.putExtra(AudioEffect.EXTRA_AUDIO_SESSION, getAudioSessionId());
intent.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, context.getPackageName());
context.sendBroadcast(intent);
}
}
/**
* Writes a player state to disk. Contains information about the queue (both unshuffled
* and shuffled), current queuePosition within this list, and the current queuePosition
* of the song
* @throws IOException
*/
public void saveState(@NonNull final String nextCommand) throws IOException {
// Anticipate the outcome of a command so that if we're killed right after it executes,
// we can restore to the proper state
int reloadSeekPosition;
int reloadQueuePosition = (shuffle) ? queuePositionShuffled : queuePosition;
switch (nextCommand) {
case PlayerService.ACTION_NEXT:
if (reloadQueuePosition + 1 < queue.size()) {
reloadSeekPosition = 0;
reloadQueuePosition++;
} else {
reloadSeekPosition = mediaPlayer.getDuration();
}
break;
case PlayerService.ACTION_PREV:
if (mediaPlayer.getDuration() < 5000 && reloadQueuePosition - 1 > 0) {
reloadQueuePosition
}
reloadSeekPosition = 0;
break;
default:
reloadSeekPosition = mediaPlayer.getCurrentPosition();
break;
}
final String currentPosition = Integer.toString(reloadSeekPosition);
final String queuePosition = Integer.toString(reloadQueuePosition);
final String queueLength = Integer.toString(queue.size());
String queue = "";
for (Song s : this.queue) {
queue += " " + s.getSongId();
}
String queueShuffled = "";
for (Song s : this.queueShuffled) {
queueShuffled += " " + s.getSongId();
}
String output = currentPosition + " " + queuePosition + " "
+ queueLength + queue + queueShuffled;
File save = new File(context.getExternalFilesDir(null), QUEUE_FILE);
FileOutputStream stream = new FileOutputStream(save);
stream.write(output.getBytes());
stream.close();
}
/**
* Release the player. Call when finished with an instance
*/
public void finish() {
((AudioManager) context.getSystemService(Context.AUDIO_SERVICE)).abandonAudioFocus(this);
context.unregisterReceiver(headphoneListener);
// Unbind from the system audio effects
final Intent intent = new Intent(AudioEffect.ACTION_CLOSE_AUDIO_EFFECT_CONTROL_SESSION);
intent.putExtra(AudioEffect.EXTRA_AUDIO_SESSION, getAudioSessionId());
intent.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, context.getPackageName());
context.sendBroadcast(intent);
if (equalizer != null) {
equalizer.release();
}
active = false;
mediaPlayer.stop();
mediaPlayer.release();
mediaSession.release();
mediaPlayer = null;
context = null;
}
/**
* Initiate a MediaSession to allow the Android system to interact with the player
*/
private void initMediaSession() {
mediaSession = new MediaSessionCompat(context, TAG, null, null);
mediaSession.setCallback(new MediaSessionCompat.Callback() {
@Override
public void onPlay() {
play();
updateUi();
}
@Override
public void onSkipToQueueItem(long id) {
changeSong((int) id);
updateUi();
}
@Override
public void onPause() {
pause();
updateUi();
}
@Override
public void onSkipToNext() {
skip();
updateUi();
}
@Override
public void onSkipToPrevious() {
previous();
updateUi();
}
@Override
public void onStop() {
stop();
updateUi();
}
@Override
public void onSeekTo(long pos) {
seek((int) pos);
updateUi();
}
});
mediaSession.setSessionActivity(
PendingIntent.getActivity(
context, 0,
new Intent(context, NowPlayingActivity.class)
.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP),
PendingIntent.FLAG_CANCEL_CURRENT));
mediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS
| MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
PlaybackStateCompat.Builder state = new PlaybackStateCompat.Builder()
.setActions(PlaybackStateCompat.ACTION_PLAY
| PlaybackStateCompat.ACTION_PLAY_PAUSE
| PlaybackStateCompat.ACTION_SEEK_TO
| PlaybackStateCompat.ACTION_PLAY_FROM_MEDIA_ID
| PlaybackStateCompat.ACTION_PAUSE
| PlaybackStateCompat.ACTION_SKIP_TO_NEXT
| PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS)
.setState(PlaybackStateCompat.STATE_NONE, 0, 0f);
mediaSession.setPlaybackState(state.build());
mediaSession.setActive(true);
}
@Override
public void onAudioFocusChange(int focusChange) {
shouldResumeOnFocusGained = isPlaying() || shouldResumeOnFocusGained;
switch (focusChange) {
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
pause();
break;
case AudioManager.AUDIOFOCUS_LOSS:
stop();
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
mediaPlayer.setVolume(0.5f, 0.5f);
break;
case AudioManager.AUDIOFOCUS_GAIN:
mediaPlayer.setVolume(1f, 1f);
if (shouldResumeOnFocusGained) play();
shouldResumeOnFocusGained = false;
break;
default:
break;
}
updateNowPlaying();
updateUi();
}
@Override
public void onCompletion(MediaPlayer mp) {
logPlayCount(getNowPlaying().getSongId(), false);
if (repeat == REPEAT_ONE) {
mediaPlayer.seekTo(0);
play();
} else if (hasNextInQueue(1)) {
skip();
}
updateUi();
}
@Override
public void onPrepared(MediaPlayer mp) {
if (!isPreparing()) {
mediaPlayer.start();
updateUi();
updateNowPlaying();
}
}
private boolean hasNextInQueue(int by) {
if (shuffle) {
return queuePositionShuffled + by < queueShuffled.size();
} else {
return queuePosition + by < queue.size();
}
}
private void setQueuePosition(int position) {
if (shuffle) {
queuePositionShuffled = position;
} else {
queuePosition = position;
}
}
private void incrementQueuePosition(int by) {
if (shuffle) {
queuePositionShuffled += by;
} else {
queuePosition += by;
}
}
/**
* Change the queue and shuffle it if necessary
* @param newQueue A {@link List} of {@link Song}s to become the new queue
* @param newPosition The queuePosition in the list to start playback from
*/
public void setQueue(final List<Song> newQueue, final int newPosition) {
queue = newQueue;
queuePosition = newPosition;
if (shuffle) shuffleQueue();
updateNowPlaying();
}
/**
* Replace the contents of the queue without affecting playback
* @param newQueue A {@link List} of {@link Song}s to become the new queue
* @param newPosition The queuePosition in the list to start playback from
*/
public void editQueue(final List<Song> newQueue, final int newPosition) {
if (shuffle) {
queueShuffled = newQueue;
queuePositionShuffled = newPosition;
} else {
queue = newQueue;
queuePosition = newPosition;
}
updateNowPlaying();
}
/**
* Begin playback of a new song. Call this method after changing the queue or now playing track
*/
public void begin() {
if (getNowPlaying() != null && getFocus()) {
mediaPlayer.stop();
mediaPlayer.reset();
art = Util.fetchFullArt(getNowPlaying());
try {
mediaPlayer.setDataSource(context, Uri.parse(getNowPlaying().getLocation()));
mediaPlayer.prepareAsync();
} catch (IOException e) {
Crashlytics.logException(
new IOException("Failed to play song " + getNowPlaying().getLocation(), e));
}
}
}
/**
* Update the main thread and Android System about this player instance. This method also calls
* {@link PlayerService#notifyNowPlaying()}.
*/
public void updateNowPlaying() {
PlayerService.getInstance().notifyNowPlaying();
updateMediaSession();
}
/**
* Update the MediaSession to keep the Android system up to date with player information
*/
public void updateMediaSession() {
if (getNowPlaying() != null) {
MediaMetadataCompat.Builder metadataBuilder = new MediaMetadataCompat.Builder();
Song nowPlaying = getNowPlaying();
metadataBuilder
.putString(MediaMetadataCompat.METADATA_KEY_DISPLAY_TITLE,
nowPlaying.getSongName())
.putString(MediaMetadataCompat.METADATA_KEY_TITLE,
nowPlaying.getSongName())
.putString(MediaMetadataCompat.METADATA_KEY_ALBUM,
nowPlaying.getAlbumName())
.putString(MediaMetadataCompat.METADATA_KEY_ARTIST,
nowPlaying.getArtistName())
.putLong(MediaMetadataCompat.METADATA_KEY_DURATION, getDuration())
.putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, art);
mediaSession.setMetadata(metadataBuilder.build());
PlaybackStateCompat.Builder state = new PlaybackStateCompat.Builder().setActions(
PlaybackStateCompat.ACTION_PLAY | PlaybackStateCompat.ACTION_PLAY_PAUSE
| PlaybackStateCompat.ACTION_SEEK_TO
| PlaybackStateCompat.ACTION_PLAY_FROM_MEDIA_ID
| PlaybackStateCompat.ACTION_PAUSE
| PlaybackStateCompat.ACTION_SKIP_TO_NEXT
| PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS);
switch (mediaPlayer.getState()) {
case STARTED:
state.setState(PlaybackStateCompat.STATE_PLAYING, getCurrentPosition(), 1f);
break;
case PAUSED:
state.setState(PlaybackStateCompat.STATE_PAUSED, getCurrentPosition(), 1f);
break;
case STOPPED:
state.setState(PlaybackStateCompat.STATE_STOPPED, getCurrentPosition(), 1f);
break;
default:
state.setState(PlaybackStateCompat.STATE_NONE, getCurrentPosition(), 1f);
}
mediaSession.setPlaybackState(state.build());
mediaSession.setActive(active);
}
}
/**
* Called to notify the UI thread to refresh any player data when the player changes states
* on its own (Like when a song finishes)
*/
public void updateUi() {
context.sendBroadcast(new Intent(UPDATE_BROADCAST), null);
}
/**
* Get the song at the current queuePosition in the queue or shuffled queue
* @return The now playing {@link Song} (null if nothing is playing)
*/
public Song getNowPlaying() {
if (shuffle) {
if (queueShuffled.size() == 0 || queuePositionShuffled >= queueShuffled.size()
|| queuePositionShuffled < 0) {
return null;
}
return queueShuffled.get(queuePositionShuffled);
}
if (queue.size() == 0 || queuePosition >= queue.size() || queuePosition < 0) {
return null;
}
return queue.get(queuePosition);
}
// MEDIA CONTROL METHODS
/**
* Toggle between playing and pausing music
*/
public void togglePlay() {
if (isPlaying()) {
pause();
} else {
play();
}
}
/**
* Resume playback. Starts playback over if at the end of the last song in the queue
*/
public void play() {
if (!isPlaying() && getFocus()) {
if (shuffle) {
if (queuePositionShuffled + 1 == queueShuffled.size() && mediaPlayer.isComplete()) {
queuePositionShuffled = 0;
begin();
} else {
mediaPlayer.start();
updateNowPlaying();
}
} else {
if (queuePosition + 1 == queue.size() && mediaPlayer.isComplete()) {
queuePosition = 0;
begin();
} else {
mediaPlayer.start();
updateNowPlaying();
}
}
}
}
/**
* Pauses playback. The same as calling {@link MediaPlayer#pause()}
* and {@link Player#updateNowPlaying()}
*/
public void pause() {
if (isPlaying()) {
mediaPlayer.pause();
updateNowPlaying();
}
shouldResumeOnFocusGained = false;
}
/**
* Pauses playback and releases audio focus from the system
*/
public void stop() {
if (isPlaying()) {
pause();
}
((AudioManager) context.getSystemService(Context.AUDIO_SERVICE)).abandonAudioFocus(this);
active = false;
updateMediaSession();
}
/**
* Gain Audio focus from the system if we don't already have it
* @return whether we have gained focus (or already had it)
*/
private boolean getFocus() {
if (!active) {
AudioManager audioManager =
(AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
int response = audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN);
active = response == AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
}
return active;
}
/**
* Skip to the previous track if less than 5 seconds in, otherwise restart this song from
* the beginning
*/
public void previous() {
if (!isPreparing()) {
if (mediaPlayer.getCurrentPosition() > 5000 || !hasNextInQueue(-1)) {
mediaPlayer.seekTo(0);
updateNowPlaying();
} else {
incrementQueuePosition(-1);
begin();
}
}
}
/**
* Skip to the next track in the queue
*/
public void skip() {
if (!isPreparing()) {
if (!mediaPlayer.isComplete() && getNowPlaying() != null) {
if (mediaPlayer.getCurrentPosition() > 24000
|| mediaPlayer.getCurrentPosition() > mediaPlayer.getDuration() / 2) {
logPlayCount(getNowPlaying().getSongId(), false);
} else if (getCurrentPosition() < 20000) {
logPlayCount(getNowPlaying().getSongId(), true);
}
}
if (hasNextInQueue(1)) {
incrementQueuePosition(1);
begin();
} else if (repeat == REPEAT_ALL) {
setQueuePosition(0);
begin();
} else {
mediaPlayer.complete();
updateNowPlaying();
}
}
}
/**
* Seek to a different queuePosition in the current track
* @param position The queuePosition to seek to (in milliseconds)
*/
public void seek(int position) {
if (position <= mediaPlayer.getDuration() && getNowPlaying() != null) {
mediaPlayer.seekTo(position);
mediaSession.setPlaybackState(new PlaybackStateCompat.Builder()
.setState(
isPlaying()
? PlaybackStateCompat.STATE_PLAYING
: PlaybackStateCompat.STATE_PAUSED,
(long) mediaPlayer.getCurrentPosition(),
isPlaying() ? 1f : 0f)
.build());
}
}
/**
* Change the current song to a different song in the queue
* @param newPosition The index of the song to start playing
*/
public void changeSong(int newPosition) {
if (!mediaPlayer.isComplete()) {
if (mediaPlayer.getCurrentPosition() > 24000
|| mediaPlayer.getCurrentPosition() > mediaPlayer.getDuration() / 2) {
logPlayCount(getNowPlaying().getSongId(), false);
} else if (getCurrentPosition() < 20000) {
logPlayCount(getNowPlaying().getSongId(), true);
}
}
if (shuffle) {
if (newPosition < queueShuffled.size() && newPosition != queuePositionShuffled) {
queuePositionShuffled = newPosition;
begin();
}
} else {
if (newPosition < queue.size() && queuePosition != newPosition) {
queuePosition = newPosition;
begin();
}
}
}
// QUEUE METHODS
/**
* Add a song to the queue so it plays after the current track. If shuffle is enabled, then the
* song will also be added to the end of the unshuffled queue.
* @param song the {@link Song} to add
*/
public void queueNext(final Song song) {
if (queue.size() != 0) {
if (shuffle) {
queueShuffled.add(queuePositionShuffled + 1, song);
queue.add(song);
} else {
queue.add(queuePosition + 1, song);
}
} else {
List<Song> newQueue = new ArrayList<>();
newQueue.add(song);
setQueue(newQueue, 0);
begin();
}
}
/**
* Add a song to the end of the queue. If shuffle is enabled, then the song will also be added
* to the end of the unshuffled queue.
* @param song the {@link Song} to add
*/
public void queueLast(final Song song) {
if (queue.size() != 0) {
if (shuffle) {
queueShuffled.add(queueShuffled.size(), song);
}
queue.add(queue.size(), song);
} else {
List<Song> newQueue = new ArrayList<>();
newQueue.add(song);
setQueue(newQueue, 0);
begin();
}
}
/**
* Add songs to the queue so they play after the current track. If shuffle is enabled, then the
* songs will also be added to the end of the unshuffled queue.
* @param songs a {@link List} of {@link Song}s to add
*/
public void queueNext(final List<Song> songs) {
if (queue.size() != 0) {
if (shuffle) {
queueShuffled.addAll(queuePositionShuffled + 1, songs);
queue.addAll(songs);
} else {
queue.addAll(queuePosition + 1, songs);
}
} else {
List<Song> newQueue = new ArrayList<>();
newQueue.addAll(songs);
setQueue(newQueue, 0);
begin();
}
}
/**
* Add songs to the end of the queue. If shuffle is enabled, then the songs will also be added
* to the end of the unshuffled queue.
* @param songs an {@link List} of {@link Song}s to add
*/
public void queueLast(final List<Song> songs) {
if (queue.size() != 0) {
if (shuffle) {
queueShuffled.addAll(queueShuffled.size(), songs);
queue.addAll(queue.size(), songs);
} else {
queue.addAll(queue.size(), songs);
}
} else {
List<Song> newQueue = new ArrayList<>();
newQueue.addAll(songs);
setQueue(newQueue, 0);
begin();
}
}
// SHUFFLE & REPEAT METHODS
/**
* Shuffle the queue and put it into {@link Player#queueShuffled}. The current song will always
* be placed first in the list
*/
private void shuffleQueue() {
queueShuffled.clear();
if (queue.size() > 0) {
queuePositionShuffled = 0;
queueShuffled.add(queue.get(queuePosition));
List<Song> randomHolder = new ArrayList<>();
for (int i = 0; i < queuePosition; i++) {
randomHolder.add(queue.get(i));
}
for (int i = queuePosition + 1; i < queue.size(); i++) {
randomHolder.add(queue.get(i));
}
Collections.shuffle(randomHolder, new Random(System.nanoTime()));
queueShuffled.addAll(randomHolder);
}
}
public void setPrefs(boolean shuffleSetting, short repeatSetting) {
// Because SharedPreferences doesn't work with multiple processes (thanks Google...)
// we actually have to be told what the new settings are in order to avoid the service
// and UI doing the opposite of what they should be doing and to prevent the universe
// from exploding. It's fine to initialize the SharedPreferences by reading them like we
// do in the constructor since they haven't been modified, but if something gets written
// in one process the SharedPreferences in the other process won't be updated.
// I really wish someone had told me this earlier.
if (shuffle != shuffleSetting) {
shuffle = shuffleSetting;
if (shuffle) {
shuffleQueue();
} else if (queueShuffled.size() > 0) {
queuePosition = queue.indexOf(queueShuffled.get(queuePositionShuffled));
queueShuffled = new ArrayList<>();
}
}
repeat = repeatSetting;
updateNowPlaying();
}
// PLAY & SKIP COUNT LOGGING
/**
* Initializes {@link Player#playCountHashtable}
* @throws IOException
*/
private void openPlayCountFile() throws IOException {
File file = new File(context.getExternalFilesDir(null) + "/" + Library.PLAY_COUNT_FILENAME);
if (!file.exists()) {
//noinspection ResultOfMethodCallIgnored
file.createNewFile();
}
InputStream is = new FileInputStream(file);
try {
playCountHashtable = new Properties();
playCountHashtable.load(is);
} finally {
is.close();
}
}
/**
* Writes {@link Player#playCountHashtable} to disk
* @throws IOException
*/
private void savePlayCountFile() throws IOException {
OutputStream os = new FileOutputStream(context.getExternalFilesDir(null) + "/"
+ Library.PLAY_COUNT_FILENAME);
try {
playCountHashtable.store(os, Library.PLAY_COUNT_FILE_COMMENT);
} finally {
os.close();
}
}
/**
* Record a play or skip for a certain song
* @param songId the ID of the song written in the {@link android.provider.MediaStore}
* @param skip Whether the song was skipped (true if skipped, false if played)
*/
public void logPlayCount(long songId, boolean skip) {
try {
if (playCountHashtable == null) {
openPlayCountFile();
}
final String originalValue = playCountHashtable.getProperty(Long.toString(songId));
int playCount = 0;
int skipCount = 0;
int playDate = 0;
if (originalValue != null && !originalValue.equals("")) {
final String[] originalValues = originalValue.split(",");
playCount = Integer.parseInt(originalValues[0]);
skipCount = Integer.parseInt(originalValues[1]);
// Preserve backwards compatibility with play count files written with older
// versions of Jockey that didn't save this data
if (originalValues.length > 2) {
playDate = Integer.parseInt(originalValues[2]);
}
}
if (skip) {
skipCount++;
} else {
playDate = (int) (System.currentTimeMillis() / 1000);
playCount++;
}
playCountHashtable.setProperty(
Long.toString(songId),
playCount + "," + skipCount + "," + playDate);
savePlayCountFile();
} catch (Exception e) {
e.printStackTrace();
Crashlytics.logException(e);
}
}
// ACCESSOR METHODS
public Bitmap getArt() {
return art;
}
public boolean isPlaying() {
return mediaPlayer.getState() == ManagedMediaPlayer.Status.STARTED;
}
public boolean isPreparing() {
return mediaPlayer.getState() == ManagedMediaPlayer.Status.PREPARING;
}
public int getCurrentPosition() {
return mediaPlayer.getCurrentPosition();
}
public int getDuration() {
return mediaPlayer.getDuration();
}
public List<Song> getQueue() {
if (shuffle) {
return queueShuffled;
}
return queue;
}
public int getQueuePosition() {
if (shuffle) {
return queuePositionShuffled;
}
return queuePosition;
}
public int getAudioSessionId() {
return mediaPlayer.getAudioSessionId();
}
/**
* Receives headphone connect and disconnect intents so that music may be paused when headphones
* are disconnected
*/
public static class HeadsetListener extends BroadcastReceiver {
Player instance;
public HeadsetListener(Player instance) {
this.instance = instance;
}
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)
&& intent.getIntExtra("state", -1) == 0 && instance.isPlaying()) {
instance.pause();
instance.updateUi();
}
}
}
}
|
package org.apereo.cas.configuration.model.core.web.security;
import org.apereo.cas.configuration.model.core.authentication.PasswordEncoderProperties;
import org.apereo.cas.configuration.model.support.jpa.AbstractJpaProperties;
import org.apereo.cas.configuration.model.support.ldap.AbstractLdapAuthenticationProperties;
import org.apereo.cas.configuration.model.support.ldap.LdapAuthorizationProperties;
import org.springframework.boot.context.properties.NestedConfigurationProperty;
import org.springframework.core.io.Resource;
import java.util.Arrays;
import java.util.List;
/**
* This is {@link AdminPagesSecurityProperties}.
*
* @author Misagh Moayyed
* @since 5.0.0
*/
public class AdminPagesSecurityProperties {
private String ip = "127\\.0\\.0\\.1|0:0:0:0:0:0:0:1";
private List<String> adminRoles = Arrays.asList("ROLE_ADMIN", "ROLE_ACTUATOR");
private String loginUrl;
private String service;
private Resource users;
private boolean actuatorEndpointsEnabled;
private Jdbc jdbc = new Jdbc();
private Ldap ldap = new Ldap();
public Jdbc getJdbc() {
return jdbc;
}
public void setJdbc(final Jdbc jdbc) {
this.jdbc = jdbc;
}
public boolean isActuatorEndpointsEnabled() {
return actuatorEndpointsEnabled;
}
public void setActuatorEndpointsEnabled(final boolean actuatorEndpointsEnabled) {
this.actuatorEndpointsEnabled = actuatorEndpointsEnabled;
}
public String getIp() {
return ip;
}
public void setIp(final String ip) {
this.ip = ip;
}
public List<String> getAdminRoles() {
return adminRoles;
}
public void setAdminRoles(final List<String> adminRoles) {
this.adminRoles = adminRoles;
}
public String getLoginUrl() {
return loginUrl;
}
public void setLoginUrl(final String loginUrl) {
this.loginUrl = loginUrl;
}
public String getService() {
return service;
}
public void setService(final String service) {
this.service = service;
}
public Resource getUsers() {
return users;
}
public void setUsers(final Resource users) {
this.users = users;
}
public Ldap getLdap() {
return ldap;
}
public void setLdap(final Ldap ldap) {
this.ldap = ldap;
}
public class Ldap extends AbstractLdapAuthenticationProperties {
@NestedConfigurationProperty
private LdapAuthorizationProperties ldapAuthz = new LdapAuthorizationProperties();
/**
* Gets ldap authz.
*
* @return the ldap authz
*/
public LdapAuthorizationProperties getLdapAuthz() {
ldapAuthz.setBaseDn(getBaseDn());
ldapAuthz.setSearchFilter(getUserFilter());
return ldapAuthz;
}
public void setLdapAuthz(final LdapAuthorizationProperties ldapAuthz) {
this.ldapAuthz = ldapAuthz;
}
}
public class Jdbc extends AbstractJpaProperties {
private String rolePrefix;
private String query;
@NestedConfigurationProperty
private PasswordEncoderProperties passwordEncoder = new PasswordEncoderProperties();
public String getRolePrefix() {
return rolePrefix;
}
public void setRolePrefix(final String rolePrefix) {
this.rolePrefix = rolePrefix;
}
public String getQuery() {
return query;
}
public void setQuery(final String query) {
this.query = query;
}
public PasswordEncoderProperties getPasswordEncoder() {
return passwordEncoder;
}
public void setPasswordEncoder(final PasswordEncoderProperties passwordEncoder) {
this.passwordEncoder = passwordEncoder;
}
}
}
|
package org.commcare;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Looper;
import android.util.Base64;
import org.commcare.activities.PromptUpdateActivity;
import org.commcare.core.interfaces.HttpResponseProcessor;
import org.commcare.core.network.ModernHttpRequester;
import org.commcare.preferences.CommCareServerPreferences;
import org.commcare.utils.SessionUnavailableException;
import org.javarosa.core.io.StreamsUtil;
import org.javarosa.core.model.User;
import org.javarosa.core.util.externalizable.ExtUtil;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;
public class CommCareHeartbeatManager {
private static final long ONE_DAY_IN_MS = 24 * 60 * 60 * 1000;
private static final String TEST_RESPONSE =
"{\"latest_apk_version\":{\"value\":\"2.36.1\"},\"latest_ccz_version\":{\"value\":\"197\", \"force_by_date\":\"2017-05-01\"}}";
private static final String QUARANTINED_FORMS_PARAM = "num_quarantined_forms";
private Timer heartbeatTimer;
private final HttpResponseProcessor responseProcessor = new HttpResponseProcessor() {
@Override
public void processSuccess(int responseCode, InputStream responseData) {
try {
String responseAsString = StreamsUtil.inputStreamToByteArray(responseData).toString();
JSONObject jsonResponse = new JSONObject(responseAsString);
parseHeartbeatResponse(jsonResponse);
}
catch (JSONException e) {
System.out.println("Heartbeat response was not properly-formed JSON");
}
catch (IOException e) {
System.out.println("IO error while processing heartbeat response");
}
}
@Override
public void processRedirection(int responseCode) {
processErrorResponse(responseCode);
}
@Override
public void processClientError(int responseCode) {
processErrorResponse(responseCode);
}
@Override
public void processServerError(int responseCode) {
processErrorResponse(responseCode);
}
@Override
public void processOther(int responseCode) {
processErrorResponse(responseCode);
}
@Override
public void handleIOException(IOException exception) {
System.out.println("Encountered IOExeption while getting response stream");
}
private void processErrorResponse(int responseCode) {
System.out.println("Received error response from heartbeat request: " + responseCode);
}
};
private static CommCareHeartbeatManager INSTANCE;
public static CommCareHeartbeatManager instance() {
if (INSTANCE == null) {
INSTANCE = new CommCareHeartbeatManager();
}
return INSTANCE;
}
public void startHeartbeatCommunications() {
TimerTask heartbeatTimerTask = new TimerTask() {
@Override
public void run() {
try {
User currentUser = CommCareApplication.instance().getSession().getLoggedInUser();
//simulateRequestGettingStuck();
//requestHeartbeat(currentUser);
parseTestHeartbeatResponse();
} catch (SessionUnavailableException e) {
// Means the session has ended, so we should stop these requests
stopHeartbeatCommunications();
}
}
};
heartbeatTimer = new Timer();
heartbeatTimer.schedule(heartbeatTimerTask, new Date(), ONE_DAY_IN_MS);
}
public void stopHeartbeatCommunications() {
if (heartbeatTimer != null) {
heartbeatTimer.cancel();
}
}
public static void parseTestHeartbeatResponse() {
System.out.println("NOTE: Testing heartbeat response processing");
try {
parseHeartbeatResponse(new JSONObject(TEST_RESPONSE));
} catch (JSONException e) {
System.out.println("Test response was not properly formed JSON");
}
}
private static void simulateRequestGettingStuck() {
System.out.println("Before sleeping");
try {
Thread.sleep(5*1000);
} catch (InterruptedException e) {
System.out.println("TEST ERROR: sleep was interrupted");
}
System.out.println("After sleeping");
}
private void requestHeartbeat(User currentUser) {
CommCareApp currentApp = CommCareApplication.instance().getCurrentApp();
String urlString = currentApp.getAppPreferences().getString(
CommCareServerPreferences.PREFS_HEARTBEAT_URL_KEY, null);
if (urlString == null) {
// This app was generated before the heartbeat URL started being included, so we
// can't make the request
return;
}
try {
ModernHttpRequester requester =
CommCareApplication.instance().buildHttpRequesterForLoggedInUser(
CommCareApplication.instance(), new URL(urlString),
getParamsForHeartbeatRequest(), true, false);
requester.setResponseProcessor(responseProcessor);
requester.request();
} catch (MalformedURLException e) {
System.out.println("Heartbeat URL was malformed");
}
}
private static HashMap<String, String> getParamsForHeartbeatRequest() {
HashMap<String, String> params = new HashMap<>();
// TODO: get the actual value for this
params.put(QUARANTINED_FORMS_PARAM, "0");
return params;
}
private static void parseHeartbeatResponse(final JSONObject responseAsJson) {
try {
// Make sure the we still have an active session before parsing the response
CommCareApplication.instance().getSession();
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
// will run on UI thread
try {
if (responseAsJson.has("latest_apk_version")) {
JSONObject latestApkVersionInfo = responseAsJson.getJSONObject("latest_apk_version");
parseUpdateToPrompt(latestApkVersionInfo, true);
}
} catch (JSONException e) {
System.out.println("Latest apk version object not formatted properly");
}
try {
if (responseAsJson.has("latest_ccz_version")) {
JSONObject latestCczVersionInfo = responseAsJson.getJSONObject("latest_ccz_version");
parseUpdateToPrompt(latestCczVersionInfo, false);
}
} catch (JSONException e) {
System.out.println("Latest ccz version object not formatted properly");
}
}
});
} catch (SessionUnavailableException e) {
}
}
private static void parseUpdateToPrompt(JSONObject latestVersionInfo, boolean isForApk) {
try {
if (latestVersionInfo.has("value")) {
String versionValue = latestVersionInfo.getString("value");
String forceByDate = null;
if (latestVersionInfo.has("force_by_date")) {
forceByDate = latestVersionInfo.getString("force_by_date");
}
UpdateToPrompt updateToPrompt = new UpdateToPrompt(versionValue, forceByDate, isForApk);
updateToPrompt.registerWithSystem();
}
} catch (JSONException e) {
System.out.println("Encountered malformed json while parsing an UpdateToPrompt");
}
}
/**
*
* @param context
* @return - If the user was prompted to update
*/
public static boolean promptForUpdateIfNeeded(Activity context, int requestCodeForActivityLaunch) {
UpdateToPrompt cczUpdate = getCurrentUpdateToPrompt(false);
UpdateToPrompt apkUpdate = getCurrentUpdateToPrompt(true);
if (cczUpdate != null || apkUpdate != null) {
Intent i = new Intent(context, PromptUpdateActivity.class);
context.startActivityForResult(i, requestCodeForActivityLaunch);
return true;
}
return false;
}
/**
*
* @return an UpdateToPrompt that has been stored in SharedPreferences and is still relevant
* (i.e. the user hasn't updated to or past this version since we stored it)
*/
public static UpdateToPrompt getCurrentUpdateToPrompt(boolean forApkUpdate) {
CommCareApp currentApp = CommCareApplication.instance().getCurrentApp();
if (currentApp != null) {
String prefsKey = forApkUpdate ?
UpdateToPrompt.KEY_APK_UPDATE_TO_PROMPT : UpdateToPrompt.KEY_CCZ_UPDATE_TO_PROMPT;
String serializedUpdate = currentApp.getAppPreferences().getString(prefsKey, "");
if (!"".equals(serializedUpdate)) {
try {
byte[] updateBytes = Base64.decode(serializedUpdate, Base64.DEFAULT);
DataInputStream stream = new DataInputStream(new ByteArrayInputStream(updateBytes));
UpdateToPrompt update = (UpdateToPrompt)
ExtUtil.read(stream, UpdateToPrompt.class, ExtUtil.defaultPrototypes());
if (update.isNewerThanCurrentVersion(currentApp)) {
return update;
} else {
// The update we had stored is no longer relevant, so wipe it and return nothing
wipeStoredUpdate(forApkUpdate);
return null;
}
} catch (Exception e) {
// Something went wrong, so clear out whatever is there
System.out.println("IO error encountered while de-serializing saved UpdateToPrompt");
wipeStoredUpdate(forApkUpdate);
}
}
}
return null;
}
public static void wipeStoredUpdate(boolean forApkUpdate) {
String prefsKey = forApkUpdate ?
UpdateToPrompt.KEY_APK_UPDATE_TO_PROMPT : UpdateToPrompt.KEY_CCZ_UPDATE_TO_PROMPT;
CommCareApplication.instance().getCurrentApp().getAppPreferences().edit()
.putString(prefsKey, "").commit();
}
}
|
package com.ilya.sergeev.potlach;
import java.io.File;
import java.io.IOException;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.SearchView;
import android.view.Menu;
import android.view.MenuItem;
import com.ilya.sergeev.potlach.client.ServerSvc;
public class MainActivity extends ActionBarActivity implements NavigationDrawerFragment.NavigationDrawerCallbacks
{
private NavigationDrawerFragment mNavigationDrawerFragment;
private CharSequence mTitle;
private Uri mTempPhotoFile = null;
private SectionActionType mCurrentActionType;
private BroadcastReceiver mSignOutReceiver = new BroadcastReceiver()
{
@Override
public void onReceive(Context context, Intent intent)
{
startActivity(new Intent(MainActivity.this, LoginActivity.class));
finish();
}
};
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
onSectionAttached(SectionActionType.POTLACH_WALL);
onNavigationDrawerItemSelected(SectionActionType.POTLACH_WALL);
}
@Override
protected void onResume()
{
super.onResume();
registerReceiver(mSignOutReceiver, new IntentFilter(Broadcasts.SIGN_OUT_BROADCAST));
}
@Override
protected void onPause()
{
super.onPause();
unregisterReceiver(mSignOutReceiver);
}
@Override
public void onNavigationDrawerItemSelected(SectionActionType actionType)
{
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, FragmentFactory.getInstance(actionType))
.commit();
}
@Override
public void onSignOutSelect()
{
showSigOutDialog();
}
private void showSigOutDialog()
{
new AlertDialog.Builder(this)
.setTitle("Are you realy want to sign out?")
.setPositiveButton("Sign Out", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
ServerSvc.signout();
startActivity(new Intent(MainActivity.this, LoginActivity.class));
finish();
}
})
.create().show();
}
private void showCreatePotlachDialog()
{
deleteTempImage();
File photoFile = null;
try
{
photoFile = DialogHelper.createImageFile();
}
catch (IOException ex)
{
ex.printStackTrace();
return;
}
if (photoFile != null)
{
mTempPhotoFile = Uri.fromFile(photoFile);
DialogHelper.showPhotoResourceDialog(this, mTempPhotoFile);
}
}
private void deleteTempImage()
{
if (mTempPhotoFile != null)
{
File file = new File(mTempPhotoFile.getPath());
if (file.exists())
{
file.delete();
}
mTempPhotoFile = null;
}
}
public void onSectionAttached(SectionActionType actionType)
{
switch (actionType)
{
case POTLACH_MY:
mTitle = getString(R.string.my_gifts);
break;
case POTLACH_WALL:
mTitle = getString(R.string.new_gifts);
break;
case POTLACH_TOP_RATE:
mTitle = getString(R.string.top_rate);
break;
case POTLACH_SEARCH:
mTitle = getString(R.string.search_gifts);
break;
case SETTINGS:
mTitle = getString(R.string.settings);
break;
default:
mTitle = null;
}
mCurrentActionType = actionType;
invalidateOptionsMenu();
}
public void restoreActionBar()
{
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
if (!mNavigationDrawerFragment.isDrawerOpen())
{
switch (mCurrentActionType)
{
case POTLACH_MY:
case POTLACH_WALL:
getMenuInflater().inflate(R.menu.menu_add_gift, menu);
restoreActionBar();
return true;
case POTLACH_SEARCH:
getMenuInflater().inflate(R.menu.menu_search, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
searchView.setQueryHint("Поиск");
// TODO replace method
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener()
{
@Override
public boolean onQueryTextSubmit(String arg0)
{
// TODO Auto-generated method stub
return false;
}
@Override
public boolean onQueryTextChange(String arg0)
{
// TODO Auto-generated method stub
return false;
}
});
restoreActionBar();
return true;
case POTLACH_TOP_RATE:
case SETTINGS:
default:
break;
}
restoreActionBar();
}
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
int id = item.getItemId();
if (id == R.id.action_add_potlach)
{
showCreatePotlachDialog();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onDestroy()
{
super.onDestroy();
deleteTempImage();
}
private static class FragmentFactory
{
public static MainContentFragment getInstance(SectionActionType actionType)
{
MainContentFragment resultFragment = null;
Bundle args = new Bundle();
switch (actionType)
{
case POTLACH_MY:
resultFragment = new MyGiftsFragment();
break;
case POTLACH_WALL:
resultFragment = new GiftWallFragment();
break;
case POTLACH_TOP_RATE:
resultFragment = new TopRateFragment();
break;
case POTLACH_SEARCH:
resultFragment = new SearchFragment();
break;
case SETTINGS:
resultFragment = new SettingsFragment();
break;
default:
throw new IllegalArgumentException("user click unknown menu section");
}
if (resultFragment != null)
{
args.putString(MainContentFragment.ARG_SECTION_NUMBER, actionType.name());
resultFragment.setArguments(args);
}
return resultFragment;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == RESULT_OK)
{
if (requestCode == DialogHelper.SELECT_PHOTO_FROM_GALERY_REQUEST)
{
startActivity(CreateGiftActivity.createPotlachIntent(data.getData(), this));
}
else if (requestCode == DialogHelper.CREATE_NEW_PHOTO_REQUEST)
{
startActivity(CreateGiftActivity.createPotlachIntent(mTempPhotoFile, this));
}
}
else
{
if (requestCode == DialogHelper.CREATE_NEW_PHOTO_REQUEST && mTempPhotoFile != null)
{
deleteTempImage();
}
super.onActivityResult(requestCode, resultCode, data);
}
}
}
|
//$HeadURL: svn+ssh://mschneider@svn.wald.intevation.org/deegree/deegree3/trunk/deegree-core/deegree-core-metadata/src/main/java/org/deegree/metadata/iso/persistence/QueryHelper.java $
package org.deegree.metadata.iso.persistence.sql;
import static org.deegree.commons.jdbc.ConnectionManager.Type.MSSQL;
import static org.deegree.commons.jdbc.ConnectionManager.Type.Oracle;
import static org.deegree.commons.jdbc.ConnectionManager.Type.PostgreSQL;
import static org.slf4j.LoggerFactory.getLogger;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.deegree.commons.utils.JDBCUtils;
import org.deegree.commons.utils.StringUtils;
import org.deegree.filter.FilterEvaluationException;
import org.deegree.filter.OperatorFilter;
import org.deegree.metadata.i18n.Messages;
import org.deegree.metadata.iso.persistence.ISOMetadataResultSet;
import org.deegree.metadata.iso.persistence.ISOPropertyNameMapper;
import org.deegree.metadata.iso.persistence.queryable.Queryable;
import org.deegree.metadata.persistence.MetadataQuery;
import org.deegree.protocol.csw.CSWConstants.ResultType;
import org.deegree.protocol.csw.MetadataStoreException;
import org.deegree.sqldialect.SQLDialect;
import org.deegree.sqldialect.filter.AbstractWhereBuilder;
import org.deegree.sqldialect.filter.UnmappableException;
import org.deegree.sqldialect.filter.expression.SQLArgument;
import org.slf4j.Logger;
public class DefaultQueryService extends AbstractSqlHelper implements QueryService {
private static final Logger LOG = getLogger( DefaultQueryService.class );
/** Used to limit the fetch size for SELECT statements that potentially return a lot of rows. */
private static final int DEFAULT_FETCH_SIZE = 100;
public DefaultQueryService( SQLDialect dialect, List<Queryable> queryables ) {
super( dialect, queryables );
}
@Override
public ISOMetadataResultSet execute( MetadataQuery query, Connection conn )
throws MetadataStoreException {
ResultSet rs = null;
PreparedStatement preparedStatement = null;
try {
AbstractWhereBuilder builder = getWhereBuilder( query, conn );
StringBuilder idSelect = getPreparedStatementDatasetIDs( builder );
// TODO: use SQLDialect
if ( query != null && query.getStartPosition() != 1 && dialect.getDBType() == MSSQL ) {
String oldHeader = idSelect.toString();
idSelect = idSelect.append( " from (" ).append( oldHeader );
idSelect.append( ", ROW_NUMBER() OVER (ORDER BY X1.ID) as rownum" );
}
if ( query != null && ( query.getStartPosition() != 1 || query.getMaxRecords() > -1 )
&& dialect.getDBType() == Oracle ) {
String oldHeader = idSelect.toString();
idSelect = new StringBuilder();
idSelect.append( "select * from ( " );
if ( query.getStartPosition() != 1 ) {
idSelect.append( "select a.*, ROWNUM rnum from (" );
}
idSelect.append( oldHeader );
}
getPSBody( builder, idSelect );
if ( builder.getOrderBy() != null ) {
idSelect.append( " ORDER BY " );
idSelect.append( builder.getOrderBy().getSQL() );
}
if ( query != null && query.getStartPosition() != 1 && dialect.getDBType() == PostgreSQL ) {
idSelect.append( " OFFSET " ).append( Integer.toString( query.getStartPosition() - 1 ) );
}
if ( query != null && query.getStartPosition() != 1 && dialect.getDBType() == MSSQL ) {
idSelect.append( ") as X1 where X1.rownum > " );
idSelect.append( query.getStartPosition() - 1 );
}
// take a look in the wiki before changing this!
if ( dialect.getDBType() == PostgreSQL && query != null && query.getMaxRecords() > -1 ) {
idSelect.append( " LIMIT " ).append( query.getMaxRecords() );
}
if ( query != null && ( query.getStartPosition() != 1 || query.getMaxRecords() > -1 )
&& dialect.getDBType() == Oracle ) {
idSelect.append( " ) " );
if ( query.getStartPosition() != 1 ) {
idSelect.append( " a " );
}
if ( query.getMaxRecords() > -1 ) {
int max = query.getMaxRecords() - 1;
if ( query.getStartPosition() != -1 ) {
max += query.getStartPosition();
}
idSelect.append( " WHERE ROWNUM <= " ).append( max );
}
if ( query.getStartPosition() != 1 ) {
int min = query.getStartPosition();
idSelect.append( " ) WHERE rnum >= " ).append( min );
}
}
StringBuilder outerSelect = new StringBuilder( "SELECT " );
outerSelect.append( recordColumn );
outerSelect.append( " FROM " );
outerSelect.append( ISOPropertyNameMapper.DatabaseTables.idxtb_main );
outerSelect.append( " A INNER JOIN (" );
outerSelect.append( idSelect );
outerSelect.append( ") B ON A.id=B.id" );
// append sort criteria in the outer again, because IN statement looses ordering from inner ORDER BY
if ( builder.getOrderBy() != null ) {
outerSelect.append( " ORDER BY " );
// check that all sort columns belong to root table
String sortCols = builder.getOrderBy().getSQL().toString();
String rootTableQualifier = builder.getAliasManager().getRootTableAlias() + ".";
int columnCount = StringUtils.count( sortCols, "," ) + 1;
int rootAliasCount = StringUtils.count( sortCols, rootTableQualifier );
if ( rootAliasCount < columnCount ) {
String msg = "Sorting based on properties not stored in the root table is currently not supported.";
throw new MetadataStoreException( msg );
}
String colRegEx = builder.getAliasManager().getRootTableAlias() + ".\\S+";
for ( int i = 1; i <= columnCount; i++ ) {
sortCols = sortCols.replaceFirst( colRegEx, "crit" + i );
}
outerSelect.append( sortCols );
}
String sql = outerSelect.toString();
LOG.trace( sql );
preparedStatement = conn.prepareStatement( sql );
int i = 1;
if ( builder.getWhere() != null ) {
for ( SQLArgument o : builder.getWhere().getArguments() ) {
o.setArgument( preparedStatement, i++ );
}
}
if ( builder.getOrderBy() != null ) {
for ( SQLArgument o : builder.getOrderBy().getArguments() ) {
o.setArgument( preparedStatement, i++ );
}
}
LOG.debug( preparedStatement.toString() );
preparedStatement.setFetchSize( DEFAULT_FETCH_SIZE );
rs = preparedStatement.executeQuery();
return new ISOMetadataResultSet( rs, conn, preparedStatement );
} catch ( SQLException e ) {
JDBCUtils.close( rs, preparedStatement, conn, LOG );
String msg = Messages.getMessage( "ERROR_SQL", preparedStatement.toString(), e.getMessage() );
LOG.debug( msg );
throw new MetadataStoreException( msg );
} catch ( Throwable t ) {
JDBCUtils.close( rs, preparedStatement, conn, LOG );
String msg = Messages.getMessage( "ERROR_REQUEST_TYPE", ResultType.results.name(), t.getMessage() );
LOG.debug( msg );
throw new MetadataStoreException( msg );
} finally {
// Don't close the ResultSet or PreparedStatement if no error occurs, the ResultSet is needed in the
// ISOMetadataResultSet and both will be closed by
// org.deegree.metadata.persistence.XMLMetadataResultSet#close().
}
}
@Override
public int executeCounting( MetadataQuery query, Connection conn )
throws MetadataStoreException, FilterEvaluationException, UnmappableException {
ResultSet rs = null;
PreparedStatement preparedStatement = null;
try {
AbstractWhereBuilder builder = getWhereBuilder( query, conn );
LOG.debug( "new Counting" );
StringBuilder getDatasetIDs = new StringBuilder();
getDatasetIDs.append( "SELECT " );
getDatasetIDs.append( "COUNT( DISTINCT(" );
getDatasetIDs.append( builder.getAliasManager().getRootTableAlias() );
getDatasetIDs.append( "." );
getDatasetIDs.append( idColumn );
getDatasetIDs.append( "))" );
getPSBody( builder, getDatasetIDs );
String sql = getDatasetIDs.toString();
LOG.trace( sql );
preparedStatement = conn.prepareStatement( sql );
int i = 1;
if ( builder.getWhere() != null ) {
for ( SQLArgument o : builder.getWhere().getArguments() ) {
o.setArgument( preparedStatement, i++ );
}
}
LOG.debug( preparedStatement.toString() );
rs = preparedStatement.executeQuery();
rs.next();
LOG.debug( "rs for rowCount: " + rs.getInt( 1 ) );
return rs.getInt( 1 );
} catch ( SQLException e ) {
String msg = Messages.getMessage( "ERROR_SQL", preparedStatement.toString(), e.getMessage() );
LOG.debug( msg );
throw new MetadataStoreException( msg );
} finally {
JDBCUtils.close( rs, preparedStatement, conn, LOG );
}
}
@Override
public ISOMetadataResultSet executeGetRecordById( List<String> idList, Connection conn )
throws MetadataStoreException {
ResultSet rs = null;
PreparedStatement stmt = null;
try {
int size = idList.size();
StringBuilder select = new StringBuilder();
select.append( "SELECT " ).append( recordColumn );
select.append( " FROM " ).append( mainTable );
select.append( " WHERE " );
for ( int iter = 0; iter < size; iter++ ) {
select.append( fileIdColumn ).append( " = ? " );
if ( iter < size - 1 ) {
select.append( " OR " );
}
}
String sql = select.toString();
LOG.trace( sql );
stmt = conn.prepareStatement( sql );
stmt.setFetchSize( DEFAULT_FETCH_SIZE );
LOG.debug( "select RecordById statement: " + stmt );
int i = 1;
for ( String identifier : idList ) {
stmt.setString( i, identifier );
LOG.debug( "identifier: " + identifier );
LOG.debug( "" + stmt );
i++;
}
rs = stmt.executeQuery();
} catch ( Throwable t ) {
JDBCUtils.close( rs, stmt, conn, LOG );
String msg = Messages.getMessage( "ERROR_REQUEST_TYPE", ResultType.results.name(), t.getMessage() );
LOG.debug( msg );
throw new MetadataStoreException( msg );
} finally {
// Don't close the ResultSet or PreparedStatement if no error occurs, the ResultSet is needed in the
// ISOMetadataResultSet and both will be closed by
// org.deegree.metadata.persistence.XMLMetadataResultSet#close().
}
return new ISOMetadataResultSet( rs, conn, stmt );
}
protected AbstractWhereBuilder getWhereBuilder( MetadataQuery query, Connection conn )
throws FilterEvaluationException, UnmappableException {
return dialect.getWhereBuilder( new ISOPropertyNameMapper( dialect, queryables ),
(OperatorFilter) query.getFilter(), query.getSorting(), false );
}
}
|
package org.deeplearning4j.word2vec.vectorizer;
import org.deeplearning4j.berkeley.Counter;
import org.deeplearning4j.datasets.DataSet;
import org.deeplearning4j.datasets.vectorizer.Vectorizer;
import org.deeplearning4j.util.MathUtils;
import org.deeplearning4j.util.SetUtils;
import org.deeplearning4j.word2vec.sentenceiterator.SentenceIterator;
import org.deeplearning4j.word2vec.tokenizer.DefaultTokenizerFactory;
import org.deeplearning4j.word2vec.tokenizer.Tokenizer;
import org.deeplearning4j.word2vec.tokenizer.TokenizerFactory;
import org.deeplearning4j.word2vec.viterbi.Index;
import java.util.List;
import java.util.Collection;
/**
* Turns a set of documents in to a tfidf bag of words
* @author Adam Gibson
*/
public class TfidfVectorizer implements Vectorizer {
private int minDf;
private Index vocab = new Index();
private SentenceIterator sentenceIterator;
private TokenizerFactory tokenizerFactory = new DefaultTokenizerFactory();
private List<String> labels;
private Counter<String> tf = new Counter<>();
private Counter<String> idf = new Counter<>();
private int numDocs = 0;
/**
*
* @param sentenceIterator the document iterator
* @param tokenizerFactory the tokenizer for individual tokens
* @param labels the possible labels
*/
public TfidfVectorizer(SentenceIterator sentenceIterator,TokenizerFactory tokenizerFactory,List<String> labels) {
this.sentenceIterator = sentenceIterator;
this.tokenizerFactory = tokenizerFactory;
this.labels = labels;
}
private Collection<String> allWords() {
return SetUtils.union(tf.keySet(),idf.keySet());
}
private Counter<String> tfIdfWeights(int top) {
Counter<String> ret = new Counter<String>();
for(String word : allWords())
ret.setMinCount(word,tfidfWord(word));
ret.keepTopNKeys(top);
return ret;
}
private Counter<String> tfIdfWeights() {
Counter<String> ret = new Counter<String>();
for(String word : allWords())
ret.setMinCount(word,tfidfWord(word));
return ret;
}
private void initIndexFromTfIdf() {
Counter<String> tfidf = tfIdfWeights();
for(String key : tfidf.keySet())
this.vocab.add(key);
}
private double tfidfWord(String word) {
return MathUtils.tfidf(tfForWord(word),idfForWord(word));
}
private double tfForWord(String word) {
return MathUtils.tf((int) tf.getCount(word));
}
private double idfForWord(String word) {
return MathUtils.idf(numDocs,idf.getCount(word));
}
private void process() {
while(sentenceIterator.hasNext()) {
Tokenizer tokenizer = tokenizerFactory.create(sentenceIterator.nextSentence());
Counter<String> runningTotal = new Counter<>();
Counter<String> documentOccurrences = new Counter<>();
numDocs++;
for(String token : tokenizer.getTokens()) {
runningTotal.incrementCount(token,1.0);
//idf
if(!documentOccurrences.containsKey(token))
documentOccurrences.setMinCount(token,1.0);
}
idf.incrementAll(documentOccurrences);
tf.incrementAll(runningTotal);
}
}
@Override
public DataSet vectorize() {
process();
initIndexFromTfIdf();
Counter<String> tfIdfWeights = tfIdfWeights();
return null;
}
}
|
package com.google.sps;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.cloud.firestore.CollectionReference;
import com.google.cloud.firestore.Firestore;
import com.google.cloud.firestore.Query;
import com.google.cloud.firestore.QueryDocumentSnapshot;
import com.google.cloud.firestore.QuerySnapshot;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.cloud.FirestoreClient;
import com.google.api.core.ApiFuture;
import java.io.IOException;
import java.util.List;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ValidateUsername {
@PostMapping("/validateUsername")
String checkUsername(@RequestBody String username) throws Exception {
return isUniqueUsername(username);
}
private static String isUniqueUsername(String username) throws IOException {
Firebase.init();
Firestore db = FirestoreClient.getFirestore();
CollectionReference users = db.collection("users");
Query query = users.whereEqualTo("username", username);
try {
ApiFuture<QuerySnapshot> querySnapshot = query.get();
List<QueryDocumentSnapshot> queryDocuments = querySnapshot.get().getDocuments();
if (queryDocuments.isEmpty()) {
return "true";
}
} catch (Exception e) {
System.out.println(e);
}
return "false";
}
}
|
package org.springframework.ide.eclipse.boot.wizard;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.resources.WorkspaceJob;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.IImportWizard;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import org.springframework.ide.eclipse.boot.core.BootActivator;
import org.springframework.ide.eclipse.boot.livexp.ui.DynamicSection;
import org.springsource.ide.eclipse.commons.livexp.core.FieldModel;
import org.springsource.ide.eclipse.commons.livexp.ui.ChooseOneSectionCombo;
import org.springsource.ide.eclipse.commons.livexp.ui.CommentSection;
import org.springsource.ide.eclipse.commons.livexp.ui.DescriptionSection;
import org.springsource.ide.eclipse.commons.livexp.ui.GroupSection;
import org.springsource.ide.eclipse.commons.livexp.ui.IPageWithSections;
import org.springsource.ide.eclipse.commons.livexp.ui.ProjectLocationSection;
import org.springsource.ide.eclipse.commons.livexp.ui.StringFieldSection;
import org.springsource.ide.eclipse.commons.livexp.ui.WizardPageSection;
import org.springsource.ide.eclipse.commons.livexp.ui.WizardPageWithSections;
import org.springsource.ide.eclipse.commons.livexp.util.ExceptionUtil;
import org.springsource.ide.eclipse.commons.livexp.util.Parser;
import com.google.common.collect.ImmutableList;
public class NewSpringBootWizard extends Wizard implements INewWizard, IImportWizard {
private static final ImageDescriptor IMAGE = BootWizardImages.BOOT_WIZARD_ICON;
public static final String NO_CONTENT_AVAILABLE = "No content available.";
private InitializrFactoryModel<NewSpringBootWizardModel> model;
private IStructuredSelection selection;
private WorkingSetSection workingSetSection;
private WizardPageWithSections projectPage;
public NewSpringBootWizard() throws Exception {
setDefaultPageImageDescriptor(IMAGE);
}
//@Override
@Override
public void init(IWorkbench workbench, IStructuredSelection selection) {
try {
model = NewSpringBootWizardFactoryModel.create(BootActivator.getUrlConnectionFactory(), BootActivator.getDefault().getPreferenceStore());
this.selection = selection;
} catch (Exception e) {
MessageDialog.openError(workbench.getActiveWorkbenchWindow().getShell(), "Error opening the wizard",
ExceptionUtil.getMessage(e)+"\n\n"+
"Note that this wizard uses a webservice and needs internet access.\n"+
"A more detailed error message may be found in the Eclipse error log."
);
//Ensure exception is logged. (Eclipse UI may not log it!).
BootWizardActivator.log(e);
throw new Error(e);
}
}
@Override
public void addPages() {
super.addPages();
Assert.isLegal(model!=null, "The Spring Starter Wizard model was not initialized. Unable to open the wizard.");
addPage(projectPage = new ProjectDetailsPage(model));
addPage(new MultipleViewsDependencyPage(model));
addPage(new PageThree(model));
}
@Override
public boolean canFinish() {
return super.canFinish() && getContainer().getCurrentPage()!=projectPage;
}
public class ProjectDetailsSection extends GroupSection {
private final NewSpringBootWizardModel model;
public ProjectDetailsSection(IPageWithSections owner, NewSpringBootWizardModel model) {
super(owner, null);
this.model = model;
addSections(createSections().toArray(new WizardPageSection[0]));
}
protected List<WizardPageSection> createSections() {
List<WizardPageSection> sections = new ArrayList<>();
FieldModel<String> projectName = model.getProjectName();
sections.add(new StringFieldSection(owner, projectName));
sections.add(new ProjectLocationSection(owner, model.getLocation(), projectName.getVariable(), model.getLocationValidator()));
WizardPageSection radios = createRadioGroupsSection(owner);
if (radios!=null) {
sections.add(radios);
}
for (FieldModel<String> f : model.stringInputs) {
//caution! we already created the section for projectName because we want it at the top
if (projectName!=f) {
sections.add(new StringFieldSection(owner, f));
}
}
sections.add(workingSetSection = new WorkingSetSection(owner, selection));
return sections;
}
private WizardPageSection createRadioGroupsSection(IPageWithSections owner) {
boolean notEmpty = false;
RadioGroup bootVersion = model.getBootVersion(); //This is placed specifically somewhere else so must skip it here
ArrayList<WizardPageSection> radioSections = new ArrayList<>();
for (RadioGroup radioGroup : model.getRadioGroups().getGroups()) {
if (radioGroup!=bootVersion) {
if (radioGroup.getRadios().length>1) {
//Don't add a UI elements for something that offers no real choice
radioSections.add(
new ChooseOneSectionCombo<>(owner, radioGroup.getLabel(), radioGroup.getSelection(), radioGroup.getRadios()).grabHorizontal(true)
//new ChooseOneSectionCombo<RadioInfo>(owner, radioGroup.getLabel(), radioGroup.getSelection(), radioGroup.getRadios())
);
notEmpty = true;
}
}
}
if (notEmpty) {
return new GroupSection(owner, null, radioSections.toArray(new WizardPageSection[radioSections.size()])).columns(2, false);
}
return null;
}
}
public class ProjectDetailsPage extends WizardPageWithSections {
protected InitializrFactoryModel<NewSpringBootWizardModel> model;
public ProjectDetailsPage(InitializrFactoryModel<NewSpringBootWizardModel> model) {
super("page1", "New Spring Starter Project", null);
this.model = model;
}
@Override
protected List<WizardPageSection> createSections() {
ChooseOneSectionCombo<String> comboSection = new ChooseOneSectionCombo<>(this, model.getServiceUrlField(), model.getUrls())
.grabHorizontal(true);
comboSection.allowTextEdits(Parser.IDENTITY);
// Note: have to set the project page in the dynamic section because the dynamic section composite
// gets created at the start, and determines the initial size of the wizard page, regardless of its content.
DynamicSection dynamicSection = new DynamicSection(this, model.getModel().apply((dynamicModel) -> {
if (dynamicModel != null) {
return new ProjectDetailsSection(this, dynamicModel);
}
return new CommentSection(this, NO_CONTENT_AVAILABLE);
} ));
return ImmutableList.of(comboSection, dynamicSection);
}
}
public static class PageThree extends WizardPageWithSections {
private final InitializrFactoryModel<NewSpringBootWizardModel> model;
protected PageThree(InitializrFactoryModel<NewSpringBootWizardModel> model) {
super("page3", "New Spring Starter Project", null);
this.model = model;
}
protected WizardPageSection createDynamicContent(NewSpringBootWizardModel model) {
List<WizardPageSection> sections = new ArrayList<>();
sections.add(new GroupSection(this, "Site Info",
new StringFieldSection(this, "Base Url", model.baseUrl, model.baseUrlValidator),
new DescriptionSection(this, model.downloadUrl).label("Full Url").readOnly(false)
));
return new GroupSection(this, null, sections.toArray(new WizardPageSection[0])).grabVertical(true);
}
@Override
protected List<WizardPageSection> createSections() {
DynamicSection dynamicSection = new DynamicSection(this, model.getModel().apply((dynamicModel) -> {
if (dynamicModel != null) {
return createDynamicContent(dynamicModel);
}
return new CommentSection(this, NO_CONTENT_AVAILABLE);
} ));
return ImmutableList.of(dynamicSection);
}
}
@Override
public boolean performFinish() {
if (model.getModel().getValue() == null) {
return false;
}
model.getModel().getValue().setWorkingSets(workingSetSection.getWorkingSets()); //must be in ui thread. Don't put in job!
WorkspaceJob job = new WorkspaceJob("Import Getting Started Content") {
@Override
public IStatus runInWorkspace(IProgressMonitor mon) {
try {
// TODO: maybe the model factory should have a perform finish that does a save, which then calls the underlying model perform finish
model.save();
model.getModel().getValue().performFinish(mon);
return Status.OK_STATUS;
} catch (Throwable e) {
return ExceptionUtil.status(e);
}
}
};
//WARNING: Do not set a scheduling rule here. It breaks gradle import by causing a deadlock or rule conflict.
//job.setRule(ResourcesPlugin.getWorkspace().getRuleFactory().buildRule());
job.setPriority(Job.BUILD);
job.setUser(true); //shows progress in default eclipse config
job.schedule();
return true;
}
}
|
package com.maddyhome.idea.vim.group;
import com.google.common.collect.ImmutableList;
import com.intellij.codeInsight.lookup.impl.LookupImpl;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.actionSystem.ex.ActionManagerEx;
import com.intellij.openapi.actionSystem.ex.ActionUtil;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.keymap.Keymap;
import com.intellij.openapi.keymap.KeymapManager;
import com.intellij.openapi.keymap.ex.KeymapManagerEx;
import com.maddyhome.idea.vim.EventFacade;
import com.maddyhome.idea.vim.VimPlugin;
import com.maddyhome.idea.vim.action.VimShortcutKeyAction;
import com.maddyhome.idea.vim.command.MappingMode;
import com.maddyhome.idea.vim.ex.ExOutputModel;
import com.maddyhome.idea.vim.extension.VimExtensionHandler;
import com.maddyhome.idea.vim.handler.EditorActionHandlerBase;
import com.maddyhome.idea.vim.helper.StringHelper;
import com.maddyhome.idea.vim.key.Shortcut;
import com.maddyhome.idea.vim.key.*;
import kotlin.text.StringsKt;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.util.List;
import java.util.*;
import static com.maddyhome.idea.vim.helper.StringHelper.toKeyNotation;
import static java.util.stream.Collectors.joining;
/**
* @author vlan
*/
public class KeyGroup {
private static final String SHORTCUT_CONFLICTS_ELEMENT = "shortcut-conflicts";
private static final String SHORTCUT_CONFLICT_ELEMENT = "shortcut-conflict";
private static final String OWNER_ATTRIBUTE = "owner";
private static final String TEXT_ELEMENT = "text";
@NotNull private final Map<KeyStroke, ShortcutOwner> shortcutConflicts = new LinkedHashMap<>();
@NotNull private final Set<KeyStroke> requiredShortcutKeys = new HashSet<>(300);
@NotNull private final Map<MappingMode, ParentNode> keyRoots = new HashMap<>();
@NotNull private final Map<MappingMode, KeyMapping> keyMappings = new HashMap<>();
@Nullable private OperatorFunction operatorFunction = null;
void registerRequiredShortcutKeys(@NotNull Editor editor) {
EventFacade.getInstance().registerCustomShortcutSet(VimShortcutKeyAction.getInstance(),
toShortcutSet(requiredShortcutKeys), editor.getComponent());
}
public void registerShortcutsForLookup(@NotNull LookupImpl lookup) {
EventFacade.getInstance()
.registerCustomShortcutSet(VimShortcutKeyAction.getInstance(), toShortcutSet(requiredShortcutKeys),
lookup.getComponent(), lookup);
}
void unregisterShortcutKeys(@NotNull Editor editor) {
EventFacade.getInstance().unregisterCustomShortcutSet(VimShortcutKeyAction.getInstance(), editor.getComponent());
}
public boolean showKeyMappings(@NotNull Set<MappingMode> modes, @NotNull Editor editor) {
final List<MappingInfo> rows = getKeyMappingRows(modes);
final StringBuilder builder = new StringBuilder();
for (MappingInfo row : rows) {
builder.append(StringsKt.padEnd(getModesStringCode(row.getMappingModes()), 2, ' '));
builder.append(" ");
builder.append(StringsKt.padEnd(toKeyNotation(row.getFromKeys()), 11, ' '));
builder.append(" ");
builder.append(row.isRecursive() ? " " : "*");
builder.append(" ");
final List<KeyStroke> toKeys = row.getToKeys();
final VimExtensionHandler extensionHandler = row.getExtensionHandler();
if (toKeys != null) {
builder.append(toKeyNotation(toKeys));
}
else if (extensionHandler != null) {
builder.append("call ");
builder.append(extensionHandler.getClass().getCanonicalName());
}
else {
builder.append("<Unknown>");
}
builder.append("\n");
}
ExOutputModel.getInstance(editor).output(builder.toString());
return true;
}
public void putKeyMapping(@NotNull Set<MappingMode> modes, @NotNull List<KeyStroke> fromKeys,
@Nullable List<KeyStroke> toKeys, @Nullable VimExtensionHandler extensionHandler,
boolean recursive) {
for (MappingMode mode : modes) {
final KeyMapping mapping = getKeyMapping(mode);
mapping.put(EnumSet.of(mode), fromKeys, toKeys, extensionHandler, recursive);
}
final int oldSize = requiredShortcutKeys.size();
for (KeyStroke key : fromKeys) {
if (key.getKeyChar() == KeyEvent.CHAR_UNDEFINED) {
requiredShortcutKeys.add(key);
}
}
if (requiredShortcutKeys.size() != oldSize) {
for (Editor editor : EditorFactory.getInstance().getAllEditors()) {
unregisterShortcutKeys(editor);
registerRequiredShortcutKeys(editor);
}
}
}
@Nullable
public OperatorFunction getOperatorFunction() {
return operatorFunction;
}
public void setOperatorFunction(@NotNull OperatorFunction function) {
operatorFunction = function;
}
public void saveData(@NotNull Element element) {
final Element conflictsElement = new Element(SHORTCUT_CONFLICTS_ELEMENT);
for (Map.Entry<KeyStroke, ShortcutOwner> entry : shortcutConflicts.entrySet()) {
final ShortcutOwner owner = entry.getValue();
if (owner != ShortcutOwner.UNDEFINED) {
final Element conflictElement = new Element(SHORTCUT_CONFLICT_ELEMENT);
conflictElement.setAttribute(OWNER_ATTRIBUTE, owner.getName());
final Element textElement = new Element(TEXT_ELEMENT);
StringHelper.setSafeXmlText(textElement, entry.getKey().toString());
conflictElement.addContent(textElement);
conflictsElement.addContent(conflictElement);
}
}
element.addContent(conflictsElement);
}
public void readData(@NotNull Element element) {
final Element conflictsElement = element.getChild(SHORTCUT_CONFLICTS_ELEMENT);
if (conflictsElement != null) {
final java.util.List<Element> conflictElements = conflictsElement.getChildren(SHORTCUT_CONFLICT_ELEMENT);
for (Element conflictElement : conflictElements) {
final String ownerValue = conflictElement.getAttributeValue(OWNER_ATTRIBUTE);
ShortcutOwner owner = ShortcutOwner.UNDEFINED;
try {
owner = ShortcutOwner.fromString(ownerValue);
}
catch (IllegalArgumentException ignored) {
}
final Element textElement = conflictElement.getChild(TEXT_ELEMENT);
if (textElement != null) {
final String text = StringHelper.getSafeXmlText(textElement);
if (text != null) {
final KeyStroke keyStroke = KeyStroke.getKeyStroke(text);
if (keyStroke != null) {
shortcutConflicts.put(keyStroke, owner);
}
}
}
}
}
}
@NotNull
public List<AnAction> getKeymapConflicts(@NotNull KeyStroke keyStroke) {
final KeymapManagerEx keymapManager = KeymapManagerEx.getInstanceEx();
final Keymap keymap = keymapManager.getActiveKeymap();
final KeyboardShortcut shortcut = new KeyboardShortcut(keyStroke, null);
final Map<String, ? extends List<KeyboardShortcut>> conflicts = keymap.getConflicts("", shortcut);
final List<AnAction> actions = new ArrayList<>();
for (String actionId : conflicts.keySet()) {
final AnAction action = ActionManagerEx.getInstanceEx().getAction(actionId);
if (action != null) {
actions.add(action);
}
}
return actions;
}
@NotNull
public Map<KeyStroke, ShortcutOwner> getShortcutConflicts() {
final Set<KeyStroke> requiredShortcutKeys = this.requiredShortcutKeys;
final Map<KeyStroke, ShortcutOwner> savedConflicts = getSavedShortcutConflicts();
final Map<KeyStroke, ShortcutOwner> results = new HashMap<>();
for (KeyStroke keyStroke : requiredShortcutKeys) {
if (!VimShortcutKeyAction.VIM_ONLY_EDITOR_KEYS.contains(keyStroke)) {
final List<AnAction> conflicts = getKeymapConflicts(keyStroke);
if (!conflicts.isEmpty()) {
final ShortcutOwner owner = savedConflicts.get(keyStroke);
results.put(keyStroke, owner != null ? owner : ShortcutOwner.UNDEFINED);
}
}
}
return results;
}
@NotNull
public Map<KeyStroke, ShortcutOwner> getSavedShortcutConflicts() {
return shortcutConflicts;
}
@NotNull
public KeyMapping getKeyMapping(@NotNull MappingMode mode) {
KeyMapping mapping = keyMappings.get(mode);
if (mapping == null) {
mapping = new KeyMapping();
keyMappings.put(mode, mapping);
}
return mapping;
}
public void resetKeyMappings() {
keyMappings.clear();
}
/**
* Returns the root of the key mapping for the given mapping mode
*
* @param mappingMode The mapping mode
* @return The key mapping tree root
*/
public ParentNode getKeyRoot(@NotNull MappingMode mappingMode) {
return keyRoots.computeIfAbsent(mappingMode, (key) -> new ParentNode() {});
}
/**
* Registers a shortcut that is handled by KeyHandler#handleKey directly, rather than by an action
*
* <p>
* Digraphs are handled directly by KeyHandler#handleKey instead of via an action, but we need to still make sure the
* shortcuts are registered, or the key handler won't see them
* </p>
* @param shortcut The shortcut to register
*/
public void registerShortcutWithoutAction(Shortcut shortcut) {
registerRequiredShortcut(Arrays.asList(shortcut.getKeys()));
}
public void registerCommandAction(@NotNull EditorActionHandlerBase commandAction) {
if (ApplicationManager.getApplication().isUnitTestMode()) {
if (identityChecker == null) {
identityChecker = new HashMap<>();
prefixes = new HashMap<>();
}
for (List<KeyStroke> keys : commandAction.getKeyStrokesSet()) {
checkCommand(commandAction.getMappingModes(), commandAction, keys);
}
}
for (List<KeyStroke> keyStrokes : commandAction.getKeyStrokesSet()) {
registerRequiredShortcut(keyStrokes);
for (MappingMode mappingMode : commandAction.getMappingModes()) {
Node node = getKeyRoot(mappingMode);
final int len = keyStrokes.size();
// Add a child for each keystroke in the shortcut for this action
for (int i = 0; i < len; i++) {
if (!(node instanceof ParentNode)) {
throw new Error("Error in tree constructing");
}
node = addMNode((ParentNode)node, commandAction, keyStrokes.get(i), i == len - 1);
}
}
}
}
private void registerRequiredShortcut(@NotNull List<KeyStroke> keys) {
for (KeyStroke key : keys) {
if (key.getKeyChar() == KeyEvent.CHAR_UNDEFINED) {
requiredShortcutKeys.add(key);
}
}
}
private void checkCommand(@NotNull Set<MappingMode> mappingModes, EditorActionHandlerBase action, List<KeyStroke> keys) {
for (MappingMode mappingMode : mappingModes) {
checkIdentity(mappingMode, action.getId(), keys);
}
checkCorrectCombination(action, keys);
}
private void checkIdentity(MappingMode mappingMode, String actName, List<KeyStroke> keys) {
Set<List<KeyStroke>> keySets = identityChecker.computeIfAbsent(mappingMode, k -> new HashSet<>());
if (keySets.contains(keys)) {
throw new RuntimeException("This keymap already exists: " + mappingMode + " keys: " +
keys + " action:" + actName);
}
keySets.add(keys);
}
private void checkCorrectCombination(EditorActionHandlerBase action, List<KeyStroke> keys) {
for (Map.Entry<List<KeyStroke>, String> entry : prefixes.entrySet()) {
List<KeyStroke> prefix = entry.getKey();
if (prefix.size() == keys.size()) continue;
int shortOne = Math.min(prefix.size(), keys.size());
int i;
for (i = 0; i < shortOne; i++) {
if (!prefix.get(i).equals(keys.get(i))) break;
}
List<String> actionExceptions = Arrays.asList("VimInsertDeletePreviousWordAction", "VimInsertAfterCursorAction", "VimInsertBeforeCursorAction", "VimFilterVisualLinesAction", "VimAutoIndentMotionAction");
if (i == shortOne && !actionExceptions.contains(action.getId()) && !actionExceptions.contains(entry.getValue())) {
throw new RuntimeException("Prefix found! " +
keys +
" in command " +
action.getId() +
" is the same as " +
prefix.stream().map(Object::toString).collect(joining(", ")) +
" in " +
entry.getValue());
}
}
prefixes.put(keys, action.getId());
}
private Map<MappingMode, Set<List<KeyStroke>>> identityChecker;
private Map<List<KeyStroke>, String> prefixes;
@NotNull
private Node addMNode(@NotNull ParentNode base,
EditorActionHandlerBase action,
KeyStroke key,
boolean isLastInSequence) {
Node existing = base.getChild(key);
if (existing != null) return existing;
Node newNode;
if (isLastInSequence) {
newNode = new CommandNode(action);
} else {
newNode = new CommandPartNode();
}
base.addChild(key, newNode);
return newNode;
}
@NotNull
private static ShortcutSet toShortcutSet(@NotNull Collection<KeyStroke> keyStrokes) {
final List<com.intellij.openapi.actionSystem.Shortcut> shortcuts = new ArrayList<>();
for (KeyStroke key : keyStrokes) {
shortcuts.add(new KeyboardShortcut(key, null));
}
return new CustomShortcutSet(shortcuts.toArray(new com.intellij.openapi.actionSystem.Shortcut[0]));
}
@NotNull
private static List<MappingInfo> getKeyMappingRows(@NotNull Set<MappingMode> modes) {
final Map<ImmutableList<KeyStroke>, Set<MappingMode>> actualModes = new HashMap<>();
for (MappingMode mode : modes) {
final KeyMapping mapping = VimPlugin.getKey().getKeyMapping(mode);
for (List<KeyStroke> fromKeys : mapping) {
final ImmutableList<KeyStroke> key = ImmutableList.copyOf(fromKeys);
final Set<MappingMode> value = actualModes.get(key);
final Set<MappingMode> newValue;
if (value != null) {
newValue = new HashSet<>(value);
newValue.add(mode);
}
else {
newValue = EnumSet.of(mode);
}
actualModes.put(key, newValue);
}
}
final List<MappingInfo> rows = new ArrayList<>();
for (Map.Entry<ImmutableList<KeyStroke>, Set<MappingMode>> entry : actualModes.entrySet()) {
final ArrayList<KeyStroke> fromKeys = new ArrayList<>(entry.getKey());
final Set<MappingMode> mappingModes = entry.getValue();
if (!mappingModes.isEmpty()) {
final MappingMode mode = mappingModes.iterator().next();
final KeyMapping mapping = VimPlugin.getKey().getKeyMapping(mode);
final MappingInfo mappingInfo = mapping.get(fromKeys);
if (mappingInfo != null) {
rows.add(new MappingInfo(mappingModes, mappingInfo.getFromKeys(), mappingInfo.getToKeys(),
mappingInfo.getExtensionHandler(), mappingInfo.isRecursive()));
}
}
}
Collections.sort(rows);
return rows;
}
@NotNull
private static String getModesStringCode(@NotNull Set<MappingMode> modes) {
if (modes.equals(MappingMode.NVO)) {
return "";
}
else if (modes.contains(MappingMode.INSERT)) {
return "i";
}
else if (modes.contains(MappingMode.NORMAL)) {
return "n";
}
// TODO: Add more codes
return "";
}
@NotNull
public List<AnAction> getActions(@NotNull Component component, @NotNull KeyStroke keyStroke) {
final List<AnAction> results = new ArrayList<>();
results.addAll(getLocalActions(component, keyStroke));
results.addAll(getKeymapActions(keyStroke));
return results;
}
@NotNull
private static List<AnAction> getLocalActions(@NotNull Component component, @NotNull KeyStroke keyStroke) {
final List<AnAction> results = new ArrayList<>();
final KeyboardShortcut keyStrokeShortcut = new KeyboardShortcut(keyStroke, null);
for (Component c = component; c != null; c = c.getParent()) {
if (c instanceof JComponent) {
final List<AnAction> actions = ActionUtil.getActions((JComponent)c);
for (AnAction action : actions) {
if (action instanceof VimShortcutKeyAction) {
continue;
}
final com.intellij.openapi.actionSystem.Shortcut[] shortcuts = action.getShortcutSet().getShortcuts();
for (com.intellij.openapi.actionSystem.Shortcut shortcut : shortcuts) {
if (shortcut.isKeyboard() && shortcut.startsWith(keyStrokeShortcut) && !results.contains(action)) {
results.add(action);
}
}
}
}
}
return results;
}
@NotNull
private static List<AnAction> getKeymapActions(@NotNull KeyStroke keyStroke) {
final List<AnAction> results = new ArrayList<>();
final Keymap keymap = KeymapManager.getInstance().getActiveKeymap();
for (String id : keymap.getActionIds(keyStroke)) {
final AnAction action = ActionManager.getInstance().getAction(id);
if (action != null) {
results.add(action);
}
}
return results;
}
}
|
package org.mifosplatform.accounting.journalentry.service;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.joda.time.LocalDate;
import org.mifosplatform.accounting.closure.domain.GLClosure;
import org.mifosplatform.accounting.closure.domain.GLClosureRepository;
import org.mifosplatform.accounting.glaccount.data.GLAccountDataForLookup;
import org.mifosplatform.accounting.glaccount.domain.GLAccount;
import org.mifosplatform.accounting.glaccount.domain.GLAccountRepository;
import org.mifosplatform.accounting.glaccount.exception.GLAccountNotFoundException;
import org.mifosplatform.accounting.glaccount.service.GLAccountReadPlatformService;
import org.mifosplatform.accounting.journalentry.api.JournalEntryJsonInputParams;
import org.mifosplatform.accounting.journalentry.command.JournalEntryCommand;
import org.mifosplatform.accounting.journalentry.command.SingleDebitOrCreditEntryCommand;
import org.mifosplatform.accounting.journalentry.data.LoanDTO;
import org.mifosplatform.accounting.journalentry.data.SavingsDTO;
import org.mifosplatform.accounting.journalentry.domain.JournalEntry;
import org.mifosplatform.accounting.journalentry.domain.JournalEntryRepository;
import org.mifosplatform.accounting.journalentry.domain.JournalEntryType;
import org.mifosplatform.accounting.journalentry.exception.JournalEntriesNotFoundException;
import org.mifosplatform.accounting.journalentry.exception.JournalEntryInvalidException;
import org.mifosplatform.accounting.journalentry.exception.JournalEntryInvalidException.GL_JOURNAL_ENTRY_INVALID_REASON;
import org.mifosplatform.accounting.journalentry.serialization.JournalEntryCommandFromApiJsonDeserializer;
import org.mifosplatform.accounting.rule.domain.AccountingRule;
import org.mifosplatform.accounting.rule.domain.AccountingRuleRepository;
import org.mifosplatform.accounting.rule.exception.AccountingRuleNotFoundException;
import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.infrastructure.core.data.CommandProcessingResultBuilder;
import org.mifosplatform.infrastructure.core.exception.PlatformDataIntegrityException;
import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext;
import org.mifosplatform.organisation.office.domain.Office;
import org.mifosplatform.organisation.office.domain.OfficeRepository;
import org.mifosplatform.organisation.office.domain.OrganisationCurrencyRepositoryWrapper;
import org.mifosplatform.organisation.office.exception.OfficeNotFoundException;
import org.mifosplatform.useradministration.domain.AppUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class JournalEntryWritePlatformServiceJpaRepositoryImpl implements JournalEntryWritePlatformService {
private final static Logger logger = LoggerFactory.getLogger(JournalEntryWritePlatformServiceJpaRepositoryImpl.class);
private final GLClosureRepository glClosureRepository;
private final GLAccountRepository glAccountRepository;
private final JournalEntryRepository glJournalEntryRepository;
private final OfficeRepository officeRepository;
private final AccountingProcessorForLoanFactory accountingProcessorForLoanFactory;
private final AccountingProcessorForSavingsFactory accountingProcessorForSavingsFactory;
private final AccountingProcessorHelper helper;
private final JournalEntryCommandFromApiJsonDeserializer fromApiJsonDeserializer;
private final AccountingRuleRepository accountingRuleRepository;
private final GLAccountReadPlatformService glAccountReadPlatformService;
private final OrganisationCurrencyRepositoryWrapper organisationCurrencyRepository;
private final PlatformSecurityContext context;
@Autowired
public JournalEntryWritePlatformServiceJpaRepositoryImpl(final GLClosureRepository glClosureRepository,
final JournalEntryRepository glJournalEntryRepository, final OfficeRepository officeRepository,
final GLAccountRepository glAccountRepository, final JournalEntryCommandFromApiJsonDeserializer fromApiJsonDeserializer,
final AccountingProcessorHelper accountingProcessorHelper, final AccountingRuleRepository accountingRuleRepository,
final AccountingProcessorForLoanFactory accountingProcessorForLoanFactory,
final AccountingProcessorForSavingsFactory accountingProcessorForSavingsFactory,
final GLAccountReadPlatformService glAccountReadPlatformService,
final OrganisationCurrencyRepositoryWrapper organisationCurrencyRepository,
final PlatformSecurityContext context) {
this.glClosureRepository = glClosureRepository;
this.officeRepository = officeRepository;
this.glJournalEntryRepository = glJournalEntryRepository;
this.fromApiJsonDeserializer = fromApiJsonDeserializer;
this.glAccountRepository = glAccountRepository;
this.accountingProcessorForLoanFactory = accountingProcessorForLoanFactory;
this.accountingProcessorForSavingsFactory = accountingProcessorForSavingsFactory;
this.helper = accountingProcessorHelper;
this.accountingRuleRepository = accountingRuleRepository;
this.glAccountReadPlatformService = glAccountReadPlatformService;
this.organisationCurrencyRepository = organisationCurrencyRepository;
this.context = context;
}
@Transactional
@Override
public CommandProcessingResult createJournalEntry(final JsonCommand command) {
try {
final JournalEntryCommand journalEntryCommand = this.fromApiJsonDeserializer.commandFromApiJson(command.json());
journalEntryCommand.validateForCreate();
// check office is valid
final Long officeId = command.longValueOfParameterNamed(JournalEntryJsonInputParams.OFFICE_ID.getValue());
final Office office = this.officeRepository.findOne(officeId);
if (office == null) { throw new OfficeNotFoundException(officeId); }
final Long accountRuleId = command.longValueOfParameterNamed(JournalEntryJsonInputParams.ACCOUNTING_RULE.getValue());
final String currencyCode = command.stringValueOfParameterNamed(JournalEntryJsonInputParams.CURRENCY_CODE.getValue());
validateBusinessRulesForJournalEntries(journalEntryCommand);
/** Set a transaction Id and save these Journal entries **/
final Date transactionDate = command.DateValueOfParameterNamed(JournalEntryJsonInputParams.TRANSACTION_DATE.getValue());
final String transactionId = generateTransactionId(officeId);
final String referenceNumber = command.stringValueOfParameterNamed(JournalEntryJsonInputParams.REFERENCE_NUMBER.getValue());
if (accountRuleId != null) {
final AccountingRule accountingRule = this.accountingRuleRepository.findOne(accountRuleId);
if (accountingRule == null) { throw new AccountingRuleNotFoundException(accountRuleId); }
if (accountingRule.getAccountToCredit() == null) {
if (journalEntryCommand.getCredits() == null) { throw new JournalEntryInvalidException(
GL_JOURNAL_ENTRY_INVALID_REASON.NO_DEBITS_OR_CREDITS, null, null, null); }
if (journalEntryCommand.getDebits() != null) {
checkDebitOrCreditAccountsAreValid(accountingRule, journalEntryCommand.getCredits(),
journalEntryCommand.getDebits());
checkDebitAndCreditAmounts(journalEntryCommand.getCredits(), journalEntryCommand.getDebits());
}
saveAllDebitOrCreditEntries(journalEntryCommand, office, currencyCode, transactionDate,
journalEntryCommand.getCredits(), transactionId, JournalEntryType.CREDIT, referenceNumber);
} else {
final GLAccount creditAccountHead = accountingRule.getAccountToCredit();
validateGLAccountForTransaction(creditAccountHead);
validateDebitOrCreditArrayForExistingGLAccount(creditAccountHead, journalEntryCommand.getCredits());
saveAllDebitOrCreditEntries(journalEntryCommand, office, currencyCode, transactionDate,
journalEntryCommand.getCredits(), transactionId, JournalEntryType.CREDIT, referenceNumber);
}
if (accountingRule.getAccountToDebit() == null) {
if (journalEntryCommand.getDebits() == null) { throw new JournalEntryInvalidException(
GL_JOURNAL_ENTRY_INVALID_REASON.NO_DEBITS_OR_CREDITS, null, null, null); }
if (journalEntryCommand.getCredits() != null) {
checkDebitOrCreditAccountsAreValid(accountingRule, journalEntryCommand.getCredits(),
journalEntryCommand.getDebits());
checkDebitAndCreditAmounts(journalEntryCommand.getCredits(), journalEntryCommand.getDebits());
}
saveAllDebitOrCreditEntries(journalEntryCommand, office, currencyCode, transactionDate,
journalEntryCommand.getDebits(), transactionId, JournalEntryType.DEBIT, referenceNumber);
} else {
final GLAccount debitAccountHead = accountingRule.getAccountToDebit();
validateGLAccountForTransaction(debitAccountHead);
validateDebitOrCreditArrayForExistingGLAccount(debitAccountHead, journalEntryCommand.getDebits());
saveAllDebitOrCreditEntries(journalEntryCommand, office, currencyCode, transactionDate,
journalEntryCommand.getDebits(), transactionId, JournalEntryType.DEBIT, referenceNumber);
}
} else {
saveAllDebitOrCreditEntries(journalEntryCommand, office, currencyCode, transactionDate, journalEntryCommand.getDebits(),
transactionId, JournalEntryType.DEBIT, referenceNumber);
saveAllDebitOrCreditEntries(journalEntryCommand, office, currencyCode, transactionDate, journalEntryCommand.getCredits(),
transactionId, JournalEntryType.CREDIT, referenceNumber);
}
return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withOfficeId(officeId)
.withTransactionId(transactionId).build();
} catch (final DataIntegrityViolationException dve) {
handleJournalEntryDataIntegrityIssues(dve);
return null;
}
}
private void validateDebitOrCreditArrayForExistingGLAccount(final GLAccount glaccount,
final SingleDebitOrCreditEntryCommand[] creditOrDebits) {
/**
* If a glaccount is assigned for a rule the credits or debits array
* should have only one entry and it must be same as existing account
*/
if (creditOrDebits.length != 1) { throw new JournalEntryInvalidException(
GL_JOURNAL_ENTRY_INVALID_REASON.INVALID_DEBIT_OR_CREDIT_ACCOUNTS, null, null, null); }
for (final SingleDebitOrCreditEntryCommand creditOrDebit : creditOrDebits) {
if (!glaccount.getId().equals(creditOrDebit.getGlAccountId())) { throw new JournalEntryInvalidException(
GL_JOURNAL_ENTRY_INVALID_REASON.INVALID_DEBIT_OR_CREDIT_ACCOUNTS, null, null, null); }
}
}
@SuppressWarnings("null")
private void checkDebitOrCreditAccountsAreValid(final AccountingRule accountingRule, final SingleDebitOrCreditEntryCommand[] credits,
final SingleDebitOrCreditEntryCommand[] debits) {
// Validate the debit and credit arrays are appropriate accounts
List<GLAccountDataForLookup> allowedCreditGLAccounts = new ArrayList<GLAccountDataForLookup>();
List<GLAccountDataForLookup> allowedDebitGLAccounts = new ArrayList<GLAccountDataForLookup>();
final SingleDebitOrCreditEntryCommand[] validCredits = new SingleDebitOrCreditEntryCommand[credits.length];
final SingleDebitOrCreditEntryCommand[] validDebits = new SingleDebitOrCreditEntryCommand[debits.length];
if (credits != null && credits.length > 0) {
allowedCreditGLAccounts = this.glAccountReadPlatformService.retrieveAccountsByTagId(accountingRule.getId(),
JournalEntryType.CREDIT.getValue());
for (final GLAccountDataForLookup accountDataForLookup : allowedCreditGLAccounts) {
for (int i = 0; i < credits.length; i++) {
final SingleDebitOrCreditEntryCommand credit = credits[i];
if (credit.getGlAccountId().equals(accountDataForLookup.getId())) {
validCredits[i] = credit;
}
}
}
if (credits.length != validCredits.length) { throw new RuntimeException("Invalid credits"); }
}
if (debits != null && debits.length > 0) {
allowedDebitGLAccounts = this.glAccountReadPlatformService.retrieveAccountsByTagId(accountingRule.getId(),
JournalEntryType.DEBIT.getValue());
for (final GLAccountDataForLookup accountDataForLookup : allowedDebitGLAccounts) {
for (int i = 0; i < debits.length; i++) {
final SingleDebitOrCreditEntryCommand debit = debits[i];
if (debit.getGlAccountId().equals(accountDataForLookup.getId())) {
validDebits[i] = debit;
}
}
}
if (debits.length != validDebits.length) { throw new RuntimeException("Invalid debits"); }
}
}
private void checkDebitAndCreditAmounts(final SingleDebitOrCreditEntryCommand[] credits, final SingleDebitOrCreditEntryCommand[] debits) {
// sum of all debits must be = sum of all credits
BigDecimal creditsSum = BigDecimal.ZERO;
BigDecimal debitsSum = BigDecimal.ZERO;
for (final SingleDebitOrCreditEntryCommand creditEntryCommand : credits) {
if (creditEntryCommand.getAmount() == null || creditEntryCommand.getGlAccountId() == null) { throw new JournalEntryInvalidException(
GL_JOURNAL_ENTRY_INVALID_REASON.DEBIT_CREDIT_ACCOUNT_OR_AMOUNT_EMPTY, null, null, null); }
creditsSum = creditsSum.add(creditEntryCommand.getAmount());
}
for (final SingleDebitOrCreditEntryCommand debitEntryCommand : debits) {
if (debitEntryCommand.getAmount() == null || debitEntryCommand.getGlAccountId() == null) { throw new JournalEntryInvalidException(
GL_JOURNAL_ENTRY_INVALID_REASON.DEBIT_CREDIT_ACCOUNT_OR_AMOUNT_EMPTY, null, null, null); }
debitsSum = debitsSum.add(debitEntryCommand.getAmount());
}
if (creditsSum.compareTo(debitsSum) != 0) { throw new JournalEntryInvalidException(
GL_JOURNAL_ENTRY_INVALID_REASON.DEBIT_CREDIT_SUM_MISMATCH, null, null, null); }
}
private void validateGLAccountForTransaction(final GLAccount creditOrDebitAccountHead) {
/***
* validate that the account allows manual adjustments and is not
* disabled
**/
if (creditOrDebitAccountHead.isDisabled()) {
throw new JournalEntryInvalidException(GL_JOURNAL_ENTRY_INVALID_REASON.GL_ACCOUNT_DISABLED, null,
creditOrDebitAccountHead.getName(), creditOrDebitAccountHead.getGlCode());
} else if (!creditOrDebitAccountHead.isManualEntriesAllowed()) { throw new JournalEntryInvalidException(
GL_JOURNAL_ENTRY_INVALID_REASON.GL_ACCOUNT_MANUAL_ENTRIES_NOT_PERMITTED, null, creditOrDebitAccountHead.getName(),
creditOrDebitAccountHead.getGlCode()); }
}
@Transactional
@Override
public CommandProcessingResult revertJournalEntry(final JsonCommand command) {
// is the transaction Id valid
final List<JournalEntry> journalEntries = this.glJournalEntryRepository.findUnReversedManualJournalEntriesByTransactionId(command
.getTransactionId());
if (journalEntries.size() <= 1) { throw new JournalEntriesNotFoundException(command.getTransactionId()); }
Long officeId = journalEntries.get(0).getOffice().getId();
final String reversalTransactionId = generateTransactionId(officeId);
final boolean manualEntry = true;
for (final JournalEntry journalEntry : journalEntries) {
JournalEntry reversalJournalEntry;
final String reversalComment = "Reversal entry for Journal Entry with Entry Id :" + journalEntry.getId()
+ " and transaction Id " + command.getTransactionId();
if (journalEntry.isDebitEntry()) {
reversalJournalEntry = JournalEntry.createNew(journalEntry.getOffice(), journalEntry.getGlAccount(),
journalEntry.getCurrencyCode(), reversalTransactionId, manualEntry, journalEntry.getTransactionDate(),
JournalEntryType.CREDIT, journalEntry.getAmount(), reversalComment, null, null, journalEntry.getReferenceNumber());
} else {
reversalJournalEntry = JournalEntry.createNew(journalEntry.getOffice(), journalEntry.getGlAccount(),
journalEntry.getCurrencyCode(), reversalTransactionId, manualEntry, journalEntry.getTransactionDate(),
JournalEntryType.DEBIT, journalEntry.getAmount(), reversalComment, null, null, journalEntry.getReferenceNumber());
}
// save the reversal entry
this.glJournalEntryRepository.saveAndFlush(reversalJournalEntry);
journalEntry.setReversed(true);
journalEntry.setReversalJournalEntry(reversalJournalEntry);
// save the updated journal entry
this.glJournalEntryRepository.saveAndFlush(journalEntry);
}
return new CommandProcessingResultBuilder().withTransactionId(reversalTransactionId).build();
}
@Transactional
@Override
public void createJournalEntriesForLoan(final Map<String, Object> accountingBridgeData) {
final boolean cashBasedAccountingEnabled = (Boolean) accountingBridgeData.get("cashBasedAccountingEnabled");
final boolean accrualBasedAccountingEnabled = (Boolean) accountingBridgeData.get("accrualBasedAccountingEnabled");
if (cashBasedAccountingEnabled || accrualBasedAccountingEnabled) {
final LoanDTO loanDTO = this.helper.populateLoanDtoFromMap(accountingBridgeData, cashBasedAccountingEnabled,
accrualBasedAccountingEnabled);
final AccountingProcessorForLoan accountingProcessorForLoan = this.accountingProcessorForLoanFactory
.determineProcessor(loanDTO);
accountingProcessorForLoan.createJournalEntriesForLoan(loanDTO);
}
}
@Transactional
@Override
public void createJournalEntriesForSavings(final Map<String, Object> accountingBridgeData) {
final boolean cashBasedAccountingEnabled = (Boolean) accountingBridgeData.get("cashBasedAccountingEnabled");
final boolean accrualBasedAccountingEnabled = (Boolean) accountingBridgeData.get("accrualBasedAccountingEnabled");
if (cashBasedAccountingEnabled || accrualBasedAccountingEnabled) {
final SavingsDTO savingsDTO = this.helper.populateSavingsDtoFromMap(accountingBridgeData, cashBasedAccountingEnabled,
accrualBasedAccountingEnabled);
final AccountingProcessorForSavings accountingProcessorForSavings = this.accountingProcessorForSavingsFactory
.determineProcessor(savingsDTO);
accountingProcessorForSavings.createJournalEntriesForSavings(savingsDTO);
}
}
private void validateBusinessRulesForJournalEntries(final JournalEntryCommand command) {
/** check if date of Journal entry is valid ***/
final LocalDate entryLocalDate = command.getTransactionDate();
final Date transactionDate = entryLocalDate.toDateMidnight().toDate();
// shouldn't be in the future
final Date todaysDate = new Date();
if (transactionDate.after(todaysDate)) { throw new JournalEntryInvalidException(GL_JOURNAL_ENTRY_INVALID_REASON.FUTURE_DATE,
transactionDate, null, null); }
// shouldn't be before an accounting closure
final GLClosure latestGLClosure = this.glClosureRepository.getLatestGLClosureByBranch(command.getOfficeId());
if (latestGLClosure != null) {
if (latestGLClosure.getClosingDate().after(transactionDate) || latestGLClosure.getClosingDate().equals(transactionDate)) { throw new JournalEntryInvalidException(
GL_JOURNAL_ENTRY_INVALID_REASON.ACCOUNTING_CLOSED, latestGLClosure.getClosingDate(), null, null); }
}
/*** check if credits and debits are valid **/
final SingleDebitOrCreditEntryCommand[] credits = command.getCredits();
final SingleDebitOrCreditEntryCommand[] debits = command.getDebits();
// atleast one debit or credit must be present
if ((credits == null || credits.length <= 0) || (debits == null || debits.length <= 0)) { throw new JournalEntryInvalidException(
GL_JOURNAL_ENTRY_INVALID_REASON.NO_DEBITS_OR_CREDITS, null, null, null); }
checkDebitAndCreditAmounts(credits, debits);
}
private void saveAllDebitOrCreditEntries(final JournalEntryCommand command, final Office office, final String currencyCode,
final Date transactionDate, final SingleDebitOrCreditEntryCommand[] singleDebitOrCreditEntryCommands,
final String transactionId, final JournalEntryType type, final String referenceNumber) {
final boolean manualEntry = true;
for (final SingleDebitOrCreditEntryCommand singleDebitOrCreditEntryCommand : singleDebitOrCreditEntryCommands) {
final GLAccount glAccount = this.glAccountRepository.findOne(singleDebitOrCreditEntryCommand.getGlAccountId());
if (glAccount == null) { throw new GLAccountNotFoundException(singleDebitOrCreditEntryCommand.getGlAccountId()); }
validateGLAccountForTransaction(glAccount);
String comments = command.getComments();
if (!StringUtils.isBlank(singleDebitOrCreditEntryCommand.getComments())) {
comments = singleDebitOrCreditEntryCommand.getComments();
}
/** Validate current code is appropriate **/
this.organisationCurrencyRepository.findOneWithNotFoundDetection(currencyCode);
final JournalEntry glJournalEntry = JournalEntry.createNew(office, glAccount, currencyCode, transactionId, manualEntry,
transactionDate, type, singleDebitOrCreditEntryCommand.getAmount(), comments, null, null, referenceNumber);
this.glJournalEntryRepository.saveAndFlush(glJournalEntry);
}
}
/**
* TODO: Need a better implementation with guaranteed uniqueness (but not a
* long UUID)...maybe something tied to system clock..
*/
private String generateTransactionId(Long officeId) {
AppUser user = this.context.authenticatedUser();
Long time = System.currentTimeMillis();
String uniqueVal = String.valueOf(time) + user.getId() + officeId;
String transactionId = Long.toHexString(Long.parseLong(uniqueVal));
return transactionId;
}
private void handleJournalEntryDataIntegrityIssues(final DataIntegrityViolationException dve) {
final Throwable realCause = dve.getMostSpecificCause();
logger.error(dve.getMessage(), dve);
throw new PlatformDataIntegrityException("error.msg.glJournalEntry.unknown.data.integrity.issue",
"Unknown data integrity issue with resource Journal Entry: " + realCause.getMessage());
}
}
|
package com.x.processplatform.assemble.surface.jaxrs.attachment;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.container.AsyncResponse;
import javax.ws.rs.container.Suspended;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import org.apache.commons.lang3.StringUtils;
import org.glassfish.jersey.media.multipart.FormDataBodyPart;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataMultiPart;
import org.glassfish.jersey.media.multipart.FormDataParam;
import com.google.gson.JsonElement;
import com.x.base.core.project.annotation.JaxrsDescribe;
import com.x.base.core.project.annotation.JaxrsMethodDescribe;
import com.x.base.core.project.annotation.JaxrsParameterDescribe;
import com.x.base.core.project.http.ActionResult;
import com.x.base.core.project.http.EffectivePerson;
import com.x.base.core.project.http.HttpMediaType;
import com.x.base.core.project.jaxrs.ResponseFactory;
import com.x.base.core.project.jaxrs.StandardJaxrsAction;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
@Path("attachment")
@JaxrsDescribe("")
public class AttachmentAction extends StandardJaxrsAction {
private static Logger logger = LoggerFactory.getLogger(AttachmentAction.class);
@JaxrsMethodDescribe(value = ".", action = ActionAvailable.class)
@GET
@Path("{id}/available")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void available(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
@JaxrsParameterDescribe("") @PathParam("id") String id) {
ActionResult<ActionAvailable.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionAvailable().execute(effectivePerson, id);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = "WorkId.", action = ActionGetWithWork.class)
@GET
@Path("{id}/work/{workId}")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void getWithWork(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
@JaxrsParameterDescribe("") @PathParam("workId") String workId,
@JaxrsParameterDescribe("") @PathParam("id") String id) {
ActionResult<ActionGetWithWork.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionGetWithWork().execute(effectivePerson, id, workId);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = "WorkCompletedId", action = ActionGetWithWorkCompleted.class)
@GET
@Path("{id}/workcompleted/{workCompletedId}")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void getWithWorkCompleted(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
@JaxrsParameterDescribe("") @PathParam("workCompletedId") String workCompletedId,
@JaxrsParameterDescribe("") @PathParam("id") String id) {
ActionResult<ActionGetWithWorkCompleted.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionGetWithWorkCompleted().execute(effectivePerson, id, workCompletedId);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = "WorkCompletedId", action = ActionGetWithWorkOrWorkCompleted.class)
@GET
@Path("{id}/workorworkcompleted/{workOrWorkCompleted}")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void getWithWorkOrWorkCompleted(@Suspended final AsyncResponse asyncResponse,
@Context HttpServletRequest request,
@JaxrsParameterDescribe("") @PathParam("workOrWorkCompleted") String workOrWorkCompleted,
@JaxrsParameterDescribe("") @PathParam("id") String id) {
ActionResult<ActionGetWithWorkOrWorkCompleted.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionGetWithWorkOrWorkCompleted().execute(effectivePerson, id, workOrWorkCompleted);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = "WorkAttachment.", action = ActionListWithWork.class)
@GET
@Path("list/work/{workId}")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void listWithWork(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
@JaxrsParameterDescribe("") @PathParam("workId") String workId) {
ActionResult<List<ActionListWithWork.Wo>> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionListWithWork().execute(effectivePerson, workId);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = "WorkCompletedAttachment.", action = ActionListWithWorkCompleted.class)
@GET
@Path("list/workcompleted/{workCompletedId}")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void listWithWorkCompleted(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
@JaxrsParameterDescribe("") @PathParam("workCompletedId") String workCompletedId) {
ActionResult<List<ActionListWithWorkCompleted.Wo>> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionListWithWorkCompleted().execute(effectivePerson, workCompletedId);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = "Attachment.", action = ActionListWithWorkOrWorkCompleted.class)
@GET
@Path("list/workorworkcompleted/{workOrWorkCompleted}")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void listWithWorkOrWorkCompleted(@Suspended final AsyncResponse asyncResponse,
@Context HttpServletRequest request,
@JaxrsParameterDescribe("") @PathParam("workOrWorkCompleted") String workOrWorkCompleted) {
ActionResult<List<ActionListWithWorkOrWorkCompleted.Wo>> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionListWithWorkOrWorkCompleted().execute(effectivePerson, workOrWorkCompleted);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = "jobAttachment.", action = ActionListWithJob.class)
@GET
@Path("list/job/{job}")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void listWithJob(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
@JaxrsParameterDescribe("job") @PathParam("job") String job) {
ActionResult<List<ActionListWithJob.Wo>> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionListWithJob().execute(effectivePerson, job);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = "work.", action = ActionDeleteWithWork.class)
@DELETE
@Path("{id}/work/{workId}")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void deleteWithWork(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
@JaxrsParameterDescribe("") @PathParam("id") String id,
@JaxrsParameterDescribe("") @PathParam("workId") String workId) {
ActionResult<ActionDeleteWithWork.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionDeleteWithWork().execute(effectivePerson, id, workId);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = "Mock Get To Delete.", action = ActionDeleteWithWork.class)
@GET
@Path("{id}/work/{workId}/mockdeletetoget")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void deleteWithWorkMockDeleteToGet(@Suspended final AsyncResponse asyncResponse,
@Context HttpServletRequest request, @JaxrsParameterDescribe("") @PathParam("id") String id,
@JaxrsParameterDescribe("") @PathParam("workId") String workId) {
ActionResult<ActionDeleteWithWork.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionDeleteWithWork().execute(effectivePerson, id, workId);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = "workCompleted. ", action = ActionDeleteWithWorkCompleted.class)
@DELETE
@Path("{id}/workcompleted/{workCompletedId}")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void deleteWithWorkCompleted(@Suspended final AsyncResponse asyncResponse,
@Context HttpServletRequest request, @JaxrsParameterDescribe("") @PathParam("id") String id,
@JaxrsParameterDescribe("") @PathParam("workCompletedId") String workCompletedId) {
ActionResult<ActionDeleteWithWorkCompleted.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionDeleteWithWorkCompleted().execute(effectivePerson, id, workCompletedId);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = "Mock Get To Delete.", action = ActionDeleteWithWorkCompleted.class)
@GET
@Path("{id}/workcompleted/{workCompletedId}/mockdeletetoget")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void deleteWithWorkCompletedMockDeleteToGet(@Suspended final AsyncResponse asyncResponse,
@Context HttpServletRequest request, @JaxrsParameterDescribe("") @PathParam("id") String id,
@JaxrsParameterDescribe("") @PathParam("workCompletedId") String workCompletedId) {
ActionResult<ActionDeleteWithWorkCompleted.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionDeleteWithWorkCompleted().execute(effectivePerson, id, workCompletedId);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = "", action = ActionDownload.class)
@GET
@Path("download/{id}")
@Consumes(MediaType.APPLICATION_JSON)
public void download(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
@JaxrsParameterDescribe("") @PathParam("id") String id,
@JaxrsParameterDescribe("") @QueryParam("fileName") String fileName) {
ActionResult<ActionDownload.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionDownload().execute(effectivePerson, id, fileName);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = ",stream", action = ActionDownloadStream.class)
@GET
@Path("download/{id}/stream")
@Consumes(MediaType.APPLICATION_JSON)
public void downloadStream(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
@JaxrsParameterDescribe("") @PathParam("id") String id,
@JaxrsParameterDescribe("") @QueryParam("fileName") String fileName) {
ActionResult<ActionDownloadStream.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionDownloadStream().execute(effectivePerson, id, fileName);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = "Work", action = ActionDownloadWithWork.class)
@GET
@Path("download/{id}/work/{workId}")
@Consumes(MediaType.APPLICATION_JSON)
public void downloadWithWork(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
@JaxrsParameterDescribe("") @PathParam("id") String id,
@JaxrsParameterDescribe("") @PathParam("workId") String workId,
@JaxrsParameterDescribe("") @QueryParam("fileName") String fileName) {
ActionResult<ActionDownloadWithWork.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionDownloadWithWork().execute(effectivePerson, id, workId, fileName);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = "Work,", action = ActionDownloadWithWork.class)
@GET
@Path("download/{id}/work/{workId}/{fileName}.{extension}")
@Consumes(MediaType.APPLICATION_JSON)
public void downloadWithWorkWithExtension(@Suspended final AsyncResponse asyncResponse,
@Context HttpServletRequest request, @JaxrsParameterDescribe("") @PathParam("id") String id,
@JaxrsParameterDescribe("") @PathParam("workId") String workId,
@JaxrsParameterDescribe("") @QueryParam("fileName") String fileName) {
ActionResult<ActionDownloadWithWork.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionDownloadWithWork().execute(effectivePerson, id, workId, fileName);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = "Work,stream", action = ActionDownloadWithWorkStream.class)
@GET
@Path("download/{id}/work/{workId}/stream")
@Consumes(MediaType.APPLICATION_JSON)
public void downloadWithWorkStream(@Suspended final AsyncResponse asyncResponse,
@Context HttpServletRequest request, @JaxrsParameterDescribe("") @PathParam("id") String id,
@JaxrsParameterDescribe("") @PathParam("workId") String workId,
@JaxrsParameterDescribe("") @QueryParam("fileName") String fileName) {
ActionResult<ActionDownloadWithWorkStream.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionDownloadWithWorkStream().execute(effectivePerson, id, workId, fileName);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = "Work,stream.", action = ActionDownloadWithWorkStream.class)
@GET
@Path("download/{id}/work/{workId}/stream/{fileName}.{extension}")
@Consumes(MediaType.APPLICATION_JSON)
public void downloadWithWorkStreamWithExtension(@Suspended final AsyncResponse asyncResponse,
@Context HttpServletRequest request, @JaxrsParameterDescribe("") @PathParam("id") String id,
@JaxrsParameterDescribe("") @PathParam("workId") String workId,
@JaxrsParameterDescribe("") @QueryParam("fileName") String fileName) {
ActionResult<ActionDownloadWithWorkStream.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionDownloadWithWorkStream().execute(effectivePerson, id, workId, fileName);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = "WorkCompleted", action = ActionDownloadWithWorkCompleted.class)
@GET
@Path("download/{id}/workcompleted/{workCompletedId}")
@Consumes(MediaType.APPLICATION_JSON)
public void downloadWithWorkCompleted(@Suspended final AsyncResponse asyncResponse,
@Context HttpServletRequest request, @JaxrsParameterDescribe("") @PathParam("id") String id,
@JaxrsParameterDescribe("") @PathParam("workCompletedId") String workCompletedId,
@JaxrsParameterDescribe("") @QueryParam("fileName") String fileName) {
ActionResult<ActionDownloadWithWorkCompleted.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionDownloadWithWorkCompleted().execute(effectivePerson, id, workCompletedId, fileName);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = "WorkCompleted,.", action = ActionDownloadWithWorkCompleted.class)
@GET
@Path("download/{id}/workcompleted/{workCompletedId}/{fileName}.{extension}")
@Consumes(MediaType.APPLICATION_JSON)
public void downloadWithWorkCompletedWithExtension(@Suspended final AsyncResponse asyncResponse,
@Context HttpServletRequest request, @JaxrsParameterDescribe("") @PathParam("id") String id,
@JaxrsParameterDescribe("") @PathParam("workCompletedId") String workCompletedId,
@JaxrsParameterDescribe("") @QueryParam("fileName") String fileName) {
ActionResult<ActionDownloadWithWorkCompleted.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionDownloadWithWorkCompleted().execute(effectivePerson, id, workCompletedId, fileName);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = "WorkCompleted", action = ActionDownloadWithWorkCompletedStream.class)
@GET
@Path("download/{id}/workcompleted/{workCompletedId}/stream")
@Consumes(MediaType.APPLICATION_JSON)
public void downloadWithWorkCompletedStream(@Suspended final AsyncResponse asyncResponse,
@Context HttpServletRequest request, @JaxrsParameterDescribe("") @PathParam("id") String id,
@JaxrsParameterDescribe("") @PathParam("workCompletedId") String workCompletedId,
@JaxrsParameterDescribe("") @QueryParam("fileName") String fileName) {
ActionResult<ActionDownloadWithWorkCompletedStream.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionDownloadWithWorkCompletedStream().execute(effectivePerson, id, workCompletedId,
fileName);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = "WorkCompleted,.", action = ActionDownloadWithWorkCompletedStream.class)
@GET
@Path("download/{id}/workcompleted/{workCompletedId}/stream/{fileName}.{extension}")
@Consumes(MediaType.APPLICATION_JSON)
public void downloadWithWorkCompletedStreamWithExtension(@Suspended final AsyncResponse asyncResponse,
@Context HttpServletRequest request, @JaxrsParameterDescribe("") @PathParam("id") String id,
@JaxrsParameterDescribe("") @PathParam("workCompletedId") String workCompletedId,
@JaxrsParameterDescribe("") @QueryParam("fileName") String fileName) {
ActionResult<ActionDownloadWithWorkCompletedStream.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionDownloadWithWorkCompletedStream().execute(effectivePerson, id, workCompletedId,
fileName);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = ".", action = ActionUploadWithWork.class)
@POST
@Path("upload/work/{workId}")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.MULTIPART_FORM_DATA)
public void upload(FormDataMultiPart form, @Suspended final AsyncResponse asyncResponse,
@Context HttpServletRequest request, @JaxrsParameterDescribe("") @PathParam("workId") String workId,
@JaxrsParameterDescribe("") @FormDataParam("site") String site,
@JaxrsParameterDescribe("") @FormDataParam(FILENAME_FIELD) String fileName,
@JaxrsParameterDescribe("") @FormDataParam("extraParam") String extraParam,
@FormDataParam(FILE_FIELD) byte[] bytes,
@FormDataParam(FILE_FIELD) final FormDataContentDisposition disposition) {
ActionResult<ActionUploadWithWork.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
if (StringUtils.isEmpty(extraParam)) {
extraParam = this.request2Json(request);
}
if (bytes == null) {
Map<String, List<FormDataBodyPart>> map = form.getFields();
for (String key : map.keySet()) {
FormDataBodyPart part = map.get(key).get(0);
if ("application".equals(part.getMediaType().getType())) {
bytes = part.getValueAs(byte[].class);
break;
}
}
}
result = new ActionUploadWithWork().execute(effectivePerson, workId, site, fileName, bytes, disposition,
extraParam);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = ".", action = ActionUploadWithWorkCompleted.class)
@POST
@Path("upload/workcompleted/{workCompletedId}")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.MULTIPART_FORM_DATA)
public void uploadWithWorkCompleted(FormDataMultiPart form, @Suspended final AsyncResponse asyncResponse,
@Context HttpServletRequest request,
@JaxrsParameterDescribe("") @PathParam("workCompletedId") String workCompletedId,
@JaxrsParameterDescribe("") @FormDataParam("site") String site,
@JaxrsParameterDescribe("") @FormDataParam(FILENAME_FIELD) String fileName,
@JaxrsParameterDescribe("") @FormDataParam("extraParam") String extraParam,
@FormDataParam(FILE_FIELD) byte[] bytes,
@FormDataParam(FILE_FIELD) final FormDataContentDisposition disposition) {
ActionResult<ActionUploadWithWorkCompleted.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
if (StringUtils.isEmpty(extraParam)) {
extraParam = this.request2Json(request);
}
if (bytes == null) {
Map<String, List<FormDataBodyPart>> map = form.getFields();
for (String key : map.keySet()) {
FormDataBodyPart part = map.get(key).get(0);
if ("application".equals(part.getMediaType().getType())) {
bytes = part.getValueAs(byte[].class);
break;
}
}
}
result = new ActionUploadWithWorkCompleted().execute(effectivePerson, workCompletedId, site, fileName,
bytes, disposition, extraParam);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = ".", action = ActionUploadCallback.class)
@POST
@Path("upload/work/{workId}/callback/{callback}")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(HttpMediaType.TEXT_HTML_UTF_8)
public void uploadCallback(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
@JaxrsParameterDescribe("") @PathParam("workId") String workId,
@JaxrsParameterDescribe("") @PathParam("callback") String callback,
@JaxrsParameterDescribe("") @FormDataParam("site") String site,
@JaxrsParameterDescribe("") @FormDataParam(FILENAME_FIELD) String fileName,
@FormDataParam(FILE_FIELD) final byte[] bytes,
@FormDataParam(FILE_FIELD) final FormDataContentDisposition disposition) {
ActionResult<ActionUploadCallback.Wo<ActionUploadCallback.WoObject>> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionUploadCallback().execute(effectivePerson, workId, callback, site, fileName, bytes,
disposition);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = ".", action = ActionUpdate.class)
@PUT
@Path("update/{id}/work/{workId}")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.MULTIPART_FORM_DATA)
public void update(FormDataMultiPart form, @Suspended final AsyncResponse asyncResponse,
@Context HttpServletRequest request, @JaxrsParameterDescribe("") @PathParam("id") String id,
@JaxrsParameterDescribe("") @PathParam("workId") String workId,
@JaxrsParameterDescribe("") @FormDataParam(FILENAME_FIELD) String fileName,
@JaxrsParameterDescribe("") @FormDataParam("extraParam") String extraParam,
@FormDataParam(FILE_FIELD) byte[] bytes,
@JaxrsParameterDescribe("") @FormDataParam(FILE_FIELD) final FormDataContentDisposition disposition) {
ActionResult<ActionUpdate.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
if (StringUtils.isEmpty(extraParam)) {
extraParam = this.request2Json(request);
}
if (bytes == null) {
Map<String, List<FormDataBodyPart>> map = form.getFields();
for (String key : map.keySet()) {
FormDataBodyPart part = map.get(key).get(0);
if ("application".equals(part.getMediaType().getType())) {
bytes = part.getValueAs(byte[].class);
break;
}
}
}
result = new ActionUpdate().execute(effectivePerson, id, workId, fileName, bytes, disposition, extraParam);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = "Mock Get To Delete.", action = ActionUpdate.class)
@POST
@Path("update/{id}/work/{workId}/mockputtopost")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.MULTIPART_FORM_DATA)
public void updateMockPutToPost(FormDataMultiPart form, @Suspended final AsyncResponse asyncResponse,
@Context HttpServletRequest request, @JaxrsParameterDescribe("") @PathParam("id") String id,
@JaxrsParameterDescribe("") @PathParam("workId") String workId,
@JaxrsParameterDescribe("") @FormDataParam(FILENAME_FIELD) String fileName,
@JaxrsParameterDescribe("") @FormDataParam("extraParam") String extraParam,
@FormDataParam(FILE_FIELD) byte[] bytes,
@JaxrsParameterDescribe("") @FormDataParam(FILE_FIELD) final FormDataContentDisposition disposition) {
ActionResult<ActionUpdate.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
if (StringUtils.isEmpty(extraParam)) {
extraParam = this.request2Json(request);
}
if (bytes == null) {
Map<String, List<FormDataBodyPart>> map = form.getFields();
for (String key : map.keySet()) {
FormDataBodyPart part = map.get(key).get(0);
if ("application".equals(part.getMediaType().getType())) {
bytes = part.getValueAs(byte[].class);
break;
}
}
}
result = new ActionUpdate().execute(effectivePerson, id, workId, fileName, bytes, disposition, extraParam);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = "Attachment", action = ActionUpdateContent.class)
@PUT
@Path("update/content/{id}/work/{workId}")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void updateContent(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
@JaxrsParameterDescribe("") @PathParam("id") String id,
@JaxrsParameterDescribe("") @PathParam("workId") String workId, JsonElement jsonElement) {
ActionResult<ActionUpdateContent.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionUpdateContent().execute(effectivePerson, id, workId, jsonElement);
} catch (Exception e) {
logger.error(e, effectivePerson, request, jsonElement);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = "Mock Get To Delete.", action = ActionUpdateContent.class)
@POST
@Path("update/content/{id}/work/{workId}/mockputtopost")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void updateContentMockPutToPost(@Suspended final AsyncResponse asyncResponse,
@Context HttpServletRequest request, @JaxrsParameterDescribe("") @PathParam("id") String id,
@JaxrsParameterDescribe("") @PathParam("workId") String workId, JsonElement jsonElement) {
ActionResult<ActionUpdateContent.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionUpdateContent().execute(effectivePerson, id, workId, jsonElement);
} catch (Exception e) {
logger.error(e, effectivePerson, request, jsonElement);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = ",callback,POST.", action = ActionUpdateCallback.class)
@POST
@Path("update/{id}/work/{workId}/callback/{callback}")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(HttpMediaType.TEXT_HTML_UTF_8)
public void updateCallback(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
@JaxrsParameterDescribe("") @PathParam("id") String id,
@JaxrsParameterDescribe("") @PathParam("workId") String workId,
@JaxrsParameterDescribe("") @PathParam("callback") String callback,
@JaxrsParameterDescribe("") @FormDataParam(FILENAME_FIELD) String fileName,
@FormDataParam(FILE_FIELD) final byte[] bytes,
@JaxrsParameterDescribe("") @FormDataParam(FILE_FIELD) final FormDataContentDisposition disposition) {
ActionResult<ActionUpdateCallback.Wo<ActionUpdateCallback.WoObject>> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionUpdateCallback().execute(effectivePerson, id, workId, callback, fileName, bytes,
disposition);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
/** update,ntkopost */
@JaxrsMethodDescribe(value = ".", action = ActionUpdate.class)
@POST
@Path("update/{id}/work/{workId}")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.MULTIPART_FORM_DATA)
public void updatePost(FormDataMultiPart form, @Suspended final AsyncResponse asyncResponse,
@Context HttpServletRequest request, @JaxrsParameterDescribe("") @PathParam("id") String id,
@JaxrsParameterDescribe("") @PathParam("workId") String workId,
@JaxrsParameterDescribe("") @FormDataParam(FILENAME_FIELD) String fileName,
@JaxrsParameterDescribe("") @FormDataParam("extraParam") String extraParam,
@FormDataParam(FILE_FIELD) byte[] bytes,
@JaxrsParameterDescribe("") @FormDataParam(FILE_FIELD) final FormDataContentDisposition disposition) {
ActionResult<ActionUpdate.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
if (StringUtils.isEmpty(extraParam)) {
extraParam = this.request2Json(request);
}
if (bytes == null) {
Map<String, List<FormDataBodyPart>> map = form.getFields();
for (String key : map.keySet()) {
FormDataBodyPart part = map.get(key).get(0);
if ("application".equals(part.getMediaType().getType())) {
bytes = part.getValueAs(byte[].class);
break;
}
}
}
result = new ActionUpdate().execute(effectivePerson, id, workId, fileName, bytes, disposition, extraParam);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = ".", action = ActionCopyToWork.class)
@POST
@Path("copy/work/{workId}")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void copyToWork(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
@JaxrsParameterDescribe("") @PathParam("workId") String workId, JsonElement jsonElement) {
ActionResult<List<ActionCopyToWork.Wo>> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionCopyToWork().execute(effectivePerson, workId, jsonElement);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = ".", action = ActionCopyToWorkCompleted.class)
@POST
@Path("copy/workcompleted/{workCompletedId}")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void copyToWorkCompleted(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
@JaxrsParameterDescribe("") @PathParam("workCompletedId") String workCompletedId,
JsonElement jsonElement) {
ActionResult<List<ActionCopyToWorkCompleted.Wo>> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionCopyToWorkCompleted().execute(effectivePerson, workCompletedId, jsonElement);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = "().", action = ActionCopyToWorkSoft.class)
@POST
@Path("copy/work/{workId}/soft")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void copyToWorkSoft(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
@JaxrsParameterDescribe("") @PathParam("workId") String workId, JsonElement jsonElement) {
ActionResult<List<ActionCopyToWorkSoft.Wo>> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionCopyToWorkSoft().execute(effectivePerson, workId, jsonElement);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = "().", action = ActionCopyToWorkCompletedSoft.class)
@POST
@Path("copy/workcompleted/{workCompletedId}/soft")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void copyToWorkCompletedSoft(@Suspended final AsyncResponse asyncResponse,
@Context HttpServletRequest request,
@JaxrsParameterDescribe("") @PathParam("workCompletedId") String workCompletedId,
JsonElement jsonElement) {
ActionResult<List<ActionCopyToWorkCompletedSoft.Wo>> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionCopyToWorkCompletedSoft().execute(effectivePerson, workCompletedId, jsonElement);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = ".", action = ActionChangeSite.class)
@GET
@Path("{id}/work/{workId}/change/site/{site}")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void changeSite(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
@JaxrsParameterDescribe("") @PathParam("id") String id,
@JaxrsParameterDescribe("") @PathParam("workId") String workId,
@JaxrsParameterDescribe("") @PathParam("site") String site) {
ActionResult<ActionChangeSite.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionChangeSite().execute(effectivePerson, id, workId, site);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = ".", action = ActionEdit.class)
@PUT
@Path("edit/{id}/work/{workId}")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void edit(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
@JaxrsParameterDescribe("") @PathParam("id") String id,
@JaxrsParameterDescribe("") @PathParam("workId") String workId, JsonElement jsonElement) {
ActionResult<ActionEdit.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionEdit().execute(effectivePerson, id, workId, jsonElement);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = "Mock Get To Delete.", action = ActionEdit.class)
@POST
@Path("edit/{id}/work/{workId}/mockputtopost")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void editMockPutToPost(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
@JaxrsParameterDescribe("") @PathParam("id") String id,
@JaxrsParameterDescribe("") @PathParam("workId") String workId, JsonElement jsonElement) {
ActionResult<ActionEdit.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionEdit().execute(effectivePerson, id, workId, jsonElement);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = ".", action = ActionEdit.class)
@GET
@Path("{id}/work/{workId}/change/ordernumber/{orderNumber}")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void changeOrderNumber(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
@JaxrsParameterDescribe("") @PathParam("id") String id,
@JaxrsParameterDescribe("") @PathParam("workId") String workId,
@PathParam("orderNumber") Integer orderNumber) {
ActionResult<ActionChangeOrderNumber.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionChangeOrderNumber().execute(effectivePerson, id, workId, orderNumber);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = ".", action = ActionEditText.class)
@PUT
@Path("edit/{id}/work/{workId}/text")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void exitText(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
@JaxrsParameterDescribe("") @PathParam("id") String id,
@JaxrsParameterDescribe("") @PathParam("workId") String workId, JsonElement jsonElement) {
ActionResult<ActionEditText.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionEditText().execute(effectivePerson, id, workId, jsonElement);
} catch (Exception e) {
logger.error(e, effectivePerson, request, jsonElement);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = "Mock Get To Delete.", action = ActionEditText.class)
@POST
@Path("edit/{id}/work/{workId}/text/mockputtopost")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void exitTextMockPutToPost(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
@JaxrsParameterDescribe("") @PathParam("id") String id,
@JaxrsParameterDescribe("") @PathParam("workId") String workId, JsonElement jsonElement) {
ActionResult<ActionEditText.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionEditText().execute(effectivePerson, id, workId, jsonElement);
} catch (Exception e) {
logger.error(e, effectivePerson, request, jsonElement);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = ".", action = ActionGetText.class)
@GET
@Path("{id}/work/{workId}/text")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void getText(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
@JaxrsParameterDescribe("") @PathParam("id") String id,
@JaxrsParameterDescribe("") @PathParam("workId") String workId) {
ActionResult<ActionGetText.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionGetText().execute(effectivePerson, id, workId);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = "HTMLWord.", action = ActionDocToWord.class)
@POST
@Path("doc/to/word/work/{workId}")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void docToWord(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
@JaxrsParameterDescribe("") @PathParam("workId") String workId, JsonElement jsonElement) {
ActionResult<ActionDocToWord.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionDocToWord().execute(effectivePerson, workId, jsonElement);
} catch (Exception e) {
logger.error(e, effectivePerson, request, jsonElement);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = "HTMLWord,WorkIdWorkCompletedId.", action = ActionDocToWordWorkOrWorkCompleted.class)
@POST
@Path("doc/to/word/workorworkcompleted/{workOrWorkCompleted}")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void docToWordWorkOrWorkCompleted(@Suspended final AsyncResponse asyncResponse,
@Context HttpServletRequest request,
@JaxrsParameterDescribe("") @PathParam("workOrWorkCompleted") String workOrWorkCompleted,
JsonElement jsonElement) {
ActionResult<ActionDocToWordWorkOrWorkCompleted.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionDocToWordWorkOrWorkCompleted().execute(effectivePerson, workOrWorkCompleted,
jsonElement);
} catch (Exception e) {
logger.error(e, effectivePerson, request, jsonElement);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = "pdf,doc,docx.", action = ActionPreviewPdf.class)
@GET
@Path("{id}/preview/pdf")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void previewPdf(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
@JaxrsParameterDescribe("") @PathParam("id") String id) {
ActionResult<ActionPreviewPdf.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionPreviewPdf().execute(effectivePerson, id);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = "pdf.", action = ActionPreviewPdfResult.class)
@GET
@Path("preview/pdf/{flag}/result")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void previewPdfResult(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
@JaxrsParameterDescribe("") @PathParam("flag") String flag) {
ActionResult<ActionPreviewPdfResult.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionPreviewPdfResult().execute(effectivePerson, flag);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = "image,doc,docx", action = ActionPreviewImage.class)
@GET
@Path("{id}/preview/image/page/{page}")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void previewImage(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
@JaxrsParameterDescribe("") @PathParam("id") String id,
@JaxrsParameterDescribe("") @PathParam("page") Integer page) {
ActionResult<ActionPreviewImage.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionPreviewImage().execute(effectivePerson, id, page);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = "image.", action = ActionPreviewImageResult.class)
@GET
@Path("preview/image/{flag}/result")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void previewImageResult(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
@JaxrsParameterDescribe("") @PathParam("flag") String flag) {
ActionResult<ActionPreviewImageResult.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionPreviewImageResult().execute(effectivePerson, flag);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = "WorkWorkCompleted,stream", action = ActionBatchDownloadWithWorkOrWorkCompletedStream.class)
@GET
@Path("batch/download/work/{workId}/site/{site}/stream")
@Consumes(MediaType.APPLICATION_JSON)
public void batchDownloadWithWorkOrWorkCompletedStream(@Suspended final AsyncResponse asyncResponse,
@Context HttpServletRequest request,
@JaxrsParameterDescribe("*WorkWorkCompleted") @PathParam("workId") String workId,
@JaxrsParameterDescribe("*,~,(0)") @PathParam("site") String site,
@JaxrsParameterDescribe("") @QueryParam("fileName") String fileName,
@JaxrsParameterDescribe("uploadWorkInfoid") @QueryParam("flag") String flag) {
ActionResult<ActionBatchDownloadWithWorkOrWorkCompletedStream.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionBatchDownloadWithWorkOrWorkCompletedStream().execute(effectivePerson, workId, site,
fileName, flag);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = "WorkWorkCompleted", action = ActionBatchDownloadWithWorkOrWorkCompleted.class)
@GET
@Path("batch/download/work/{workId}/site/{site}")
@Consumes(MediaType.APPLICATION_JSON)
public void batchDownloadWithWorkOrWorkCompleted(@Suspended final AsyncResponse asyncResponse,
@Context HttpServletRequest request,
@JaxrsParameterDescribe("*WorkWorkCompleted") @PathParam("workId") String workId,
@JaxrsParameterDescribe("*,~,(0)") @PathParam("site") String site,
@JaxrsParameterDescribe("") @QueryParam("fileName") String fileName,
@JaxrsParameterDescribe("uploadWorkInfoid") @QueryParam("flag") String flag) {
ActionResult<ActionBatchDownloadWithWorkOrWorkCompleted.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionBatchDownloadWithWorkOrWorkCompleted().execute(effectivePerson, workId, site, fileName,
flag);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = "html.", action = ActionUploadWorkInfo.class)
@PUT
@Path("upload/work/{workId}/save/as/{flag}")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void uploadWorkInfo(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
@JaxrsParameterDescribe("WorkWorkCompleted") @PathParam("workId") String workId,
@JaxrsParameterDescribe("(0)|pdfpdf|wordword") @PathParam("flag") String flag,
JsonElement jsonElement) {
ActionResult<ActionUploadWorkInfo.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionUploadWorkInfo().execute(effectivePerson, workId, flag, jsonElement);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = "Mock Get To Delete.", action = ActionUploadWorkInfo.class)
@POST
@Path("upload/work/{workId}/save/as/{flag}/mockputtopost")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void uploadWorkInfoMockPutToPost(@Suspended final AsyncResponse asyncResponse,
@Context HttpServletRequest request,
@JaxrsParameterDescribe("WorkWorkCompleted") @PathParam("workId") String workId,
@JaxrsParameterDescribe("(0)|pdfpdf|wordword") @PathParam("flag") String flag,
JsonElement jsonElement) {
ActionResult<ActionUploadWorkInfo.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionUploadWorkInfo().execute(effectivePerson, workId, flag, jsonElement);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = "html", action = ActionDownloadWorkInfo.class)
@GET
@Path("download/work/{workId}/att/{flag}")
@Consumes(MediaType.APPLICATION_JSON)
public void downloadWorkInfo(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
@JaxrsParameterDescribe("*WorkWorkCompleted") @PathParam("workId") String workId,
@JaxrsParameterDescribe("*uploadWorkInfoid") @PathParam("flag") String flag) {
ActionResult<ActionDownloadWorkInfo.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionDownloadWorkInfo().execute(effectivePerson, workId, flag);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = ".", action = ActionManageBatchUpload.class)
@POST
@Path("batch/upload/manage")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.MULTIPART_FORM_DATA)
public void manageBatchUpload(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
@JaxrsParameterDescribe("") @FormDataParam("workIds") String workIds,
@JaxrsParameterDescribe("") @FormDataParam("site") String site,
@JaxrsParameterDescribe("") @FormDataParam(FILENAME_FIELD) String fileName,
@JaxrsParameterDescribe("") @FormDataParam("person") String person,
@JaxrsParameterDescribe("") @FormDataParam("orderNumber") Integer orderNumber,
@JaxrsParameterDescribe("") @FormDataParam("isSoftUpload") Boolean isSoftUpload,
@JaxrsParameterDescribe("(isSoftUploadtrue)") @FormDataParam("mainWork") String mainWork,
@JaxrsParameterDescribe("") @FormDataParam("extraParam") String extraParam,
@FormDataParam(FILE_FIELD) final byte[] bytes,
@FormDataParam(FILE_FIELD) final FormDataContentDisposition disposition) {
ActionResult<ActionManageBatchUpload.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionManageBatchUpload().execute(effectivePerson, workIds, site, fileName, bytes, disposition,
extraParam, person, orderNumber, isSoftUpload, mainWork);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = "", action = ActionManageDownload.class)
@GET
@Path("download/{id}/manage")
@Consumes(MediaType.APPLICATION_JSON)
public void manageDownload(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
@JaxrsParameterDescribe("") @PathParam("id") String id) {
ActionResult<ActionManageDownload.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionManageDownload().execute(effectivePerson, id);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = ",stream", action = ActionManageDownloadStream.class)
@GET
@Path("download/{id}/manage/stream")
@Consumes(MediaType.APPLICATION_JSON)
public void manageDownloadStream(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
@JaxrsParameterDescribe("") @PathParam("id") String id) {
ActionResult<ActionManageDownloadStream.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionManageDownloadStream().execute(effectivePerson, id);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = "htmlpdf,downloadTransfer", action = ActionHtmlToPdf.class)
@POST
@Path("html/to/pdf")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void htmlToPdf(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
JsonElement jsonElement) {
ActionResult<ActionHtmlToPdf.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionHtmlToPdf().execute(effectivePerson, jsonElement);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = "", action = ActionDownloadTransfer.class)
@GET
@Path("download/transfer/flag/{flag}")
@Consumes(MediaType.APPLICATION_JSON)
public void downloadTransfer(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
@JaxrsParameterDescribe("*id") @PathParam("flag") String flag) {
ActionResult<ActionDownloadTransfer.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionDownloadTransfer().execute(effectivePerson, flag);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = ".", action = ActionManageBatchUpdate.class)
@POST
@Path("batch/update/manage")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.MULTIPART_FORM_DATA)
public void manageBatchUpdate(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
@JaxrsParameterDescribe("Id") @FormDataParam("ids") String ids,
@JaxrsParameterDescribe("") @FormDataParam(FILENAME_FIELD) String fileName,
@JaxrsParameterDescribe("") @FormDataParam("extraParam") String extraParam,
@FormDataParam(FILE_FIELD) final byte[] bytes,
@FormDataParam(FILE_FIELD) final FormDataContentDisposition disposition) {
ActionResult<ActionManageBatchUpdate.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionManageBatchUpdate().execute(effectivePerson, ids, fileName, bytes, disposition,
extraParam);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = ".", action = ActionManageBatchDelete.class)
@POST
@Path("batch/delete/manage")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void manageBatchDelete(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
JsonElement jsonElement) {
ActionResult<ActionManageBatchDelete.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionManageBatchDelete().execute(effectivePerson, jsonElement);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = "", action = ActionUploadWithUrl.class)
@POST
@Path("upload/with/url")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void uploadWithUrl(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
JsonElement jsonElement) {
ActionResult<ActionUploadWithUrl.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionUploadWithUrl().execute(effectivePerson, jsonElement);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = "htmldownloadWithWorkdownloadTransfer.", action = ActionHtmlToImage.class)
@POST
@Path("html/to/image")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void htmlToImage(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
JsonElement jsonElement) {
ActionResult<ActionHtmlToImage.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionHtmlToImage().execute(effectivePerson, jsonElement);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = "V2_workworkCompleted,.", action = V2UploadWorkOrWorkCompleted.class)
@POST
@Path("v2/upload/workorworkcompleted/{workOrWorkCompleted}")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.MULTIPART_FORM_DATA)
public void v2UploadWorkOrWorkCompleted(FormDataMultiPart form, @Suspended final AsyncResponse asyncResponse,
@Context HttpServletRequest request,
@JaxrsParameterDescribe("") @PathParam("workOrWorkCompleted") String workOrWorkCompleted,
@JaxrsParameterDescribe("") @FormDataParam("site") String site,
@JaxrsParameterDescribe("") @FormDataParam(FILENAME_FIELD) String fileName,
@FormDataParam(FILE_FIELD) byte[] bytes,
@FormDataParam(FILE_FIELD) final FormDataContentDisposition disposition) {
ActionResult<V2UploadWorkOrWorkCompleted.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new V2UploadWorkOrWorkCompleted().execute(effectivePerson, workOrWorkCompleted, site, fileName,
bytes, disposition);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
}
|
package com.muhavision.control;
public class ExpoController {
//If it crashes it's because of this + mami ne dotike se.
public static double getExpo(int power){
if (power<0) return-(0.6 * Math.exp(-0.035*(double)power) - 0.6);
return 0.6 * Math.exp(0.035*(double)power) - 0.6;
}
}
|
package org.opencb.opencga.storage.core.variant.annotation;
import org.junit.Test;
import org.opencb.biodata.models.variant.Variant;
import org.opencb.biodata.models.variant.avro.AdditionalAttribute;
import org.opencb.biodata.models.variant.avro.ConsequenceType;
import org.opencb.biodata.models.variant.avro.VariantAnnotation;
import org.opencb.commons.datastore.core.ObjectMap;
import org.opencb.commons.datastore.core.Query;
import org.opencb.commons.datastore.core.QueryOptions;
import org.opencb.opencga.storage.core.config.StorageConfiguration;
import org.opencb.opencga.storage.core.exceptions.StorageEngineException;
import org.opencb.opencga.storage.core.metadata.ProjectMetadata;
import org.opencb.opencga.storage.core.variant.VariantStorageBaseTest;
import org.opencb.opencga.storage.core.variant.VariantStorageEngine;
import org.opencb.opencga.storage.core.variant.adaptors.VariantField;
import org.opencb.opencga.storage.core.variant.adaptors.VariantQueryParam;
import org.opencb.opencga.storage.core.variant.annotation.annotators.VariantAnnotator;
import org.opencb.opencga.storage.core.variant.annotation.annotators.VariantAnnotatorFactory;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import static org.junit.Assert.*;
import static org.opencb.opencga.storage.core.variant.adaptors.VariantField.AdditionalAttributes.GROUP_NAME;
import static org.opencb.opencga.storage.core.variant.adaptors.VariantField.AdditionalAttributes.VARIANT_ID;
import static org.opencb.opencga.storage.core.variant.annotation.VariantAnnotationManager.*;
public abstract class VariantAnnotationManagerTest extends VariantStorageBaseTest {
@Test
public void testChangeAnnotator() throws Exception {
VariantStorageEngine variantStorageEngine = getVariantStorageEngine();
runDefaultETL(smallInputUri, variantStorageEngine, newStudyConfiguration(),
new ObjectMap(VariantStorageEngine.Options.ANNOTATE.key(), false));
variantStorageEngine.getOptions()
.append(VARIANT_ANNOTATOR_CLASSNAME, TestAnnotator.class.getName())
.append(ANNOTATOR, VariantAnnotatorFactory.AnnotationSource.OTHER);
// First annotation. Should run ok.
variantStorageEngine.annotate(new Query(), new ObjectMap(TestAnnotator.ANNOT_KEY, "v1"));
assertEquals("v1", variantStorageEngine.getStudyConfigurationManager().getProjectMetadata().first().getAnnotation().getCurrent().getAnnotator().getVersion());
// Second annotation. New annotator. Overwrite. Should run ok.
variantStorageEngine.annotate(new Query(), new ObjectMap(TestAnnotator.ANNOT_KEY, "v2").append(OVERWRITE_ANNOTATIONS, true));
assertEquals("v2", variantStorageEngine.getStudyConfigurationManager().getProjectMetadata().first().getAnnotation().getCurrent().getAnnotator().getVersion());
// Third annotation. New annotator. Do not overwrite. Should fail.
thrown.expect(VariantAnnotatorException.class);
variantStorageEngine.annotate(new Query(), new ObjectMap(TestAnnotator.ANNOT_KEY, "v3").append(OVERWRITE_ANNOTATIONS, false));
}
@Test
public void testChangeAnnotatorFail() throws Exception {
VariantStorageEngine variantStorageEngine = getVariantStorageEngine();
runDefaultETL(smallInputUri, variantStorageEngine, newStudyConfiguration(),
new ObjectMap(VariantStorageEngine.Options.ANNOTATE.key(), false));
variantStorageEngine.getOptions()
.append(VARIANT_ANNOTATOR_CLASSNAME, TestAnnotator.class.getName())
.append(ANNOTATOR, VariantAnnotatorFactory.AnnotationSource.OTHER);
// First annotation. Should run ok.
variantStorageEngine.annotate(new Query(), new ObjectMap(TestAnnotator.ANNOT_KEY, "v1"));
try {
// Second annotation. New annotator. Overwrite. Fail annotation
variantStorageEngine.annotate(new Query(), new ObjectMap(TestAnnotator.ANNOT_KEY, "v2")
.append(TestAnnotator.FAIL, true)
.append(OVERWRITE_ANNOTATIONS, true));
fail("Expected to fail!");
} catch (VariantAnnotatorException e) {
e.printStackTrace();
// Annotator information does not change
assertEquals("v1", variantStorageEngine.getStudyConfigurationManager().getProjectMetadata().first().getAnnotation().getCurrent().getAnnotator().getVersion());
}
// Second annotation bis. New annotator. Overwrite.
variantStorageEngine.annotate(new Query(), new ObjectMap(TestAnnotator.ANNOT_KEY, "v2")
.append(TestAnnotator.FAIL, false)
.append(OVERWRITE_ANNOTATIONS, true));
assertEquals("v2", variantStorageEngine.getStudyConfigurationManager().getProjectMetadata().first().getAnnotation().getCurrent().getAnnotator().getVersion());
}
@Test
public void testMultiAnnotations() throws Exception {
VariantStorageEngine variantStorageEngine = getVariantStorageEngine();
runDefaultETL(smallInputUri, variantStorageEngine, newStudyConfiguration(),
new ObjectMap(VariantStorageEngine.Options.ANNOTATE.key(), false));
variantStorageEngine.getOptions()
.append(VARIANT_ANNOTATOR_CLASSNAME, TestAnnotator.class.getName())
.append(ANNOTATOR, VariantAnnotatorFactory.AnnotationSource.OTHER);
variantStorageEngine.saveAnnotation("v0", new ObjectMap());
variantStorageEngine.annotate(new Query(), new ObjectMap(TestAnnotator.ANNOT_KEY, "v1").append(OVERWRITE_ANNOTATIONS, true));
variantStorageEngine.saveAnnotation("v1", new ObjectMap());
variantStorageEngine.annotate(new Query(), new ObjectMap(TestAnnotator.ANNOT_KEY, "v2").append(OVERWRITE_ANNOTATIONS, true));
variantStorageEngine.saveAnnotation("v2", new ObjectMap());
variantStorageEngine.annotate(new Query(VariantQueryParam.REGION.key(), "1"), new ObjectMap(TestAnnotator.ANNOT_KEY, "v3").append(OVERWRITE_ANNOTATIONS, true));
assertEquals(0, variantStorageEngine.getAnnotation("v0", null, null).getResult().size());
checkAnnotationSnapshot(variantStorageEngine, "v1", "v1");
checkAnnotationSnapshot(variantStorageEngine, "v2", "v2");
checkAnnotationSnapshot(variantStorageEngine, VariantAnnotationManager.CURRENT, VariantAnnotationManager.CURRENT, "v3", new Query(VariantQueryParam.REGION.key(), "1"));
checkAnnotationSnapshot(variantStorageEngine, VariantAnnotationManager.CURRENT, "v2", "v2", new Query(VariantQueryParam.REGION.key(), "2"));
variantStorageEngine.deleteAnnotation("v1", new ObjectMap());
testQueries(variantStorageEngine);
}
public void testQueries(VariantStorageEngine variantStorageEngine) throws StorageEngineException {
long count = variantStorageEngine.count(new Query()).first();
long partialCount = 0;
int batchSize = (int) Math.ceil(count / 10.0);
for (int i = 0; i < 10; i++) {
partialCount += variantStorageEngine.getAnnotation("v2", null, new QueryOptions(QueryOptions.LIMIT, batchSize)
.append(QueryOptions.SKIP, batchSize * i)).getResult().size();
}
assertEquals(count, partialCount);
for (int chr = 1; chr < 22; chr += 2) {
Query query = new Query(VariantQueryParam.REGION.key(), chr + "," + (chr + 1));
count = variantStorageEngine.count(query).first();
partialCount = variantStorageEngine.getAnnotation("v2", query, new QueryOptions()).getResult().size();
assertEquals(count, partialCount);
}
String consequenceTypes = VariantField.ANNOTATION_CONSEQUENCE_TYPES.fieldName().replace(VariantField.ANNOTATION.fieldName() + ".", "");
for (VariantAnnotation annotation : variantStorageEngine.getAnnotation("v2", null, new QueryOptions(QueryOptions.INCLUDE, consequenceTypes)).getResult()) {
assertEquals(1, annotation.getConsequenceTypes().size());
}
for (VariantAnnotation annotation : variantStorageEngine.getAnnotation("v2", null, new QueryOptions(QueryOptions.EXCLUDE, consequenceTypes)).getResult()) {
assertTrue(annotation.getConsequenceTypes() == null || annotation.getConsequenceTypes().isEmpty());
}
// Get annotations from a deleted snapshot
thrown.expectMessage("Variant Annotation snapshot \"v1\" not found!");
assertEquals(0, variantStorageEngine.getAnnotation("v1", null, null).getResult().size());
}
public void checkAnnotationSnapshot(VariantStorageEngine variantStorageEngine, String annotationName, String expectedId) throws Exception {
checkAnnotationSnapshot(variantStorageEngine, annotationName, annotationName, expectedId, null);
}
public void checkAnnotationSnapshot(VariantStorageEngine variantStorageEngine, String annotationName, String expectedAnnotationName, String expectedId, Query query) throws Exception {
int count = 0;
for (VariantAnnotation annotation: variantStorageEngine.getAnnotation(annotationName, query, null).getResult()) {
assertEquals("an id -- " + expectedId, annotation.getId());
// assertEquals("1", annotation.getAdditionalAttributes().get("opencga").getAttribute().get("release"));
assertEquals(expectedAnnotationName, annotation.getAdditionalAttributes().get(GROUP_NAME.key())
.getAttribute().get(VariantField.AdditionalAttributes.ANNOTATION_ID.key()));
count++;
}
assertEquals(count, variantStorageEngine.count(query).first().intValue());
}
public static class TestAnnotator extends VariantAnnotator {
public static final String ANNOT_KEY = "ANNOT_KEY";
public static final String FAIL = "ANNOT_FAIL";
private final boolean fail;
private String key;
public TestAnnotator(StorageConfiguration configuration, ProjectMetadata projectMetadata, ObjectMap options) throws VariantAnnotatorException {
super(configuration, projectMetadata, options);
key = options.getString(ANNOT_KEY);
fail = options.getBoolean(FAIL, false);
}
@Override
public List<VariantAnnotation> annotate(List<Variant> variants) throws VariantAnnotatorException {
if (fail) {
throw new VariantAnnotatorException("Fail because reasons");
}
return variants.stream().map(v -> {
VariantAnnotation a = new VariantAnnotation();
a.setChromosome(v.getChromosome());
a.setStart(v.getStart());
a.setEnd(v.getEnd());
a.setReference(v.getReference());
a.setAlternate(v.getAlternate());
a.setId("an id -- " + key);
ConsequenceType ct = new ConsequenceType();
ct.setGeneName("a gene");
ct.setSequenceOntologyTerms(Collections.emptyList());
ct.setExonOverlap(Collections.emptyList());
ct.setTranscriptAnnotationFlags(Collections.emptyList());
a.setConsequenceTypes(Collections.singletonList(ct));
a.setAdditionalAttributes(
Collections.singletonMap(GROUP_NAME.key(),
new AdditionalAttribute(Collections.singletonMap(VARIANT_ID.key(), v.toString()))));
return a;
}).collect(Collectors.toList());
}
@Override
public ProjectMetadata.VariantAnnotatorProgram getVariantAnnotatorProgram() throws IOException {
return new ProjectMetadata.VariantAnnotatorProgram("MyAnnotator", key, null);
}
@Override
public List<ObjectMap> getVariantAnnotatorSourceVersion() throws IOException {
return Collections.singletonList(new ObjectMap("data", "genes"));
}
}
}
|
package org.opendaylight.controller.topologymanager.internal;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.Dictionary;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.LinkedBlockingQueue;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.felix.dm.Component;
import org.eclipse.osgi.framework.console.CommandInterpreter;
import org.eclipse.osgi.framework.console.CommandProvider;
import org.opendaylight.controller.clustering.services.CacheConfigException;
import org.opendaylight.controller.clustering.services.CacheExistException;
import org.opendaylight.controller.clustering.services.ICacheUpdateAware;
import org.opendaylight.controller.clustering.services.IClusterContainerServices;
import org.opendaylight.controller.clustering.services.IClusterServices;
import org.opendaylight.controller.configuration.IConfigurationContainerAware;
import org.opendaylight.controller.sal.core.Edge;
import org.opendaylight.controller.sal.core.Host;
import org.opendaylight.controller.sal.core.Node;
import org.opendaylight.controller.sal.core.NodeConnector;
import org.opendaylight.controller.sal.core.Property;
import org.opendaylight.controller.sal.core.TimeStamp;
import org.opendaylight.controller.sal.core.UpdateType;
import org.opendaylight.controller.sal.topology.IListenTopoUpdates;
import org.opendaylight.controller.sal.topology.ITopologyService;
import org.opendaylight.controller.sal.topology.TopoEdgeUpdate;
import org.opendaylight.controller.sal.utils.GlobalConstants;
import org.opendaylight.controller.sal.utils.IObjectReader;
import org.opendaylight.controller.sal.utils.ObjectReader;
import org.opendaylight.controller.sal.utils.ObjectWriter;
import org.opendaylight.controller.sal.utils.Status;
import org.opendaylight.controller.sal.utils.StatusCode;
import org.opendaylight.controller.topologymanager.ITopologyManager;
import org.opendaylight.controller.topologymanager.ITopologyManagerAware;
import org.opendaylight.controller.topologymanager.ITopologyManagerClusterWideAware;
import org.opendaylight.controller.topologymanager.TopologyUserLinkConfig;
import org.osgi.framework.BundleContext;
import org.osgi.framework.FrameworkUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The class describes TopologyManager which is the central repository of the
* network topology. It provides service for applications to interact with
* topology database and notifies all the listeners of topology changes.
*/
public class TopologyManagerImpl implements
ICacheUpdateAware,
ITopologyManager,
IConfigurationContainerAware,
IListenTopoUpdates,
IObjectReader,
CommandProvider {
static final String TOPOEDGESDB = "topologymanager.edgesDB";
static final String TOPOHOSTSDB = "topologymanager.hostsDB";
static final String TOPONODECONNECTORDB = "topologymanager.nodeConnectorDB";
static final String TOPOUSERLINKSDB = "topologymanager.userLinksDB";
private static final Logger log = LoggerFactory.getLogger(TopologyManagerImpl.class);
private ITopologyService topoService;
private IClusterContainerServices clusterContainerService;
// DB of all the Edges with properties which constitute our topology
private ConcurrentMap<Edge, Set<Property>> edgesDB;
// DB of all NodeConnector which are part of ISL Edges, meaning they
// are connected to another NodeConnector on the other side of an ISL link.
// NodeConnector of a Production Edge is not part of this DB.
private ConcurrentMap<NodeConnector, Set<Property>> nodeConnectorsDB;
// DB of all the NodeConnectors with an Host attached to it
private ConcurrentMap<NodeConnector, Set<ImmutablePair<Host, Set<Property>>>> hostsDB;
// Topology Manager Aware listeners
private Set<ITopologyManagerAware> topologyManagerAware = new CopyOnWriteArraySet<ITopologyManagerAware>();
// Topology Manager Aware listeners - for clusterwide updates
private Set<ITopologyManagerClusterWideAware> topologyManagerClusterWideAware =
new CopyOnWriteArraySet<ITopologyManagerClusterWideAware>();
private static String ROOT = GlobalConstants.STARTUPHOME.toString();
private String userLinksFileName;
private ConcurrentMap<String, TopologyUserLinkConfig> userLinksDB;
private BlockingQueue<TopoEdgeUpdate> notifyQ = new LinkedBlockingQueue<TopoEdgeUpdate>();
private volatile Boolean shuttingDown = false;
private Thread notifyThread;
void nonClusterObjectCreate() {
edgesDB = new ConcurrentHashMap<Edge, Set<Property>>();
hostsDB = new ConcurrentHashMap<NodeConnector, Set<ImmutablePair<Host, Set<Property>>>>();
nodeConnectorsDB = new ConcurrentHashMap<NodeConnector, Set<Property>>();
userLinksDB = new ConcurrentHashMap<String, TopologyUserLinkConfig>();
}
void setTopologyManagerAware(ITopologyManagerAware s) {
if (this.topologyManagerAware != null) {
log.debug("Adding ITopologyManagerAware: {}", s);
this.topologyManagerAware.add(s);
}
}
void unsetTopologyManagerAware(ITopologyManagerAware s) {
if (this.topologyManagerAware != null) {
log.debug("Removing ITopologyManagerAware: {}", s);
this.topologyManagerAware.remove(s);
}
}
void setTopologyManagerClusterWideAware(ITopologyManagerClusterWideAware s) {
if (this.topologyManagerClusterWideAware != null) {
log.debug("Adding ITopologyManagerClusterWideAware: {}", s);
this.topologyManagerClusterWideAware.add(s);
}
}
void unsetTopologyManagerClusterWideAware(ITopologyManagerClusterWideAware s) {
if (this.topologyManagerClusterWideAware != null) {
log.debug("Removing ITopologyManagerClusterWideAware: {}", s);
this.topologyManagerClusterWideAware.remove(s);
}
}
void setTopoService(ITopologyService s) {
log.debug("Adding ITopologyService: {}", s);
this.topoService = s;
}
void unsetTopoService(ITopologyService s) {
if (this.topoService == s) {
log.debug("Removing ITopologyService: {}", s);
this.topoService = null;
}
}
void setClusterContainerService(IClusterContainerServices s) {
log.debug("Cluster Service set");
this.clusterContainerService = s;
}
void unsetClusterContainerService(IClusterContainerServices s) {
if (this.clusterContainerService == s) {
log.debug("Cluster Service removed!");
this.clusterContainerService = null;
}
}
/**
* Function called by the dependency manager when all the required
* dependencies are satisfied
*
*/
void init(Component c) {
allocateCaches();
retrieveCaches();
String containerName = null;
Dictionary<?, ?> props = c.getServiceProperties();
if (props != null) {
containerName = (String) props.get("containerName");
} else {
// In the Global instance case the containerName is empty
containerName = "UNKNOWN";
}
userLinksFileName = ROOT + "userTopology_" + containerName + ".conf";
registerWithOSGIConsole();
loadConfiguration();
// Restore the shuttingDown status on init of the component
shuttingDown = false;
notifyThread = new Thread(new TopologyNotify(notifyQ));
}
@SuppressWarnings({ "unchecked", "deprecation" })
private void allocateCaches() {
try {
this.edgesDB =
(ConcurrentMap<Edge, Set<Property>>) this.clusterContainerService.createCache(TOPOEDGESDB,
EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
} catch (CacheExistException cee) {
log.debug(TOPOEDGESDB + " Cache already exists - destroy and recreate if needed");
} catch (CacheConfigException cce) {
log.error(TOPOEDGESDB + " Cache configuration invalid - check cache mode");
}
try {
this.hostsDB =
(ConcurrentMap<NodeConnector, Set<ImmutablePair<Host, Set<Property>>>>) this.clusterContainerService.createCache(
TOPOHOSTSDB, EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
} catch (CacheExistException cee) {
log.debug(TOPOHOSTSDB + " Cache already exists - destroy and recreate if needed");
} catch (CacheConfigException cce) {
log.error(TOPOHOSTSDB + " Cache configuration invalid - check cache mode");
}
try {
this.nodeConnectorsDB =
(ConcurrentMap<NodeConnector, Set<Property>>) this.clusterContainerService.createCache(
TOPONODECONNECTORDB, EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
} catch (CacheExistException cee) {
log.debug(TOPONODECONNECTORDB + " Cache already exists - destroy and recreate if needed");
} catch (CacheConfigException cce) {
log.error(TOPONODECONNECTORDB + " Cache configuration invalid - check cache mode");
}
try {
this.userLinksDB =
(ConcurrentMap<String, TopologyUserLinkConfig>) this.clusterContainerService.createCache(
TOPOUSERLINKSDB, EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
} catch (CacheExistException cee) {
log.debug(TOPOUSERLINKSDB + " Cache already exists - destroy and recreate if needed");
} catch (CacheConfigException cce) {
log.error(TOPOUSERLINKSDB + " Cache configuration invalid - check cache mode");
}
}
@SuppressWarnings({ "unchecked", "deprecation" })
private void retrieveCaches() {
if (this.clusterContainerService == null) {
log.error("Cluster Services is null, can't retrieve caches.");
return;
}
this.edgesDB = (ConcurrentMap<Edge, Set<Property>>) this.clusterContainerService.getCache(TOPOEDGESDB);
if (edgesDB == null) {
log.error("Failed to get cache for " + TOPOEDGESDB);
}
this.hostsDB =
(ConcurrentMap<NodeConnector, Set<ImmutablePair<Host, Set<Property>>>>) this.clusterContainerService.getCache(TOPOHOSTSDB);
if (hostsDB == null) {
log.error("Failed to get cache for " + TOPOHOSTSDB);
}
this.nodeConnectorsDB =
(ConcurrentMap<NodeConnector, Set<Property>>) this.clusterContainerService.getCache(TOPONODECONNECTORDB);
if (nodeConnectorsDB == null) {
log.error("Failed to get cache for " + TOPONODECONNECTORDB);
}
this.userLinksDB =
(ConcurrentMap<String, TopologyUserLinkConfig>) this.clusterContainerService.getCache(TOPOUSERLINKSDB);
if (userLinksDB == null) {
log.error("Failed to get cache for " + TOPOUSERLINKSDB);
}
}
/**
* Function called after the topology manager has registered the service in
* OSGi service registry.
*
*/
void started() {
// Start the batcher thread for the cluster wide topology updates
notifyThread.start();
// SollicitRefresh MUST be called here else if called at init
// time it may sollicit refresh too soon.
log.debug("Sollicit topology refresh");
topoService.sollicitRefresh();
}
void stop() {
shuttingDown = true;
notifyThread.interrupt();
}
/**
* Function called by the dependency manager when at least one dependency
* become unsatisfied or when the component is shutting down because for
* example bundle is being stopped.
*
*/
void destroy() {
notifyQ.clear();
notifyThread = null;
}
@SuppressWarnings("unchecked")
private void loadConfiguration() {
ObjectReader objReader = new ObjectReader();
ConcurrentMap<String, TopologyUserLinkConfig> confList =
(ConcurrentMap<String, TopologyUserLinkConfig>) objReader.read(this, userLinksFileName);
if (confList != null) {
for (TopologyUserLinkConfig conf : confList.values()) {
addUserLink(conf);
}
}
}
@Override
public Status saveConfig() {
return saveConfigInternal();
}
public Status saveConfigInternal() {
ObjectWriter objWriter = new ObjectWriter();
Status saveStatus = objWriter.write(
new ConcurrentHashMap<String, TopologyUserLinkConfig>(userLinksDB), userLinksFileName);
if (! saveStatus.isSuccess()) {
return new Status(StatusCode.INTERNALERROR, "Topology save failed: " + saveStatus.getDescription());
}
return saveStatus;
}
@Override
public Map<Node, Set<Edge>> getNodeEdges() {
if (this.edgesDB == null) {
return null;
}
Map<Node, Set<Edge>> res = new HashMap<Node, Set<Edge>>();
for (Edge edge : this.edgesDB.keySet()) {
// Lets analyze the tail
Node node = edge.getTailNodeConnector().getNode();
Set<Edge> nodeEdges = res.get(node);
if (nodeEdges == null) {
nodeEdges = new HashSet<Edge>();
res.put(node, nodeEdges);
}
nodeEdges.add(edge);
// Lets analyze the head
node = edge.getHeadNodeConnector().getNode();
nodeEdges = res.get(node);
if (nodeEdges == null) {
nodeEdges = new HashSet<Edge>();
res.put(node, nodeEdges);
}
nodeEdges.add(edge);
}
return res;
}
@Override
public boolean isInternal(NodeConnector p) {
if (this.nodeConnectorsDB == null) {
return false;
}
// This is an internal NodeConnector if is connected to
// another Node i.e it's part of the nodeConnectorsDB
return (this.nodeConnectorsDB.get(p) != null);
}
/**
* This method returns true if the edge is an ISL link.
*
* @param e
* The edge
* @return true if it is an ISL link
*/
public boolean isISLink(Edge e) {
return (!isProductionLink(e));
}
/**
* This method returns true if the edge is a production link.
*
* @param e
* The edge
* @return true if it is a production link
*/
public boolean isProductionLink(Edge e) {
return (e.getHeadNodeConnector().getType().equals(NodeConnector.NodeConnectorIDType.PRODUCTION)
|| e.getTailNodeConnector().getType().equals(NodeConnector.NodeConnectorIDType.PRODUCTION));
}
/**
* The Map returned is a copy of the current topology hence if the topology
* changes the copy doesn't
*
* @return A Map representing the current topology expressed as edges of the
* network
*/
@Override
public Map<Edge, Set<Property>> getEdges() {
if (this.edgesDB == null) {
return null;
}
Map<Edge, Set<Property>> edgeMap = new HashMap<Edge, Set<Property>>();
Set<Property> props;
for (Map.Entry<Edge, Set<Property>> edgeEntry : edgesDB.entrySet()) {
// Sets of props are copied because the composition of
// those properties could change with time
props = new HashSet<Property>(edgeEntry.getValue());
// We can simply reuse the key because the object is
// immutable so doesn't really matter that we are
// referencing the only owned by a different table, the
// meaning is the same because doesn't change with time.
edgeMap.put(edgeEntry.getKey(), props);
}
return edgeMap;
}
@Override
public Set<NodeConnector> getNodeConnectorWithHost() {
if (this.hostsDB == null) {
return null;
}
return (new HashSet<NodeConnector>(this.hostsDB.keySet()));
}
@Override
public Map<Node, Set<NodeConnector>> getNodesWithNodeConnectorHost() {
if (this.hostsDB == null) {
return null;
}
HashMap<Node, Set<NodeConnector>> res = new HashMap<Node, Set<NodeConnector>>();
Node node;
Set<NodeConnector> portSet;
for (NodeConnector nc : this.hostsDB.keySet()) {
node = nc.getNode();
portSet = res.get(node);
if (portSet == null) {
// Create the HashSet if null
portSet = new HashSet<NodeConnector>();
res.put(node, portSet);
}
// Keep updating the HashSet, given this is not a
// clustered map we can just update the set without
// worrying to update the hashmap.
portSet.add(nc);
}
return (res);
}
@Override
public Host getHostAttachedToNodeConnector(NodeConnector port) {
List<Host> hosts = getHostsAttachedToNodeConnector(port);
if(hosts != null && !hosts.isEmpty()){
return hosts.get(0);
}
return null;
}
@Override
public List<Host> getHostsAttachedToNodeConnector(NodeConnector p) {
Set<ImmutablePair<Host, Set<Property>>> hosts;
if (this.hostsDB == null || (hosts = this.hostsDB.get(p)) == null) {
return null;
}
// create a list of hosts
List<Host> retHosts = new LinkedList<Host>();
for(ImmutablePair<Host, Set<Property>> host : hosts) {
retHosts.add(host.getLeft());
}
return retHosts;
}
@Override
public void updateHostLink(NodeConnector port, Host h, UpdateType t, Set<Property> props) {
// Clone the property set in case non null else just
// create an empty one. Caches allocated via infinispan
// don't allow null values
if (props == null) {
props = new HashSet<Property>();
} else {
props = new HashSet<Property>(props);
}
ImmutablePair<Host, Set<Property>> thisHost = new ImmutablePair<Host, Set<Property>>(h, props);
// get the host list
Set<ImmutablePair<Host, Set<Property>>> hostSet = this.hostsDB.get(port);
if(hostSet == null) {
hostSet = new HashSet<ImmutablePair<Host, Set<Property>>>();
}
switch (t) {
case ADDED:
case CHANGED:
hostSet.add(thisHost);
this.hostsDB.put(port, hostSet);
break;
case REMOVED:
hostSet.remove(thisHost);
if(hostSet.isEmpty()) {
//remove only if hasn't been concurrently modified
this.hostsDB.remove(port, hostSet);
} else {
this.hostsDB.put(port, hostSet);
}
break;
}
}
private TopoEdgeUpdate edgeUpdate(Edge e, UpdateType type, Set<Property> props) {
switch (type) {
case ADDED:
// Make sure the props are non-null
if (props == null) {
props = new HashSet<Property>();
} else {
props = new HashSet<Property>(props);
}
//in case of node switch-over to a different cluster controller,
//let's retain edge props
Set<Property> currentProps = this.edgesDB.get(e);
if (currentProps != null){
props.addAll(currentProps);
}
// Now make sure there is the creation timestamp for the
// edge, if not there, stamp with the first update
boolean found_create = false;
for (Property prop : props) {
if (prop instanceof TimeStamp) {
TimeStamp t = (TimeStamp) prop;
if (t.getTimeStampName().equals("creation")) {
found_create = true;
break;
}
}
}
if (!found_create) {
TimeStamp t = new TimeStamp(System.currentTimeMillis(), "creation");
props.add(t);
}
// Now add this in the database eventually overriding
// something that may have been already existing
this.edgesDB.put(e, props);
// Now populate the DB of NodeConnectors
// NOTE WELL: properties are empty sets, not really needed
// for now.
// The DB only contains ISL ports
if (isISLink(e)) {
this.nodeConnectorsDB.put(e.getHeadNodeConnector(), new HashSet<Property>(1));
this.nodeConnectorsDB.put(e.getTailNodeConnector(), new HashSet<Property>(1));
}
log.trace("Edge {} {}", e.toString(), type.name());
break;
case REMOVED:
// Now remove the edge from edgesDB
this.edgesDB.remove(e);
// Now lets update the NodeConnectors DB, the assumption
// here is that two NodeConnector are exclusively
// connected by 1 and only 1 edge, this is reasonable in
// the same plug (virtual of phisical) we can assume two
// cables won't be plugged. This could break only in case
// of devices in the middle that acts as hubs, but it
// should be safe to assume that won't happen.
this.nodeConnectorsDB.remove(e.getHeadNodeConnector());
this.nodeConnectorsDB.remove(e.getTailNodeConnector());
log.trace("Edge {} {}", e.toString(), type.name());
break;
case CHANGED:
Set<Property> oldProps = this.edgesDB.get(e);
// When property changes lets make sure we can change it
// all except the creation time stamp because that should
// be changed only when the edge is destroyed and created
// again
TimeStamp timeStamp = null;
for (Property prop : oldProps) {
if (prop instanceof TimeStamp) {
TimeStamp tsProp = (TimeStamp) prop;
if (tsProp.getTimeStampName().equals("creation")) {
timeStamp = tsProp;
break;
}
}
}
// Now lets make sure new properties are non-null
if (props == null) {
props = new HashSet<Property>();
} else {
// Copy the set so noone is going to change the content
props = new HashSet<Property>(props);
}
// Now lets remove the creation property if exist in the
// new props
for (Iterator<Property> i = props.iterator(); i.hasNext();) {
Property prop = i.next();
if (prop instanceof TimeStamp) {
TimeStamp t = (TimeStamp) prop;
if (t.getTimeStampName().equals("creation")) {
i.remove();
break;
}
}
}
// Now lets add the creation timestamp in it
if (timeStamp != null) {
props.add(timeStamp);
}
// Finally update
this.edgesDB.put(e, props);
log.trace("Edge {} {}", e.toString(), type.name());
break;
}
return new TopoEdgeUpdate(e, props, type);
}
@Override
public void edgeUpdate(List<TopoEdgeUpdate> topoedgeupdateList) {
List<TopoEdgeUpdate> teuList = new ArrayList<TopoEdgeUpdate>();
for (int i = 0; i < topoedgeupdateList.size(); i++) {
Edge e = topoedgeupdateList.get(i).getEdge();
Set<Property> p = topoedgeupdateList.get(i).getProperty();
UpdateType type = topoedgeupdateList.get(i).getUpdateType();
TopoEdgeUpdate teu = edgeUpdate(e, type, p);
teuList.add(teu);
}
// Now update the listeners
for (ITopologyManagerAware s : this.topologyManagerAware) {
try {
s.edgeUpdate(teuList);
} catch (Exception exc) {
log.error("Exception on edge update:", exc);
}
}
}
private Edge getReverseLinkTuple(TopologyUserLinkConfig link) {
TopologyUserLinkConfig rLink = new TopologyUserLinkConfig(
link.getName(), link.getDstNodeConnector(), link.getSrcNodeConnector());
return getLinkTuple(rLink);
}
private Edge getLinkTuple(TopologyUserLinkConfig link) {
NodeConnector srcNodeConnector = NodeConnector.fromString(link.getSrcNodeConnector());
NodeConnector dstNodeConnector = NodeConnector.fromString(link.getDstNodeConnector());
try {
return new Edge(srcNodeConnector, dstNodeConnector);
} catch (Exception e) {
return null;
}
}
@Override
public ConcurrentMap<String, TopologyUserLinkConfig> getUserLinks() {
return new ConcurrentHashMap<String, TopologyUserLinkConfig>(userLinksDB);
}
@Override
public Status addUserLink(TopologyUserLinkConfig userLink) {
if (!userLink.isValid()) {
return new Status(StatusCode.BADREQUEST,
"User link configuration invalid.");
}
userLink.setStatus(TopologyUserLinkConfig.STATUS.LINKDOWN);
//Check if this link already configured
//NOTE: infinispan cache doesn't support Map.containsValue()
// (which is linear time in most ConcurrentMap impl anyway)
for (TopologyUserLinkConfig existingLink : userLinksDB.values()) {
if (existingLink.equals(userLink)) {
return new Status(StatusCode.CONFLICT, "Link configuration exists");
}
}
//attempt put, if mapping for this key already existed return conflict
if (userLinksDB.putIfAbsent(userLink.getName(), userLink) != null) {
return new Status(StatusCode.CONFLICT, "Link with name : " + userLink.getName()
+ " already exists. Please use another name");
}
Edge linkTuple = getLinkTuple(userLink);
if (linkTuple != null) {
if (!isProductionLink(linkTuple)) {
edgeUpdate(linkTuple, UpdateType.ADDED, new HashSet<Property>());
}
linkTuple = getReverseLinkTuple(userLink);
if (linkTuple != null) {
userLink.setStatus(TopologyUserLinkConfig.STATUS.SUCCESS);
if (!isProductionLink(linkTuple)) {
edgeUpdate(linkTuple, UpdateType.ADDED, new HashSet<Property>());
}
}
}
return new Status(StatusCode.SUCCESS);
}
@Override
public Status deleteUserLink(String linkName) {
if (linkName == null) {
return new Status(StatusCode.BADREQUEST, "User link name cannot be null.");
}
TopologyUserLinkConfig link = userLinksDB.remove(linkName);
Edge linkTuple;
if ((link != null) && ((linkTuple = getLinkTuple(link)) != null)) {
if (! isProductionLink(linkTuple)) {
edgeUpdate(linkTuple, UpdateType.REMOVED, null);
}
linkTuple = getReverseLinkTuple(link);
if (! isProductionLink(linkTuple)) {
edgeUpdate(linkTuple, UpdateType.REMOVED, null);
}
}
return new Status(StatusCode.SUCCESS);
}
private void registerWithOSGIConsole() {
BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass())
.getBundleContext();
bundleContext.registerService(CommandProvider.class.getName(), this,
null);
}
@Override
public String getHelp() {
StringBuffer help = new StringBuffer();
help.append("
help.append("\t addUserLink <name> <node connector string> <node connector string>\n");
help.append("\t deleteUserLink <name>\n");
help.append("\t printUserLink\n");
help.append("\t printNodeEdges\n");
return help.toString();
}
public void _printUserLink(CommandInterpreter ci) {
for (String name : this.userLinksDB.keySet()) {
TopologyUserLinkConfig linkConfig = userLinksDB.get(name);
ci.println("Name : " + name);
ci.println(linkConfig);
ci.println("Edge " + getLinkTuple(linkConfig));
ci.println("Reverse Edge " + getReverseLinkTuple(linkConfig));
}
}
public void _addUserLink(CommandInterpreter ci) {
String name = ci.nextArgument();
if ((name == null)) {
ci.println("Please enter a valid Name");
return;
}
String ncStr1 = ci.nextArgument();
if (ncStr1 == null) {
ci.println("Please enter two node connector strings");
return;
}
String ncStr2 = ci.nextArgument();
if (ncStr2 == null) {
ci.println("Please enter second node connector string");
return;
}
NodeConnector nc1 = NodeConnector.fromString(ncStr1);
if (nc1 == null) {
ci.println("Invalid input node connector 1 string: " + ncStr1);
return;
}
NodeConnector nc2 = NodeConnector.fromString(ncStr2);
if (nc2 == null) {
ci.println("Invalid input node connector 2 string: " + ncStr2);
return;
}
TopologyUserLinkConfig config = new TopologyUserLinkConfig(name, ncStr1, ncStr2);
ci.println(this.addUserLink(config));
}
public void _deleteUserLink(CommandInterpreter ci) {
String name = ci.nextArgument();
if ((name == null)) {
ci.println("Please enter a valid Name");
return;
}
this.deleteUserLink(name);
}
public void _printNodeEdges(CommandInterpreter ci) {
Map<Node, Set<Edge>> nodeEdges = getNodeEdges();
if (nodeEdges == null) {
return;
}
Set<Node> nodeSet = nodeEdges.keySet();
if (nodeSet == null) {
return;
}
ci.println(" Node Edge");
for (Node node : nodeSet) {
Set<Edge> edgeSet = nodeEdges.get(node);
if (edgeSet == null) {
continue;
}
for (Edge edge : edgeSet) {
ci.println(node + " " + edge);
}
}
}
@Override
public Object readObject(ObjectInputStream ois)
throws FileNotFoundException, IOException, ClassNotFoundException {
return ois.readObject();
}
@Override
public Status saveConfiguration() {
return saveConfig();
}
@Override
public void edgeOverUtilized(Edge edge) {
log.warn("Link Utilization above normal: {}", edge);
}
@Override
public void edgeUtilBackToNormal(Edge edge) {
log.warn("Link Utilization back to normal: {}", edge);
}
private void edgeUpdateClusterWide(Edge e, UpdateType type, Set<Property> props, boolean isLocal) {
TopoEdgeUpdate upd = new TopoEdgeUpdate(e, props, type);
upd.setLocal(isLocal);
notifyQ.add(upd);
}
@Override
public void entryCreated(final Object key, final String cacheName, final boolean originLocal) {
if (cacheName.equals(TOPOEDGESDB)) {
// This is the case of an Edge being added to the topology DB
final Edge e = (Edge) key;
log.trace("Edge {} CREATED isLocal:{}", e, originLocal);
edgeUpdateClusterWide(e, UpdateType.ADDED, null, originLocal);
}
}
@Override
public void entryUpdated(final Object key, final Object new_value, final String cacheName, final boolean originLocal) {
if (cacheName.equals(TOPOEDGESDB)) {
final Edge e = (Edge) key;
log.trace("Edge {} CHANGED isLocal:{}", e, originLocal);
final Set<Property> props = (Set<Property>) new_value;
edgeUpdateClusterWide(e, UpdateType.CHANGED, props, originLocal);
}
}
@Override
public void entryDeleted(final Object key, final String cacheName, final boolean originLocal) {
if (cacheName.equals(TOPOEDGESDB)) {
final Edge e = (Edge) key;
log.trace("Edge {} DELETED isLocal:{}", e, originLocal);
edgeUpdateClusterWide(e, UpdateType.REMOVED, null, originLocal);
}
}
class TopologyNotify implements Runnable {
private final BlockingQueue<TopoEdgeUpdate> notifyQ;
private TopoEdgeUpdate entry;
private List<TopoEdgeUpdate> teuList = new ArrayList<TopoEdgeUpdate>();
private boolean notifyListeners;
TopologyNotify(BlockingQueue<TopoEdgeUpdate> notifyQ) {
this.notifyQ = notifyQ;
}
@Override
public void run() {
while (true) {
try {
log.trace("New run of TopologyNotify");
notifyListeners = false;
// First we block waiting for an element to get in
entry = notifyQ.take();
// Then we drain the whole queue if elements are
// in it without getting into any blocking condition
for (; entry != null; entry = notifyQ.poll()) {
teuList.add(entry);
notifyListeners = true;
}
// Notify listeners only if there were updates drained else
// give up
if (notifyListeners) {
log.trace("Notifier thread, notified a listener");
// Now update the listeners
for (ITopologyManagerClusterWideAware s : topologyManagerClusterWideAware) {
try {
s.edgeUpdate(teuList);
} catch (Exception exc) {
log.error("Exception on edge update:", exc);
}
}
}
teuList.clear();
// Lets sleep for sometime to allow aggregation of event
Thread.sleep(100);
} catch (InterruptedException e1) {
if (shuttingDown) {
return;
}
log.warn("TopologyNotify interrupted {}", e1.getMessage());
} catch (Exception e2) {
log.error("", e2);
}
}
}
}
}
|
package com.precisionguessworks.frc;
import edu.wpi.first.wpilibj.*;
public class Robot2011 extends IterativeRobot {
private DigitalInput line1;
private DigitalInput line2;
private RobotDrive drive;
private Joystick joystick1;
private Joystick joystick2;
private int lastSeen;
private boolean left, right;
private Ultrasonic ultra;
int sample = 0;
int sampleCount = 0;
public void robotInit() {
System.out.println("Beginning robot initialization");
this.line1 = new DigitalInput(1);
this.line2 = new DigitalInput(2);
this.drive = new RobotDrive(2, 3, 4, 5);
this.joystick1 = new Joystick(1);
this.joystick2 = new Joystick(2);
this.ultra = new Ultrasonic(3, 4);
this.ultra.setAutomaticMode(true);
System.out.println("Robot initialized");
}
public void disabledPeriodic() {
}
public static final double AUTO_SPEED = -.3;
public static final double TURN_SPEED = -.25;
public static final int LEFT = 1;
public static final int RIGHT = 2;
public static final int BOTH = 3;
public void autonomousPeriodic() {
if(sampleCount == 4)
{
sample >>= 4;
}
if(sampleCount == 5)
{
sampleCount = 0;
sample = 0;
}
sample += ultra.getRangeMM();
sampleCount++;
left = !line1.get();
right = !line2.get();
if(left && right)
{
drive.setLeftRightMotorOutputs(AUTO_SPEED, AUTO_SPEED);
lastSeen = BOTH;
System.out.println("Both on");
}
else if(left)
{
drive.setLeftRightMotorOutputs(AUTO_SPEED, AUTO_SPEED);
lastSeen = LEFT;
System.out.println("1 on");
}
else if(right)
{
drive.setLeftRightMotorOutputs(AUTO_SPEED, AUTO_SPEED);
lastSeen = RIGHT;
System.out.println("2 on");
}
else
{
if(lastSeen == LEFT)
drive.setLeftRightMotorOutputs(TURN_SPEED, -TURN_SPEED);
else if(lastSeen == RIGHT)
drive.setLeftRightMotorOutputs(-TURN_SPEED, TURN_SPEED);
else
drive.setLeftRightMotorOutputs(0, 0);
System.out.println("None on");
}
}
public void teleopPeriodic() {
sample++;
if(sample == 10)
{
System.out.println("$" + ultra.getRangeMM() + "@$");
sample = 0;
}
left = !line1.get();
right = !line2.get();
if(!(joystick1.getTrigger() || joystick2.getTrigger()))
this.drive.setLeftRightMotorOutputs(joystick1.getY() / 2, joystick2.getY() / 2);
else
this.drive.setLeftRightMotorOutputs(joystick1.getY(), joystick2.getY());
// if(left && right)
// System.out.println("Both on");
// else if(left)
// System.out.println("1 on");
// else if(right)
// System.out.println("2 on");
// else
// System.out.print("None on: ");
// if(lastSeen == LEFT)
// System.out.println("left seen last");
// else if(lastSeen == RIGHT)
// System.out.println("right seen last");
}
}
|
package org.eclipse.che.ide.ext.git.server.nativegit;
import org.eclipse.che.api.core.ServerException;
import org.eclipse.che.api.git.CredentialsProvider;
import org.eclipse.che.api.git.GitException;
import org.eclipse.che.api.git.UserCredential;
import org.eclipse.che.api.git.shared.GitUser;
import org.eclipse.che.api.user.server.dao.PreferenceDao;
import org.eclipse.che.commons.env.EnvironmentContext;
import org.eclipse.che.commons.user.User;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map;
import static com.google.common.base.Strings.isNullOrEmpty;
import static org.eclipse.che.dto.server.DtoFactory.newDto;
/**
* Credentials provider for Che
*
* @author Alexander Garagatyi
* @author Valeriy Svydenko
*/
@Singleton
public class CheAccessTokenCredentialProvider implements CredentialsProvider {
private final String cheHostName;
private PreferenceDao preferenceDao;
@Inject
public CheAccessTokenCredentialProvider(@Named("api.endpoint") String apiEndPoint,
PreferenceDao preferenceDao) throws URISyntaxException {
this.preferenceDao = preferenceDao;
this.cheHostName = new URI(apiEndPoint).getHost();
}
@Override
public UserCredential getUserCredential() throws GitException {
String token = EnvironmentContext.getCurrent()
.getUser()
.getToken();
if (token != null) {
return new UserCredential(token, "x-che", "che");
}
return null;
}
@Override
public GitUser getUser() throws GitException {
User user = EnvironmentContext.getCurrent().getUser();
GitUser gitUser = newDto(GitUser.class);
if (user.isTemporary()) {
gitUser.setEmail("anonymous@noemail.com");
gitUser.setName("Anonymous");
} else {
String name = null;
String email = null;
try {
Map<String, String> preferences = preferenceDao.getPreferences(EnvironmentContext.getCurrent().getUser().getId(),
"git.committer.\\w+");
name = preferences.get("git.committer.name");
email = preferences.get("git.committer.email");
} catch (ServerException e) {
//ignored
}
gitUser.setName(isNullOrEmpty(name) ? "Anonymous" : name);
gitUser.setEmail(isNullOrEmpty(email) ? "anonymous@noemail.com" : email);
}
return gitUser;
}
@Override
public String getId() {
return "che";
}
@Override
public boolean canProvideCredentials(String url) {
return url.contains(cheHostName);
}
}
|
package com.rapid.server;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.rapid.core.Application.RapidLoadingException;
import com.rapid.core.Applications;
import com.rapid.core.Applications.Versions;
import com.rapid.server.filter.RapidFilter;
public class RapidSessionListener implements HttpSessionListener {
private static Map<String, HttpSession> _sessions;
private Logger _logger;
public RapidSessionListener() {
// instantiate the concurrent hash map which should make it thread safe, alternatively there is the Collections.synchronizedMap
_sessions = new ConcurrentHashMap<String,HttpSession>() ;
}
@Override
public void sessionCreated(HttpSessionEvent event) {
HttpSession session = event.getSession();
String sessionId = session.getId();
_sessions.put(sessionId, session);
if (_logger == null) _logger = LogManager.getLogger(this.getClass());
_logger.debug("Session created " + sessionId);
}
@Override
public void sessionDestroyed(HttpSessionEvent event) {
HttpSession session = event.getSession();
String userName = (String) session.getAttribute(RapidFilter.SESSION_VARIABLE_USER_NAME);
if (_logger == null) _logger = LogManager.getLogger(this.getClass());
_logger.debug("Destroying session " + session.getId() + " for " + userName);
if (userName != null) {
ServletContext servletContext = session.getServletContext();
Applications applications = (Applications) servletContext.getAttribute("applications");
if (applications != null) {
for (String appId : applications.getIds()) {
Versions versions = applications.getVersions(appId);
for (String versionId : versions.keySet()) {
try {
if (versions.get(versionId).removeUserPageLocks(servletContext, userName) > 0) {
_logger.debug("Removed page locks from " + userName + " for " + appId + "/" + versionId);
}
} catch (RapidLoadingException ex) {
_logger.error("Error removing page locks for " + appId + "/" + versionId + " from " + session.getId(), ex);
}
}
}
}
}
_sessions.remove(session.getId());
_logger.debug("Session destroyed " + session.getId());
}
public synchronized static HttpSession getSession(String sessionId) {
if (_sessions == null) {
return null;
} else {
return _sessions.get(sessionId);
}
}
public synchronized static Map<String,HttpSession> getSessions() {
return _sessions;
}
public synchronized static int getTotalSessionCount() {
if (_sessions == null) {
return -1;
} else {
Map<String,HttpSession> sessions = Collections.synchronizedMap(_sessions);
return sessions.size();
}
}
}
|
package com.opengamma.financial.analytics.volatility.surface;
import it.unimi.dsi.fastutil.doubles.DoubleArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.threeten.bp.LocalDate;
import org.threeten.bp.ZonedDateTime;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.opengamma.OpenGammaRuntimeException;
import com.opengamma.analytics.financial.model.interestrate.curve.ForwardCurve;
import com.opengamma.analytics.financial.model.interestrate.curve.YieldCurve;
import com.opengamma.analytics.financial.model.volatility.BlackFormulaRepository;
import com.opengamma.core.config.ConfigSource;
import com.opengamma.core.id.ExternalSchemes;
import com.opengamma.core.marketdatasnapshot.VolatilitySurfaceData;
import com.opengamma.engine.ComputationTarget;
import com.opengamma.engine.ComputationTargetSpecification;
import com.opengamma.engine.function.AbstractFunction;
import com.opengamma.engine.function.FunctionCompilationContext;
import com.opengamma.engine.function.FunctionExecutionContext;
import com.opengamma.engine.function.FunctionInputs;
import com.opengamma.engine.target.ComputationTargetType;
import com.opengamma.engine.value.ComputedValue;
import com.opengamma.engine.value.ValueProperties;
import com.opengamma.engine.value.ValuePropertyNames;
import com.opengamma.engine.value.ValueRequirement;
import com.opengamma.engine.value.ValueRequirementNames;
import com.opengamma.engine.value.ValueSpecification;
import com.opengamma.financial.OpenGammaCompilationContext;
import com.opengamma.financial.analytics.model.FutureOptionExpiries;
import com.opengamma.financial.analytics.model.InstrumentTypeProperties;
import com.opengamma.financial.analytics.model.curve.forward.ForwardCurveValuePropertyNames;
import com.opengamma.financial.analytics.model.equity.EquitySecurityUtils;
import com.opengamma.id.ExternalId;
import com.opengamma.id.ExternalIdentifiable;
import com.opengamma.id.ExternalScheme;
import com.opengamma.id.UniqueId;
import com.opengamma.util.money.Currency;
import com.opengamma.util.tuple.Pair;
public class EquityOptionVolatilitySurfaceDataFunction extends AbstractFunction.NonCompiledInvoker {
/** The logger */
private static final Logger s_logger = LoggerFactory.getLogger(EquityOptionVolatilitySurfaceDataFunction.class);
private static final Set<ExternalScheme> s_validSchemes = ImmutableSet.of(ExternalSchemes.BLOOMBERG_TICKER, ExternalSchemes.BLOOMBERG_TICKER_WEAK, ExternalSchemes.ACTIVFEED_TICKER);
@Override
/**
* {@inheritDoc} <p>
* INPUT: We are taking a VolatilitySurfaceData object, which contains all number of missing data, plus strikes and vols are in percentages <p>
* OUTPUT: and converting this into a StandardVolatilitySurfaceData object, which has no empty values, expiry is in years, and the strike and vol scale is without unit (35% -> 0.35)
*/
public Set<ComputedValue> execute(final FunctionExecutionContext executionContext, final FunctionInputs inputs, final ComputationTarget target, final Set<ValueRequirement> desiredValues) {
final ZonedDateTime valTime = ZonedDateTime.now(executionContext.getValuationClock());
final LocalDate valDate = valTime.toLocalDate();
final ValueRequirement desiredValue = Iterables.getOnlyElement(desiredValues);
final Object specificationObject = inputs.getValue(ValueRequirementNames.VOLATILITY_SURFACE_SPEC);
if (specificationObject == null) {
throw new OpenGammaRuntimeException("Could not get volatility surface specification");
}
final VolatilitySurfaceSpecification specification = (VolatilitySurfaceSpecification) specificationObject;
final String surfaceQuoteUnits = specification.getQuoteUnits();
// Get the volatility surface data object
final Object rawSurfaceObject = inputs.getValue(ValueRequirementNames.VOLATILITY_SURFACE_DATA);
if (rawSurfaceObject == null) {
throw new OpenGammaRuntimeException("Could not get volatility surface");
}
@SuppressWarnings("unchecked")
final VolatilitySurfaceData<Number, Double> rawSurface = (VolatilitySurfaceData<Number, Double>) rawSurfaceObject;
final VolatilitySurfaceData<Double, Double> stdVolSurface;
if (surfaceQuoteUnits.equals(SurfaceAndCubePropertyNames.VOLATILITY_QUOTE)) {
stdVolSurface = getSurfaceFromVolatilityQuote(valDate, rawSurface);
} else if (surfaceQuoteUnits.equals(SurfaceAndCubePropertyNames.PRICE_QUOTE)) {
// Get the discount curve
final Object discountCurveObject = inputs.getValue(ValueRequirementNames.YIELD_CURVE);
if (discountCurveObject == null) {
throw new OpenGammaRuntimeException("Could not get discount curve");
}
final YieldCurve discountCurve = (YieldCurve) discountCurveObject;
// Get the forward curve
final Object forwardCurveObject = inputs.getValue(ValueRequirementNames.FORWARD_CURVE);
if (forwardCurveObject == null) {
throw new OpenGammaRuntimeException("Could not get forward curve");
}
final ForwardCurve forwardCurve = (ForwardCurve) forwardCurveObject;
stdVolSurface = getSurfaceFromPriceQuote(valDate, rawSurface, forwardCurve, discountCurve, specification);
} else {
throw new OpenGammaRuntimeException("Cannot handle quote units " + surfaceQuoteUnits);
}
// Return
final ValueProperties constraints = desiredValue.getConstraints().copy()
.with(ValuePropertyNames.FUNCTION, getUniqueId())
.get();
final ValueSpecification stdVolSpec = new ValueSpecification(ValueRequirementNames.STANDARD_VOLATILITY_SURFACE_DATA,
target.toSpecification(), constraints);
return Collections.singleton(new ComputedValue(stdVolSpec, stdVolSurface));
}
@Override
public ComputationTargetType getTargetType() {
return ComputationTargetType.PRIMITIVE; // Bloomberg ticker, weak ticker or Activ ticker
}
@Override
public boolean canApplyTo(final FunctionCompilationContext context, final ComputationTarget target) {
if (target.getValue() instanceof ExternalIdentifiable) {
final ExternalId identifier = ((ExternalIdentifiable) target.getValue()).getExternalId();
return s_validSchemes.contains(identifier.getScheme());
}
return false;
}
@Override
public Set<ValueSpecification> getResults(final FunctionCompilationContext context, final ComputationTarget target) {
final ValueProperties properties = ValueProperties.all();
final ValueSpecification spec = new ValueSpecification(ValueRequirementNames.STANDARD_VOLATILITY_SURFACE_DATA, target.toSpecification(),
properties);
return Collections.singleton(spec);
}
@Override
public Set<ValueRequirement> getRequirements(final FunctionCompilationContext context, final ComputationTarget target, final ValueRequirement desiredValue) {
// Function requires a VolatilitySurfaceData
// Build the surface name, in two parts: the given name and the target
final ValueProperties constraints = desiredValue.getConstraints();
final Set<String> instrumentTypes = constraints.getValues(InstrumentTypeProperties.PROPERTY_SURFACE_INSTRUMENT_TYPE);
if (instrumentTypes != null && instrumentTypes.size() == 1) {
if (!Iterables.getOnlyElement(instrumentTypes).equals(InstrumentTypeProperties.EQUITY_OPTION)) {
return null;
}
}
final Set<String> surfaceNames = constraints.getValues(ValuePropertyNames.SURFACE);
if (surfaceNames == null || surfaceNames.size() != 1) {
s_logger.error("Function takes only get a single surface. Asked for {}", surfaceNames);
return null;
}
final String givenName = Iterables.getOnlyElement(surfaceNames);
//FIXME: Modify to take ExternalId to avoid incorrect cast to UniqueId
final String fullName = givenName + "_" + EquitySecurityUtils.getTrimmedTarget(UniqueId.parse(target.getValue().toString()));
final ConfigSource configSource = OpenGammaCompilationContext.getConfigSource(context);
final ConfigDBVolatilitySurfaceSpecificationSource volSpecSource = new ConfigDBVolatilitySurfaceSpecificationSource(configSource);
final VolatilitySurfaceSpecification specification = volSpecSource.getSpecification(fullName, InstrumentTypeProperties.EQUITY_OPTION);
if (specification == null) {
s_logger.error("Could not get volatility surface specification with name " + fullName);
return null;
}
// Build the ValueRequirements' constraints
final String quoteUnits = specification.getQuoteUnits();
final ValueProperties properties = ValueProperties.builder()
.with(ValuePropertyNames.SURFACE, givenName)
.with(InstrumentTypeProperties.PROPERTY_SURFACE_INSTRUMENT_TYPE, InstrumentTypeProperties.EQUITY_OPTION)
.with(SurfaceAndCubePropertyNames.PROPERTY_SURFACE_QUOTE_TYPE, specification.getSurfaceQuoteType())
.with(SurfaceAndCubePropertyNames.PROPERTY_SURFACE_UNITS, quoteUnits)
.get();
final ValueRequirement surfaceReq = new ValueRequirement(ValueRequirementNames.VOLATILITY_SURFACE_DATA, target.toSpecification(), properties);
final ValueRequirement specificationReq = new ValueRequirement(ValueRequirementNames.VOLATILITY_SURFACE_SPEC, target.toSpecification(), properties);
final Set<ValueRequirement> requirements = new HashSet<>();
requirements.add(surfaceReq);
requirements.add(specificationReq);
if (quoteUnits.equals(SurfaceAndCubePropertyNames.PRICE_QUOTE)) {
// We require forward and discount curves to imply the volatility
final Set<String> curveNameValues = constraints.getValues(ValuePropertyNames.CURVE);
if (curveNameValues == null || curveNameValues.size() != 1) {
return null;
}
final Set<String> curveCalculationValues = constraints.getValues(ValuePropertyNames.CURVE_CALCULATION_CONFIG);
if (curveCalculationValues == null || curveCalculationValues.size() != 1) {
return null;
}
final Set<String> curveCurrencyValues = constraints.getValues(ValuePropertyNames.CURVE_CURRENCY);
if (curveCurrencyValues == null || curveCurrencyValues.size() != 1) {
return null;
}
final String curveName = Iterables.getOnlyElement(curveNameValues);
final String curveCalculationConfig = Iterables.getOnlyElement(curveCalculationValues);
final Currency ccy = Currency.of(Iterables.getOnlyElement(curveCurrencyValues));
// DiscountCurve
final ValueProperties fundingProperties = ValueProperties.builder() // Note that createValueProperties is _not_ used - otherwise engine can't find the requirement
.with(ValuePropertyNames.CURVE, curveName)
.with(ValuePropertyNames.CURVE_CALCULATION_CONFIG, curveCalculationConfig)
.get();
final ValueRequirement discountCurveRequirement = new ValueRequirement(ValueRequirementNames.YIELD_CURVE, ComputationTargetSpecification.of(ccy), fundingProperties);
requirements.add(discountCurveRequirement);
// ForwardCurve
final String curveCalculationMethod = ForwardCurveValuePropertyNames.PROPERTY_YIELD_CURVE_IMPLIED_METHOD; // TODO Remove hard-coding of forward curve calculation method by adding as property
final ValueProperties curveProperties = ValueProperties.builder()
.with(ValuePropertyNames.CURVE, curveName)
.with(ForwardCurveValuePropertyNames.PROPERTY_FORWARD_CURVE_CALCULATION_METHOD, curveCalculationMethod)
.get();
final ValueRequirement forwardCurveRequirement = new ValueRequirement(ValueRequirementNames.FORWARD_CURVE, target.toSpecification(), curveProperties);
requirements.add(forwardCurveRequirement);
}
return requirements;
}
@Override
public Set<ValueSpecification> getResults(final FunctionCompilationContext context, final ComputationTarget target, final Map<ValueSpecification, ValueRequirement> inputs) {
final ValueProperties.Builder properties = createValueProperties()
.with(InstrumentTypeProperties.PROPERTY_SURFACE_INSTRUMENT_TYPE, InstrumentTypeProperties.EQUITY_OPTION);
boolean surfaceNameSet = false;
for (final Map.Entry<ValueSpecification, ValueRequirement> entry : inputs.entrySet()) {
final ValueSpecification key = entry.getKey();
if (key.getValueName().equals(ValueRequirementNames.VOLATILITY_SURFACE_DATA)) {
properties.with(ValuePropertyNames.SURFACE, key.getProperty(ValuePropertyNames.SURFACE));
surfaceNameSet = true;
} else if (key.getValueName().equals(ValueRequirementNames.FORWARD_CURVE)) {
final ValueProperties curveProperties = key.getProperties().copy()
.withoutAny(ValuePropertyNames.FUNCTION)
.get();
for (final String property : curveProperties.getProperties()) {
properties.with(property, curveProperties.getValues(property));
}
//don't check if forward curve is set, because it isn't needed if the quotes are volatility
}
}
assert surfaceNameSet;
return Collections.singleton(new ValueSpecification(ValueRequirementNames.STANDARD_VOLATILITY_SURFACE_DATA, target.toSpecification(), properties.get()));
}
private static VolatilitySurfaceData<Double, Double> getSurfaceFromVolatilityQuote(final LocalDate valDate, final VolatilitySurfaceData<Number, Double> rawSurface) {
// Remove empties, convert expiries from number to years, and scale vols
final Map<Pair<Double, Double>, Double> volValues = new HashMap<>();
final DoubleArrayList tList = new DoubleArrayList();
final DoubleArrayList kList = new DoubleArrayList();
Number[] xAsNumbers = getXs(rawSurface.getXs());
for (final Number nthExpiry : xAsNumbers) {
final Double t = FutureOptionExpiries.EQUITY.getFutureOptionTtm(nthExpiry.intValue(), valDate);
if (t > 5. / 365.) { // Bootstrapping vol surface to this data causes far more trouble than any gain. The data simply isn't reliable.
Double[] ysAsDoubles = getYs(rawSurface.getYs());
for (final Double strike : ysAsDoubles) {
final Double vol = rawSurface.getVolatility(nthExpiry, strike);
if (vol != null) {
tList.add(t);
kList.add(strike);
volValues.put(Pair.of(t, strike), vol / 100.);
}
}
}
}
final VolatilitySurfaceData<Double, Double> stdVolSurface = new VolatilitySurfaceData<>(rawSurface.getDefinitionName(), rawSurface.getSpecificationName(), rawSurface.getTarget(),
tList.toArray(new Double[0]), kList.toArray(new Double[0]), volValues);
return stdVolSurface;
}
private static VolatilitySurfaceData<Double, Double> getSurfaceFromPriceQuote(final LocalDate valDate, final VolatilitySurfaceData<Number, Double> rawSurface,
final ForwardCurve forwardCurve, final YieldCurve discountCurve, final VolatilitySurfaceSpecification specification) {
final String surfaceQuoteType = specification.getSurfaceQuoteType();
double callAboveStrike = 0;
if (specification.getSurfaceInstrumentProvider() instanceof CallPutSurfaceInstrumentProvider) {
callAboveStrike = ((CallPutSurfaceInstrumentProvider<?, ?>) specification.getSurfaceInstrumentProvider()).useCallAboveStrike();
}
// Remove empties, convert expiries from number to years, and imply vols
final Map<Pair<Double, Double>, Double> volValues = new HashMap<>();
final DoubleArrayList tList = new DoubleArrayList();
final DoubleArrayList kList = new DoubleArrayList();
Number[] xAsNumbers = getXs(rawSurface.getXs());
for (final Number nthExpiry : xAsNumbers) {
final Double t = FutureOptionExpiries.EQUITY.getFutureOptionTtm(nthExpiry.intValue(), valDate);
final double forward = forwardCurve.getForward(t);
final double zerobond = discountCurve.getDiscountFactor(t);
if (t > 5. / 365.) { // Bootstrapping vol surface to this data causes far more trouble than any gain. The data simply isn't reliable.
Double[] ysAsDoubles = getYs(rawSurface.getYs());
for (final Double strike : ysAsDoubles) {
final Double price = rawSurface.getVolatility(nthExpiry, strike);
if (price != null) {
final double fwdPrice = price / zerobond;
try {
final double vol;
if (surfaceQuoteType.equals(SurfaceAndCubeQuoteType.CALL_STRIKE)) {
vol = BlackFormulaRepository.impliedVolatility(fwdPrice, forward, strike, t, true);
} else if (surfaceQuoteType.equals(SurfaceAndCubeQuoteType.PUT_STRIKE)) {
vol = BlackFormulaRepository.impliedVolatility(fwdPrice, forward, strike, t, false);
} else if (surfaceQuoteType.equals(SurfaceAndCubeQuoteType.CALL_AND_PUT_STRIKE)) {
final boolean isCall = strike > callAboveStrike ? true : false;
vol = BlackFormulaRepository.impliedVolatility(fwdPrice, forward, strike, t, isCall);
} else {
throw new OpenGammaRuntimeException("Cannot handle surface quote type " + surfaceQuoteType);
}
tList.add(t);
kList.add(strike);
volValues.put(Pair.of(t, strike), vol);
} catch (final Exception e) {
}
}
}
}
}
final VolatilitySurfaceData<Double, Double> stdVolSurface = new VolatilitySurfaceData<>(rawSurface.getDefinitionName(), rawSurface.getSpecificationName(), rawSurface.getTarget(),
tList.toArray(new Double[0]), kList.toArray(new Double[0]), volValues);
return stdVolSurface;
}
//TODO
private static Number[] getXs(Object xs) {
if (xs instanceof Number[]) {
return (Number[]) xs;
}
Object[] tempArray = (Object[]) xs;
final Number[] result = new Number[tempArray.length];
for (int i = 0; i < tempArray.length; i++) {
result[i] = (Number) tempArray[i];
}
return result;
}
private static Double[] getYs(Object ys) {
if (ys instanceof Double[]) {
return (Double[]) ys;
}
Object[] tempArray = (Object[]) ys;
final Double[] result = new Double[tempArray.length];
for (int i = 0; i < tempArray.length; i++) {
result[i] = (Double) tempArray[i];
}
return result;
}
}
|
package restaurant_rancho.gui;
import agent_rancho.Agent;
import restaurant_rancho.CashierAgent;
import restaurant_rancho.CookAgent;
import restaurant_rancho.CustomerAgent;
import restaurant_rancho.HostAgent;
import restaurant_rancho.WaiterAgent;
import bank.gui.Bank;
import simcity.PersonAgent;
import simcity.gui.SimCityGui;
import simcity.RestMenu;
import simcity.Restaurant;
import javax.swing.*;
import market.Market;
import java.awt.*;
import java.util.List;
import java.util.ArrayList;
import java.util.Hashtable;
/**
* Panel in frame that contains all the restaurant information,
* including host, cook, waiters, and customers.
*/
public class RestaurantRancho extends JPanel implements Restaurant {
private static final long serialVersionUID = 1L;
//Host, cook, waiters and customers
String name;
String type;
Bank bank;
Market market;
private Hashtable<PersonAgent, CustomerAgent> returningCusts = new Hashtable<PersonAgent, CustomerAgent>();
private HostAgent host;
private CookAgent cook;
private CashierAgent cashier;
private List<WaiterAgent> waiters = new ArrayList<WaiterAgent>();
private List<CustomerAgent> customers = new ArrayList<CustomerAgent>();
private JPanel restLabel = new JPanel();
private ListPanel customerPanel = new ListPanel(this, "Customers");
private ListPanel waiterPanel = new ListPanel (this, "Waiters");
private JPanel group = new JPanel();
private RestMenu menu = new RestMenu();
boolean isOpen;
private SimCityGui gui;
private CookGui cookgui;
public RestaurantRancho(SimCityGui g, String n) {
name = n;
type = "Mexican";
this.gui = g;
menu.addItem("Citrus Fire-Grilled Chicken", 13.49);
menu.addItem("Red Chile Enchilada Platter", 9.99);
menu.addItem("Soft Tacos Monterrey", 10.99);
menu.addItem("Burrito Sonora", 10.99);
menu.addItem("Chicken Tortilla Soup", 5.99);
setLayout(new GridLayout(1, 2, 20, 20));
group.setLayout(new BoxLayout(group, BoxLayout.Y_AXIS));
group.add(customerPanel);
group.add(waiterPanel);
add(restLabel);
add(group);
}
public SimCityGui getGui() {
return gui;
}
public void setBank(Bank b) {
bank = b;
if (cashier!=null) setBank(b);
}
public boolean isOpen() {
return (cook!=null && waiters.size()>0 && cashier!=null && host!=null);
}
public RestMenu getMenu() {
return menu;
}
public String getRestaurantName() { return name; }
public String getType() { return type; }
// public void personAs(String type, String name, PersonAgent p) {
public void personAs(PersonAgent p, String type, String name, double money){
addPerson(p, type, name, money);
}
public void PauseandUnpauseAgents() {
for (WaiterAgent w : waiters) {
w.pauseOrRestart();
}
for (CustomerAgent c : customers) {
c.pauseOrRestart();
}
cook.pauseOrRestart();
host.pauseOrRestart();
cashier.pauseOrRestart();
}
public void waiterWantsBreak(WaiterAgent w) {
host.msgWantBreak(w);
}
public void waiterWantsOffBreak(WaiterAgent w) {
host.msgBackFromBreak(w);
}
/**
* Sets up the restaurant label that includes the menu,
* and host and cook information
*/
private void initRestLabel() {
JLabel label = new JLabel();
restLabel.setLayout(new BorderLayout());
label.setText(
"<html><h3><u>Tonight's Staff</u></h3><table><tr><td>host:</td><td>" + host.getName() + "</td></tr></table><h3><u> Menu</u></h3><table><tr><td>Steak</td><td>$14.50</td></tr><tr><td>Chicken</td><td>$12.50</td></tr><tr><td>Salad</td><td>$7.50</td></tr><tr><td>Pizza</td><td>$10.50</td></tr><tr><td>Latte</td><td>$3.25</td></tr></table><br></html>");
label.setFont(new Font("Helvetica", Font.PLAIN, 13));
restLabel.setBorder(BorderFactory.createRaisedBevelBorder());
restLabel.add(label, BorderLayout.CENTER);
restLabel.add(new JLabel(" "), BorderLayout.EAST);
restLabel.add(new JLabel(" "), BorderLayout.WEST);
}
/**
* When a customer or waiter is clicked, this function calls
* updatedInfoPanel() from the main gui so that person's information
* will be shown
*
* @param type indicates whether the person is a customer or waiter
* @param name name of person
*/
/*
public void showInfo(String type, String name) {
if (type.equals("Customer")) {
for (int i = 0; i < customers.size(); i++) {
CustomerAgent temp = customers.get(i);
//if (temp.getName() == name)
// gui.updateInfoPanel(temp);
}
}
if (type.equals("Waiter")) {
for (int i = 0; i < waiters.size(); i++) {
WaiterAgent temp = waiters.get(i);
if(temp.getName() == name) {
gui.updateWInfoPanel(temp);
}
}
}
}
*/
/**
* Adds a customer or waiter to the appropriate list
*
* @param type indicates whether the person is a customer or waiter (later)
* @param name name of person
*/
public void addPerson(PersonAgent p, String type, String name, double money) {
if (type.equals("Customer")) {
//if ((p!=null) && returningCusts.containsKey(p)) {
// returningCusts.get(p).getGui().setHungry();
//else {
CustomerAgent c = new CustomerAgent(name);
CustomerGui g = new CustomerGui(c, gui, customers.size());
if (p!=null) c.setPerson(p);
//returningCusts.put(p, c);
g.setHungry();
gui.ranchoAniPanel.addGui(g);
if (host!=null) c.setHost(host);
c.setGui(g);
if (cashier!=null) c.setCashier(cashier);
c.setCash(money);
customers.add(c);
c.startThread();
g.updatePosition();
}
else if (type.equals("Waiter")) {
WaiterAgent w = new WaiterAgent(name, this);
WaiterGui g = new WaiterGui(w, waiters.size());
if (p!=null) w.setPerson(p);
gui.ranchoAniPanel.addGui(g);
if (host!=null) w.setHost(host);
if (cook!= null) w.setCook(cook);
if (cashier!=null)w.setCashier(cashier);
if (host!=null) host.addWaiter(w);
w.setGui(g);
waiters.add(w);
w.startThread();
g.updatePosition();
}
else if (type.equals("Host")) {
if (host == null) {
host = new HostAgent(name);
if (p!=null) host.setPerson(p);
host.startThread();
initRestLabel();
for (WaiterAgent w : waiters) {
host.addWaiter(w);
w.setHost(host);
}
}
}
else if (type.equals("Cook")) {
if (cook == null) {
System.out.println("heyo market is " + market.getName());
cook = new CookAgent(name, this, market);
cookgui = new CookGui(cook);
if (p!=null) cook.setPerson(p);
cook.setGui(cookgui);
//cookgui.updatePosition();
for (WaiterAgent w : waiters) {
w.setCook(cook);
}
gui.ranchoAniPanel.addGui(cookgui);
cook.startThread();
}
}
else if (type.equals("Cashier")) {
if (cashier == null) {
cashier = new CashierAgent(name);
if (p!=null) cashier.setPerson(p);
if (bank!=null) cashier.setBank(bank);
if (market!=null) cashier.setMarket(market);
for (WaiterAgent w : waiters) {
w.setCashier(cashier);
}
cashier.startThread();
}
}
}
@Override
public void setMarket(Market m) {
market = m;
System.out.println("heyo" + "market is " + market.getName());
if (cashier!=null) {
cashier.setMarket(m);
}
if (cook!=null) {
cook.setMarket(m);
}
}
@Override
public void msgHereIsOrder(String food, int quantity, int ID) {
cook.msgHereIsOrder(food, quantity, ID);
}
}
|
package com.speedment.runtime.connector.sqlite.internal;
import com.speedment.common.injector.Injector;
import com.speedment.common.injector.State;
import com.speedment.common.injector.annotation.ExecuteBefore;
import com.speedment.common.injector.annotation.Inject;
import com.speedment.common.logger.Logger;
import com.speedment.common.logger.LoggerManager;
import com.speedment.runtime.config.*;
import com.speedment.runtime.config.mutator.ForeignKeyColumnMutator;
import com.speedment.runtime.config.mutator.IndexMutator;
import com.speedment.runtime.config.trait.HasId;
import com.speedment.runtime.config.util.DocumentDbUtil;
import com.speedment.runtime.config.util.DocumentUtil;
import com.speedment.runtime.connector.sqlite.internal.types.SqlTypeMappingHelper;
import com.speedment.runtime.connector.sqlite.internal.util.MetaDataUtil;
import com.speedment.runtime.core.component.ProjectComponent;
import com.speedment.runtime.core.component.connectionpool.ConnectionPoolComponent;
import com.speedment.runtime.core.db.DatabaseNamingConvention;
import com.speedment.runtime.core.db.DbmsMetadataHandler;
import com.speedment.runtime.core.db.JavaTypeMap;
import com.speedment.runtime.core.db.SqlFunction;
import com.speedment.runtime.core.db.SqlPredicate;
import com.speedment.runtime.core.db.SqlSupplier;
import com.speedment.runtime.core.db.metadata.ColumnMetaData;
import com.speedment.runtime.core.exception.SpeedmentException;
import com.speedment.runtime.core.util.ProgressMeasure;
import com.speedment.runtime.typemapper.TypeMapper;
import com.speedment.runtime.typemapper.primitive.PrimitiveTypeMapper;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.StringJoiner;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import static com.speedment.common.invariant.NullUtil.requireNonNulls;
import static com.speedment.runtime.connector.sqlite.internal.util.LoggingUtil.describe;
import static com.speedment.runtime.connector.sqlite.internal.util.MetaDataUtil.getOrderType;
import static com.speedment.runtime.connector.sqlite.internal.util.MetaDataUtil.isAutoIncrement;
import static com.speedment.runtime.connector.sqlite.internal.util.MetaDataUtil.isWrapper;
import static com.speedment.runtime.core.internal.db.AbstractDbmsOperationHandler.SHOW_METADATA;
import static java.lang.String.format;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toCollection;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toSet;
/**
* Implementation of {@link DbmsMetadataHandler} for SQLite databases.
*
* @author Emil Forslund
* @since 3.1.10
*/
public final class SqliteMetadataHandler implements DbmsMetadataHandler {
private final static Logger LOGGER = LoggerManager.getLogger(SqliteMetadataHandler.class);
private final static String[] TABLES_AND_VIEWS = {"TABLE", "VIEW"};
private final static String ORIGINAL_TYPE = "originalDatabaseType";
private final static Pattern BINARY_TYPES = Pattern.compile(
"^(?:(?:TINY|MEDIUM|LONG)?\\s?BLOB|(?:VAR)?BINARY)(?:\\(\\d+\\))?$");
private final static Pattern INTEGER_BOOLEAN_TYPE = Pattern.compile(
"^(?:BIT|INT|INTEGER|TINYINT)\\(1\\)$");
private final static Pattern BIT_TYPES = Pattern.compile(
"^BIT\\((\\d+)\\)$");
private final static Pattern SHORT_TYPES = Pattern.compile(
"^(?:UNSIGNED\\s+TINY\\s?INT|SHORT(?:\\s?INT)?)(?:\\((\\d+)\\))?$");
private final static Pattern INT_TYPES = Pattern.compile(
"^(?:UNSIGNED (?:SHORT|MEDIUM\\s?INT)|INT(?:EGER)?|MEDIUM\\s?INT)(?:\\((\\d+)\\))?$");
private final static Pattern LONG_TYPES = Pattern.compile(
"^(?:UNSIGNED(?: INT(?:EGER)?)|(?:UNSIGNED\\s*)?(?:BIG\\s?INT|LONG))(?:\\((\\d+)\\))?$");
/**
* Fix #566: Some connectors throw an exception if getIndexInfo() is invoked
* for a database VIEW.
*/
private final static boolean IGNORE_VIEW_INDEXES = false;
private final static boolean APPROXIMATE_INDEX = true;
private @Inject ConnectionPoolComponent connectionPool;
private @Inject ProjectComponent projects;
private @Inject SqliteDbmsType dbmsType;
private JavaTypeMap javaTypeMap;
private SqlTypeMappingHelper typeMappingHelper;
@ExecuteBefore(State.INITIALIZED)
void initJavaTypeMap() {
javaTypeMap = JavaTypeMap.create();
javaTypeMap.addRule((mappings, md) ->
md.getTypeName().toUpperCase().startsWith("NUMERIC(")
? Optional.of(Double.class) : Optional.empty()
);
javaTypeMap.addRule((mappings, md) ->
md.getTypeName().toUpperCase().startsWith("DECIMAL(")
? Optional.of(Double.class) : Optional.empty()
);
javaTypeMap.addRule((mappings, md) ->
Optional.of(md.getTypeName())
.map(String::toUpperCase)
.filter(str -> INTEGER_BOOLEAN_TYPE.matcher(str).find())
.map(str -> Boolean.class)
);
javaTypeMap.addRule((mappings, md) -> patternMapper(SHORT_TYPES, md, Short.class));
javaTypeMap.addRule((mappings, md) -> patternMapper(LONG_TYPES, md, Long.class));
javaTypeMap.addRule((mappings, md) -> patternMapper(INT_TYPES, md, Integer.class));
javaTypeMap.addRule((mappings, md) ->
Optional.of(md.getTypeName())
.map(String::toUpperCase)
.map(BIT_TYPES::matcher)
.filter(Matcher::find)
.map(match -> match.group(1))
.map(Integer::parseInt)
.map(bits -> {
if (bits > Integer.SIZE) return Long.class;
else if (bits > Short.SIZE) return Integer.class;
else if (bits > Byte.SIZE) return Short.class;
else return Byte.class;
})
);
javaTypeMap.addRule((mappings, md) ->
Optional.of(md.getTypeName())
.map(String::toUpperCase)
.filter(str -> BINARY_TYPES.matcher(str).find())
.map(str -> byte[].class)
);
}
private static Optional<Class<?>> patternMapper(Pattern pattern, ColumnMetaData md, Class<?> expected) {
return Optional.of(md.getTypeName())
.map(String::toUpperCase)
.map(pattern::matcher)
.filter(Matcher::find)
.map(match -> {
final String group = match.group(1);
if (group == null) {
return expected;
} else {
final int digits = Integer.parseInt(group);
if (digits > 11) return Long.class;
else if (digits > 4) return Integer.class;
else if (digits > 2) return Short.class;
else return Byte.class;
}
});
}
@ExecuteBefore(State.RESOLVED)
void initSqlTypeMappingHelper(Injector injector) {
typeMappingHelper = SqlTypeMappingHelper.create(injector, javaTypeMap);
}
@Override
public String getDbmsInfoString(Dbms dbms) throws SQLException {
try (final Connection conn = connectionPool.getConnection(dbms)) {
final DatabaseMetaData md = conn.getMetaData();
return md.getDatabaseProductName() + ", " +
md.getDatabaseProductVersion() + ", " +
md.getDriverName() + " " +
md.getDriverVersion() + ", JDBC version " +
md.getJDBCMajorVersion() + "." +
md.getJDBCMinorVersion();
}
}
@Override
public CompletableFuture<Project> readSchemaMetadata(
Dbms dbms, ProgressMeasure progress,
Predicate<String> filterCriteria) {
// Create a deep copy of the project document.
final Project projectCopy = projects.getProject().deepCopy();
// Make sure there are not multiple dbmses with the same id
final Set<String> ids = new HashSet<>();
if (!projectCopy.dbmses().map(Dbms::getId).allMatch(ids::add)) {
final Set<String> duplicates = new HashSet<>();
ids.clear();
projectCopy.dbmses()
.map(Dbms::getId)
.forEach(s -> {
if (!ids.add(s)) {
duplicates.add(s);
}
});
throw new SpeedmentException(
"The following dbmses have duplicates in the config document: "
+ duplicates
);
}
// Locate the dbms in the copy.
final Dbms dbmsCopy = projectCopy.dbmses()
.filter(d -> d.getId().equals(dbms.getId()))
.findAny().orElseThrow(() -> new SpeedmentException(
"Could not find Dbms document in copy."
));
return readSchemaMetadata(
projectCopy, dbmsCopy, progress
).whenCompleteAsync((project, ex) -> {
progress.setProgress(ProgressMeasure.DONE);
if (ex != null) {
progress.setCurrentAction("Error!");
throw new SpeedmentException("Unable to read schema metadata.", ex);
} else {
progress.setCurrentAction("Done!");
}
});
}
private CompletableFuture<Project> readSchemaMetadata(
Project project, Dbms dbms, ProgressMeasure progress) {
//final DbmsType dbmsType = dbmsTypeOf(dbmsHandlerComponent, dbms);
progress.setCurrentAction(describe(dbms));
LOGGER.info(describe(dbms));
final CompletableFuture<Map<String, Class<?>>> typeMappingTask
= typeMappingHelper.loadFor(dbms);
final Schema schema = dbms.mutator().addNewSchema();
schema.mutator().setId("schema");
schema.mutator().setName("schema");
return readTableMetadata(schema, typeMappingTask, progress)
.thenApplyAsync($ -> project);
}
private CompletableFuture<Schema> readTableMetadata(
Schema schema,
CompletableFuture<Map<String, Class<?>>> typeMappingTask,
ProgressMeasure progress) {
final CompletableFuture<Void> tablesTask = CompletableFuture.runAsync(() -> {
final Dbms dbms = schema.getParentOrThrow();
try (final Connection connection = connectionPool.getConnection(dbms)) {
try (final ResultSet rsTable = connection.getMetaData().getTables(null, null, null, TABLES_AND_VIEWS)) {
if (SHOW_METADATA) {
final ResultSetMetaData rsmd = rsTable.getMetaData();
final int numberOfColumns = rsmd.getColumnCount();
for (int x = 1; x <= numberOfColumns; x++) {
LOGGER.debug(new StringJoiner(", ")
.add(rsmd.getColumnName(x))
.add(rsmd.getColumnClassName(x))
.add(Integer.toString(rsmd.getColumnType(x)))
.toString()
);
}
}
while (rsTable.next()) {
if (SHOW_METADATA) {
final ResultSetMetaData rsmd = rsTable.getMetaData();
final int numberOfColumns = rsmd.getColumnCount();
for (int x = 1; x <= numberOfColumns; x++) {
LOGGER.debug(rsmd.getColumnName(x) +
":'" + rsTable.getObject(x) + "'");
}
}
final Table table = schema.mutator().addNewTable();
final String tableName = rsTable.getString("TABLE_NAME");
final String tableType = rsTable.getString("TABLE_TYPE");
table.mutator().setId(tableName);
table.mutator().setName(tableName);
table.mutator().setView("VIEW".equals(tableType));
}
} catch (final SQLException ex) {
throw new SpeedmentException(format(
"Error reading results from SQLite-database '%s'.",
DocumentUtil.toStringHelper(dbms)
), ex);
}
} catch (final SQLException ex) {
throw new SpeedmentException(format(
"Error getting connection to SQLite-database '%s'.",
DocumentUtil.toStringHelper(dbms)
), ex);
}
});
return tablesTask.thenComposeAsync($ -> typeMappingTask)
.thenComposeAsync(sqlTypeMappings -> {
final Dbms dbms = schema.getParentOrThrow();
final AtomicInteger cnt = new AtomicInteger();
final double noTables = schema.tables().count();
return CompletableFuture.allOf(
schema.tables().map(table -> CompletableFuture.runAsync(() -> {
try (final Connection conn = connectionPool.getConnection(dbms)) {
progress.setCurrentAction(describe(table));
columns(conn, sqlTypeMappings, table, progress);
indexes(conn, table, progress);
foreignKeys(conn, table, progress);
primaryKeyColumns(conn, table, progress);
if (!table.isView()) {
// If no INTEGER PRIMARY KEY exists, a rowId should be created.
if (table.columns()
.filter(col -> col.getAsString(ORIGINAL_TYPE).filter("INTEGER"::equalsIgnoreCase).isPresent())
.noneMatch(col -> table.primaryKeyColumns().anyMatch(pkc -> DocumentDbUtil.isSame(pkc.findColumn().get(), col)))
&& table.columns().map(Column::getId).noneMatch("rowid"::equalsIgnoreCase)) {
final Column column = table.mutator().addNewColumn();
column.mutator().setId("rowid");
column.mutator().setName("rowid");
column.mutator().setOrdinalPosition(0);
column.mutator().setDatabaseType(Long.class);
column.mutator().setAutoIncrement(true);
column.mutator().setNullable(false);
column.mutator().setTypeMapper(PrimitiveTypeMapper.class);
// When we introduce a new primary key, we need to
// add a UNIQUE index that represents the same set
// of columns as the old primary key.
if (table.primaryKeyColumns().anyMatch(pkc -> true)) {
final Set<String> oldPks = table.primaryKeyColumns()
.map(PrimaryKeyColumn::getId)
.collect(toCollection(LinkedHashSet::new));
// Make sure such an index doesn't already exist
if (table.indexes()
.filter(Index::isUnique)
.noneMatch(idx -> oldPks.equals(idx.indexColumns()
.map(IndexColumn::getId)
.collect(toCollection(LinkedHashSet::new))
))) {
final Index pkReplacement = table.mutator().addNewIndex();
final String idxName = md5(oldPks.toString());
final IndexMutator<? extends Index> mutator = pkReplacement.mutator();
mutator.setId(idxName);
mutator.setName(idxName);
mutator.setUnique(true);
table.primaryKeyColumns().forEachOrdered(pkc -> {
final int ordNo = 1 + (int) pkReplacement.indexColumns().count();
final IndexColumn idxCol = mutator.addNewIndexColumn();
idxCol.mutator().setId(pkc.getId());
idxCol.mutator().setName(pkc.getName());
idxCol.mutator().setOrdinalPosition(ordNo);
});
}
// Remove the existing primary key since the rowid is
// the only value that should be considered part of
// the primary key
table.getData().remove(Table.PRIMARY_KEY_COLUMNS);
}
final PrimaryKeyColumn pkc = table.mutator().addNewPrimaryKeyColumn();
pkc.mutator().setId("rowid");
pkc.mutator().setName("rowid");
pkc.mutator().setOrdinalPosition(1);
} else {
table.columns()
.filter(col -> col.getAsString(ORIGINAL_TYPE).filter("INTEGER"::equalsIgnoreCase).isPresent())
.filter(col -> table.primaryKeyColumns().anyMatch(pkc -> DocumentDbUtil.isSame(pkc.findColumn().get(), col)))
.forEach(col -> col.mutator().setAutoIncrement(true));
}
}
table.columns().forEach(col -> {
col.getData().remove(ORIGINAL_TYPE);
});
progress.setProgress(cnt.incrementAndGet() / noTables);
} catch (final SQLException ex) {
throw new SpeedmentException(ex);
}
})).toArray(CompletableFuture[]::new)
).thenApplyAsync(v -> schema);
});
}
private void columns(Connection conn, Map<String, Class<?>> sqlTypeMapping, Table table, ProgressMeasure progress) {
requireNonNulls(conn, sqlTypeMapping, table, progress);
final SqlSupplier<ResultSet> supplier = () ->
conn.getMetaData().getColumns(null, null, table.getId(), null);
final TableChildMutator<Column> mutator = (column, rs) -> {
final ColumnMetaData md = ColumnMetaData.of(rs);
final String columnName = md.getColumnName();
column.getData().put(ORIGINAL_TYPE, md.getTypeName());
column.mutator().setId(columnName);
column.mutator().setName(columnName);
column.mutator().setOrdinalPosition(md.getOrdinalPosition());
column.mutator().setNullable(MetaDataUtil.isNullable(md));
column.mutator().setDatabaseType(
typeMappingHelper.findFor(sqlTypeMapping, md)
.orElseGet(() -> {
LOGGER.warn(format(
"Unable to determine mapping for table %s, " +
"column %s. Type name %s, data type %d, decimal " +
"digits %d. Fallback to JDBC-type %s",
table.getId(),
column.getId(),
md.getTypeName(),
md.getDataType(),
md.getDecimalDigits(),
Object.class.getName()
));
return Object.class;
})
);
if (!md.isDecimalDigitsNull() && md.getDecimalDigits() != 10) {
column.mutator().setDecimalDigits(md.getDecimalDigits());
}
if (!md.isColumnSizeNull() && md.getColumnSize() != 2_000_000_000) {
column.mutator().setColumnSize(md.getColumnSize());
}
if (isAutoIncrement(md)) {
column.mutator().setAutoIncrement(true);
}
if (!column.isNullable() && isWrapper(column.findDatabaseType())) {
column.mutator().setTypeMapper(TypeMapper.primitive().getClass());
}
if ("ENUM".equalsIgnoreCase(md.getTypeName())) {
final Dbms dbms = DocumentUtil.ancestor(table, Dbms.class).get();
final List<String> constants = enumConstantsOf(dbms, table, columnName);
column.mutator().setEnumConstants(constants.stream().collect(joining(",")));
}
progress.setCurrentAction(describe(column));
};
tableChilds(
table,
Column.class,
table.mutator()::addNewColumn,
supplier,
rsChild -> ColumnMetaData.of(rsChild).getColumnName(),
mutator
);
}
private void primaryKeyColumns(Connection conn, Table table, ProgressMeasure progress) {
requireNonNulls(conn, table, progress);
final SqlSupplier<ResultSet> supplier = () ->
conn.getMetaData().getPrimaryKeys(null, null, table.getId());
final TableChildMutator<PrimaryKeyColumn> mutator = (pkc, rs) -> {
final String columnName = rs.getString("COLUMN_NAME");
pkc.mutator().setId(columnName);
pkc.mutator().setName(columnName);
pkc.mutator().setOrdinalPosition(rs.getInt("KEY_SEQ"));
};
tableChilds(
table,
PrimaryKeyColumn.class,
table.mutator()::addNewPrimaryKeyColumn,
supplier,
rsChild -> rsChild.getString("COLUMN_NAME"),
mutator
);
if (!table.isView() && table.primaryKeyColumns().noneMatch(pk -> true)) {
LOGGER.warn(format("Table '%s' does not have any primary key.",
table.getId()));
}
}
private void indexes(Connection conn, Table table, ProgressMeasure progress) {
requireNonNulls(conn, table, progress);
if (table.isView() && IGNORE_VIEW_INDEXES) return;
final SqlSupplier<ResultSet> supplier = () ->
conn.getMetaData().getIndexInfo(null, null, table.getId(), false,
APPROXIMATE_INDEX);
final TableChildMutator<Index> mutator = (index, rs) -> {
final String indexName = rs.getString("INDEX_NAME");
index.mutator().setId(indexName);
index.mutator().setName(indexName);
index.mutator().setUnique(!rs.getBoolean("NON_UNIQUE"));
final IndexColumn indexColumn = index.mutator().addNewIndexColumn();
final String columnName = rs.getString("COLUMN_NAME");
indexColumn.mutator().setId(columnName);
indexColumn.mutator().setName(columnName);
indexColumn.mutator().setOrdinalPosition(rs.getInt("ORDINAL_POSITION"));
indexColumn.mutator().setOrderType(getOrderType(rs));
};
final SqlPredicate<ResultSet> filter = rs -> rs.getString("INDEX_NAME") != null;
tableChilds(
table,
Index.class,
table.mutator()::addNewIndex,
supplier,
rsChild -> rsChild.getString("INDEX_NAME"),
mutator,
filter
);
}
private void foreignKeys(Connection conn, Table table, ProgressMeasure progress) {
requireNonNulls(conn, table);
final Schema schema = table.getParentOrThrow();
final SqlSupplier<ResultSet> supplier = () ->
conn.getMetaData().getImportedKeys(null, null, table.getId());
final Set<String> fksThatNeedNewNames = new LinkedHashSet<>();
final TableChildMutator<ForeignKey> mutator = (foreignKey, rs) -> {
final String foreignKeyName = rs.getString("FK_NAME");
if (foreignKeyName == null || foreignKeyName.trim().isEmpty()) {
if (rs.getInt("KEY_SEQ") == 1) {
final String uniqueName = UUID.randomUUID().toString();
foreignKey.mutator().setId(uniqueName);
foreignKey.mutator().setName(uniqueName);
fksThatNeedNewNames.add(uniqueName);
}
} else {
foreignKey.mutator().setId(foreignKeyName);
foreignKey.mutator().setName(foreignKeyName);
}
final ForeignKeyColumn foreignKeyColumn = foreignKey.mutator().addNewForeignKeyColumn();
final ForeignKeyColumnMutator<?> fkcMutator = foreignKeyColumn.mutator();
final String fkColumnName = rs.getString("FKCOLUMN_NAME");
fkcMutator.setId(fkColumnName);
fkcMutator.setName(fkColumnName);
fkcMutator.setOrdinalPosition(rs.getInt("KEY_SEQ"));
fkcMutator.setForeignTableName(rs.getString("PKTABLE_NAME"));
fkcMutator.setForeignColumnName(rs.getString("PKCOLUMN_NAME"));
// FKs always point to the same DBMS but can
// be changed to another one using the config
fkcMutator.setForeignDatabaseName(schema.getParentOrThrow().getId());
fkcMutator.setForeignSchemaName("schema");
};
tableChilds(
table,
ForeignKey.class,
table.mutator()::addNewForeignKey,
supplier,
rsChild -> rsChild.getInt("KEY_SEQ") == 1 ? ""
: fksThatNeedNewNames.stream()
.skip(fksThatNeedNewNames.size() - 1)
.findFirst().orElseThrow(IllegalStateException::new),
mutator
);
// Fix foreign keys without any id by finding an index with the same
// set of columns.
table.foreignKeys()
.filter(fk -> fksThatNeedNewNames.contains(fk.getId()))
.forEach(fk -> {
final Set<String> thisSet = fk.foreignKeyColumns()
.map(ForeignKeyColumn::getId)
.collect(toSet());
final Optional<? extends Index> found = table.indexes()
.filter(idx -> idx.indexColumns()
.map(IndexColumn::getId)
.collect(toSet())
.equals(thisSet)
).findFirst();
if (found.isPresent()) {
fk.mutator().setId(found.get().getId());
fk.mutator().setName(found.get().getName());
} else {
final String randName = md5(thisSet.toString());
fk.mutator().setId(randName);
fk.mutator().setName(randName);
LOGGER.error(format(
"Found a foreign key in table '%s' with no name. " +
"Assigning it a random name '%s'",
table.getId(), randName));
}
});
}
private static String md5(String str) {
try {
final MessageDigest md = MessageDigest.getInstance("MD5");
final byte[] mdbytes = md.digest(str.getBytes(StandardCharsets.UTF_8));
final StringBuilder sb = new StringBuilder();
for (byte mdbyte : mdbytes) {
sb.append(Integer.toString((mdbyte & 0xff) + 0x100, 16).substring(1));
}
return sb.toString();
} catch (NoSuchAlgorithmException ex) {
throw new RuntimeException("MD5 algorithm not supported.", ex);
}
}
private <T extends Document & HasId> void tableChilds(
final Table table,
final Class<T> childType,
final Supplier<T> childSupplier,
final SqlSupplier<ResultSet> resultSetSupplier,
final SqlFunction<ResultSet, String> childIdGetter,
final TableChildMutator<T> resultSetMutator) {
tableChilds(table, childType, childSupplier, resultSetSupplier,
childIdGetter, resultSetMutator, rs -> true);
}
private <T extends Document & HasId> void tableChilds(
final Table table,
final Class<T> childType,
final Supplier<T> childSupplier,
final SqlSupplier<ResultSet> resultSetSupplier,
final SqlFunction<ResultSet, String> childIdGetter,
final TableChildMutator<T> resultSetMutator,
final SqlPredicate<ResultSet> filter) {
requireNonNulls(childSupplier, resultSetSupplier, resultSetMutator);
try (final ResultSet rsChild = resultSetSupplier.get()) {
if (SHOW_METADATA) {
final ResultSetMetaData rsmd = rsChild.getMetaData();
final int numberOfColumns = rsmd.getColumnCount();
for (int x = 1; x <= numberOfColumns; x++) {
final int columnType = rsmd.getColumnType(x);
LOGGER.info(x + ":" + rsmd.getColumnName(x) + ", " +
rsmd.getColumnClassName(x) + ", " + columnType);
}
}
while (rsChild.next()) {
if (SHOW_METADATA) {
final ResultSetMetaData rsmd = rsChild.getMetaData();
final int numberOfColumns = rsmd.getColumnCount();
for (int x = 1; x <= numberOfColumns; x++) {
final Object val = rsChild.getObject(x);
LOGGER.info(x + ":" + rsmd.getColumnName(x) + ":'" +
val + "'");
}
}
if (filter.test(rsChild)) {
final String id = childIdGetter.apply(rsChild);
final Optional<T> existing = DocumentDbUtil.typedChildrenOf(table)
.filter(childType::isInstance)
.map(childType::cast)
.filter(idx -> id.equals(idx.getId()))
.findAny();
final T child = existing.orElseGet(childSupplier);
resultSetMutator.mutate(child, rsChild);
} else {
LOGGER.info("Skipped due to RS filtering. This is normal " +
"for some DBMS types.");
}
}
} catch (final SQLException sqle) {
LOGGER.error(sqle, "Unable to read table child.");
throw new SpeedmentException(sqle);
}
}
/**
* Queries the database for a list of ENUM constants belonging to the specified table and
* column.
*
* @param dbms the dbms
* @param table the table
* @param columnName the column name
* @return list of enum constants.
* @throws SQLException if an error occured
*/
private List<String> enumConstantsOf(Dbms dbms, Table table, String columnName) throws SQLException {
final DatabaseNamingConvention naming = dbmsType.getDatabaseNamingConvention();
final String sql = String.format(
"show columns from %s where field=%s;",
naming.fullNameOf(table),
naming.quoteField(columnName)
);
try (final Connection conn = connectionPool.getConnection(dbms);
final PreparedStatement ps = conn.prepareStatement(sql);
final ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
final String fullResult = rs.getString(2);
if (fullResult.startsWith("enum('")
&& fullResult.endsWith("')")) {
final String middle = fullResult.substring(5, fullResult.length() - 1);
return Stream.of(middle.split(","))
.map(s -> s.substring(1, s.length() - 1))
.filter(s -> !s.isEmpty())
.collect(toList());
} else {
throw new SpeedmentException("Unexpected response (" + fullResult + ").");
}
} else {
throw new SpeedmentException("Expected an result.");
}
}
}
@FunctionalInterface
protected interface TableChildMutator<T> {
void mutate(T t, ResultSet u) throws SQLException;
}
}
|
package net.ssehub.easy.reasoning.sseReasoner;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import net.ssehub.easy.basics.logger.EASyLoggerFactory;
import net.ssehub.easy.basics.logger.EASyLoggerFactory.EASyLogger;
import net.ssehub.easy.basics.modelManagement.Utils;
import net.ssehub.easy.reasoning.core.reasoner.ReasonerConfiguration;
import net.ssehub.easy.reasoning.core.reasoner.ReasonerConfiguration.IAdditionalInformationLogger;
import net.ssehub.easy.reasoning.core.reasoner.ReasoningErrorCodes;
import net.ssehub.easy.reasoning.sseReasoner.functions.FailedElementDetails;
import net.ssehub.easy.reasoning.sseReasoner.functions.FailedElements;
import net.ssehub.easy.reasoning.sseReasoner.functions.ScopeAssignments;
import net.ssehub.easy.reasoning.sseReasoner.model.ContainerConstraintsFinder;
import net.ssehub.easy.reasoning.sseReasoner.model.SubstitutionVisitor;
import net.ssehub.easy.reasoning.sseReasoner.model.DefaultConstraint;
import net.ssehub.easy.reasoning.sseReasoner.model.VariablesInNotSimpleAssignmentConstraintsFinder;
import net.ssehub.easy.reasoning.sseReasoner.model.VariablesMap;
import net.ssehub.easy.varModel.confModel.AssignmentState;
import net.ssehub.easy.varModel.confModel.CompoundVariable;
import net.ssehub.easy.varModel.confModel.Configuration;
import net.ssehub.easy.varModel.confModel.IAssignmentState;
import net.ssehub.easy.varModel.confModel.IConfigurationElement;
import net.ssehub.easy.varModel.confModel.IDecisionVariable;
import net.ssehub.easy.varModel.cst.AttributeVariable;
import net.ssehub.easy.varModel.cst.CSTSemanticException;
import net.ssehub.easy.varModel.cst.CSTUtils;
import net.ssehub.easy.varModel.cst.CompoundAccess;
import net.ssehub.easy.varModel.cst.CompoundInitializer;
import net.ssehub.easy.varModel.cst.ConstantValue;
import net.ssehub.easy.varModel.cst.ConstraintSyntaxTree;
import net.ssehub.easy.varModel.cst.ContainerInitializer;
import net.ssehub.easy.varModel.cst.OCLFeatureCall;
import net.ssehub.easy.varModel.cst.Variable;
import net.ssehub.easy.varModel.cstEvaluation.EvaluationVisitor;
import net.ssehub.easy.varModel.cstEvaluation.EvaluationVisitor.Message;
import net.ssehub.easy.varModel.cstEvaluation.IResolutionListener;
import net.ssehub.easy.varModel.cstEvaluation.IValueChangeListener;
import net.ssehub.easy.varModel.model.AbstractVariable;
import net.ssehub.easy.varModel.model.Attribute;
import net.ssehub.easy.varModel.model.AttributeAssignment;
import net.ssehub.easy.varModel.model.AttributeAssignment.Assignment;
import net.ssehub.easy.varModel.model.Constraint;
import net.ssehub.easy.varModel.model.DecisionVariableDeclaration;
import net.ssehub.easy.varModel.model.IModelElement;
import net.ssehub.easy.varModel.model.ModelVisitorAdapter;
import net.ssehub.easy.varModel.model.OperationDefinition;
import net.ssehub.easy.varModel.model.PartialEvaluationBlock;
import net.ssehub.easy.varModel.model.Project;
import net.ssehub.easy.varModel.model.datatypes.Compound;
import net.ssehub.easy.varModel.model.datatypes.ConstraintType;
import net.ssehub.easy.varModel.model.datatypes.Container;
import net.ssehub.easy.varModel.model.datatypes.DerivedDatatype;
import net.ssehub.easy.varModel.model.datatypes.IDatatype;
import net.ssehub.easy.varModel.model.datatypes.MetaType;
import net.ssehub.easy.varModel.model.datatypes.OclKeyWords;
import net.ssehub.easy.varModel.model.datatypes.TypeQueries;
import net.ssehub.easy.varModel.model.filter.FilterType;
import net.ssehub.easy.varModel.model.filter.VariablesInConstraintFinder;
import net.ssehub.easy.varModel.model.values.ConstraintValue;
import net.ssehub.easy.varModel.model.values.ContainerValue;
import net.ssehub.easy.varModel.model.values.Value;
import net.ssehub.easy.varModel.model.values.ValueDoesNotMatchTypeException;
import net.ssehub.easy.varModel.model.values.ValueFactory;
import static net.ssehub.easy.reasoning.sseReasoner.ReasoningUtils.*;
/**
* Constraint identifier, resolver and executor. Assumption that constraints are not evaluated in parallel (see some
* comments). This resolver can be re-used. Therefore, call {@link #markForReuse()} before the first call to
* {@link #resolve()} and after reasoning completed, call {@link #clear()}. When performing a further reasoning on this
* instance, call {@link #reInit()}.
*
* @author Sizonenko
* @author El-Sharkawy
* @author Holger Eichelberger
*/
public class Resolver {
private static final EASyLogger LOGGER
= EASyLoggerFactory.INSTANCE.getLogger(Resolver.class, Descriptor.BUNDLE_NAME);
@SuppressWarnings("unused")
private IAdditionalInformationLogger infoLogger;
private ReasonerConfiguration reasonerConfig;
private Configuration config;
private boolean incremental = false;
private boolean considerFrozenConstraints = true;
private EvalVisitor evaluator = new EvalVisitor();
private FailedElements failedElements = new FailedElements();
private ScopeAssignments scopeAssignments = new ScopeAssignments();
private VariablesMap constraintMap = new VariablesMap();
private Map<Constraint, IDecisionVariable> constraintVariableMap = new HashMap<Constraint, IDecisionVariable>();
private Deque<Constraint> constraintBase = new LinkedList<Constraint>();
private Deque<Constraint> constraintBaseCopy = null;
private Set<Constraint> constraintBaseSet = new HashSet<Constraint>();
private List<Constraint> defaultConstraints = new LinkedList<Constraint>();
private List<Constraint> deferredDefaultConstraints = new LinkedList<Constraint>();
private List<Constraint> topLevelConstraints = new LinkedList<Constraint>();
private List<Constraint> otherConstraints = new LinkedList<Constraint>();
// Stats
private int constraintCounter = 0;
private int variablesInConstraintsCounter = 0;
private int reevaluationCounter = 0;
private int variablesCounter = 0;
private boolean hasTimeout = false;
private boolean isRunning = false;
private boolean wasStopped = false;
// global temporary variables avoiding parameter passing (performance)
private Project project;
private transient Set<IDecisionVariable> usedVariables = new HashSet<IDecisionVariable>(100);
private transient SubstitutionVisitor substVisitor = new SubstitutionVisitor();
private transient Map<AbstractVariable, CompoundAccess> varMap = new HashMap<AbstractVariable, CompoundAccess>(100);
private transient ContainerConstraintsFinder containerFinder = new ContainerConstraintsFinder();
private transient VariablesInNotSimpleAssignmentConstraintsFinder simpleAssignmentFinder
= new VariablesInNotSimpleAssignmentConstraintsFinder(constraintMap);
private transient ConstraintTranslationVisitor projectVisitor = new ConstraintTranslationVisitor();
private transient VariablesInConstraintFinder variablesFinder = new VariablesInConstraintFinder();
private transient long endTimestamp;
// >>> from here the names follows the reasoner.tex documentation
private IValueChangeListener listener = new IValueChangeListener() {
@Override
public void notifyUnresolved(IDecisionVariable variable) {
}
@Override
public void notifyChanged(IDecisionVariable variable, Value oldValue) {
if (!variable.isLocal()) {
if (Descriptor.LOGGING) {
LOGGER.debug("Value changed: " + variable.getDeclaration().getName() + " " + variable.getValue()
+ " Parent: " + (null == variable.getParent() ? null : variable.getParent()));
}
scopeAssignments.addAssignedVariable(variable);
// TODO if value type changes (currently not part of the notification), change also constraints
rescheduleConstraintsForChilds(variable);
// All constraints for the parent (as this was also changed)
rescheduleConstraintsForParent(variable);
}
}
/**
* Tries rescheduling the given constraints. Does not add a constraint to the constraint base if already
* scheduled.
*
* @param constraints the constraints to reschedule (may be <b>null</b>, ignored then)
*/
private void reschedule(Set<Constraint> constraints) {
if (null != constraints) {
for (Constraint varConstraint : constraints) {
if (!constraintBaseSet.contains(varConstraint)) {
addToConstraintBase(varConstraint);
}
}
}
}
/**
* Determines the constraints needed for the parents of <code>variable</code>.
*
* @param variable the variable to analyze
* @param constraintsToReevaluate the constraint set to be modified as a side effect
*/
private void rescheduleConstraintsForParent(IDecisionVariable variable) {
IConfigurationElement parent = variable.getParent();
if (parent instanceof IDecisionVariable) {
IDecisionVariable pVar = (IDecisionVariable) parent;
AbstractVariable declaration = pVar.getDeclaration();
reschedule(constraintMap.getRelevantConstraints(declaration));
rescheduleConstraintsForParent(pVar);
}
}
/**
* Determines the constraints needed for <code>variable</code> and its (transitive) child slots.
*
* @param variable the variable to analyze
* @param constraintsToReevaluate the constraint set to be modified as a side effect
*/
private void rescheduleConstraintsForChilds(IDecisionVariable variable) {
AbstractVariable declaration = variable.getDeclaration();
reschedule(constraintMap.getRelevantConstraints(declaration));
// All constraints for childs (as they may also changed)
for (int j = 0, nChilds = variable.getNestedElementsCount(); j < nChilds; j++) {
rescheduleConstraintsForChilds(variable.getNestedElement(j));
}
}
};
/**
* Listener for the {@link #evaluator} to record changed variables.
*/
private IResolutionListener resolutionListener = new IResolutionListener() {
@Override
public void notifyResolved(IDecisionVariable compound, String slotName, IDecisionVariable resolved) {
if (!(resolved.isLocal())) {
usedVariables.add(resolved);
}
}
@Override
public void notifyResolved(AbstractVariable declaration, IDecisionVariable resolved) {
if (!(resolved.isLocal())) {
usedVariables.add(resolved);
}
}
};
// <<< documented until here
/**
* Main constructor that activates Resolver constructor.
* @param project Project for evaluation.
* @param config Configuration to reason on.
* @param reasonerConfig the reasoner configuration to be used for reasoning (e.g. taken from the UI,
* may be <b>null</b>)
*/
public Resolver(Project project, Configuration config, ReasonerConfiguration reasonerConfig) {
this.reasonerConfig = reasonerConfig;
this.infoLogger = reasonerConfig.getLogger();
this.config = config;
}
/**
* Main constructor that activates Resolver constructor with clean {@link Configuration}.
* @param project Project for evaluation.
* @param reasonerConfig the reasoner configuration to be used for reasoning (e.g. taken from the UI,
* may be <b>null</b>)
*/
public Resolver(Project project, ReasonerConfiguration reasonerConfig) {
new Resolver(project, createCleanConfiguration(project), reasonerConfig);
}
/**
* Main constructor that activates Resolver constructor.
* @param config Configuration to reason on.
* @param reasonerConfig the reasoner configuration to be used for reasoning (e.g. taken from the UI,
* may be <b>null</b>)
*/
public Resolver(Configuration config, ReasonerConfiguration reasonerConfig) {
new Resolver(config.getProject(), config, reasonerConfig);
}
// >>> from here the names follow the reasoner.tex documentation
/**
* Resolves the (initial) values of the configuration.
*
* @see Utils#discoverImports(net.ssehub.easy.basics.modelManagement.IModel)
* @see #translateConstraints()
* @see #evaluateConstraints()
* @see Configuration#freeze(net.ssehub.easy.varModel.confModel.IFreezeSelector)
*/
public void resolve() {
isRunning = true;
// Stack of importedProject (start with inner most imported project)
evaluator.init(config, null, false, listener); // also for defaults as they may refer to each other
evaluator.setResolutionListener(resolutionListener);
evaluator.setScopeAssignments(scopeAssignments);
List<Project> projects = Utils.discoverImports(config.getProject());
endTimestamp = reasonerConfig.getTimeout() <= 0
? -1 : System.currentTimeMillis() + reasonerConfig.getTimeout();
for (int p = 0; !hasTimeout && !wasStopped && p < projects.size(); p++) {
project = projects.get(p);
if (Descriptor.LOGGING) {
LOGGER.debug("Project:" + project.getName());
}
translateConstraints();
evaluateConstraints();
// Freezes values after each scope
config.freezeValues(project, FilterType.NO_IMPORTS);
// TODO do incremental freezing in here -> required by interfaces with propagation constraints
if (Descriptor.LOGGING) {
printFailedElements(failedElements);
}
}
evaluator.clear();
isRunning = false;
}
/**
* Evaluates and reschedules failed constraints.
*
* @see #resolve()
*/
private void evaluateConstraints() {
if (Descriptor.LOGGING) {
printConstraints(constraintBase);
}
scopeAssignments.clearScopeAssignments();
evaluator.setDispatchScope(project);
while (!constraintBase.isEmpty() && !wasStopped) { // reasoner.tex -> hasTimeout see end of loop
usedVariables.clear();
Constraint constraint = constraintBase.pop();
constraintBaseSet.remove(constraint);
ConstraintSyntaxTree cst = constraint.getConsSyntax();
evaluator.setAssignmentState(constraint.isDefaultConstraint()
? AssignmentState.DEFAULT : AssignmentState.DERIVED);
reevaluationCounter++;
if (cst != null) {
if (Descriptor.LOGGING) {
LOGGER.debug("Resolving: " + reevaluationCounter + ": " + toIvmlString(cst)
+ " : " + constraint.getTopLevelParent());
}
evaluator.visit(cst);
analyzeEvaluationResult(constraint);
if (Descriptor.LOGGING) {
LOGGER.debug("Result: " + evaluator.getResult());
LOGGER.debug("
}
evaluator.clearIntermediary();
}
if (endTimestamp > 0 && System.currentTimeMillis() > endTimestamp) {
hasTimeout = true;
break;
}
}
}
/**
* Visits the contents of a project for translation. Do not store stateful information in this class.
*
* @author Holger Eichelberger
*/
private class ConstraintTranslationVisitor extends ModelVisitorAdapter {
// don't follow project imports here, just structural top-level traversal of the actual project!
private List<PartialEvaluationBlock> evals = null;
@Override // iterate over all elements declared in project, implicitly skipping not implemented elements
public void visitProject(Project project) {
for (int e = 0; e < project.getElementCount(); e++) {
project.getElement(e).accept(this);
}
if (null != evals) {
// prioritize top-level project contents over eval blocks
for (PartialEvaluationBlock block : evals) {
for (int i = 0; i < block.getNestedCount(); i++) {
block.getNested(i).accept(this);
}
for (int i = 0; i < block.getEvaluableCount(); i++) {
block.getEvaluable(i).accept(this);
}
}
}
}
@Override // translate all top-level/enum/attribute assignment declarations
public void visitDecisionVariableDeclaration(DecisionVariableDeclaration decl) {
translateDeclaration(decl, config.getDecision(decl), null);
}
@Override // collect all top-level/enum/attribute assignment constraints
public void visitConstraint(Constraint constraint) {
addConstraint(topLevelConstraints, constraint, true); // topLevelConstraints
}
@Override // iterate over nested blocks/contained constraints
public void visitPartialEvaluationBlock(PartialEvaluationBlock block) {
if (null == evals) {
evals = new LinkedList<PartialEvaluationBlock>();
}
evals.add(block);
}
@Override // iterate over nested blocks/contained, translate the individual blocks if not incremental
public void visitAttributeAssignment(AttributeAssignment assignment) {
for (int v = 0; v < assignment.getElementCount(); v++) {
assignment.getElement(v).accept(this);
}
for (int a = 0; a < assignment.getAssignmentCount(); a++) {
assignment.getAssignment(a).accept(this);
}
if (!incremental) {
translateAnnotationAssignments(assignment, null, null);
}
}
}
/**
* Extracts, translates and collects the internal constraints of <code>type</code> and stores them
* in {@link #derivedTypeConstraints}.
*
* @param decl VariableDeclaration of <code>DerivedDatatype</code>
* @param dType the type to translate
* @param localDecl the declaration of an iterator variable if quantified constraints shall be created,
* <b>null</b> for normal constraints
* @param parent the parent model element for creating constraint instances
*/
private void translateDerivedDatatypeConstraints(AbstractVariable decl, DerivedDatatype dType,
DecisionVariableDeclaration localDecl, IModelElement parent) {
int count = dType.getConstraintCount();
DecisionVariableDeclaration dVar = dType.getTypeDeclaration();
AbstractVariable declaration = null == localDecl ? decl : localDecl;
if (count > 0 && dVar != declaration) {
substVisitor.setMappings(varMap);
substVisitor.addVariableMapping(dVar, declaration);
//Copy and replace each instance of the internal declaration with the given instance
for (int i = 0; i < count; i++) {
ConstraintSyntaxTree cst = substVisitor.accept(dType.getConstraint(i).getConsSyntax());
if (null != localDecl) {
cst = createContainerCall(new Variable(decl), Container.FORALL, cst, localDecl);
}
try {
cst.inferDatatype();
addConstraint(topLevelConstraints, new Constraint(cst, parent), true);
} catch (CSTSemanticException e) {
LOGGER.exception(e);
}
}
substVisitor.clear();
}
IDatatype basis = dType.getBasisType();
if (basis instanceof DerivedDatatype) {
translateDerivedDatatypeConstraints(decl, (DerivedDatatype) basis, localDecl, parent);
}
}
/**
* Translates annotation default value expressions.
*
* @param decl {@link AbstractVariable} with annotations.
* @param variable {@link IDecisionVariable} with annotations.
* @param compound {@link CompoundAccess} null if variable is not nested.
*/
private void translateAnnotationDefaults(AbstractVariable decl, IDecisionVariable variable,
CompoundAccess compound) {
for (int i = 0; i < variable.getAttributesCount(); i++) {
Attribute attribute = (Attribute) variable.getAttribute(i).getDeclaration();
ConstraintSyntaxTree defaultValue = attribute.getDefaultValue();
if (null != defaultValue) {
try {
ConstraintSyntaxTree op;
if (compound == null) {
op = new AttributeVariable(new Variable(decl), attribute);
} else {
op = new AttributeVariable(compound, attribute);
}
defaultValue = new OCLFeatureCall(op, OclKeyWords.ASSIGNMENT, defaultValue);
defaultValue.inferDatatype(); // defaultAnnotationConstraints
addConstraint(otherConstraints, new DefaultConstraint(defaultValue, project), false);
} catch (CSTSemanticException e) {
e.printStackTrace();
}
}
}
}
/**
* Translates the (transitive) defaults and type constraints for a declaration.
*
* @param decl The {@link AbstractVariable} for which the default value should be resolved.
* @param var the instance of <tt>decl</tt>.
* @param cAcc if variable is a nested compound.
*/
protected void translateDeclaration(AbstractVariable decl, IDecisionVariable var, CompoundAccess cAcc) {
variablesCounter++;
IDatatype type = decl.getType();
ConstraintSyntaxTree defaultValue = decl.getDefaultValue();
AbstractVariable self = null;
ConstraintSyntaxTree selfEx = null;
if (type instanceof DerivedDatatype) {
translateDerivedDatatypeConstraints(decl, (DerivedDatatype) type, null, decl.getTopLevelParent());
}
if (!incremental) {
translateAnnotationDefaults(decl, var, cAcc);
}
if (null != defaultValue) { // considering the actual type rather than base, after derived (!)
type = inferTypeSafe(defaultValue, type);
}
if (TypeQueries.isCompound(type)) { // this is a compound value -> default constraints, do not defer
self = decl;
translateCompoundDeclaration(decl, var, cAcc, type);
} else if (TypeQueries.isContainer(type)) { // this is a container value -> default constraints, do not defer
translateContainerDeclaration(decl, var, type);
} else if (null != defaultValue && !incremental) {
if (null != cAcc) { // defer self/override init constraints to prevent accidental init override
selfEx = cAcc.getCompoundExpression();
}
} else if (incremental) { // remaining defaults
defaultValue = null;
}
if (null != defaultValue) {
try {
if (TypeQueries.isConstraint(decl.getType())) { // handle and register constraint variables
variablesCounter
// use closest parent instead of project -> runtime analysis
createConstraintVariableConstraint(defaultValue, selfEx, self, var.getDeclaration(), var);
} else { // Create default constraint
defaultValue = new OCLFeatureCall(null != selfEx ? cAcc : new Variable(decl),
OclKeyWords.ASSIGNMENT, defaultValue);
defaultValue = substituteVariables(defaultValue, selfEx, self, false);
List<Constraint> targetCons = defaultConstraints;
if (substVisitor.containsSelf() || isOverriddenSlot(decl)) {
targetCons = deferredDefaultConstraints;
}
addConstraint(targetCons, new DefaultConstraint(defaultValue, project), true);
}
substVisitor.clear(); // clear false above
} catch (CSTSemanticException e) {
LOGGER.exception(e); // should not occur, ok to log
}
}
}
/**
* Translates the (transitive) defaults and type constraints for a container declaration.
*
* @param decl The {@link AbstractVariable} for which the default value should be resolved.
* @param var the instance of <tt>decl</tt>.
* @param type the (specific) datatype ({@link Container})
*/
private void translateContainerDeclaration(AbstractVariable decl, IDecisionVariable var, IDatatype type) {
if (null != decl.getDefaultValue() && !incremental) {
Set<Compound> used = getUsedTypes(decl.getDefaultValue(), Compound.class);
if (null != used && !used.isEmpty()) {
Set<Compound> done = new HashSet<Compound>();
for (Compound uType : used) {
translateDefaultsCompoundContainer(decl, uType, done);
done.clear();
}
}
}
translateContainerCompoundConstraints(decl, var, null, otherConstraints);
IDatatype containedType = ((Container) type).getContainedType();
if (containedType instanceof DerivedDatatype) {
translateDerivedDatatypeConstraints(decl, (DerivedDatatype) containedType,
new DecisionVariableDeclaration("derivedType", containedType, null), project);
}
}
/**
* Translates constraints representing compound defaults in containers of compounds.
*
* @param decl the container variable
* @param cmpType the compound type used in the actual <code>decl</code> value to focus the constraints created
* @param done the already processed types (to be modified as a side effect)
*/
private void translateDefaultsCompoundContainer(AbstractVariable decl, Compound cmpType, Set<Compound> done) {
if (!done.contains(cmpType)) {
done.add(cmpType);
for (int d = 0; d < cmpType.getDeclarationCount(); d++) {
DecisionVariableDeclaration uDecl = cmpType.getDeclaration(d);
ConstraintSyntaxTree defaultValue = uDecl.getDefaultValue();
if (null != defaultValue) {
DecisionVariableDeclaration localDecl = new DecisionVariableDeclaration("cmp", cmpType, null);
try {
Variable localDeclVar = new Variable(localDecl);
defaultValue = substituteVariables(defaultValue, localDeclVar, null, true); // replace self
defaultValue = new OCLFeatureCall(new CompoundAccess(localDeclVar, uDecl.getName()),
OclKeyWords.ASSIGNMENT, defaultValue);
ConstraintSyntaxTree containerOp = new Variable(decl);
if (!TypeQueries.sameTypes(decl.getType(), cmpType)) {
containerOp = new OCLFeatureCall(containerOp, OclKeyWords.TYPE_SELECT,
new ConstantValue(ValueFactory.createValue(MetaType.TYPE, cmpType)));
}
if (isNestedContainer(decl.getType())) {
containerOp = new OCLFeatureCall(containerOp, OclKeyWords.FLATTEN);
}
defaultValue = createContainerCall(containerOp, Container.FORALL, defaultValue, localDecl);
defaultValue.inferDatatype();
addConstraint(deferredDefaultConstraints, new DefaultConstraint(defaultValue, project), true);
} catch (CSTSemanticException e) {
LOGGER.exception(e); // should not occur, ok to log
} catch (ValueDoesNotMatchTypeException e) {
LOGGER.exception(e); // should not occur, ok to log
}
}
}
// attributes??
for (int r = 0; r < cmpType.getRefinesCount(); r++) {
translateDefaultsCompoundContainer(decl, cmpType.getRefines(r), done);
}
}
}
/**
* Method for retrieving constraints from compounds initialized in containers. <code>variable</code>
* must be a container and <code>decl</code> of type container.
*
* @param decl AbstractVariable.
* @param variable the instance of <tt>decl</tt>.
* @param topcmpAccess {@link CompoundAccess} if container is a nested element.
* @param results the resulting constraints
*/
private void translateContainerCompoundConstraints(AbstractVariable decl, IDecisionVariable variable,
CompoundAccess topcmpAccess, List<Constraint> results) {
IDatatype containedType = ((Container) decl.getType()).getContainedType();
for (IDatatype tmp : identifyContainedTypes(variable, containedType)) {
if (TypeQueries.isCompound(tmp)) {
translateContainerCompoundConstraints((Compound) tmp, containedType, decl, topcmpAccess, results);
}
}
}
/**
* Method for transforming a compound constraint into container forAll constraint.
* @param cmpType Specific compound type (with constraints).
* @param declaredContainedType the declared contained type of the container.
* @param decl {@link AbstractVariable}.
* @param topcmpAccess {@link CompoundAccess} if container is a nested element.
* @param result List of transformed constraints, to be modified as a side effect.
*/
private void translateContainerCompoundConstraints(Compound cmpType, IDatatype declaredContainedType,
AbstractVariable decl, CompoundAccess topcmpAccess, List<Constraint> result) {
DecisionVariableDeclaration localDecl = new DecisionVariableDeclaration("cmp", cmpType, null);
// fill varMap
for (int i = 0, n = cmpType.getInheritedElementCount(); i < n; i++) {
AbstractVariable nestedDecl = cmpType.getInheritedElement(i);
CompoundAccess cmpAccess = null;
cmpAccess = new CompoundAccess(new Variable(localDecl), nestedDecl.getName());
varMap.put(nestedDecl, cmpAccess);
}
List<Constraint> thisCompoundConstraints = new ArrayList<Constraint>();
allCompoundConstraints(cmpType, thisCompoundConstraints, true);
ConstraintSyntaxTree typeExpression = null;
if (!TypeQueries.sameTypes(cmpType, declaredContainedType)) {
typeExpression = createTypeValueConstantSafe(cmpType);
}
for (int i = 0; i < thisCompoundConstraints.size(); i++) {
ConstraintSyntaxTree itExpression = thisCompoundConstraints.get(i).getConsSyntax();
itExpression = substituteVariables(itExpression, null, localDecl, true);
if (Descriptor.LOGGING) {
LOGGER.debug("New loop constraint " + toIvmlString(itExpression));
}
try {
ConstraintSyntaxTree containerOp = topcmpAccess == null ? new Variable(decl) : topcmpAccess;
containerOp.inferDatatype();
if (null != typeExpression) {
containerOp = new OCLFeatureCall(containerOp, Container.SELECT_BY_KIND.getName(), typeExpression);
}
if (containerOp != null) {
containerOp.inferDatatype();
containerOp = createContainerCall(containerOp, Container.FORALL, itExpression, localDecl);
}
if (containerOp != null) {
containerOp.inferDatatype();
addConstraint(result, new Constraint(containerOp, project), true);
}
} catch (CSTSemanticException e) {
LOGGER.exception(e);
}
}
}
/**
* Method for translating compound default value declarations. Requires
* {@link #buildVariableMapping(AbstractVariable, IDecisionVariable, CompoundAccess, IDatatype)} before.
*
* @param decl The {@link AbstractVariable} for which the default value should be resolved.
* @param variable the instance of <tt>decl</tt>.
* @param compound if variable is a nested compound, the access expression to
* <code>decl</code>/<code>variable</code>
* @param type specific {@link Compound} type.
*/
private void translateCompoundDeclaration(AbstractVariable decl, IDecisionVariable variable,
CompoundAccess compound, IDatatype type) {
Compound cmpType = (Compound) type;
CompoundVariable cmpVar = (CompoundVariable) variable;
// resolve compound access first for all slots
for (int i = 0, n = cmpVar.getNestedElementsCount(); i < n; i++) {
IDecisionVariable nestedVar = cmpVar.getNestedElement(i);
AbstractVariable nestedDecl = nestedVar.getDeclaration();
CompoundAccess cmpAccess;
if (compound == null) {
cmpAccess = new CompoundAccess(new Variable(decl), nestedDecl.getName());
} else {
cmpAccess = new CompoundAccess(createAsTypeCast(compound, type, cmpVar.getValue().getType()),
nestedDecl.getName());
}
inferTypeSafe(cmpAccess, null);
// fill varMap
varMap.put(nestedDecl, cmpAccess);
}
for (int i = 0, n = cmpVar.getNestedElementsCount(); i < n; i++) {
IDecisionVariable nestedVar = cmpVar.getNestedElement(i);
AbstractVariable nestedDecl = nestedVar.getDeclaration();
translateDeclaration(nestedDecl, cmpVar.getNestedVariable(nestedDecl.getName()),
varMap.get(nestedDecl));
}
// create constraints on mutually interacting constraints now
for (int i = 0, n = cmpVar.getNestedElementsCount(); i < n; i++) {
IDecisionVariable nestedVar = cmpVar.getNestedElement(i);
AbstractVariable nestedDecl = nestedVar.getDeclaration();
IDatatype nestedType = nestedDecl.getType();
if (Container.isContainer(nestedType, ConstraintType.TYPE)
&& nestedVar.getValue() instanceof ContainerValue) {
createContainerConstraintValueConstraints((ContainerValue) nestedVar.getValue(), decl, nestedDecl,
nestedVar);
}
if (TypeQueries.isContainer(nestedType)) {
translateContainerCompoundConstraints(nestedDecl, variable, varMap.get(nestedDecl),
otherConstraints);
}
}
// Nested attribute assignments handling
if (!incremental) {
for (int a = 0; a < cmpType.getAssignmentCount(); a++) {
translateAnnotationAssignments(cmpType.getAssignment(a), null, compound);
}
}
List<Constraint> thisCompoundConstraints = new ArrayList<Constraint>();
allCompoundConstraints(cmpType, thisCompoundConstraints, false);
for (int i = 0; i < thisCompoundConstraints.size(); i++) {
ConstraintSyntaxTree oneConstraint = thisCompoundConstraints.get(i).getConsSyntax();
// changed null to decl
oneConstraint = substituteVariables(oneConstraint, null, decl, true);
try { // compoundConstraints
Constraint constraint = new Constraint(oneConstraint, decl);
addConstraint(otherConstraints, constraint, true);
} catch (CSTSemanticException e) {
LOGGER.exception(e);
}
}
processCompoundEvals(cmpType);
}
/**
* Method for extracting constraints from compounds eval blocks (also refined compounds).
* @param cmpType Compound to be analyzed
*/
private void processCompoundEvals(Compound cmpType) {
for (int r = 0; r < cmpType.getRefinesCount(); r++) {
processCompoundEvals(cmpType.getRefines(r));
}
for (int i = 0; i < cmpType.getModelElementCount(); i++) {
if (cmpType.getModelElement(i) instanceof PartialEvaluationBlock) {
PartialEvaluationBlock evalBlock = (PartialEvaluationBlock) cmpType.getModelElement(i);
processEvalConstraints(evalBlock);
}
}
}
/**
* Method for handling eval blocks - searching for nested eval blocks and extracting constraints.
* @param evalBlock Eval block to be processed.
*/
private void processEvalConstraints(PartialEvaluationBlock evalBlock) {
for (int i = 0; i < evalBlock.getNestedCount(); i++) {
processEvalConstraints(evalBlock.getNested(i));
}
for (int i = 0; i < evalBlock.getEvaluableCount(); i++) {
if (evalBlock.getEvaluable(i) instanceof Constraint) {
Constraint evalConstraint = (Constraint) evalBlock.getEvaluable(i);
ConstraintSyntaxTree evalCst = evalConstraint.getConsSyntax();
ConstraintSyntaxTree cst = substituteVariables(evalCst, null, null, true);
try {
addConstraint(otherConstraints, new Constraint(cst, project), true);
} catch (CSTSemanticException e) {
LOGGER.exception(e);
}
}
}
}
/**
* Creates a constraint from a (nested) constraint variable adding the result to
* {@link #constraintVariablesConstraints}.
*
* @param cst the constraint
* @param selfEx the expression representing <i>self</i> in <code>cst</code>, both, <code>self</code> and
* <code>selfEx</code> must not be different from <b>null</b> at the same time (may be <b>null</b> for none)
* @param self the declaration of the variable representing <i>self</i> in <code>cst</code> (may be <b>null</b>
* for none)
* @param parent the parent for new constraints
* @param variable the actually (nested) variable, used to fill {@link #constraintVariableMap}
* @return the created constraint
*/
private Constraint createConstraintVariableConstraint(ConstraintSyntaxTree cst, ConstraintSyntaxTree selfEx,
AbstractVariable self, IModelElement parent, IDecisionVariable variable) {
Constraint constraint = null;
if (cst != null) {
cst = substituteVariables(cst, selfEx, self, true);
try {
constraint = new Constraint(cst, parent);
addConstraint(otherConstraints, constraint, true); // constraintVariablesConstraints
// TODO reverse mapping for changing constraint types through value upon value change
constraintVariableMap.put(constraint, variable);
if (Descriptor.LOGGING) {
LOGGER.debug((null != self ? self.getName() + "." : "") + variable.getDeclaration().getName()
+ " compound constraint variable " + toIvmlString(cst));
}
} catch (CSTSemanticException e) {
LOGGER.exception(e);
}
}
return constraint;
}
/**
* Checks a container value for nested constraint values, i.e., values of nested constraint variables.
*
* @param val the container value
* @param decl the variable declaration representing <i>self</i> in the container/constraint value
* @param parent the parent for new constraints
* @param nestedVariable the variable holding the constraint value
*/
private void createContainerConstraintValueConstraints(ContainerValue val, AbstractVariable decl,
IModelElement parent, IDecisionVariable nestedVariable) {
for (int n = 0; n < val.getElementSize(); n++) {
Value cVal = val.getElement(n);
if (cVal instanceof ConstraintValue) {
ConstraintValue constraint = (ConstraintValue) cVal;
createConstraintVariableConstraint(constraint.getValue(), null, decl, parent, nestedVariable);
}
}
}
/**
* Translates attribute assignments. It is important to recall that in case of nested (orthogonal) attribute
* assignments, the outer one(s) must also be applied to the inner ones.
*
* @param assignment Attribute assignments on top-level.
* @param effectiveAssignments the list of effective current assignments, use <b>null</b> if not recursive.
* @param compound Parent {@link CompoundAccess}.
*/
private void translateAnnotationAssignments(AttributeAssignment assignment, List<Assignment> effectiveAssignments,
CompoundAccess compound) {
List<Assignment> assng = null == effectiveAssignments ? new ArrayList<Assignment>() : effectiveAssignments;
for (int d = 0; d < assignment.getAssignmentDataCount(); d++) {
assng.add(assignment.getAssignmentData(d));
}
for (int d = 0; d < assng.size(); d++) {
Assignment effectiveAssignment = assng.get(d);
for (int e = 0; e < assignment.getElementCount(); e++) {
DecisionVariableDeclaration aElt = assignment.getElement(e);
IDatatype aEltType = aElt.getType();
translateAnnotationAssignment(effectiveAssignment, aElt, compound);
if (TypeQueries.isCompound(aEltType)) {
Compound cmp = (Compound) aEltType;
for (int s = 0; s < cmp.getDeclarationCount(); s++) {
DecisionVariableDeclaration slot = cmp.getDeclaration(s);
CompoundAccess cmpAccess;
if (compound == null) {
cmpAccess = new CompoundAccess(new Variable(aElt), slot.getName());
} else {
cmpAccess = new CompoundAccess(compound, slot.getName());
}
varMap.put(slot, cmpAccess);
inferTypeSafe(cmpAccess, null);
}
for (int s = 0; s < cmp.getDeclarationCount(); s++) {
DecisionVariableDeclaration slot = cmp.getDeclaration(s);
translateAnnotationAssignment(effectiveAssignment, slot, varMap.get(slot));
}
}
}
}
for (int a = 0; a < assignment.getAssignmentCount(); a++) {
translateAnnotationAssignments(assignment.getAssignment(a), assng, compound);
}
}
/**
* Method for creating attribute constraint for a specific element.
* @param assignment Attribute assignment constraint.
* @param element Elements to which the attribute is assigned.
* @param compound Nesting compound if there is one, may be <b>null</b> for none.
*/
private void translateAnnotationAssignment(Assignment assignment, DecisionVariableDeclaration element,
CompoundAccess compound) {
String attributeName = assignment.getName();
Attribute attrib = (Attribute) element.getAttribute(attributeName);
if (null != attrib) {
ConstraintSyntaxTree cst;
//handle annotations in compounds
if (null == compound) {
compound = varMap.get(element);
}
if (compound == null) {
cst = new AttributeVariable(new Variable(element), attrib);
} else {
cst = new AttributeVariable(compound, attrib);
}
cst = new OCLFeatureCall(cst, OclKeyWords.ASSIGNMENT,
substituteVariables(assignment.getExpression(), null, null, true));
inferTypeSafe(cst, null);
try { // assignedAttributeConstraints
addConstraint(otherConstraints, new Constraint(cst, project), false);
} catch (CSTSemanticException e) {
LOGGER.exception(e);
}
}
}
/**
* Translates and collects all constraints in {@link #project} by adding the collected constraints to the
* {@link #constraintBase}.
*
* @see #resolve()
*/
private void translateConstraints() {
// translate only if not marked for reuse and copy of constraint base is already available
if (null == constraintBaseCopy || constraintBaseCopy.isEmpty()) {
varMap.clear();
project.accept(projectVisitor);
addAllToConstraintBase(defaultConstraints);
addAllToConstraintBase(deferredDefaultConstraints);
addAllToConstraintBase(topLevelConstraints);
addAllToConstraintBase(otherConstraints);
constraintCounter = constraintBase.size();
variablesInConstraintsCounter = constraintMap.getDeclarationSize();
clearConstraintLists();
// if marked for re-use, copy constraint base
if (null != constraintBaseCopy) {
constraintBaseCopy.addAll(constraintBase);
}
}
}
/**
* Adding a constraint to a constraint set, checking for contained container/compound initializers if
* requested.
*
* @param target the target container to add the constraint to
* @param constraint the constraint
* @param checkForInitializers check also for initializers if (<code>true</code>), add only if (<code>false</code>)
*/
private void addConstraint(Collection<Constraint> target, Constraint constraint, boolean checkForInitializers) {
ConstraintSyntaxTree cst = constraint.getConsSyntax();
boolean add = true;
if (incremental) {
add = !CSTUtils.isAssignment(cst);
}
if (add && !considerFrozenConstraints) {
variablesFinder.setConfiguration(config);
cst.accept(variablesFinder);
Set<IAssignmentState> states = variablesFinder.getStates();
add = (!(1 == states.size() && states.contains(AssignmentState.FROZEN)));
variablesFinder.clear();
}
if (add) {
if (checkForInitializers) {
containerFinder.accept(cst);
if (containerFinder.isConstraintContainer()) {
checkContainerInitializer(containerFinder.getExpression(), false, constraint.getParent());
}
if (containerFinder.isCompoundInitializer()) {
checkCompoundInitializer(containerFinder.getExpression(), true, constraint.getParent());
}
containerFinder.clear();
}
target.add(constraint);
simpleAssignmentFinder.acceptAndClear(constraint);
}
}
/**
* Method for checking if {@link CompoundInitializer} holds
* a {@link de.uni_hildesheim.sse.ivml.CollectionInitializer} with {@link Constraint}s.
* @param exp expression to check.
* @param substituteVars <code>true</code> if {@link #varMap} shall be applied to substitute variables in
* <code>exp</code> (if variable is nested), <code>false</code> if <code>exp</code> shall be taken over as it is.
* @param parent parent for temporary constraints
*/
private void checkCompoundInitializer(ConstraintSyntaxTree exp, boolean substituteVars, IModelElement parent) {
CompoundInitializer compoundInit = (CompoundInitializer) exp;
for (int i = 0; i < compoundInit.getExpressionCount(); i++) {
if (compoundInit.getExpression(i) instanceof ContainerInitializer) {
checkContainerInitializer(compoundInit.getExpression(i), substituteVars, parent);
}
if (compoundInit.getExpression(i) instanceof CompoundInitializer) {
checkCompoundInitializer(compoundInit.getExpression(i), substituteVars, parent);
}
}
}
/**
* Method for checking if an expression is a {@link ContainerInitializer}.
* @param exp expression to be checked.
* @param substituteVars <code>true</code> if {@link #varMap} shall be applied to substitute variables in
* <code>exp</code> (if variable is nested), <code>false</code> if <code>exp</code> shall be taken over as it is.
* @param parent parent for temporary constraints
*/
private void checkContainerInitializer(ConstraintSyntaxTree exp, boolean substituteVars, IModelElement parent) {
ContainerInitializer containerInit = (ContainerInitializer) exp;
if (ConstraintType.TYPE.isAssignableFrom(containerInit.getType().getContainedType())) {
for (int i = 0; i < containerInit.getExpressionCount(); i++) {
Constraint constraint = new Constraint(parent);
ConstraintSyntaxTree cst = containerInit.getExpression(i);
if (substituteVars) {
cst = substituteVariables(cst, null, null, true);
}
try {
constraint.setConsSyntax(cst);
addConstraint(otherConstraints, constraint, false); // collectionConstraints
} catch (CSTSemanticException e) {
LOGGER.exception(e);
}
}
}
}
/**
* Method for getting all constraints relevant to a {@link Compound}.
* @param cmpType Compound to be analyzed.
* @param thisCompoundConstraints The list to add the compound {@link Constraint}s to.
* @param host True if this is a host compound.
*/
private void allCompoundConstraints(Compound cmpType,
List<Constraint> thisCompoundConstraints, boolean host) {
for (int i = 0; i < cmpType.getConstraintsCount(); i++) {
thisCompoundConstraints.add(cmpType.getConstraint(i));
}
if (host) { // TODO why not constraint expr via refines?
for (int i = 0; i < cmpType.getInheritedElementCount(); i++) {
DecisionVariableDeclaration decl = cmpType.getInheritedElement(i);
ConstraintSyntaxTree defaultValue = decl.getDefaultValue();
if (null != defaultValue) {
if (ConstraintType.TYPE.isAssignableFrom(decl.getType())) {
Constraint constraint = new Constraint(project);
try {
constraint.setConsSyntax(defaultValue);
thisCompoundConstraints.add(constraint);
} catch (CSTSemanticException e) {
LOGGER.exception(e);
}
}
}
}
}
for (int r = 0; r < cmpType.getRefinesCount(); r++) {
allCompoundConstraints(cmpType.getRefines(r), thisCompoundConstraints, false);
}
for (int a = 0; a < cmpType.getAssignmentCount(); a++) {
allAssignmentConstraints(cmpType.getAssignment(a), thisCompoundConstraints);
}
}
/**
* Collects all assignment constraints and adds them to <code>result</code>.
*
* @param assng the assignment constraint
* @param result the list of constraints to be modified as a side effect
*/
private void allAssignmentConstraints(AttributeAssignment assng, List<Constraint> result) {
for (int c = 0; c < assng.getConstraintsCount(); c++) {
result.add(assng.getConstraint(c));
}
for (int a = 0; a < assng.getAssignmentCount(); a++) {
allAssignmentConstraints(assng.getAssignment(a), result);
}
}
// <<< documented until here
// messages
/**
* Records information about the evaluation result, failed evaluation messages.
*
* @param constraint the constraint to record the actual messages for
*/
private void analyzeEvaluationResult(Constraint constraint) {
if (evaluator.constraintFailed()) {
FailedElementDetails failedElementDetails = new FailedElementDetails();
failedElementDetails.setProblemPoints(new HashSet<IDecisionVariable>(usedVariables));
failedElementDetails.setProblemConstraintPart(getFailedConstraintPart());
failedElementDetails.setProblemConstraint(constraint);
failedElementDetails.setErrorClassifier(ReasoningErrorCodes.FAILED_CONSTRAINT);
failedElements.addProblemConstraint(constraint, failedElementDetails);
if (Descriptor.LOGGING) {
LOGGER.debug("Failed constraint: " + toIvmlString(constraint));
printModelElements(config, "constraint resolved");
printProblemPoints(usedVariables);
}
} else if (evaluator.constraintFulfilled()) {
failedElements.removeProblemConstraint(constraint);
if (Descriptor.LOGGING) {
LOGGER.debug("Constraint fulfilled: " + toIvmlString(constraint));
}
}
for (int j = 0; j < evaluator.getMessageCount(); j++) {
Message msg = evaluator.getMessage(j);
AbstractVariable var = msg.getVariable();
if (var != null) {
// no local variable, i.e., defined for/within user-defined operation or within constraint
if (!(var.getParent() instanceof OperationDefinition) && !(var.getParent() instanceof Constraint)) {
usedVariables.clear();
usedVariables.add(msg.getDecision());
FailedElementDetails failedelementDetails = new FailedElementDetails();
failedelementDetails.setProblemPoints(new HashSet<IDecisionVariable>(usedVariables));
// due to NULL result if failed assignment
failedelementDetails.setProblemConstraintPart(constraint.getConsSyntax());
failedelementDetails.setProblemConstraint(constraint);
failedelementDetails.setErrorClassifier(ReasoningErrorCodes.FAILED_REASSIGNMENT);
failedElements.addProblemVariable(var, failedelementDetails);
if (Descriptor.LOGGING) {
LOGGER.debug("Assigment error: " + evaluator.getMessage(j).getVariable());
printProblemPoints(usedVariables);
}
}
}
}
}
// helpers, accessors
/**
* Adds <code>constraint</code> to the constraint base.
*
* @param constraint the constraint
*/
private void addToConstraintBase(Constraint constraint) {
constraintBase.addLast(constraint);
constraintBaseSet.add(constraint);
}
/**
* Method for using {@link SubstitutionVisitor} for constraint transformation. Uses the actual
* variable mapping in {@link #varMap} and may consider a mapping for <code>self</code>.
*
* @param cst Constraint to be transformed.
* @param selfEx an expression representing <i>self</i> (ignored if <b>null</b>, <code>self</code> and
* <code>selfEx</code> shall never both be specified/not <b>null</b>).
* @param self an variable declaration representing <i>self</i> (ignored if <b>null</b>).
* @param clear clear {@link #substVisitor} if <code>true</code> or leave its state for further queries requring
* the caller to explicitly clear the copy visitor after usage
* @return Transformed constraint.
*/
private ConstraintSyntaxTree substituteVariables(ConstraintSyntaxTree cst, ConstraintSyntaxTree selfEx,
AbstractVariable self, boolean clear) {
substVisitor.setMappings(varMap);
if (selfEx != null) {
substVisitor.setSelf(selfEx);
}
if (self != null) {
substVisitor.setSelf(self);
}
cst = substVisitor.acceptAndClear(cst);
inferTypeSafe(cst, null);
return cst;
}
/**
* Adds all <code>constraints</code> to the constraint base.
*
* @param constraints the constraints
*/
private void addAllToConstraintBase(Collection<Constraint> constraints) {
constraintBase.addAll(constraints);
constraintBaseSet.addAll(constraints);
}
/**
* Method for clearing all constraint lists.
*/
private void clearConstraintLists() {
defaultConstraints.clear();
deferredDefaultConstraints.clear();
topLevelConstraints.clear();
otherConstraints.clear();
}
/**
* Will be called after a failure was detected in a default constraint of an {@link AbstractVariable}.
* @param decl The conflicting declaration of an {@link AbstractVariable}.
* Call {@link AbstractVariable#getDefaultValue()} to retrieve the conflicting constraint.
*/
@SuppressWarnings("unused")
private void conflictingDefault(AbstractVariable decl) {
// currently unused
}
/**
* Method for creating a clean {@link Configuration}.
* @param project Project for {@link Configuration}
* @return Created {@link Configuration}
*/
private Configuration createCleanConfiguration(Project project) {
return new Configuration(project, false);
}
/**
* Method for checking part of a failed constraints against null.
* @return null or part of a failed constraint.
*/
private ConstraintSyntaxTree getFailedConstraintPart() {
ConstraintSyntaxTree cstPart = null;
if (evaluator.getFailedExpression() != null) {
cstPart = evaluator.getFailedExpression()[0];
}
return cstPart;
}
/**
* Getter for the map of all ConstraintVariables.
* and their {@link Constraint}s.
* @return Map of constraint variables and their constraints.
*/
Map<Constraint, IDecisionVariable> getConstraintVariableMap() {
return constraintVariableMap;
}
/**
* Method for returning the overall count of evaluated constraints in the model.
* @return number of evaluated constraints.
*/
int constraintCount() {
return constraintCounter;
}
/**
* Method for returning the overall number of variables in the model.
* @return number of variables.
*/
int variableCount() {
return variablesCounter;
}
/**
* Method for returning the number of variables involved in constraints.
* @return number of variables.
*/
int variableInConstraintCount() {
return variablesInConstraintsCounter;
}
/**
* Method for returning the overall number of reevaluations in the model.
* @return number of reevaluations.
*/
int reevaluationCount() {
return reevaluationCounter;
}
/**
* Method for retrieving {@link FailedElements} with failed {@link Constraint}s and {@link IDecisionVariable}s.
* @return {@link FailedElements}
*/
FailedElements getFailedElements() {
return failedElements;
}
/**
* Sets whether reasoning shall happen incrementally.
*
* @param incremental if reasoning shall happen incrementally
* @see #setConsiderFrozenConstraints(boolean)
*/
void setIncremental(boolean incremental) {
this.incremental = incremental;
}
/**
* Defines whether frozen constraints shall be considered. Can speed up incremental reasoning.
*
* @param considerFrozenConstraints whether frozen constraint shall be considered (default <code>true</code>)
* @see #setIncremental(boolean)
*/
void setConsiderFrozenConstraints(boolean considerFrozenConstraints) {
this.considerFrozenConstraints = considerFrozenConstraints;
}
/**
* Factory method for creating the evaluation visitor.
*
* @return the evaluation visitor
*/
protected EvaluationVisitor createEvaluationVisitor() {
return new EvalVisitor();
}
/**
* Returns whether reasoning stopped due to a timeout.
*
* @return <code>true</code> for timeout, <code>false</code> else
*/
boolean hasTimeout() {
return hasTimeout;
}
/**
* Returns whether reasoning was stopped due to a user-request.
*
* @return <code>true</code> for stopped, <code>false</code> else
*/
boolean wasStopped() {
return wasStopped;
}
/**
* Returns whether the reasoner is (still) operating.
*
* @return <code>true</code> for operating, <code>false</code> else
*/
boolean isRunning() {
return isRunning;
}
/**
* Stops/terminates reasoning. If possible, a reasoner shall stop the reasoning
* operations as quick as possible. A reasoner must not implement this operation.
*
* @return <code>true</code> if the reasoner tries to stop, <code>false</code> else
* (operation not implemented)
*/
boolean stop() {
wasStopped = true;
return true;
}
/**
* Marks this instance for re-use. Must be called before the first call to {@link #resolve()}.
*/
void markForReuse() {
constraintBaseCopy = new LinkedList<Constraint>();
}
/**
* Clears this instance for reuse to free most of the resources.
*
* @see #markForReuse()
* @see #reInit()
*/
void clear() {
clearConstraintLists();
failedElements.clear();
scopeAssignments.clearScopeAssignments();
// keep the constraintMap
// keep the constraintVariableMap
constraintBase.clear();
constraintBaseSet.clear();
// keep constraintCounter - is set during translation
// keep variablesInConstraintsCounter - is set during translation
reevaluationCounter = 0;
// keep variablesCounter - is set during translation
hasTimeout = false;
isRunning = false;
wasStopped = false;
usedVariables.clear();
substVisitor.clear();
varMap.clear();
containerFinder.clear();
simpleAssignmentFinder.clear();
}
/**
* Re-initializes this resolver instance to allocated resources only if really needed.
*
* @see #markForReuse()
* @see #reInit()
*/
void reInit() {
if (null != constraintBaseCopy) {
constraintBase.addAll(constraintBaseCopy);
constraintBaseSet.addAll(constraintBaseCopy);
}
}
}
|
package org.safehaus.subutai.impl.elasticsearch;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.safehaus.subutai.api.agentmanager.AgentManager;
import org.safehaus.subutai.api.commandrunner.AgentResult;
import org.safehaus.subutai.api.elasticsearch.Elasticsearch;
import org.safehaus.subutai.api.elasticsearch.Config;
import org.safehaus.subutai.api.commandrunner.Command;
import org.safehaus.subutai.api.commandrunner.CommandRunner;
import org.safehaus.subutai.api.dbmanager.DbManager;
import org.safehaus.subutai.api.networkmanager.NetworkManager;
import org.safehaus.subutai.api.lxcmanager.LxcCreateException;
import org.safehaus.subutai.api.lxcmanager.LxcDestroyException;
import org.safehaus.subutai.api.lxcmanager.LxcManager;
import org.safehaus.subutai.shared.operation.ProductOperation;
import org.safehaus.subutai.api.tracker.Tracker;
import org.safehaus.subutai.shared.protocol.Agent;
public class ElasticsearchImpl implements Elasticsearch {
private DbManager dbManager;
private Tracker tracker;
private LxcManager lxcManager;
private ExecutorService executor;
private NetworkManager networkManager;
private CommandRunner commandRunner;
private AgentManager agentManager;
public AgentManager getAgentManager() {
return agentManager;
}
public void setAgentManager(AgentManager agentManager) {
this.agentManager = agentManager;
}
public void init() {
Commands.init(commandRunner);
executor = Executors.newCachedThreadPool();
}
public void destroy() {
executor.shutdown();
}
public void setLxcManager(LxcManager lxcManager) {
this.lxcManager = lxcManager;
}
public void setDbManager(DbManager dbManager) {
this.dbManager = dbManager;
}
public void setTracker(Tracker tracker) {
this.tracker = tracker;
}
public void setNetworkManager(NetworkManager networkManager) {
this.networkManager = networkManager;
}
public void setCommandRunner(CommandRunner commandRunner) {
this.commandRunner = commandRunner;
}
public UUID installCluster(final Config config) {
final ProductOperation po = tracker.createProductOperation(Config.PRODUCT_KEY, "Installing Elasticsearch...");
executor.execute(new Runnable() {
public void run() {
if (dbManager.getInfo(Config.PRODUCT_KEY, config.getClusterName(), Config.class) != null) {
po.addLogFailed(String.format("Cluster with name '%s' already exists\nInstallation aborted", config.getClusterName()));
return;
}
try {
po.addLog(String.format("Creating %d LXC containers for Elasticsearch cluster...", config.getNumberOfNodes()));
Map<Agent, Set<Agent>> lxcAgentsMap = CustomPlacementStrategy.createNodes(
lxcManager, config.getNumberOfNodes());
for (Map.Entry<Agent, Set<Agent>> entry : lxcAgentsMap.entrySet()) {
config.getNodes().addAll(entry.getValue());
}
// Master nodes
Set<Agent> masterNodes = new HashSet();
for ( Agent agent : config.getNodes() ) {
masterNodes.add( agent );
if ( masterNodes.size() == config.getNumberOfMasterNodes() ) {
break;
}
}
config.setMasterNodes( masterNodes );
// Data nodes
for ( Agent agent : config.getNodes() ) {
config.getDataNodes().add( agent );
if ( config.getDataNodes().size() == config.getNumberOfDataNodes() ) {
break;
}
}
po.addLog("Lxc containers created successfully.");
po.addLog("Updating db...");
if (dbManager.saveInfo(Config.PRODUCT_KEY, config.getClusterName(), config)) {
po.addLog("Cluster info saved to DB");
// Install
po.addLog("Installing...");
Command installCommand = Commands.getInstallCommand(config.getNodes());
commandRunner.runCommand(installCommand);
if (installCommand.hasSucceeded()) {
po.addLog("Installation succeeded");
} else {
po.addLogFailed(String.format("Installation failed, %s", installCommand.getAllErrors()));
return;
}
// Setting cluster name
po.addLog( "Setting cluster name: " + config.getClusterName() );
Command setClusterNameCommand = Commands.getConfigureCommand(config.getNodes(), "cluster.name " + config.getClusterName());
commandRunner.runCommand(setClusterNameCommand);
if (setClusterNameCommand.hasSucceeded()) {
po.addLog("Configure cluster name succeeded");
} else {
po.addLogFailed(String.format("Installation failed, %s", setClusterNameCommand.getAllErrors()));
return;
}
// Setting master nodes
po.addLog( "Setting master nodes..." );
Command setMasterNodesCommand = Commands.getConfigureCommand( config.getMasterNodes(), "node.master true" );
commandRunner.runCommand(setMasterNodesCommand);
if (setMasterNodesCommand.hasSucceeded()) {
po.addLog("Master nodes setup successful");
} else {
po.addLogFailed(String.format("Installation failed, %s", setMasterNodesCommand.getAllErrors()));
return;
}
// Setting data nodes
po.addLog( "Setting data nodes..." );
Command dataNodesCommand =
Commands.getConfigureCommand( config.getDataNodes(), "node.data true" );
commandRunner.runCommand( dataNodesCommand );
if ( dataNodesCommand.hasSucceeded() ) {
po.addLog( "Data nodes setup successful" );
}
else {
po.addLogFailed(
String.format( "Installation failed, %s", dataNodesCommand.getAllErrors() ) );
return;
}
// Setting number of shards
po.addLog( "Setting number of shards..." );
Command shardsCommand = Commands.getConfigureCommand( config.getNodes(),
"index.number_of_shards " + config.getNumberOfShards() );
commandRunner.runCommand( shardsCommand );
if ( !shardsCommand.hasSucceeded() ) {
po.addLogFailed( String.format( "Installation failed, %s", shardsCommand.getAllErrors() ) );
return;
}
// Setting number of replicas
po.addLog( "Setting number of replicas..." );
Command numberOfReplicasCommand = Commands.getConfigureCommand( config.getNodes(),
"index.number_of_replicas " + config.getNumberOfReplicas() );
commandRunner.runCommand( numberOfReplicasCommand );
if ( !numberOfReplicasCommand.hasSucceeded() ) {
po.addLogFailed( String.format( "Installation failed, %s", numberOfReplicasCommand.getAllErrors() ) );
return;
}
// Done
po.addLogDone("Installation of Elasticsearch cluster succeeded");
} else {
// In case of error - destroy created LXCs
try {
lxcManager.destroyLxcs(config.getNodes());
} catch (LxcDestroyException ex) {
po.addLogFailed("Could not save cluster info to DB! Please see logs. Use LXC module to cleanup\nInstallation aborted");
}
po.addLogFailed("Could not save cluster info to DB! Please see logs\nInstallation aborted");
}
} catch(LxcCreateException ex) {
po.addLogFailed(ex.getMessage());
}
}
});
return po.getId();
}
@Override
public UUID uninstallCluster(final String clusterName) {
final ProductOperation po = tracker.createProductOperation(Config.PRODUCT_KEY,
String.format("Destroying cluster %s", clusterName));
executor.execute(new Runnable() {
public void run() {
Config config = dbManager.getInfo(Config.PRODUCT_KEY, clusterName, Config.class);
if (config == null) {
po.addLogFailed(String.format("Cluster with name %s does not exist\nOperation aborted", clusterName));
return;
}
po.addLog("Destroying lxc containers...");
try {
lxcManager.destroyLxcs(config.getNodes());
po.addLog("Lxc containers successfully destroyed");
} catch (LxcDestroyException ex) {
po.addLog(String.format("%s, skipping...", ex.getMessage()));
}
po.addLog("Updating db...");
if (dbManager.deleteInfo(Config.PRODUCT_KEY, config.getClusterName())) {
po.addLogDone("Cluster info deleted from DB\nDone");
} else {
po.addLogFailed("Error while deleting cluster info from DB. Check logs.\nFailed");
}
}
});
return po.getId();
}
@Override
public UUID startAllNodes( final String clusterName ) {
final ProductOperation po = tracker.createProductOperation( Config.PRODUCT_KEY,
String.format( "Starting cluster %s", clusterName ) );
executor.execute( new Runnable() {
public void run() {
Config config = dbManager.getInfo( Config.PRODUCT_KEY, clusterName, Config.class );
if ( config == null ) {
po.addLogFailed(
String.format( "Cluster with name %s does not exist\nOperation aborted", clusterName ) );
return;
}
Command startServiceCommand = Commands.getStartCommand( config.getNodes() );
commandRunner.runCommand( startServiceCommand );
if ( startServiceCommand.hasSucceeded() ) {
po.addLogDone( "Start succeeded" );
}
else {
po.addLogFailed( String.format( "Start failed, %s", startServiceCommand.getAllErrors() ) );
}
}
} );
return po.getId();
}
@Override
public UUID stopAllNodes( final String clusterName ) {
final ProductOperation po = tracker.createProductOperation( Config.PRODUCT_KEY,
String.format( "Stopping cluster %s", clusterName ) );
executor.execute( new Runnable() {
public void run() {
Config config = dbManager.getInfo( Config.PRODUCT_KEY, clusterName, Config.class );
if ( config == null ) {
po.addLogFailed(
String.format( "Cluster with name %s does not exist\nOperation aborted", clusterName ) );
return;
}
Command stopServiceCommand = Commands.getStopCommand( config.getNodes() );
commandRunner.runCommand( stopServiceCommand );
if ( stopServiceCommand.hasSucceeded() ) {
po.addLogDone( "Stop succeeded" );
}
else {
po.addLogFailed( String.format( "Start failed, %s", stopServiceCommand.getAllErrors() ) );
}
}
} );
return po.getId();
}
@Override
public UUID checkAllNodes( final String clusterName ) {
final ProductOperation po = tracker.createProductOperation( Config.PRODUCT_KEY,
String.format( "Checking cluster %s", clusterName ) );
executor.execute( new Runnable() {
public void run() {
Config config = dbManager.getInfo( Config.PRODUCT_KEY, clusterName, Config.class );
if ( config == null ) {
po.addLogFailed(
String.format( "Cluster with name %s does not exist\nOperation aborted", clusterName ) );
return;
}
Command checkStatusCommand = Commands.getStatusCommand( config.getNodes() );
commandRunner.runCommand( checkStatusCommand );
if ( checkStatusCommand.hasSucceeded() ) {
po.addLogDone( "All nodes are running." );
}
else {
logStatusResults( po, checkStatusCommand );
}
}
} );
return po.getId();
}
private void logStatusResults( ProductOperation po, Command checkStatusCommand ) {
String log = "";
for ( Map.Entry<UUID, AgentResult> e : checkStatusCommand.getResults().entrySet() ) {
String status = "UNKNOWN";
if ( e.getValue().getExitCode() == 0 ) {
status = "RUNNING";
} else if ( e.getValue().getExitCode() == 768 ) {
status = "NOT RUNNING";
}
log += String.format( "- %s: %s\n", e.getValue().getAgentUUID(), status );
}
po.addLogDone( log );
}
@Override
public List<Config> getClusters() {
return dbManager.getInfo(Config.PRODUCT_KEY, Config.class);
}
@Override
public Config getCluster(String clusterName) {
return dbManager.getInfo(Config.PRODUCT_KEY, clusterName, Config.class);
}
}
|
package com.opengamma.financial.analytics.model.forex.defaultproperties;
import java.util.Collections;
import java.util.Set;
import com.opengamma.engine.ComputationTarget;
import com.opengamma.engine.ComputationTargetType;
import com.opengamma.engine.function.FunctionCompilationContext;
import com.opengamma.engine.value.ValuePropertyNames;
import com.opengamma.engine.value.ValueRequirement;
import com.opengamma.engine.value.ValueRequirementNames;
import com.opengamma.financial.analytics.model.forex.ForexOptionBlackFunction;
import com.opengamma.financial.analytics.model.forex.ForexVisitors;
import com.opengamma.financial.property.DefaultPropertyFunction;
import com.opengamma.financial.security.FinancialSecurity;
import com.opengamma.financial.security.option.FXBarrierOptionSecurity;
import com.opengamma.financial.security.option.FXDigitalOptionSecurity;
import com.opengamma.financial.security.option.FXOptionSecurity;
import com.opengamma.util.ArgumentChecker;
import com.opengamma.util.money.Currency;
public class ForexOptionBlackDefaultPropertiesFunction extends DefaultPropertyFunction {
private static final String[] VALUE_REQUIREMENTS = new String[] {
ValueRequirementNames.PRESENT_VALUE,
ValueRequirementNames.FX_CURRENCY_EXPOSURE,
ValueRequirementNames.VALUE_VEGA,
ValueRequirementNames.VEGA_MATRIX,
ValueRequirementNames.VEGA_QUOTE_MATRIX,
ValueRequirementNames.FX_CURVE_SENSITIVITIES,
ValueRequirementNames.YIELD_CURVE_NODE_SENSITIVITIES
};
private final String _putCurveName;
private final String _putForwardCurveName;
private final String _putCurveCalculationMethod;
private final String _callCurveName;
private final String _callForwardCurveName;
private final String _callCurveCalculationMethod;
private final String _surfaceName;
private final String _putCurrency;
private final String _callCurrency;
public ForexOptionBlackDefaultPropertiesFunction(final String putCurveName, final String putForwardCurveName, final String putCurveCalculationMethod, final String callCurveName,
final String callForwardCurveName, final String callCurveCalculationMethod, final String surfaceName, final String putCurrency, final String callCurrency) {
super(ComputationTargetType.SECURITY, true);
ArgumentChecker.notNull(putCurveName, "put curve name");
ArgumentChecker.notNull(putForwardCurveName, "put forward curve name");
ArgumentChecker.notNull(putCurveCalculationMethod, "put curve calculation method");
ArgumentChecker.notNull(putCurveName, "call curve name");
ArgumentChecker.notNull(putForwardCurveName, "call forward curve name");
ArgumentChecker.notNull(callCurveCalculationMethod, "call curve calculation method");
ArgumentChecker.notNull(surfaceName, "surface name");
ArgumentChecker.notNull(putCurrency, "put currency");
ArgumentChecker.notNull(callCurrency, "call currency");
_putCurveName = putCurveName;
_putForwardCurveName = putForwardCurveName;
_putCurveCalculationMethod = putCurveCalculationMethod;
_callCurveName = callCurveName;
_callForwardCurveName = callForwardCurveName;
_callCurveCalculationMethod = callCurveCalculationMethod;
_surfaceName = surfaceName;
_putCurrency = putCurrency;
_callCurrency = callCurrency;
}
@Override
public boolean canApplyTo(final FunctionCompilationContext context, final ComputationTarget target) {
if (target.getType() != ComputationTargetType.SECURITY) {
return false;
}
if (!(target.getSecurity() instanceof FinancialSecurity)) {
return false;
}
final FinancialSecurity security = (FinancialSecurity) target.getSecurity();
if (!(security instanceof FXOptionSecurity || security instanceof FXBarrierOptionSecurity || security instanceof FXDigitalOptionSecurity)) {
return false;
}
final Currency putCurrency = security.accept(ForexVisitors.getPutCurrencyVisitor());
final Currency callCurrency = security.accept(ForexVisitors.getCallCurrencyVisitor());
return callCurrency.getCode().equals(_callCurrency) && putCurrency.getCode().equals(_putCurrency);
}
@Override
protected void getDefaults(final PropertyDefaults defaults) {
for (final String valueRequirement : VALUE_REQUIREMENTS) {
defaults.addValuePropertyName(valueRequirement, ForexOptionBlackFunction.PROPERTY_PUT_CURVE);
defaults.addValuePropertyName(valueRequirement, ForexOptionBlackFunction.PROPERTY_PUT_FORWARD_CURVE);
defaults.addValuePropertyName(valueRequirement, ForexOptionBlackFunction.PROPERTY_PUT_CURVE_CALCULATION_METHOD);
defaults.addValuePropertyName(valueRequirement, ForexOptionBlackFunction.PROPERTY_CALL_CURVE);
defaults.addValuePropertyName(valueRequirement, ForexOptionBlackFunction.PROPERTY_CALL_FORWARD_CURVE);
defaults.addValuePropertyName(valueRequirement, ForexOptionBlackFunction.PROPERTY_CALL_CURVE_CALCULATION_METHOD);
defaults.addValuePropertyName(valueRequirement, ValuePropertyNames.SURFACE);
}
}
@Override
protected Set<String> getDefaultValue(final FunctionCompilationContext context, final ComputationTarget target, final ValueRequirement desiredValue, final String propertyName) {
if (ForexOptionBlackFunction.PROPERTY_CALL_CURVE.equals(propertyName)) {
return Collections.singleton(_callCurveName);
}
if (ForexOptionBlackFunction.PROPERTY_CALL_FORWARD_CURVE.equals(propertyName)) {
return Collections.singleton(_callForwardCurveName);
}
if (ForexOptionBlackFunction.PROPERTY_CALL_CURVE_CALCULATION_METHOD.equals(propertyName)) {
return Collections.singleton(_callCurveCalculationMethod);
}
if (ForexOptionBlackFunction.PROPERTY_PUT_CURVE.equals(propertyName)) {
return Collections.singleton(_putCurveName);
}
if (ForexOptionBlackFunction.PROPERTY_PUT_FORWARD_CURVE.equals(propertyName)) {
return Collections.singleton(_putForwardCurveName);
}
if (ForexOptionBlackFunction.PROPERTY_PUT_CURVE_CALCULATION_METHOD.equals(propertyName)) {
return Collections.singleton(_putCurveCalculationMethod);
}
if (ValuePropertyNames.SURFACE.equals(propertyName)) {
return Collections.singleton(_surfaceName);
}
return null;
}
}
|
package gov.nih.nci.cabig.report2adeers;
import gov.nih.nci.cabig.caaers2adeers.Caaers2AdeersRouteBuilder;
import org.apache.camel.ExchangePattern;
import static gov.nih.nci.cabig.caaers2adeers.exchnage.ExchangePreProcessor.*;
import static gov.nih.nci.cabig.caaers2adeers.track.IntegrationLog.Stage.*;
import static gov.nih.nci.cabig.caaers2adeers.track.Tracker.track;
import static gov.nih.nci.cabig.report2adeers.exchange.AdeersReportSubmissionProcessor.*;
/**
* will transform the caaers XML to AdEERS XML and publish the request to AdEERS Report Service
*/
public class ToAdeersReportServiceRouteBuilder {
public void configure(Caaers2AdeersRouteBuilder rb){
rb.from("activemq:adeers-ae-message.inputQueue?concurrentConsumers=5")
.streamCaching()
.to("log:gov.nih.nci.cabig.report2adeers.first-request?showHeaders=true&multiline=true&level=ERROR")
.setProperty(OPERATION_NAME, rb.constant("sendReportToAdeers"))
.setProperty(ENTITY_NAME, rb.constant("SafetyReport"))
.processRef("adeersHeaderGeneratorProcessor")
.processRef("headerGeneratorProcessor")
.to("log:gov.nih.nci.cabig.report2adeers.split-path?showHeaders=true&multiline=true&level=DEBUG")
.choice()
.when(rb.header(REPORT_WITHDRAW).isEqualTo("true"))
.to("direct:submit-report")
.when(rb.header(REPORT_WITHDRAW).isEqualTo("false"))
.to("direct:submit-report")
.otherwise()
.to("direct:morgue");
rb.from("direct:submit-report")
.process(track(REPORT_SUBMISSION_REQUEST))
.to(rb.getFileTracker().fileURI(REPORT_SUBMISSION_REQUEST))
.to("xslt:xslt/adeers/request/report-transformer.xsl")
.to("log:gov.nih.nci.cabig.report2adeers.presubmit-request?showHeaders=true&multiline=true&level=ERROR")
.process(track(ADEERS_REPORT_REQUEST))
.to(rb.getFileTracker().fileURI(ADEERS_REPORT_REQUEST))
.setExchangePattern(ExchangePattern.InOut)
.processRef("adeersReportSubmissionProcessor")
.to("log:gov.nih.nci.cabig.report2adeers.adeers-response?showHeaders=true&multiline=true&level=ERROR")
.process(track(ADEERS_REPORT_RESPONSE))
.to(rb.getFileTracker().fileURI(ADEERS_REPORT_RESPONSE))
.choice()
.when(rb.header(REPORT_SUBMISSION_STATUS).isEqualTo("ERROR"))
.to("direct:communication-error")
.otherwise()
.to("direct:adeers-response");
rb.from("direct:communication-error")
.process(track(ADEERS_SUBMISSION_FAILED, "Communication error"))
.to("xslt:xslt/adeers/response/report-error-transformer.xsl")
.process(track(REPORT_SUBMISSION_RESPONSE))
.to(rb.getFileTracker().fileURI(REPORT_SUBMISSION_RESPONSE))
.to("log:gov.nih.nci.cabig.report2adeers.pre-multicast?showHeaders=true&multiline=true&level=WARN")
.to("activemq:adeers-ae-message.outputQueue", "direct:routeAdEERSResponseSink");
rb.from("direct:adeers-response")
.to("xslt:xslt/adeers/response/report-transformer.xsl")
.process(track(REPORT_SUBMISSION_RESPONSE))
.to(rb.getFileTracker().fileURI(REPORT_SUBMISSION_RESPONSE))
.to("log:gov.nih.nci.cabig.report2adeers.response-sent?showHeaders=true&multiline=true&level=WARN")
.multicast()
.to("direct:toE2bAck", "direct:toJms");
rb.from("direct:toJms")
.to("log:gov.nih.nci.cabig.report2adeers.to-caaers-jms?showHeaders=true&multiline=true&level=WARN")
.to("activemq:adeers-ae-message.outputQueue");
rb.from("direct:toE2bAck")
.to("log:gov.nih.nci.cabig.report2adeers.to-e2b-ack?showHeaders=true&multiline=true&level=WARN")
.to("direct:routeAdEERSResponseSink");
}
}
|
package org.openhealthtools.mdht.uml.ui.dev.actions;
import java.util.Collections;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.operations.IUndoableOperation;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Status;
import org.eclipse.emf.common.util.TreeIterator;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.emf.transaction.TransactionalEditingDomain;
import org.eclipse.emf.transaction.util.TransactionUtil;
import org.eclipse.emf.workspace.AbstractEMFOperation;
import org.eclipse.emf.workspace.IWorkspaceCommandStack;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IActionDelegate;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.uml2.uml.Association;
import org.eclipse.uml2.uml.Class;
import org.eclipse.uml2.uml.Element;
import org.eclipse.uml2.uml.NamedElement;
import org.eclipse.uml2.uml.Profile;
import org.eclipse.uml2.uml.Property;
import org.eclipse.uml2.uml.Stereotype;
import org.openhealthtools.mdht.uml.cda.core.util.CDAProfileUtil;
import org.openhealthtools.mdht.uml.cda.core.util.ICDAProfileConstants;
import org.openhealthtools.mdht.uml.cda.ui.filters.TextAttributeFilter;
import org.openhealthtools.mdht.uml.term.ui.filters.CodedAttributeFilter;
public class TransformValidationSupportAction implements IObjectActionDelegate {
private NamedElement namedElement;
public TransformValidationSupportAction() {
super();
}
/**
* @see IActionDelegate#run(IAction)
*/
public void run(IAction action) {
try {
TransactionalEditingDomain editingDomain = TransactionUtil.getEditingDomain(namedElement);
IUndoableOperation operation = new AbstractEMFOperation(editingDomain, "Transform Validation Support") {
@Override
protected IStatus doExecute(IProgressMonitor monitor, IAdaptable info) {
TreeIterator<?> iterator = EcoreUtil.getAllContents(Collections.singletonList(namedElement));
while (iterator != null && iterator.hasNext()) {
Object child = iterator.next();
if (child instanceof NamedElement) {
// NamedElement childElement = (NamedElement) child;
// Stereotype validationSupport = CDAProfileUtil.getAppliedCDAStereotype(childElement,
// ICDAProfileConstants.VALIDATION_SUPPORT);
// if (validationSupport != null) {
// String message = (String) childElement.getValue(validationSupport, ICDAProfileConstants.VALIDATION_SUPPORT_MESSAGE);
// EnumerationLiteral literal = (EnumerationLiteral) childElement.getValue(validationSupport,
// ICDAProfileConstants.VALIDATION_SUPPORT_SEVERITY);
// String severity = (literal != null) ? literal.getName() : null;
// Stereotype validation = applyValidationStereotype(childElement);
// if (validation != null) {
// childElement.setValue(validation, ICDAProfileConstants.VALIDATION_SEVERITY, severity);
// childElement.setValue(validation, ICDAProfileConstants.VALIDATION_MESSAGE, message);
// childElement.unapplyStereotype(validationSupport);
// else {
// System.err.println("Error: could not migrate ValidationSupport on " + childElement.getQualifiedName());
}
}
return Status.OK_STATUS;
}
};
try {
IWorkspaceCommandStack commandStack = (IWorkspaceCommandStack) editingDomain.getCommandStack();
operation.addContext(commandStack.getDefaultUndoContext());
commandStack.getOperationHistory().execute(operation, new NullProgressMonitor(), null);
} catch (ExecutionException ee) {
ee.printStackTrace();
}
} catch (Exception e) {
throw new RuntimeException(e.getCause());
}
}
/**
* @see IObjectActionDelegate#setActivePart(IAction, IWorkbenchPart)
*/
public void setActivePart(IAction action, IWorkbenchPart targetPart) {
}
/**
* @see IActionDelegate#selectionChanged(IAction, ISelection)
*/
public void selectionChanged(IAction action, ISelection selection) {
namedElement = null;
if (((IStructuredSelection) selection).size() == 1) {
Object selected = ((IStructuredSelection) selection).getFirstElement();
if (selected instanceof IAdaptable) {
selected = ((IAdaptable) selected).getAdapter(EObject.class);
}
if (selected instanceof NamedElement) {
namedElement = (NamedElement) selected;
}
}
action.setEnabled(namedElement != null);
}
@SuppressWarnings({ "unused", "deprecation" })
private Stereotype applyValidationStereotype(Element element) {
Profile cdaProfile = CDAProfileUtil.getCDAProfile(element.eResource().getResourceSet());
Stereotype stereotype = CDAProfileUtil.getAppliedCDAStereotype(element, ICDAProfileConstants.VALIDATION);
if (stereotype == null && cdaProfile != null) {
if (element instanceof Association) {
stereotype = CDAProfileUtil.applyCDAStereotype(element, ICDAProfileConstants.ASSOCIATION_VALIDATION);
} else if (element instanceof Class) {
stereotype = CDAProfileUtil.applyCDAStereotype(element, ICDAProfileConstants.CLASS_VALIDATION);
} else if (element instanceof Property) {
if (new CodedAttributeFilter().select(element)) {
stereotype = CDAProfileUtil.applyCDAStereotype(element, ICDAProfileConstants.VOCAB_SPECIFICATION);
} else if (new TextAttributeFilter().select(element)) {
stereotype = CDAProfileUtil.applyCDAStereotype(element, ICDAProfileConstants.TEXT_VALUE);
} else {
stereotype = CDAProfileUtil.applyCDAStereotype(element, ICDAProfileConstants.PROPERTY_VALIDATION);
}
}
}
return stereotype;
}
}
|
package org.monarchinitiative.exomiser.autoconfigure.genome;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import de.charite.compbio.jannovar.data.JannovarData;
import de.charite.compbio.jannovar.data.JannovarDataSerializer;
import de.charite.compbio.jannovar.data.SerializationException;
import org.h2.mvstore.MVStore;
import org.monarchinitiative.exomiser.autoconfigure.ExomiserAutoConfigurationException;
import org.monarchinitiative.exomiser.core.genome.*;
import org.monarchinitiative.exomiser.core.genome.dao.*;
import org.monarchinitiative.exomiser.core.model.frequency.FrequencySource;
import org.monarchinitiative.exomiser.core.model.pathogenicity.PathogenicitySource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.sql.DataSource;
import java.nio.file.Path;
/**
* Acts as a manual version of Spring component discovery and DI. This is required as there can be more than one
* {@link org.monarchinitiative.exomiser.core.genome.GenomeAnalysisService} present to provide data for different genome
* assemblies. The {@link org.monarchinitiative.exomiser.core.genome.GenomeAnalysisService} has multiple layers of
* dependencies and as such is not a simple to construct, hence this class.
*
* @author Jules Jacobsen <j.jacobsen@qmul.ac.uk>
*/
public abstract class GenomeAnalysisServiceConfigurer implements GenomeAnalysisServiceConfiguration {
private static final Logger logger = LoggerFactory.getLogger(GenomeAnalysisServiceConfigurer.class);
private final GenomeProperties genomeProperties;
private final GenomeData genomeData;
protected final DataSource dataSource;
private final JannovarData jannovarData;
private final MVStore mvStore;
public GenomeAnalysisServiceConfigurer(GenomeProperties genomeProperties, Path exomiserDataDirectory) {
this.genomeProperties = genomeProperties;
logger.info("Configuring {} assembly (data-version={}, transcript-source={})", genomeProperties.getAssembly(), genomeProperties
.getDataVersion(), genomeProperties.getTranscriptSource());
this.genomeData = new GenomeData(genomeProperties, exomiserDataDirectory);
this.jannovarData = loadJannovarData();
this.dataSource = loadGenomeDataSource();
mvStore = new MVStore.Builder()
.fileName("C:/Users/hhx640/Documents/exomiser-build/data/allele_importer/mvStore/alleles.mv.db")
.readOnly()
.open();
logger.info("MVStore opened with maps: {}", mvStore.getMapNames());
logger.info("{}", genomeProperties.getDatasource());
}
private VariantFactory variantFactory() {
return new VariantFactoryImpl(new JannovarVariantAnnotator(genomeProperties.getAssembly(), jannovarData));
}
private GenomeDataService genomeDataService() {
RegulatoryFeatureDao regulatoryFeatureDao = new RegulatoryFeatureDao(dataSource);
TadDao tadDao = new TadDao(dataSource);
GeneFactory geneFactory = new GeneFactory(jannovarData);
return new GenomeDataServiceImpl(geneFactory, regulatoryFeatureDao, tadDao);
}
private VariantDataService variantDataService() {
return VariantDataServiceImpl.builder()
.defaultFrequencyDao(defaultFrequencyDao())
.localFrequencyDao(localFrequencyDao())
.pathogenicityDao(pathogenicityDao())
.remmDao(remmDao())
.caddDao(caddDao())
.build();
}
// The protected methods here are exposed so that the concrete sub-classes can call these as a bean method in order that
// Spring can intercept any caching annotations, but otherwise keep the duplicated GenomeAnalysisServices separate from
// any autowiring and autoconfiguration which will cause name clashes.
protected GenomeAnalysisService buildGenomeAnalysisService() {
return new GenomeAnalysisServiceImpl(genomeProperties.getAssembly(), genomeDataService(), variantDataService(), variantFactory());
}
@Override
public FrequencyDao defaultFrequencyDao() {
if (genomeProperties.getFrequencyPath().isEmpty()) {
//TODO: Once we've finished testing tabix - remove this check and go straight to tabix
return new DefaultFrequencyDao(dataSource);
}
return new DefaultFrequencyDaoMvStore(mvStore);
// return new DefaultFrequencyDaoTabix(defaultFrequencyTabixDataSource());
}
@Override
public PathogenicityDao pathogenicityDao() {
if (genomeProperties.getPathogenicityPath().isEmpty()) {
//TODO: Once we've finished testing tabix - remove this check and go straight to tabix
return new DefaultPathogenicityDao(dataSource);
}
return new DefaultPathogenicityDaoMvStore(mvStore);
// return new DefaultPathogenicityDaoTabix(defaultPathogenicityTabixDataSource());
}
protected TabixDataSource defaultFrequencyTabixDataSource() {
String frequencyPath = genomeProperties.getFrequencyPath();
Path pathToTabixGzFile = genomeData.resolveAbsoluteResourcePath(frequencyPath);
logger.info("Reading variant frequency data from {}", pathToTabixGzFile);
return TabixDataSourceLoader.load(pathToTabixGzFile);
}
protected TabixDataSource defaultPathogenicityTabixDataSource() {
String pathogenicityPath = genomeProperties.getPathogenicityPath();
Path pathToTabixGzFile = genomeData.resolveAbsoluteResourcePath(pathogenicityPath);
logger.info("Reading variant pathogenicity data from {}", pathToTabixGzFile);
return TabixDataSourceLoader.load(pathToTabixGzFile);
}
protected TabixDataSource caddInDelTabixDataSource() {
String caddInDelPath = genomeProperties.getCaddInDelPath();
logTabixPathIfNotEmpty("Reading CADD InDel file from:", caddInDelPath);
return getTabixDataSourceOrDefaultForProperty(caddInDelPath, "CADD InDel");
}
protected TabixDataSource caddSnvTabixDataSource() {
String caddSnvPath = genomeProperties.getCaddSnvPath();
logTabixPathIfNotEmpty("Reading CADD snv file from:", caddSnvPath);
return getTabixDataSourceOrDefaultForProperty(caddSnvPath, "CADD snv");
}
/**
* Optional full system path to REMM remmData.tsv.gz and remmData.tsv.gz.tbi file pair.
* <p>
* Default is empty and will return no data.
*
* @return
*/
protected TabixDataSource remmTabixDataSource() {
String remmPath = genomeProperties.getRemmPath();
logTabixPathIfNotEmpty("Reading REMM data file from:", remmPath);
return getTabixDataSourceOrDefaultForProperty(remmPath, PathogenicitySource.REMM.name());
}
/**
* Optional full system path to local frequency .tsv.gz and .tsv.gz.tbi file pair.
* <p>
* Default is empty and will return no data.
*
* @return
*/
protected TabixDataSource localFrequencyTabixDataSource() {
String localFrequencyPath = genomeProperties.getLocalFrequencyPath();
logTabixPathIfNotEmpty("Reading LOCAL frequency file from:", localFrequencyPath);
return getTabixDataSourceOrDefaultForProperty(localFrequencyPath, FrequencySource.LOCAL.name());
}
private void logTabixPathIfNotEmpty(String prefixMessage, String tabixPath) {
if (!tabixPath.isEmpty()) {
logger.info("{} {}", prefixMessage, tabixPath);
}
}
private TabixDataSource getTabixDataSourceOrDefaultForProperty(String pathToTabixGzFile, String dataSourceName) {
if (pathToTabixGzFile.isEmpty()) {
logger.warn("Data for {} is not configured. THIS WILL LEAD TO ERRORS IF REQUIRED DURING ANALYSIS. Check the application.properties is pointing to a valid file.", dataSourceName);
String message = "Data for " + dataSourceName + " is not configured. Check the application.properties is pointing to a valid file.";
return new ErrorThrowingTabixDataSource(message);
}
Path resourceFilePath = genomeData.resolveAbsoluteResourcePath(pathToTabixGzFile);
return TabixDataSourceLoader.load(resourceFilePath);
}
/**
* This takes a few seconds to de-serialise. Can be overridden by defining your own bean.
*/
private JannovarData loadJannovarData() {
Path transcriptFilePath = transcriptFilePath();
try {
return new JannovarDataSerializer(transcriptFilePath.toString()).load();
} catch (SerializationException e) {
throw new ExomiserAutoConfigurationException("Could not load Jannovar data from " + transcriptFilePath, e);
}
}
private Path transcriptFilePath() {
TranscriptSource transcriptSource = genomeProperties.getTranscriptSource();
//e.g 1710_hg19_transcripts_ucsc.ser
String transcriptFileNameValue = String.format("%s_transcripts_%s.ser", genomeData.getVersionAssemblyPrefix(), transcriptSource
.toString());
Path transcriptFilePath = genomeData.getPath().resolve(transcriptFileNameValue);
logger.info("Using {} transcript source for {}", transcriptSource, genomeProperties.getAssembly());
return transcriptFilePath;
}
private DataSource loadGenomeDataSource() {
return new HikariDataSource(genomeDataSourceConfig());
}
private HikariConfig genomeDataSourceConfig() {
//omit the .h2.db extensions
String dbFileName = String.format("%s_exomiser_genome", genomeData.getVersionAssemblyPrefix());
Path dbPath = genomeData.getPath().resolve(dbFileName);
String startUpArgs = ";MODE=PostgreSQL;SCHEMA=EXOMISER;DATABASE_TO_UPPER=FALSE;IFEXISTS=TRUE;AUTO_RECONNECT=TRUE;ACCESS_MODE_DATA=r;";
String jdbcUrl = String.format("jdbc:h2:file:%s%s", dbPath.toAbsolutePath(), startUpArgs);
HikariConfig config = new HikariConfig();
config.setDriverClassName("org.h2.Driver");
config.setJdbcUrl(jdbcUrl);
config.setUsername("sa");
config.setPassword("");
config.setMaximumPoolSize(3);
config.setPoolName(String.format("exomiser-genome-%s-%s", genomeProperties.getAssembly(), genomeProperties.getDataVersion()));
return config;
}
}
|
package org.jboss.as.test.integration.deployment.structure.war.symbolicLink;
import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import org.junit.Assert;
import org.junit.Assume;
import org.apache.commons.lang.SystemUtils;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.client.ModelControllerClient;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.as.test.shared.TestSuiteEnvironment;
import org.jboss.dmr.ModelNode;
import org.jboss.logging.Logger;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Unit test to make sure that the symbolic linking feature on the web subsystem is enabled properly.
* Corresponding JIRA: AS7-3414.
*
* @author navssurtani
*/
@RunWith(Arquillian.class)
@RunAsClient
public class SymlinkingUnitTestCase {
private static final Logger logger = Logger.getLogger(SymlinkingUnitTestCase.class);
private static final String WAR_NAME = "explodedDeployment.war";
private static File warDeployment = null;
private static File symbolic = null;
private static ModelControllerClient controllerClient = TestSuiteEnvironment.getModelControllerClient();
@BeforeClass
public static void beforeClass() throws IOException, InterruptedException {
Assume.assumeFalse(SystemUtils.IS_OS_WINDOWS);
logger.infof("beforeClass() call.");
// We are going to check whether or not the war deployment actually exists.
Assert.assertTrue(checkForDeployment());
// Now create the symlink.
createSymlink();
}
@AfterClass
public static void afterClass() throws IOException {
if (SystemUtils.IS_OS_WINDOWS) {
// skip windows;
} else {
logger.infof("afterClass() call.");
// Delete the symlink
symbolic.delete();
controllerClient.close();
controllerClient = null;
}
}
@After
public void tearDown() throws IOException {
logger.infof("In the tearDown() call.");
ModelNode removeSystemProperty = Util.createRemoveOperation(PathAddress.pathAddress(systemPropertyAddress()));
// Define the content.
ModelNode content = new ModelNode();
content.get(0).get(ModelDescriptionConstants.ARCHIVE).set(false);
content.get(0).get(ModelDescriptionConstants.PATH).set(warDeployment.getAbsolutePath());
// Undeploy operation.
ModelNode undeployOperation = Util.getEmptyOperation(ModelDescriptionConstants.UNDEPLOY, new ModelNode().add(ModelDescriptionConstants.DEPLOYMENT, WAR_NAME));
undeployOperation.get(ModelDescriptionConstants.CONTENT).set(ModelDescriptionConstants.CONTENT);
undeployOperation.get(ModelDescriptionConstants.ENABLE).set(true);
// Remove operation.
ModelNode removeOperation = Util.getEmptyOperation(ModelDescriptionConstants.REMOVE, new ModelNode().add(ModelDescriptionConstants.DEPLOYMENT, WAR_NAME));
removeOperation.get(ModelDescriptionConstants.CONTENT).set(ModelDescriptionConstants.CONTENT);
removeOperation.get(ModelDescriptionConstants.ENABLE).set(true);
// Composite operation.
ModelNode compositeOperation = Util.getEmptyOperation(ModelDescriptionConstants.COMPOSITE, new ModelNode());
ModelNode steps = compositeOperation.get(ModelDescriptionConstants.STEPS);
steps.add(undeployOperation);
steps.add(removeOperation);
steps.add(removeSystemProperty);
//logger.infof("Composite operation: %s", compositeOperation.toString());
ModelNode compositeResult = controllerClient.execute(compositeOperation);
Assert.assertEquals(ModelDescriptionConstants.SUCCESS, compositeResult.get(ModelDescriptionConstants.OUTCOME).asString());
}
@Test
public void testEnabled() throws IOException {
//logger.infof("Testing enabled bit");
// By default we should not be able to browse to the symlinked page.
Assert.assertTrue(getURLcode("symbolic") == 404);
setup(true);
// First make sure that we can browse to index.html. This should work in the enabled or disabled version.
Assert.assertTrue(getURLcode("index") == 200);
// Now with symbolic.html.
Assert.assertTrue(getURLcode("symbolic") == 200);
}
@Test
public void testDisabled() throws IOException {
logger.infof("Testing disabled bit.");
// By default we should not be able to browse to the symlinked page.
Assert.assertTrue(getURLcode("symbolic") == 404);
setup(false);
// First make sure that we can browse to index.html. This should work in the enabled or disabled version.
Assert.assertTrue(getURLcode("index") == 200);
// Now with symbolic.html.
Assert.assertTrue(getURLcode("symbolic") == 404);
}
private void setup(boolean symlinkingEnabled) throws IOException {
logger.infof("Entered the setup call within %s & the boolean parameter is %s",
this.getClass().getName(), symlinkingEnabled);
ModelNode addSysProperty = Util.createAddOperation(PathAddress.pathAddress(systemPropertyAddress()));
addSysProperty.get(ModelDescriptionConstants.VALUE).set(Boolean.toString(symlinkingEnabled));
ModelNode result = controllerClient.execute(addSysProperty);
Assert.assertEquals(ModelDescriptionConstants.SUCCESS, result.get(ModelDescriptionConstants.OUTCOME).asString());
// Define the content.
ModelNode content = new ModelNode();
content.get(0).get(ModelDescriptionConstants.ARCHIVE).set(false);
content.get(0).get(ModelDescriptionConstants.PATH).set(warDeployment.getAbsolutePath());
// Add operation.
ModelNode addOperation = Util.getEmptyOperation(ModelDescriptionConstants.ADD, new ModelNode().add(ModelDescriptionConstants.DEPLOYMENT, WAR_NAME));
addOperation.get(ModelDescriptionConstants.CONTENT).set(content);
addOperation.get(ModelDescriptionConstants.ENABLE).set(true);
result = controllerClient.execute(addOperation);
Assert.assertEquals(ModelDescriptionConstants.SUCCESS, result.get(ModelDescriptionConstants.OUTCOME).asString());
// Deployment operation.
ModelNode deploymentOperation = Util.getEmptyOperation(ModelDescriptionConstants.DEPLOY, new ModelNode().add(ModelDescriptionConstants.DEPLOYMENT, WAR_NAME));
deploymentOperation.get(ModelDescriptionConstants.CONTENT).set(content);
deploymentOperation.get(ModelDescriptionConstants.ENABLE).set(true);
result = controllerClient.execute(deploymentOperation);
Assert.assertEquals(ModelDescriptionConstants.SUCCESS, result.get(ModelDescriptionConstants.OUTCOME).asString());
}
private int getURLcode(String htmlPage) {
int code = 0;
try {
String url = "http://" + TestSuiteEnvironment.getServerAddress() + ":8080/explodedDeployment/"
+ htmlPage + ".html";
logger.infof("%s is the built URL.", url);
HttpURLConnection urlConnection = (HttpURLConnection) new URL(url).openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
code = urlConnection.getResponseCode();
logger.infof("Received response code of: " + code);
} catch (Exception e) {
logger.infof("Exception of type: %s caught", e.getClass(), e);
}
return code;
}
private ModelNode systemPropertyAddress() {
ModelNode address = new ModelNode();
address.add("system-property", "symbolic-linking-enabled");
address.protect();
return address;
}
private static boolean checkForDeployment() {
String warLocation = getWarLocation();
warDeployment = new File(warLocation);
logger.infof("Checking to see if exploded deployment exists at path: " + warDeployment.getAbsolutePath());
return warDeployment.exists();
}
private static String getWarLocation() {
return SymlinkingUnitTestCase.class.getResource(WAR_NAME).getPath();
}
private static void createSymlink() throws IOException, InterruptedException {
// TODO: navssurtani: once AS7 is on a minimum of Java 7 then we can change the approach used to create the symlink.
File index = new File(warDeployment, "index.html");
logger.infof("Path to index file is: " + index.getAbsolutePath());
Assert.assertTrue(index.exists());
// Now set up the information to create the symlink.
String toExecute;
if (SystemUtils.IS_OS_WINDOWS) {
logger.infof("Windows based OS detected.");
toExecute = "mklink \\D " + index.getAbsolutePath() + " " + warDeployment.getAbsolutePath()
+ "\\symbolic.html";
} else {
logger.infof("UNIX based OS detected.");
toExecute = "ln -s " + index.getAbsolutePath() + " " + warDeployment.getAbsolutePath() + "/symbolic.html";
}
logger.infof("String to be executed is: " + toExecute);
Runtime.getRuntime().exec(toExecute).waitFor();
symbolic = new File(warDeployment.getAbsolutePath(), "symbolic.html");
logger.infof("Absolute path of symbolic file is located at %s. Checking to see if the file really exists.",
symbolic.getAbsolutePath());
Assert.assertTrue(symbolic.exists());
}
}
|
package biz.netcentric.cq.tools.actool.authorizableinstaller.impl;
import static java.util.Arrays.asList;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.verifyZeroInteractions;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.Value;
import javax.jcr.ValueFactory;
import org.apache.commons.lang.StringUtils;
import org.apache.jackrabbit.api.security.user.Authorizable;
import org.apache.jackrabbit.api.security.user.Group;
import org.apache.jackrabbit.api.security.user.User;
import org.apache.jackrabbit.api.security.user.UserManager;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Enclosed;
import org.junit.runners.Parameterized;
import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.Spy;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.runners.MockitoJUnitRunner;
import org.mockito.stubbing.Answer;
import com.adobe.granite.crypto.CryptoException;
import com.adobe.granite.crypto.CryptoSupport;
import biz.netcentric.cq.tools.actool.authorizableinstaller.AuthorizableCreatorException;
import biz.netcentric.cq.tools.actool.configmodel.AcConfiguration;
import biz.netcentric.cq.tools.actool.configmodel.AuthorizableConfigBean;
import biz.netcentric.cq.tools.actool.configmodel.GlobalConfiguration;
import biz.netcentric.cq.tools.actool.history.PersistableInstallationLogger;
@RunWith(Enclosed.class)
public class AuthorizableInstallerServiceImplTest {
@RunWith(MockitoJUnitRunner.class)
public static final class BASE_TESTS {
public static final String TESTGROUP = "testGroup";
public static final String GROUP1 = "group1";
public static final String GROUP2 = "group2";
public static final String GROUP3 = "group3";
public static final String EXTERNALGROUP = "externalGroup";
public static final String USER1 = "user1";
public static final String SYSTEM_USER1 = "systemuser1";
// class under test
@Spy
private AuthorizableInstallerServiceImpl cut = new AuthorizableInstallerServiceImpl();
private AcConfiguration acConfiguration = new AcConfiguration();
private GlobalConfiguration globalConfiguration = new GlobalConfiguration();
private PersistableInstallationLogger status = new PersistableInstallationLogger();
@Mock
private UserManager userManager;
@Mock
private Session session;
@Mock
private ValueFactory valueFactory;
@Mock
private Group testGroup;
@Mock
private Group group1;
@Mock
private Group group2;
@Mock
private Group group3;
@Mock
private Group externalGroup;
@Mock
private User systemUser1;
@Mock
private User regularUser1;
@Before
public void setup() throws RepositoryException {
doReturn(valueFactory).when(session).getValueFactory();
Mockito.when(valueFactory.createValue(anyString())).thenAnswer(new Answer<Value>() {
@Override
public Value answer(InvocationOnMock invocation) throws Throwable {
Value mock = mock(Value.class);
Object val = invocation.getArguments()[0];
doReturn(val).when(mock).getString();
return mock;
}
});
acConfiguration.setGlobalConfiguration(globalConfiguration);
setupAuthorizable(testGroup, TESTGROUP, true, false);
setupAuthorizable(group1, GROUP1, true, false);
setupAuthorizable(group2, GROUP2, true, false);
setupAuthorizable(group3, GROUP3, true, false);
setupAuthorizable(externalGroup, EXTERNALGROUP, true, false);
setupAuthorizable(systemUser1, SYSTEM_USER1, false, true);
setupAuthorizable(regularUser1, USER1, false, false);
}
private void setupAuthorizable(Authorizable authorizable, String id, boolean isGroup, boolean isSystemUser) throws RepositoryException {
doReturn(authorizable).when(userManager).getAuthorizable(id);
doReturn(id).when(authorizable).getID();
doReturn(isGroup).when(authorizable).isGroup();
doReturn("/home/" + (isGroup ? "groups" : "users") + (isSystemUser ? "/system" : "") + "/test").when(authorizable).getPath();
}
@Test
public void testApplyGroupMembershipConfigIsMemberOf() throws Exception {
HashSet<String> configuredGroups = new HashSet<String>(Arrays.asList(GROUP1, GROUP2));
HashSet<String> groupsInRepo = new HashSet<String>(Arrays.asList(GROUP2, GROUP3, EXTERNALGROUP));
globalConfiguration.setDefaultUnmanagedExternalIsMemberOfRegex("external.*");
// just return the value as passed in as fourth argument
doAnswer(new Answer<Set<String>>() {
public Set<String> answer(InvocationOnMock invocation) throws Throwable {
return (Set<String>) invocation.getArguments()[4];
}
}).when(cut).validateAssignedGroups(userManager, acConfiguration.getAuthorizablesConfig(), null, TESTGROUP, configuredGroups, status);
Set<String> authorizablesInConfig = new HashSet<String>(asList(GROUP1));
AuthorizableConfigBean authorizableConfigBean = new AuthorizableConfigBean();
authorizableConfigBean.setAuthorizableId(TESTGROUP);
cut.applyGroupMembershipConfigIsMemberOf(authorizableConfigBean, acConfiguration, status, userManager, null, configuredGroups,
groupsInRepo,
authorizablesInConfig);
verifyZeroInteractions(group2); // in configuredGroups and in groupsInRepo
verifyZeroInteractions(externalGroup); // matches external.* and hence must not be removed (even though it is not in the
// configuration)
verify(group1).addMember(testGroup);
verifyNoMoreInteractions(group1);
verify(group3).removeMember(testGroup);
verifyNoMoreInteractions(group3);
}
@Test
public void testApplyGroupMembershipConfigMembers() throws Exception {
PersistableInstallationLogger history = new PersistableInstallationLogger();
acConfiguration.setGlobalConfiguration(new GlobalConfiguration());
AuthorizableConfigBean authorizableConfigBean = new AuthorizableConfigBean();
authorizableConfigBean.setAuthorizableId(TESTGROUP);
Set<String> authorizablesInConfig = new HashSet<String>(asList(GROUP1));
// test no change
authorizableConfigBean.setMembers(new String[] { GROUP2, GROUP3, SYSTEM_USER1 });
doReturn(asList(group2, group3, regularUser1, systemUser1).iterator()).when(testGroup).getDeclaredMembers();
cut.applyGroupMembershipConfigMembers(acConfiguration, authorizableConfigBean, history, TESTGROUP, userManager, authorizablesInConfig);
verify(testGroup, times(0)).addMember(any(Authorizable.class));
verify(testGroup, times(0)).removeMember(any(Authorizable.class));
reset(testGroup);
// test removed in config
authorizableConfigBean.setMembers(new String[] {});
doReturn(asList(group2, group3, regularUser1, systemUser1).iterator()).when(testGroup).getDeclaredMembers();
cut.applyGroupMembershipConfigMembers(acConfiguration, authorizableConfigBean, history, TESTGROUP, userManager, authorizablesInConfig);
verify(testGroup, times(0)).addMember(any(Authorizable.class));
verify(testGroup).removeMember(group2);
verify(testGroup).removeMember(group3);
verify(testGroup).removeMember(systemUser1);
verify(testGroup, times(0)).removeMember(regularUser1);// regular user must not be removed
reset(testGroup);
// test to be added as in config but not in repo
authorizableConfigBean.setMembers(new String[] { GROUP2, GROUP3, SYSTEM_USER1 });
doReturn(asList().iterator()).when(testGroup).getDeclaredMembers();
cut.applyGroupMembershipConfigMembers(acConfiguration, authorizableConfigBean, history, TESTGROUP, userManager, authorizablesInConfig);
verify(testGroup).addMember(group2);
verify(testGroup).addMember(group3);
verify(testGroup).addMember(systemUser1);
verify(testGroup, times(0)).removeMember(any(Authorizable.class));
reset(testGroup);
// test authorizable in config not removed
authorizableConfigBean.setMembers(new String[] {});
doReturn(asList(group1, group2).iterator()).when(testGroup).getDeclaredMembers();
cut.applyGroupMembershipConfigMembers(acConfiguration, authorizableConfigBean, history, TESTGROUP, userManager, authorizablesInConfig);
verify(testGroup, times(0)).addMember(any(Authorizable.class));
verify(testGroup, times(0)).removeMember(group1); // must not be removed since it's contained in config
verify(testGroup).removeMember(group2);
reset(testGroup);
// test authorizable in config not removed if defaultUnmanagedExternalMembersRegex is configured
acConfiguration.getGlobalConfiguration().setDefaultUnmanagedExternalMembersRegex("group2.*");
authorizableConfigBean.setMembers(new String[] {});
doReturn(asList(group1, group2).iterator()).when(testGroup).getDeclaredMembers();
cut.applyGroupMembershipConfigMembers(acConfiguration, authorizableConfigBean, history, TESTGROUP, userManager, authorizablesInConfig);
verify(testGroup, times(0)).addMember(any(Authorizable.class));
verify(testGroup, times(0)).removeMember(group1); // must not be removed since it's contained in config
verify(testGroup, times(0)).removeMember(group2); // must not be removed since allowExternalGroupNamesRegEx config
reset(testGroup);
}
@Test
public void testSetAuthorizableProperties() throws Exception {
AuthorizableConfigBean authorizableConfig = new AuthorizableConfigBean();
authorizableConfig.setIsGroup(false);
authorizableConfig.setName("John Doe");
authorizableConfig.setDescription("Test Description");
cut.setAuthorizableProperties(regularUser1, authorizableConfig, session, status);
verify(regularUser1).setProperty(eq("profile/givenName"), Matchers.argThat(new ValueMatcher("John")));
verify(regularUser1).setProperty(eq("profile/familyName"), Matchers.argThat(new ValueMatcher("Doe")));
verify(regularUser1).setProperty(eq("profile/aboutMe"), Matchers.argThat(new ValueMatcher("Test Description")));
authorizableConfig.setName("Van der Broek, Sebastian");
cut.setAuthorizableProperties(regularUser1, authorizableConfig, session, status);
verify(regularUser1).setProperty(eq("profile/givenName"), Matchers.argThat(new ValueMatcher("Sebastian")));
verify(regularUser1).setProperty(eq("profile/familyName"), Matchers.argThat(new ValueMatcher("Van der Broek")));
authorizableConfig.setName("Johann Sebastian Bach");
cut.setAuthorizableProperties(regularUser1, authorizableConfig, session, status);
verify(regularUser1).setProperty(eq("profile/givenName"), Matchers.argThat(new ValueMatcher("Johann Sebastian")));
verify(regularUser1).setProperty(eq("profile/familyName"), Matchers.argThat(new ValueMatcher("Bach")));
}
private final class ValueMatcher extends BaseMatcher<Value> {
private String expectedVal;
public ValueMatcher(String expectedVal) {
this.expectedVal = expectedVal;
}
@Override
public boolean matches(Object actualVal) {
if (!(actualVal instanceof Value)) {
return false;
} else {
try {
return StringUtils.equals(((Value) actualVal).getString(), expectedVal);
} catch (IllegalStateException | RepositoryException e) {
return false;
}
}
}
@Override
public void describeTo(Description desc) {
desc.appendText(" is " + expectedVal);
}
}
}
@RunWith(Parameterized.class)
public static final class SetUserPassword {
private static final String UNPROTECTED_PASSWORD = "unprotected_pass";
@Mock
private User user;
@Mock
private CryptoSupport cryptoSupportMock;
private AuthorizableInstallerServiceImpl service;
private String password;
private String expectedPassword;
public SetUserPassword(String password, String expectedPassword) {
this.password = password;
this.expectedPassword = expectedPassword;
}
@Parameterized.Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][] {
{ "{some_protected_pass}", UNPROTECTED_PASSWORD },
{ "bracketsAtTheEnd{pass}", "bracketsAtTheEnd{pass}" },
{ "{pass}bracketsAtTheStart", "{pass}bracketsAtTheStart" },
{ "bracketsIn{pass}TheMiddle", "bracketsIn{pass}TheMiddle" },
{ "noBrackets", "noBrackets" },
});
}
@Before
public void setUp() throws CryptoException {
MockitoAnnotations.initMocks(this);
service = new AuthorizableInstallerServiceImpl();
service.cryptoSupport = cryptoSupportMock;
doReturn(UNPROTECTED_PASSWORD).when(cryptoSupportMock).unprotect(anyString());
}
@Test
public void test() throws RepositoryException, AuthorizableCreatorException {
final AuthorizableConfigBean bean = new AuthorizableConfigBean();
bean.setPassword(password);
service.setUserPassword(bean, user);
verify(user).changePassword(eq(expectedPassword));
}
}
}
|
package org.openhab.binding.networkupstools.internal;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.networkupstools.jnut.Client;
import org.networkupstools.jnut.Device;
import org.networkupstools.jnut.Variable;
import org.openhab.binding.networkupstools.NetworkUpsToolsBindingProvider;
import org.openhab.core.binding.AbstractActiveBinding;
import org.openhab.core.items.Item;
import org.openhab.core.library.items.NumberItem;
import org.openhab.core.library.items.StringItem;
import org.openhab.core.library.items.SwitchItem;
import org.openhab.core.library.types.DecimalType;
import org.openhab.core.library.types.OnOffType;
import org.openhab.core.library.types.StringType;
import org.openhab.core.types.State;
import org.osgi.service.cm.ConfigurationException;
import org.osgi.service.cm.ManagedService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
/**
* The RefreshService polls all configured ups parameters with a configurable
* interval and post all values to the internal event bus. The interval is 1
* minute by default and can be changed via openhab.cfg.
*
* @author jaroslawmazgaj
* @since 1.7.0
*/
public class NetworkUpsToolsBinding extends AbstractActiveBinding<NetworkUpsToolsBindingProvider>
implements ManagedService {
private static final Logger logger = LoggerFactory.getLogger(NetworkUpsToolsBinding.class);
private Map<String, NutConfig> upses = new HashMap<String, NutConfig>();
/**
* the refresh interval which is used to poll values from the NetworkUpsTools
* server (optional, defaults to 60000ms)
*/
private long refreshInterval = 60000;
/**
* @{inheritDoc}
*/
@Override
protected long getRefreshInterval() {
return refreshInterval;
}
/**
* @{inheritDoc}
*/
@Override
protected String getName() {
return "NetworkUpsTools Refresh Service";
}
/**
* @{inheritDoc}
*/
@Override
protected void execute() {
Multimap<String, ItemDefinition> items = HashMultimap.create();
for (NetworkUpsToolsBindingProvider provider : providers) {
for (String itemName : provider.getItemNames()) {
String name = provider.getUps(itemName);
Class<? extends Item> itemType = provider.getItemType(itemName);
String property = provider.getProperty(itemName);
items.put(name, new ItemDefinition(itemName, itemType, property));
}
}
for (String name : items.keySet()) {
NutConfig nut = upses.get(name);
if (nut == null) {
logger.error("No configuration for UPS with name: '{}'", name);
continue;
}
Client client = null;
try {
client = new Client(nut.host, nut.port, nut.login, nut.pass);
Device device = client.getDevice(nut.device);
for (ItemDefinition definition : items.get(name)) {
Variable variable = device.getVariable(definition.property);
String value = variable.getValue();
Class<? extends Item> itemType = definition.itemType;
String itemName = definition.itemName;
// Change to a state
State state = null;
if (itemType.isAssignableFrom(StringItem.class)) {
state = StringType.valueOf(value);
} else if (itemType.isAssignableFrom(NumberItem.class)) {
state = DecimalType.valueOf(value);
} else if (itemType.isAssignableFrom(SwitchItem.class)) {
state = OnOffType.valueOf(value);
}
if (state != null) {
eventPublisher.postUpdate(itemName, state);
} else {
logger.error(
"'{}' couldn't be parsed to a State. Valid State-Types are String, Number and Switch",
variable.toString());
}
}
} catch (Exception ex) {
logger.error("Nut processing error", ex);
} finally {
if (client != null) {
client.disconnect();
}
}
}
}
protected void addBindingProvider(NetworkUpsToolsBindingProvider bindingProvider) {
super.addBindingProvider(bindingProvider);
}
protected void removeBindingProvider(NetworkUpsToolsBindingProvider bindingProvider) {
super.removeBindingProvider(bindingProvider);
}
/**
* @{inheritDoc}
*/
@Override
public void updated(Dictionary<String, ?> config) throws ConfigurationException {
if (config != null) {
String refreshIntervalString = (String) config.get("refresh");
if (StringUtils.isNotBlank(refreshIntervalString)) {
refreshInterval = Long.parseLong(refreshIntervalString);
}
Map<String, NutConfig> newUpses = new HashMap<String, NutConfig>();
Enumeration<String> keys = config.keys();
while (keys.hasMoreElements()) {
String key = keys.nextElement();
if ("refresh".equals(key) || "service.pid".equals(key)) {
continue;
}
String[] parts = key.split("\\.");
String name = parts[0];
String prop = parts[1];
String value = (String) config.get(key);
NutConfig nutConfig = newUpses.get(name);
if (nutConfig == null) {
nutConfig = new NutConfig();
newUpses.put(name, nutConfig);
}
if ("device".equalsIgnoreCase(prop)) {
nutConfig.device = value;
} else if ("host".equalsIgnoreCase(prop)) {
nutConfig.host = value;
} else if ("login".equalsIgnoreCase(prop)) {
nutConfig.login = value;
} else if ("pass".equalsIgnoreCase(prop)) {
nutConfig.pass = value;
} else if ("port".equalsIgnoreCase(prop)) {
nutConfig.port = Integer.parseInt(value);
}
}
upses = newUpses;
setProperlyConfigured(true);
}
}
/**
* This is an internal data structure to store nut server configuration
*/
class NutConfig {
String device;
String host = "localhost";
String login = "";
String pass = "";
int port = 3493;
}
/**
* This is an internal data structure to store item definition details for given nut server
*/
class ItemDefinition {
String itemName;
Class<? extends Item> itemType;
String property;
public ItemDefinition(String itemName, Class<? extends Item> itemType, String property) {
this.itemName = itemName;
this.itemType = itemType;
this.property = property;
}
}
}
|
package org.datavec.spark.transform.client;
import com.mashape.unirest.http.ObjectMapper;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import lombok.AllArgsConstructor;
import org.datavec.api.transform.TransformProcess;
import org.datavec.image.transform.ImageTransformProcess;
import org.datavec.spark.transform.model.*;
import org.datavec.spark.transform.service.DataVecTransformService;
import org.nd4j.shade.jackson.core.JsonProcessingException;
import java.io.IOException;
@AllArgsConstructor
public class DataVecTransformClient implements DataVecTransformService {
private String url;
static {
// Only one time
Unirest.setObjectMapper(new ObjectMapper() {
private org.nd4j.shade.jackson.databind.ObjectMapper jacksonObjectMapper =
new org.nd4j.shade.jackson.databind.ObjectMapper();
public <T> T readValue(String value, Class<T> valueType) {
try {
return jacksonObjectMapper.readValue(value, valueType);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public String writeValue(Object value) {
try {
return jacksonObjectMapper.writeValueAsString(value);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
});
}
/**
* @param transformProcess
*/
@Override
public void setCSVTransformProcess(TransformProcess transformProcess) {
try {
Unirest.post(url + "/transformprocess").header("accept", "application/json")
.header("Content-Type", "application/json").body(transformProcess).asJson();
} catch (UnirestException e) {
e.printStackTrace();
}
}
@Override
public void setImageTransformProcess(ImageTransformProcess imageTransformProcess) {
throw new UnsupportedOperationException("Invalid operation for " + this.getClass());
}
/**
* @return
*/
@Override
public TransformProcess getCSVTransformProcess() {
try {
return Unirest.get(url + "/transform").header("accept", "application/json")
.header("Content-Type", "application/json").asObject(TransformProcess.class).getBody();
} catch (UnirestException e) {
e.printStackTrace();
}
return null;
}
@Override
public ImageTransformProcess getImageTransformProcess() {
throw new UnsupportedOperationException("Invalid operation for " + this.getClass());
}
/**
* @param transform
* @return
*/
@Override
public SingleCSVRecord transformIncremental(SingleCSVRecord transform) {
try {
SingleCSVRecord singleCsvRecord = Unirest.post(url + "/transformincremental")
.header("accept", "application/json")
.header("Content-Type", "application/json")
.body(transform).asObject(SingleCSVRecord.class).getBody();
return singleCsvRecord;
} catch (UnirestException e) {
e.printStackTrace();
}
return null;
}
/**
* @param batchCSVRecord
* @return
*/
@Override
public BatchCSVRecord transform(BatchCSVRecord batchCSVRecord) {
try {
BatchCSVRecord batchCSVRecord1 = Unirest.post(url + "/transform").header("accept", "application/json")
.header("Content-Type", "application/json")
.body(batchCSVRecord)
.asObject(BatchCSVRecord.class)
.getBody();
return batchCSVRecord1;
} catch (UnirestException e) {
e.printStackTrace();
}
return null;
}
/**
* @param batchCSVRecord
* @return
*/
@Override
public Base64NDArrayBody transformArray(BatchCSVRecord batchCSVRecord) {
try {
Base64NDArrayBody batchArray1 = Unirest.post(url + "/transformarray").header("accept", "application/json")
.header("Content-Type", "application/json").body(batchCSVRecord)
.asObject(Base64NDArrayBody.class).getBody();
return batchArray1;
} catch (UnirestException e) {
e.printStackTrace();
}
return null;
}
/**
* @param singleCsvRecord
* @return
*/
@Override
public Base64NDArrayBody transformArrayIncremental(SingleCSVRecord singleCsvRecord) {
try {
Base64NDArrayBody array = Unirest.post(url + "/transformincrementalarray")
.header("accept", "application/json").header("Content-Type", "application/json")
.body(singleCsvRecord).asObject(Base64NDArrayBody.class).getBody();
return array;
} catch (UnirestException e) {
e.printStackTrace();
}
return null;
}
@Override
public Base64NDArrayBody transformIncrementalArray(SingleImageRecord singleImageRecord) throws IOException {
throw new UnsupportedOperationException("Invalid operation for " + this.getClass());
}
@Override
public Base64NDArrayBody transformArray(BatchImageRecord batchImageRecord) throws IOException {
throw new UnsupportedOperationException("Invalid operation for " + this.getClass());
}
/**
* @param singleCsvRecord
* @return
*/
@Override
public Base64NDArrayBody transformSequenceArrayIncremental(BatchCSVRecord singleCsvRecord) {
try {
Base64NDArrayBody array = Unirest.post(url + "/transformincrementalarray")
.header("accept", "application/json")
.header("Content-Type", "application/json")
.header(SEQUENCE_OR_NOT_HEADER,"true")
.body(singleCsvRecord).asObject(Base64NDArrayBody.class).getBody();
return array;
} catch (UnirestException e) {
e.printStackTrace();
}
return null;
}
/**
* @param batchCSVRecord
* @return
*/
@Override
public Base64NDArrayBody transformSequenceArray(SequenceBatchCSVRecord batchCSVRecord) {
try {
Base64NDArrayBody batchArray1 = Unirest.post(url + "/transformarray").header("accept", "application/json")
.header("Content-Type", "application/json")
.header(SEQUENCE_OR_NOT_HEADER,"true")
.body(batchCSVRecord)
.asObject(Base64NDArrayBody.class).getBody();
return batchArray1;
} catch (UnirestException e) {
e.printStackTrace();
}
return null;
}
/**
* @param batchCSVRecord
* @return
*/
@Override
public SequenceBatchCSVRecord transformSequence(SequenceBatchCSVRecord batchCSVRecord) {
try {
SequenceBatchCSVRecord batchCSVRecord1 = Unirest.post(url + "/transform")
.header("accept", "application/json")
.header("Content-Type", "application/json")
.header(SEQUENCE_OR_NOT_HEADER,"true")
.body(batchCSVRecord)
.asObject(SequenceBatchCSVRecord.class).getBody();
return batchCSVRecord1;
} catch (UnirestException e) {
e.printStackTrace();
}
return null;
}
/**
* @param transform
* @return
*/
@Override
public SequenceBatchCSVRecord transformSequenceIncremental(BatchCSVRecord transform) {
try {
SequenceBatchCSVRecord singleCsvRecord = Unirest.post(url + "/transformincremental")
.header("accept", "application/json")
.header("Content-Type", "application/json")
.header(SEQUENCE_OR_NOT_HEADER,"true")
.body(transform).asObject(SequenceBatchCSVRecord.class).getBody();
return singleCsvRecord;
} catch (UnirestException e) {
e.printStackTrace();
}
return null;
}
}
|
package com.khacks.srp;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Point;
import android.location.Location;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import org.json.JSONArray;
import org.json.JSONObject;
import java.net.URLEncoder;
import java.util.ArrayList;
public class MapsActivity extends FragmentActivity
implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
private EditText mFromField;
private EditText mToField;
private Button mSend;
private RequestQueue mQueue;
private String mMapQuestUrl;
private GoogleApiClient mGoogleApiClient;
private Location mLastLocation;
@Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
@Override
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
// Function to hide keyboard
public static void hideSoftKeyboard(Activity activity) {
InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
buildGoogleApiClient();
setUpMapIfNeeded();
// Setup the layout elements
mFromField = (EditText) findViewById(R.id.fromField);
mToField = (EditText) findViewById(R.id.toField);
mSend = (Button) findViewById(R.id.searchButton);
// Instantiate the RequestQueue.
mQueue = Volley.newRequestQueue(this);
final Activity mActivity = this;
mSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String from = mFromField.getText().toString();
String to = mToField.getText().toString();
if (!from.isEmpty() && !to.isEmpty()) {
// Hide keyboard
hideSoftKeyboard(mActivity);
// Initialize variables
try {
mMapQuestUrl ="http://open.mapquestapi.com/directions/v2/route?key=Fmjtd%7Cluu8210ynq%2C8w%3Do5-94r504&ambiguities=ignore&avoidTimedConditions=false&outFormat=json&routeType=fastest&enhancedNarrative=false&shapeFormat=raw&generalize=0&locale=en_US&unit=m&from="+
URLEncoder.encode(from, "utf-8")+"&to="+
URLEncoder.encode(to, "utf-8");
}
catch (Exception e) {
e.printStackTrace();
}
Log.v("LO", mMapQuestUrl);
Toast.makeText(getApplicationContext(), "Calculating route", Toast.LENGTH_SHORT).show();
doGETRequest(mMapQuestUrl, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
Toast.makeText(context, response.toString(), duration).show();
drawJSONDirection(response);
callJSolaServer(response);
}
});
}
else {
// One of the fields is empty, create a toast
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
if (from.isEmpty()) Toast.makeText(context, "Origin is missing!", duration).show();
else Toast.makeText(context, "Destination is missing!", duration).show();
}
}
});
}
void callJSolaServer(JSONObject response) {
String url = "http://37.187.81.177:8000/point/route";
JSONArray array = new JSONArray();
JSONObject query = new JSONObject();
try {
array = response.getJSONObject("route").getJSONArray("legs").
getJSONObject(0).getJSONArray("maneuvers");
query.accumulate("maneuvers", array);
}
catch (Exception e) {
e.printStackTrace();
}
Log.v("LO", response.toString());
doPOSTRequest(url, query, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
searchControlPoints(response);
}
});
}
void doGETRequest(String url, Response.Listener<JSONObject> listener) {
// Request a string response from the provided URL.
Log.v("LO", "WOLO");
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.GET, url, null, listener, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
Log.v("LO", error.getMessage());
}
});
// Add the request to the RequestQueue.
mQueue.add(jsObjRequest);
}
private void doPOSTRequest(String url, JSONObject query, Response.Listener<JSONObject> listener) {
// Request a string response from the provided URL.
Log.v("LO", url);
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.POST, url, query, listener, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
if (error != null) {
if (error.getMessage() != null) {
Log.v("LO", error.getMessage());
}
else {
Log.v("LO", "WOLO :(");
}
}
else {
Log.v("LO", "WOLO :(((((");
}
}
});
// Add the request to the RequestQueue.
mQueue.add(jsObjRequest);
}
private void searchControlPoints(JSONObject jsonObject) {
try {
JSONObject query = new JSONObject();
JSONArray array = jsonObject.getJSONArray("blackPoints");
for (int i = 0; i < array.length(); i++) {
JSONObject info = new JSONObject();
double lat = array.getJSONObject(i).getJSONObject("location").getDouble("lat");
double lng = array.getJSONObject(i).getJSONObject("location").getDouble("lng");
info.put("lat",lat);
info.put("lng",lng);
info.put("weight",100);
info.put("radius",5);
query.accumulate("routeControlPointCollection", info);
addBlueMarker(new LatLng(lat, lng), "Point " + i);
}
doPOSTRequest(mMapQuestUrl, query, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
Toast.makeText(context, "CONTROL POINTS!", duration).show();
JSONArray array2 = new JSONArray();
try {
array2 = response.getJSONObject("route").getJSONArray("shapePoints");
}
catch (Exception e) {
}
}
});
}
catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
/**
* Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
* installed) and the map has not already been instantiated.. This will ensure that we only ever
* call {@link #setUpMap()} once when {@link #mMap} is not null.
* <p/>
* If it isn't installed {@link SupportMapFragment} (and
* {@link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
* install/update the Google Play services APK on their device.
* <p/>
* A user can return to this FragmentActivity after following the prompt and correctly
* installing/updating/enabling the Google Play services. Since the FragmentActivity may not
* have been completely destroyed during this process (it is likely that it would only be
* stopped or paused), {@link #onCreate(Bundle)} may not be called again so we should call this
* method in {@link #onResume()} to guarantee that it will be called.
*/
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
/**
* This is where we can add markers or lines, add listeners or move the camera. In this case, we
* just add a marker near Africa.
* <p/>
* This should only be called once and when we are sure that {@link #mMap} is not null.
*/
private void setUpMap() {
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(false);
}
/**
* Draw the route from the JSON object in the map
*/
private void drawJSONDirection(JSONObject direction) {
Polyline line = mMap.addPolyline(new PolylineOptions()
.add(new LatLng(51.5, -0.1), new LatLng(40.7, -74.0))
.width(5)
.color(Color.RED));
JSONArray jArray = null;
ArrayList<LatLng> points = new ArrayList<LatLng>();
try {
jArray = direction.getJSONObject("route").getJSONObject("shape").
getJSONArray("shapePoints");
if (jArray != null) {
for (int i=0;i<jArray.length();i+=2){
points.add(new LatLng((double)jArray.get(i), (double)jArray.get(i+1)));
}
}
} catch (Exception e) {
e.printStackTrace();
}
// Remove previous roads and marks
mMap.clear();
mMap.addPolyline(new PolylineOptions().addAll(points).width(5).color(Color.RED));
focusCameraOnPath(points);
}
/**
* Zooms the camera so that the path fits in the screen
* @param path set of points that form the path
*/
private void focusCameraOnPath(ArrayList<LatLng> path) {
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (LatLng point : path) {
builder.include(point);
}
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
final int width = size.x;
final int height = size.y;
final int padding = 40;
mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(
builder.build(), width, height, padding));
}
private void addBlueMarker(LatLng coord, String markerString) {
if (markerString == null) markerString = "Blue Marker";
mMap.addMarker(new MarkerOptions().position(coord).title(markerString).
icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
@Override
public void onConnected(Bundle connectionHint) {
// Connected to Google Play services!
// The good stuff goes here.
Log.v("LO", "WOLO");
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mLastLocation.getLatitude(),
mLastLocation.getLongitude()), 13));
}
}
@Override
public void onConnectionSuspended(int cause) {
// The connection has been interrupted.
// Disable any UI components that depend on Google APIs
// until onConnected() is called.
Log.v("LO", "WOLO :(");
}
@Override
public void onConnectionFailed(ConnectionResult result) {
// This callback is important for handling errors that
// may occur while attempting to connect with Google.
// More about this in the next section.
Log.v("LO", "WOLO :((((((((");
}
}
|
package copyleaks.sdk.api.models;
import com.google.gson.annotations.SerializedName;
public class ResultRecord implements Comparable<ResultRecord>
{
public ResultRecord(String URL, int Percents, int NumberOfCopiedWords){
this.URL = URL;
this.Percents = Percents;
this.NumberOfCopiedWords = NumberOfCopiedWords;
}
public ResultRecord(){
// For serialization.
}
@SerializedName("URL")
private String URL;
public String getURL()
{
return URL;
}
@SerializedName("Percents")
private int Percents;
public int getPercents()
{
return Percents;
}
@SerializedName("NumberOfCopiedWords")
private int NumberOfCopiedWords;
public int getNumberOfCopiedWords()
{
return NumberOfCopiedWords;
}
@SerializedName("ComparisonReport")
private String ComparisonReport;
public String getComparisonReport()
{
return ComparisonReport;
}
@SerializedName("CachedVersion")
private String CachedVersion;
public String getCachedVersion()
{
return CachedVersion;
}
@SerializedName("Title")
private String Title;
public String getTitle()
{
return Title;
}
@SerializedName("Introduction")
private String Introduction;
public String getIntroduction()
{
return Introduction;
}
@SerializedName("EmbededComparison")
private String EmbededComparison;
public String getEmbededComparison()
{
return EmbededComparison;
}
@Override
public int compareTo(ResultRecord o) {
return Integer.compare(this.getPercents(), o.getPercents());
}
}
|
package org.opennms.features.topology.app.internal.jung;
public interface LayoutConstants {
public static final int LAYOUT_HEIGHT = 2000;
public static final int LAYOUT_WIDTH = LAYOUT_HEIGHT*16/9;
public static final int LAYOUT_REPULSION = 150;
}
|
package com.x.processplatform.service.processing.processor.manual;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.script.Bindings;
import javax.script.ScriptContext;
import org.apache.commons.collections4.ListUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import com.x.base.core.container.EntityManagerContainer;
import com.x.base.core.entity.JpaObject;
import com.x.base.core.project.config.Config;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.base.core.project.organization.EmpowerLog;
import com.x.base.core.project.script.ScriptFactory;
import com.x.base.core.project.tools.DateTools;
import com.x.base.core.project.tools.ListTools;
import com.x.base.core.project.tools.NumberTools;
import com.x.base.core.project.utils.time.WorkTime;
import com.x.processplatform.core.entity.content.Read;
import com.x.processplatform.core.entity.content.Task;
import com.x.processplatform.core.entity.content.TaskCompleted;
import com.x.processplatform.core.entity.content.Work;
import com.x.processplatform.core.entity.content.WorkLog;
import com.x.processplatform.core.entity.element.ActivityType;
import com.x.processplatform.core.entity.element.Manual;
import com.x.processplatform.core.entity.element.Route;
import com.x.processplatform.core.entity.element.util.WorkLogTree;
import com.x.processplatform.core.entity.element.util.WorkLogTree.Node;
import com.x.processplatform.core.entity.log.Signal;
import com.x.processplatform.service.processing.Business;
import com.x.processplatform.service.processing.processor.AeiObjects;
/**
* @author Zhou Rui
*/
public class ManualProcessor extends AbstractManualProcessor {
private static Logger logger = LoggerFactory.getLogger(ManualProcessor.class);
public ManualProcessor(EntityManagerContainer entityManagerContainer) throws Exception {
super(entityManagerContainer);
}
@Override
protected Work arriving(AeiObjects aeiObjects, Manual manual) throws Exception {
// ProcessingSignal
aeiObjects.getProcessingAttributes().push(Signal.manualArrive(aeiObjects.getWork().getActivityToken(), manual));
// manualparallelSoleTaskCompleted
List<String> identities = calculateTaskIdentities(aeiObjects, manual);
Work merge = this.arrivingMergeSameJob(aeiObjects, manual, identities);
if (null != merge) {
return merge;
}
this.arrivingPassSame(aeiObjects, identities);
aeiObjects.getWork().setManualTaskIdentityList(new ArrayList<>(identities));
return aeiObjects.getWork();
}
private Work arrivingMergeSameJob(AeiObjects aeiObjects, Manual manual, List<String> identities) throws Exception {
if (!BooleanUtils.isTrue(manual.getManualMergeSameJobActivity())) {
return null;
}
List<String> exists = this.arriving_sameJobActivityExistIdentities(aeiObjects, manual);
if (ListTools.isNotEmpty(exists)) {
Work other = aeiObjects.getWorks().stream().filter(o -> {
return StringUtils.equals(aeiObjects.getWork().getJob(), o.getJob())
&& StringUtils.equals(aeiObjects.getWork().getActivity(), o.getActivity())
&& (!Objects.equals(aeiObjects.getWork(), o));
}).findFirst().orElse(null);
if (null != other) {
identities.removeAll(exists);
if (ListTools.isEmpty(identities)) {
this.mergeTaskCompleted(aeiObjects, aeiObjects.getWork(), other);
this.mergeRead(aeiObjects, aeiObjects.getWork(), other);
this.mergeReadCompleted(aeiObjects, aeiObjects.getWork(), other);
this.mergeReview(aeiObjects, aeiObjects.getWork(), other);
this.mergeAttachment(aeiObjects, aeiObjects.getWork(), other);
this.mergeWorkLog(aeiObjects, aeiObjects.getWork(), other);
if (ListTools.size(aeiObjects.getWork().getSplitTokenList()) > ListTools
.size(other.getSplitTokenList())) {
other.setSplitTokenList(aeiObjects.getWork().getSplitTokenList());
other.setSplitToken(aeiObjects.getWork().getSplitToken());
other.setSplitValue(aeiObjects.getWork().getSplitValue());
other.setSplitting(true);
}
aeiObjects.getUpdateWorks().add(other);
aeiObjects.getDeleteWorks().add(aeiObjects.getWork());
return other;
}
}
}
return null;
}
private void arrivingPassSame(AeiObjects aeiObjects, List<String> identities) throws Exception {
// passSameTarget
Route route = aeiObjects.getRoutes().stream().filter(o -> BooleanUtils.isTrue(o.getPassSameTarget()))
.findFirst().orElse(null);
// passSameTarget,ArriveWorkLog,
if ((null != route) && ((null != aeiObjects.getArriveWorkLog(aeiObjects.getWork())))
&& (!aeiObjects.getProcessingAttributes().ifForceJoinAtArrive())) {
WorkLog workLog = findPassSameTargetWorkLog(aeiObjects);
logger.debug("pass same target work:{}, workLog:{}.", aeiObjects.getWork(), workLog);
if (null == workLog) {
return;
}
for (TaskCompleted o : aeiObjects.getJoinInquireTaskCompleteds()) {
if (StringUtils.equals(o.getActivityToken(), workLog.getArrivedActivityToken())) {
List<String> values = ListUtils.intersection(identities,
aeiObjects.business().organization().identity().listWithPerson(o.getPerson()));
if (!values.isEmpty()) {
TaskCompleted obj = new TaskCompleted(aeiObjects.getWork(), route, o);
obj.setIdentity(values.get(0));
obj.setUnit(aeiObjects.business().organization().unit().getWithIdentity(obj.getIdentity()));
obj.setProcessingType(TaskCompleted.PROCESSINGTYPE_SAMETARGET);
obj.setRouteName(route.getName());
obj.setOpinion(route.getOpinion());
Date now = new Date();
obj.setStartTime(now);
obj.setStartTimeMonth(DateTools.format(now, DateTools.format_yyyyMM));
obj.setCompletedTime(now);
obj.setCompletedTimeMonth(DateTools.format(now, DateTools.format_yyyyMM));
obj.setDuration(0L);
obj.setExpired(false);
obj.setExpireTime(null);
obj.setTask(null);
obj.setLatest(true);
aeiObjects.getCreateTaskCompleteds().add(obj);
}
}
}
}
}
private List<String> calculateTaskIdentities(AeiObjects aeiObjects, Manual manual) throws Exception {
TaskIdentities taskIdentities = new TaskIdentities();
if (!aeiObjects.getWork().getProperties().getManualForceTaskIdentityList().isEmpty()) {
List<String> identities = new ArrayList<>();
identities.addAll(aeiObjects.getWork().getProperties().getManualForceTaskIdentityList());
identities = aeiObjects.business().organization().identity().list(identities);
if (ListTools.isNotEmpty(identities)) {
taskIdentities.addIdentities(identities);
}
}
if (taskIdentities.isEmpty()) {
Route route = aeiObjects.business().element().get(aeiObjects.getWork().getDestinationRoute(), Route.class);
if ((null != route) && (StringUtils.equals(route.getType(), Route.TYPE_BACK))) {
List<String> identities = new ArrayList<>();
List<WorkLog> workLogs = new ArrayList<>();
workLogs.addAll(aeiObjects.getUpdateWorkLogs());
workLogs.addAll(aeiObjects.getCreateWorkLogs());
for (WorkLog o : aeiObjects.getWorkLogs()) {
if (!workLogs.contains(o)) {
workLogs.add(o);
}
}
WorkLogTree tree = new WorkLogTree(workLogs);
Node node = tree.location(aeiObjects.getWork());
if (null != node) {
for (Node n : tree.up(node)) {
if (StringUtils.equals(manual.getId(), n.getWorkLog().getFromActivity())) {
for (TaskCompleted t : aeiObjects.getTaskCompleteds()) {
if (StringUtils.equals(n.getWorkLog().getFromActivityToken(), t.getActivityToken())
&& BooleanUtils.isTrue(t.getJoinInquire())) {
identities.add(t.getIdentity());
}
}
break;
}
}
identities = aeiObjects.business().organization().identity().list(identities);
if (ListTools.isNotEmpty(identities)) {
taskIdentities.addIdentities(identities);
}
}
}
}
if (taskIdentities.isEmpty()) {
taskIdentities = TranslateTaskIdentityTools.translate(aeiObjects, manual);
this.ifTaskIdentitiesEmptyForceToCreatorOrMaintenance(aeiObjects, manual, taskIdentities);
this.writeToEmpowerMap(aeiObjects, taskIdentities);
}
return taskIdentities.identities();
}
// ,, maintenanceIdentity
private void ifTaskIdentitiesEmptyForceToCreatorOrMaintenance(AeiObjects aeiObjects, Manual manual,
TaskIdentities taskIdentities) throws Exception {
if (taskIdentities.isEmpty()) {
String identity = aeiObjects.business().organization().identity()
.get(aeiObjects.getWork().getCreatorIdentity());
if (StringUtils.isNotEmpty(identity)) {
logger.info("{}[{}], :{}, id:{}, :{}.", aeiObjects.getProcess().getName(),
manual.getName(), aeiObjects.getWork().getTitle(), aeiObjects.getWork().getId(), identity);
taskIdentities.addIdentity(identity);
} else {
identity = aeiObjects.business().organization().identity()
.get(Config.processPlatform().getMaintenanceIdentity());
if (StringUtils.isNotEmpty(identity)) {
logger.info("{}[{}], , :{}, id:{}, :{}.",
aeiObjects.getProcess().getName(), manual.getName(), aeiObjects.getWork().getTitle(),
aeiObjects.getWork().getId(), identity);
taskIdentities.addIdentity(identity);
} else {
throw new ExceptionExpectedEmpty(aeiObjects.getWork().getTitle(), aeiObjects.getWork().getId(),
aeiObjects.getActivity().getName(), aeiObjects.getActivity().getId());
}
}
}
}
// ,surfaceworkThroughManual=false ,.
private void writeToEmpowerMap(AeiObjects aeiObjects, TaskIdentities taskIdentities) throws Exception {
// EmpowerMap
aeiObjects.getWork().getProperties().setManualEmpowerMap(new LinkedHashMap<String, String>());
if (!(StringUtils.equals(aeiObjects.getWork().getWorkCreateType(), Work.WORKCREATETYPE_SURFACE)
&& BooleanUtils.isFalse(aeiObjects.getWork().getWorkThroughManual()))) {
List<String> values = taskIdentities.identities();
values = ListUtils.subtract(values, aeiObjects.getProcessingAttributes().getIgnoreEmpowerIdentityList());
taskIdentities.empower(aeiObjects.business().organization().empower().listWithIdentityObject(
aeiObjects.getWork().getApplication(), aeiObjects.getProcess().getEdition(),
aeiObjects.getWork().getProcess(), aeiObjects.getWork().getId(), values));
for (TaskIdentity taskIdentity : taskIdentities) {
if (StringUtils.isNotEmpty(taskIdentity.getFromIdentity())) {
aeiObjects.getWork().getProperties().getManualEmpowerMap().put(taskIdentity.getIdentity(),
taskIdentity.getFromIdentity());
}
}
}
}
private WorkLog findPassSameTargetWorkLog(AeiObjects aeiObjects) throws Exception {
WorkLogTree tree = new WorkLogTree(aeiObjects.getWorkLogs());
List<WorkLog> parents = tree.parents(aeiObjects.getArriveWorkLog(aeiObjects.getWork()));
logger.debug("pass same target rollback parents:{}.", parents);
WorkLog workLog = null;
for (WorkLog o : parents) {
if (Objects.equals(ActivityType.manual, o.getArrivedActivityType())) {
workLog = o;
break;
} else if (Objects.equals(ActivityType.choice, o.getArrivedActivityType())) {
continue;
} else if (Objects.equals(ActivityType.agent, o.getArrivedActivityType())) {
continue;
} else if (Objects.equals(ActivityType.invoke, o.getArrivedActivityType())) {
continue;
} else if (Objects.equals(ActivityType.service, o.getArrivedActivityType())) {
continue;
} else {
break;
}
}
logger.debug("pass same target find workLog:{}.", workLog);
return workLog;
}
@Override
protected void arrivingCommitted(AeiObjects aeiObjects, Manual manual) throws Exception {
// nothing
}
@Override
protected List<Work> executing(AeiObjects aeiObjects, Manual manual) throws Exception {
List<Work> results = new ArrayList<>();
boolean passThrough = false;
List<String> identities = aeiObjects.business().organization().identity()
.list(aeiObjects.getWork().getManualTaskIdentityList());
if (identities.isEmpty()) {
identities = calculateTaskIdentities(aeiObjects, manual);
logger.info(",,:{}, id:{}, :{}.", aeiObjects.getWork().getTitle(),
aeiObjects.getWork().getId(), identities);
// identitis.remove()
aeiObjects.getWork().setManualTaskIdentityList(new ArrayList<>(identities));
}
// ProcessingSignal
aeiObjects.getProcessingAttributes().push(Signal.manualExecute(aeiObjects.getWork().getActivityToken(), manual,
Objects.toString(manual.getManualMode(), ""), identities));
switch (manual.getManualMode()) {
case single:
passThrough = this.single(aeiObjects, manual, identities);
break;
case parallel:
passThrough = this.parallel(aeiObjects, manual, identities);
break;
case queue:
passThrough = this.queue(aeiObjects, manual, identities);
break;
case grab:
passThrough = this.single(aeiObjects, manual, identities);
break;
default:
throw new ExceptionManualModeError(manual.getId());
}
if (passThrough) {
results.add(aeiObjects.getWork());
}
return results;
}
@Override
protected void executingCommitted(AeiObjects aeiObjects, Manual manual) throws Exception {
// nothing
}
@Override
protected List<Route> inquiring(AeiObjects aeiObjects, Manual manual) throws Exception {
// ProcessingSignal
aeiObjects.getProcessingAttributes()
.push(Signal.manualInquire(aeiObjects.getWork().getActivityToken(), manual));
List<Route> results = new ArrayList<>();
if (aeiObjects.getRoutes().size() == 1) {
results.add(aeiObjects.getRoutes().get(0));
} else if (aeiObjects.getRoutes().size() > 1) {
List<TaskCompleted> taskCompletedList = aeiObjects.getJoinInquireTaskCompleteds().stream()
.filter(o -> StringUtils.equals(o.getActivityToken(), aeiObjects.getWork().getActivityToken())
&& aeiObjects.getWork().getManualTaskIdentityList().contains(o.getIdentity()))
.collect(Collectors.toList());
String name = this.choiceRouteName(taskCompletedList, aeiObjects.getRoutes());
for (Route o : aeiObjects.getRoutes()) {
if (o.getName().equalsIgnoreCase(name)) {
results.add(o);
break;
}
}
}
if (!results.isEmpty()) {
aeiObjects.getWork().getProperties().setManualForceTaskIdentityList(new ArrayList<String>());
}
return results;
}
private String choiceRouteName(List<TaskCompleted> list, List<Route> routes) throws Exception {
String result = "";
List<String> names = new ArrayList<>();
ListTools.trim(list, false, false).stream().forEach(o -> names.add(o.getRouteName()));
Route soleRoute = routes.stream().filter(o -> BooleanUtils.isTrue(o.getSoleDirect())).findFirst().orElse(null);
if ((null != soleRoute) && names.contains(soleRoute.getName())) {
result = soleRoute.getName();
} else {
result = maxCountOrLatest(list);
}
if (StringUtils.isEmpty(result)) {
throw new ExceptionChoiceRouteNameError(
ListTools.extractProperty(list, JpaObject.id_FIELDNAME, String.class, false, false));
}
return result;
}
private String maxCountOrLatest(List<TaskCompleted> list) {
Map<String, List<TaskCompleted>> map = list.stream()
.collect(Collectors.groupingBy(TaskCompleted::getRouteName));
Optional<Entry<String, List<TaskCompleted>>> optional = map.entrySet().stream().sorted((o1, o2) -> {
int c = o2.getValue().size() - o1.getValue().size();
if (c == 0) {
Date d1 = o1.getValue().stream().sorted(Comparator.comparing(TaskCompleted::getCreateTime).reversed())
.findFirst().get().getCreateTime();
Date d2 = o2.getValue().stream().sorted(Comparator.comparing(TaskCompleted::getCreateTime).reversed())
.findFirst().get().getCreateTime();
return ObjectUtils.compare(d2, d1);
} else {
return c;
}
}).findFirst();
return optional.isPresent() ? optional.get().getKey() : null;
}
private boolean single(AeiObjects aeiObjects, Manual manual, List<String> identities) throws Exception {
boolean passThrough = false;
Long count = aeiObjects.getJoinInquireTaskCompleteds().stream().filter(o -> {
if (StringUtils.equals(aeiObjects.getWork().getActivityToken(), o.getActivityToken())
&& (identities.contains(o.getIdentity()))) {
return true;
} else {
return false;
}
}).count();
if (count > 0) {
aeiObjects.getTasks().stream().filter(o -> {
return StringUtils.equals(aeiObjects.getWork().getId(), o.getWork());
}).forEach(o -> {
if (BooleanUtils.isTrue(manual.getManualUncompletedTaskToRead())) {
aeiObjects.getCreateReads()
.add(new Read(aeiObjects.getWork(), o.getIdentity(), o.getUnit(), o.getPerson()));
}
aeiObjects.deleteTask(o);
});
passThrough = true;
} else {
// List
if (ListTools.isEmpty(identities)) {
throw new ExceptionExpectedEmpty(aeiObjects.getWork().getTitle(), aeiObjects.getWork().getId(),
manual.getName(), manual.getId());
}
aeiObjects.getTasks().stream()
.filter(o -> StringUtils.equals(aeiObjects.getWork().getActivityToken(), o.getActivityToken())
&& (!ListTools.contains(identities, o.getIdentity())))
.forEach(aeiObjects::deleteTask);
aeiObjects.getTasks().stream()
.filter(o -> StringUtils.equals(aeiObjects.getWork().getActivityToken(), o.getActivityToken())
&& (ListTools.contains(identities, o.getIdentity())))
.forEach(o -> identities.remove(o.getIdentity()));
if (!identities.isEmpty()) {
for (String identity : identities) {
aeiObjects.createTask(this.createTask(aeiObjects, manual, identity));
}
}
}
return passThrough;
}
private boolean parallel(AeiObjects aeiObjects, Manual manual, List<String> identities) throws Exception {
boolean passThrough = false;
List<TaskCompleted> taskCompleteds = this.listJoinInquireTaskCompleted(aeiObjects, identities);
// ,.soleDirect
// Route soleRoute = aeiObjects.getRoutes().stream()
// .filter(r -> BooleanUtils.isTrue(r.getSole()) && BooleanUtils.isTrue(r.getSoleDirect())).findFirst()
// .orElse(null);
Route soleRoute = aeiObjects.getRoutes().stream().filter(r -> BooleanUtils.isTrue(r.getSoleDirect()))
.findFirst().orElse(null);
if (null != soleRoute) {
TaskCompleted soleTaskCompleted = taskCompleteds.stream()
.filter(t -> BooleanUtils.isTrue(t.getJoinInquire())
&& StringUtils.equals(t.getRouteName(), soleRoute.getName()))
.findFirst().orElse(null);
if (null != soleTaskCompleted) {
this.parallelSoleTaskCompleted(aeiObjects);
return true;
}
}
aeiObjects.getJoinInquireTaskCompleteds().stream().filter(o -> {
return StringUtils.equals(aeiObjects.getWork().getActivityToken(), o.getActivityToken());
}).forEach(o -> identities.remove(o.getIdentity()));
aeiObjects.getTasks().stream().filter(o -> {
return StringUtils.equals(aeiObjects.getWork().getActivityToken(), o.getActivityToken())
&& (!ListTools.contains(identities, o.getIdentity()));
}).forEach(aeiObjects::deleteTask);
if (identities.isEmpty()) {
passThrough = true;
} else {
passThrough = false;
aeiObjects.getTasks().stream()
.filter(o -> StringUtils.equals(aeiObjects.getWork().getActivityToken(), o.getActivityToken()))
.forEach(o -> identities.remove(o.getIdentity()));
if (!identities.isEmpty()) {
for (String identity : identities) {
aeiObjects.createTask(this.createTask(aeiObjects, manual, identity));
}
}
}
return passThrough;
}
private void parallelSoleTaskCompleted(AeiObjects aeiObjects) throws Exception {
aeiObjects.getTasks().stream().filter(o -> {
return StringUtils.equals(aeiObjects.getWork().getActivityToken(), o.getActivityToken());
}).forEach(aeiObjects::deleteTask);
}
private boolean queue(AeiObjects aeiObjects, Manual manual, List<String> identities) throws Exception {
boolean passThrough = false;
List<TaskCompleted> taskCompleteds = this.listJoinInquireTaskCompleted(aeiObjects, identities);
Route soleRoute = aeiObjects.getRoutes().stream().filter(r -> BooleanUtils.isTrue(r.getSoleDirect()))
.findFirst().orElse(null);
if (null != soleRoute) {
TaskCompleted soleTaskCompleted = taskCompleteds.stream()
.filter(t -> BooleanUtils.isTrue(t.getJoinInquire())
&& StringUtils.equals(t.getRouteName(), soleRoute.getName()))
.findFirst().orElse(null);
if (null != soleTaskCompleted) {
return true;
}
}
for (TaskCompleted o : taskCompleteds) {
identities.remove(o.getIdentity());
}
if (identities.isEmpty()) {
passThrough = true;
} else {
passThrough = false;
String identity = identities.get(0);
boolean find = false;
for (Task t : aeiObjects.getTasks()) {
if (StringUtils.equals(aeiObjects.getWork().getActivityToken(), t.getActivityToken())) {
if (!StringUtils.equals(t.getIdentity(), identity)) {
aeiObjects.deleteTask(t);
} else {
find = true;
}
}
}
if (!find) {
aeiObjects.createTask(this.createTask(aeiObjects, manual, identity));
}
}
return passThrough;
}
// , reset,retract,appendTask
private List<TaskCompleted> listJoinInquireTaskCompleted(AeiObjects aeiObjects, List<String> identities)
throws Exception {
return aeiObjects.getJoinInquireTaskCompleteds().stream()
.filter(o -> StringUtils.equals(aeiObjects.getWork().getActivityToken(), o.getActivityToken())
&& identities.contains(o.getIdentity()) && BooleanUtils.isTrue(o.getJoinInquire()))
.collect(Collectors.toList());
}
@Override
protected void inquiringCommitted(AeiObjects aeiObjects, Manual manual) throws Exception {
// nothing
}
private void calculateExpire(AeiObjects aeiObjects, Manual manual, Task task) throws Exception {
if (null != manual.getTaskExpireType()) {
switch (manual.getTaskExpireType()) {
case never:
this.expireNever(task);
break;
case appoint:
this.expireAppoint(manual, task);
break;
case script:
this.expireScript(aeiObjects, manual, task);
break;
default:
break;
}
}
// work
if (null != aeiObjects.getWork().getExpireTime()) {
if (null == task.getExpireTime()) {
task.setExpireTime(aeiObjects.getWork().getExpireTime());
} else {
if (task.getExpireTime().after(aeiObjects.getWork().getExpireTime())) {
task.setExpireTime(aeiObjects.getWork().getExpireTime());
}
}
}
if (null != task.getExpireTime()) {
task.setUrgeTime(DateUtils.addHours(task.getExpireTime(), -2));
} else {
task.setExpired(false);
task.setUrgeTime(null);
task.setUrged(false);
}
}
private void expireNever(Task task) {
task.setExpireTime(null);
}
private void expireAppoint(Manual manual, Task task) throws Exception {
if (BooleanUtils.isTrue(manual.getTaskExpireWorkTime())) {
this.expireAppointWorkTime(task, manual);
} else {
this.expireAppointNaturalDay(task, manual);
}
}
private void expireAppointWorkTime(Task task, Manual manual) throws Exception {
Integer m = 0;
WorkTime wt = Config.workTime();
if (BooleanUtils.isTrue(NumberTools.greaterThan(manual.getTaskExpireDay(), 0))) {
m += manual.getTaskExpireDay() * wt.minutesOfWorkDay();
}
if (BooleanUtils.isTrue(NumberTools.greaterThan(manual.getTaskExpireHour(), 0))) {
m += manual.getTaskExpireHour() * 60;
}
if (m > 0) {
Date expire = wt.forwardMinutes(new Date(), m);
task.setExpireTime(expire);
} else {
task.setExpireTime(null);
}
}
private void expireAppointNaturalDay(Task task, Manual manual) throws Exception {
Integer m = 0;
if (BooleanUtils.isTrue(NumberTools.greaterThan(manual.getTaskExpireDay(), 0))) {
m += manual.getTaskExpireDay() * 60 * 24;
}
if (BooleanUtils.isTrue(NumberTools.greaterThan(manual.getTaskExpireHour(), 0))) {
m += manual.getTaskExpireHour() * 60;
}
if (m > 0) {
Calendar cl = Calendar.getInstance();
cl.add(Calendar.MINUTE, m);
task.setExpireTime(cl.getTime());
} else {
task.setExpireTime(null);
}
}
private void expireScript(AeiObjects aeiObjects, Manual manual, Task task) throws Exception {
ExpireScriptResult expire = new ExpireScriptResult();
ScriptContext scriptContext = aeiObjects.scriptContext();
Bindings bindings = scriptContext.getBindings(ScriptContext.ENGINE_SCOPE);
bindings.put(ScriptFactory.BINDING_NAME_TASK, task);
bindings.put(ScriptFactory.BINDING_NAME_EXPIRE, expire);
aeiObjects.business().element()
.getCompiledScript(aeiObjects.getWork().getApplication(), manual, Business.EVENT_MANUALTASKEXPIRE)
.eval(scriptContext);
if (BooleanUtils.isTrue(NumberTools.greaterThan(expire.getWorkHour(), 0))) {
Integer m = 0;
m += expire.getWorkHour() * 60;
if (m > 0) {
task.setExpireTime(Config.workTime().forwardMinutes(new Date(), m));
} else {
task.setExpireTime(null);
}
} else if (BooleanUtils.isTrue(NumberTools.greaterThan(expire.getHour(), 0))) {
Integer m = 0;
m += expire.getHour() * 60;
if (m > 0) {
Calendar cl = Calendar.getInstance();
cl.add(Calendar.MINUTE, m);
task.setExpireTime(cl.getTime());
} else {
task.setExpireTime(null);
}
} else if (null != expire.getDate()) {
task.setExpireTime(expire.getDate());
} else {
task.setExpireTime(null);
}
}
private Task createTask(AeiObjects aeiObjects, Manual manual, String identity) throws Exception {
String fromIdentity = aeiObjects.getWork().getProperties().getManualEmpowerMap().get(identity);
String person = aeiObjects.business().organization().person().getWithIdentity(identity);
String unit = aeiObjects.business().organization().unit().getWithIdentity(identity);
Task task = new Task(aeiObjects.getWork(), identity, person, unit, fromIdentity, new Date(), null,
aeiObjects.getRoutes(), manual.getAllowRapid());
if (BooleanUtils.isTrue(aeiObjects.getProcessingAttributes().getForceJoinAtArrive())) {
task.setFirst(false);
} else {
task.setFirst(ListTools.isEmpty(aeiObjects.getJoinInquireTaskCompleteds()));
}
this.calculateExpire(aeiObjects, manual, task);
if (StringUtils.isNotEmpty(fromIdentity)) {
aeiObjects.business().organization().empowerLog()
.log(this.createEmpowerLog(aeiObjects.getWork(), fromIdentity, identity));
String fromPerson = aeiObjects.business().organization().person().getWithIdentity(fromIdentity);
String fromUnit = aeiObjects.business().organization().unit().getWithIdentity(fromIdentity);
TaskCompleted empowerTaskCompleted = new TaskCompleted(aeiObjects.getWork());
empowerTaskCompleted.setProcessingType(TaskCompleted.PROCESSINGTYPE_EMPOWER);
empowerTaskCompleted.setIdentity(fromIdentity);
empowerTaskCompleted.setUnit(fromUnit);
empowerTaskCompleted.setPerson(fromPerson);
empowerTaskCompleted.setEmpowerToIdentity(identity);
aeiObjects.createTaskCompleted(empowerTaskCompleted);
Read empowerRead = new Read(aeiObjects.getWork(), fromIdentity, fromUnit, fromPerson);
aeiObjects.createRead(empowerRead);
}
return task;
}
private EmpowerLog createEmpowerLog(Work work, String fromIdentity, String toIdentity) {
return new EmpowerLog().setApplication(work.getApplication()).setApplicationAlias(work.getApplicationAlias())
.setApplicationName(work.getApplicationName()).setProcess(work.getProcess())
.setProcessAlias(work.getProcessAlias()).setProcessName(work.getProcessName()).setTitle(work.getTitle())
.setWork(work.getId()).setJob(work.getJob()).setFromIdentity(fromIdentity).setToIdentity(toIdentity)
.setActivity(work.getActivity()).setActivityAlias(work.getActivityAlias())
.setActivityName(work.getActivityName()).setEmpowerTime(new Date());
}
private List<String> arriving_sameJobActivityExistIdentities(AeiObjects aeiObjects, Manual manual)
throws Exception {
List<String> exists = new ArrayList<>();
aeiObjects.getTasks().stream().filter(o -> {
return StringUtils.equals(o.getActivity(), manual.getId())
&& StringUtils.equals(o.getJob(), aeiObjects.getWork().getJob());
}).forEach(o -> exists.add(o.getIdentity()));
return exists;
}
public class ExpireScriptResult {
Integer hour;
Integer workHour;
Date date;
public Integer getHour() {
return hour;
}
public void setHour(Integer hour) {
this.hour = hour;
}
public Integer getWorkHour() {
return workHour;
}
public void setWorkHour(Integer workHour) {
this.workHour = workHour;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public void setDate(String str) {
try {
this.date = DateTools.parse(str);
} catch (Exception e) {
logger.error(e);
}
}
}
}
|
package fr.synchrotron.soleil.ica.ci.service.legacymavenproxy.midlleware;
import com.github.ebx.core.MessageFilterService;
import com.github.ebx.core.MessagingTemplate;
import fr.synchrotron.soleil.ica.ci.service.legacymavenproxy.ServiceAddressRegistry;
import fr.synchrotron.soleil.ica.proxy.midlleware.MiddlewareContext;
import fr.synchrotron.soleil.ica.proxy.midlleware.ProxyService;
import fr.synchrotron.soleil.ica.proxy.midlleware.response.DefaultClientResponseHandler;
import io.netty.handler.codec.http.HttpResponseStatus;
import org.vertx.java.core.*;
import org.vertx.java.core.buffer.Buffer;
import org.vertx.java.core.eventbus.Message;
import org.vertx.java.core.http.HttpClientResponse;
import org.vertx.java.core.http.HttpHeaders;
import org.vertx.java.core.http.HttpServerRequest;
import org.vertx.java.core.json.JsonObject;
import org.vertx.java.core.logging.Logger;
import org.vertx.java.core.logging.impl.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
/**
* @author Gregory Boissinot
*/
public class POMResponseHandler extends DefaultClientResponseHandler {
private static final Logger LOG = LoggerFactory.getLogger(POMResponseHandler.class);
public POMResponseHandler(MiddlewareContext context) {
super(context);
}
@Override
public Handler<HttpClientResponse> get() {
final String clientRequestPath = context.getClientRequestPath();
final List<MessageFilterService> bodyClientResponseFilters = new ArrayList<>();
bodyClientResponseFilters.add(new MessageFilterService(ServiceAddressRegistry.EB_ADDRESS_POMMETADATA_SERVICE, "fixWrongValue"));
bodyClientResponseFilters.add(new MessageFilterService(ServiceAddressRegistry.EB_ADDRESS_POMMETADATA_SERVICE, "cache"));
return new Handler<HttpClientResponse>() {
@Override
public void handle(final HttpClientResponse clientResponse) {
final int statusCode = clientResponse.statusCode();
if (LOG.isDebugEnabled()) {
LOG.debug(String.format("Returned endpoint status code: %s", statusCode));
}
switch (statusCode) {
case 200:
processPomContent(clientResponse);
break;
case 404:
sendResponseWithoutTransferEncoding(clientResponse);
break;
default:
sendPassThroughResponseWithoutContent(clientResponse);
break;
}
}
private void processPomContent(final HttpClientResponse clientResponse) {
final Buffer clientRepsonseBody = new Buffer();
clientResponse.dataHandler(new Handler<Buffer>() {
@Override
public void handle(final Buffer data) {
clientRepsonseBody.appendBuffer(data);
}
});
clientResponse.endHandler(new VoidHandler() {
@Override
protected void handle() {
JsonObject jsonObject = new JsonObject();
jsonObject.putString("requestPath", clientRequestPath);
jsonObject.putString("content", clientRepsonseBody.toString());
applyClientResponseFiltersAndRespond(clientResponse, bodyClientResponseFilters, jsonObject);
}
});
}
private void sendResponseWithoutTransferEncoding(final HttpClientResponse clientResponse) {
final HttpServerRequest request = context.getHttpServerRequest();
request.response().setStatusCode(clientResponse.statusCode());
request.response().setStatusMessage(clientResponse.statusMessage());
request.response().headers().set(clientResponse.headers());
request.response().headers().remove(HttpHeaders.TRANSFER_ENCODING);
ProxyService proxyService = new ProxyService();
proxyService.fixWarningCookieDomain(context, clientResponse);
final Buffer clientRepsonseBody = new Buffer();
clientResponse.dataHandler(new Handler<Buffer>() {
@Override
public void handle(final Buffer data) {
clientRepsonseBody.appendBuffer(data);
}
});
clientResponse.endHandler(new VoidHandler() {
@Override
protected void handle() {
request.response().write(clientRepsonseBody);
endRequest();
}
});
}
private void sendPassThroughResponseWithoutContent(final HttpClientResponse clientResponse) {
final HttpServerRequest request = context.getHttpServerRequest();
request.response().setStatusCode(clientResponse.statusCode());
request.response().setStatusMessage(clientResponse.statusMessage());
request.response().headers().set(clientResponse.headers());
ProxyService proxyService = new ProxyService();
proxyService.fixWarningCookieDomain(context, clientResponse);
final Buffer clientRepsonseBody = new Buffer();
clientResponse.dataHandler(new Handler<Buffer>() {
@Override
public void handle(final Buffer data) {
clientRepsonseBody.appendBuffer(data);
}
});
clientResponse.endHandler(new VoidHandler() {
@Override
protected void handle() {
request.response().write(clientRepsonseBody);
endRequest();
}
});
}
};
}
private void applyClientResponseFiltersAndRespond(
final HttpClientResponse clientResponse,
final List<MessageFilterService> messageFilterServiceList,
final JsonObject jsonObjectMessage) {
final HttpServerRequest request = context.getHttpServerRequest();
final Vertx vertx = context.getVertx();
final String messagePayload = jsonObjectMessage.getString("content");
if (messageFilterServiceList.size() == 0) {
request.response().setStatusCode(clientResponse.statusCode());
request.response().setStatusMessage(clientResponse.statusMessage());
request.response().headers().set(clientResponse.headers());
request.response().putHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(messagePayload.getBytes().length));
ProxyService proxyService = new ProxyService();
proxyService.fixWarningCookieDomain(context, clientResponse);
if (!"HEAD".equals(request.method())) {
request.response().write(messagePayload);
}
endRequest();
return;
}
final MessageFilterService messageFilterService = messageFilterServiceList.get(0);
AsyncResultHandler<Message<String>> responseHandler = new AsyncResultHandler<Message<String>>() {
@Override
public void handle(AsyncResult<Message<String>> asyncResult) {
if (asyncResult.succeeded()) {
messageFilterServiceList.remove(0);
jsonObjectMessage.putString("content", asyncResult.result().body());
applyClientResponseFiltersAndRespond(clientResponse, messageFilterServiceList, jsonObjectMessage);
} else {
final Throwable throwable = asyncResult.cause();
if (throwable != null) {
LOG.error("error", throwable);
throwable.printStackTrace();
request.response().setStatusCode(HttpResponseStatus.INTERNAL_SERVER_ERROR.code());
request.response().setStatusMessage(throwable.getMessage());
request.response().headers().set(clientResponse.headers());
ProxyService proxyService = new ProxyService();
proxyService.fixWarningCookieDomain(context, clientResponse);
request.response().end();
}
}
}
};
MessagingTemplate
.address(vertx.eventBus(), messageFilterService.getAddress())
.action(messageFilterService.getAction())
.content(jsonObjectMessage).send(responseHandler);
}
}
|
package som.interpreter.actors;
import java.util.Arrays;
import com.oracle.truffle.api.CompilerDirectives.CompilationFinal;
import com.oracle.truffle.api.RootCallTarget;
import com.oracle.truffle.api.source.SourceSection;
import som.VM;
import som.interpreter.actors.Actor.ActorProcessingThread;
import som.interpreter.actors.ReceivedMessage.ReceivedCallback;
import som.interpreter.actors.SPromise.SResolver;
import som.vm.VmSettings;
import som.vmobjects.SBlock;
import som.vmobjects.SSymbol;
import tools.concurrency.TracingActivityThread;
import tools.snapshot.SnapshotBackend;
import tools.snapshot.SnapshotBuffer;
public abstract class EventualMessage {
protected final Object[] args;
protected final SResolver resolver;
protected final RootCallTarget onReceive;
/**
* Contains the messageId for Kompos tracing.
* This field is reused for snapshotting. It then contains the snapshot version at send
* time. The snapshot version is used to determine whether the message needs to be
* serialized.
*/
@CompilationFinal protected long messageId;
/**
* Indicates the case that an asynchronous message has a receiver breakpoint.
* It is not final because its value can be updated so that other breakpoints
* can reuse the stepping strategy implemented for message receiver breakpoints.
*/
protected boolean haltOnReceive;
/**
* Indicates that the implicit promise, corresponding to this message,
* has a promise resolver breakpoint.
*/
private final boolean haltOnResolver;
protected EventualMessage(final Object[] args,
final SResolver resolver, final RootCallTarget onReceive,
final boolean haltOnReceive, final boolean haltOnResolver) {
this.args = args;
this.resolver = resolver;
this.onReceive = onReceive;
this.haltOnReceive = haltOnReceive;
this.haltOnResolver = haltOnResolver;
if (VmSettings.KOMPOS_TRACING) {
this.messageId = TracingActivityThread.newEntityId();
} else {
this.messageId = 0;
}
assert onReceive.getRootNode() instanceof ReceivedMessage
|| onReceive.getRootNode() instanceof ReceivedCallback;
}
public abstract Actor getTarget();
public abstract Actor getSender();
public SResolver getResolver() {
return resolver;
}
public final long getMessageId() {
return messageId;
}
public abstract SSymbol getSelector();
public SourceSection getTargetSourceSection() {
return onReceive.getRootNode().getSourceSection();
}
public long serialize(final SnapshotBuffer sb) {
ReceivedRootNode rm = (ReceivedRootNode) this.onReceive.getRootNode();
if (VmSettings.TEST_SNAPSHOTS || VmSettings.TEST_SERIALIZE_ALL
|| sb.getSnapshotVersion() > this.getMessageId()) {
// Not sure if this is optimized, worst case need to duplicate this for all messages
return rm.getSerializer().execute(this, sb);
} else {
// need to be careful, might interfere with promise serialization...
return -1;
}
}
/**
* A message to a known receiver that is to be executed on the actor owning
* the receiver.
*
* ARGUMENTS: are wrapped eagerly on message creation
*/
public abstract static class AbstractDirectMessage extends EventualMessage {
private final SSymbol selector;
private final Actor target;
private final Actor sender;
protected AbstractDirectMessage(final Actor target, final SSymbol selector,
final Object[] arguments, final Actor sender, final SResolver resolver,
final RootCallTarget onReceive, final boolean triggerMessageReceiverBreakpoint,
final boolean triggerPromiseResolverBreakpoint) {
super(arguments, resolver, onReceive, triggerMessageReceiverBreakpoint,
triggerPromiseResolverBreakpoint);
this.selector = selector;
this.sender = sender;
this.target = target;
if (VmSettings.SNAPSHOTS_ENABLED) {
this.messageId = ActorProcessingThread.currentThread().getSnapshotId();
}
assert target != null;
assert !(args[0] instanceof SFarReference) : "needs to be guaranted by call to this constructor";
assert !(args[0] instanceof SPromise);
}
/**
* Constructor for non TracingActivityThreads, i.e. used for the initial start message or
* TimerPrim
*/
protected AbstractDirectMessage(final Actor target, final SSymbol selector,
final Object[] arguments, final Actor sender, final SResolver resolver,
final RootCallTarget onReceive) {
super(arguments, resolver, onReceive, false, false);
this.selector = selector;
this.sender = sender;
this.target = target;
if (VmSettings.SNAPSHOTS_ENABLED) {
this.messageId = SnapshotBackend.getSnapshotVersion();
}
assert target != null;
assert !(args[0] instanceof SFarReference) : "needs to be guaranted by call to this constructor";
assert !(args[0] instanceof SPromise);
}
@Override
public Actor getTarget() {
assert target != null;
return target;
}
@Override
public Actor getSender() {
assert sender != null;
return sender;
}
@Override
public SSymbol getSelector() {
return selector;
}
@Override
public boolean getHaltOnPromiseMessageResolution() {
return false;
}
@Override
public String toString() {
String t = target.toString();
return "DirectMsg(" + selector.toString() + ", "
+ Arrays.toString(args) + ", " + t
+ ", sender: " + (sender == null ? "" : sender.toString()) + ")";
}
}
public static final class DirectMessage extends AbstractDirectMessage {
public DirectMessage(final Actor target, final SSymbol selector,
final Object[] arguments, final Actor sender, final SResolver resolver,
final RootCallTarget onReceive, final boolean triggerMessageReceiverBreakpoint,
final boolean triggerPromiseResolverBreakpoint) {
super(target, selector, arguments, sender, resolver, onReceive,
triggerMessageReceiverBreakpoint, triggerPromiseResolverBreakpoint);
}
/**
* Constructor for non TracingActivityThreads, i.e. used for the initial start message or
* TimerPrim
*/
public DirectMessage(final Actor target, final SSymbol selector,
final Object[] arguments, final Actor sender, final SResolver resolver,
final RootCallTarget onReceive) {
super(target, selector, arguments, sender, resolver, onReceive);
}
}
protected static Actor determineTargetAndWrapArguments(final Object[] arguments,
Actor target, final Actor currentSender, final Actor originalSender) {
VM.thisMethodNeedsToBeOptimized("not optimized for compilation");
// target: the owner of the promise that just got resolved
// however, if a promise gets resolved to a far reference
// we need to redirect the message to the owner of that far reference
Object receiver = target.wrapForUse(arguments[0], currentSender, null);
assert !(receiver instanceof SPromise) : "TODO: handle this case as well?? Is it possible? didn't think about it";
if (receiver instanceof SFarReference) {
// now we are about to send a message to a far reference, so, it
// is better to just redirect the message back to the current actor
target = ((SFarReference) receiver).getActor();
receiver = ((SFarReference) receiver).getValue();
}
arguments[0] = receiver;
assert !(receiver instanceof SFarReference) : "this should not happen, because we need to redirect messages to the other actor, and normally we just unwrapped this";
assert !(receiver instanceof SPromise);
for (int i = 1; i < arguments.length; i++) {
arguments[i] = target.wrapForUse(arguments[i], originalSender, null);
}
return target;
}
/** A message send after a promise got resolved. */
public abstract static class PromiseMessage extends EventualMessage {
public static final int PROMISE_RCVR_IDX = 0;
public static final int PROMISE_VALUE_IDX = 1;
protected final Actor originalSender; // initial owner of the arguments
public PromiseMessage(final Object[] arguments, final Actor originalSender,
final SResolver resolver, final RootCallTarget onReceive,
final boolean triggerMessageReceiverBreakpoint,
final boolean triggerPromiseResolverBreakpoint) {
super(arguments, resolver, onReceive, triggerMessageReceiverBreakpoint,
triggerPromiseResolverBreakpoint);
this.originalSender = originalSender;
if (VmSettings.SNAPSHOTS_ENABLED) {
this.messageId = ActorProcessingThread.currentThread().getSnapshotId();
}
}
public abstract void resolve(Object rcvr, Actor target, Actor sendingActor);
@Override
public final Actor getSender() {
assert originalSender != null;
return originalSender;
}
public abstract SPromise getPromise();
/**
* Used for Fixup in deserialization.
*/
public abstract void setPromise(SPromise promise);
@Override
public boolean getHaltOnPromiseMessageResolution() {
return getPromise().getHaltOnResolution();
}
}
/**
* A message that was send with <-: to a promise, and will be delivered
* after the promise is resolved.
*/
public abstract static class AbstractPromiseSendMessage extends PromiseMessage {
private final SSymbol selector;
protected Actor target;
protected Actor finalSender;
@CompilationFinal protected SPromise originalTarget;
protected AbstractPromiseSendMessage(final SSymbol selector,
final Object[] arguments, final Actor originalSender,
final SResolver resolver, final RootCallTarget onReceive,
final boolean triggerMessageReceiverBreakpoint,
final boolean triggerPromiseResolverBreakpoint) {
super(arguments, originalSender, resolver, onReceive, triggerMessageReceiverBreakpoint,
triggerPromiseResolverBreakpoint);
this.selector = selector;
assert (args[0] instanceof SPromise);
this.originalTarget = (SPromise) args[0];
}
@Override
public void resolve(final Object rcvr, final Actor target, final Actor sendingActor) {
determineAndSetTarget(rcvr, target, sendingActor);
}
private void determineAndSetTarget(final Object rcvr, final Actor target,
final Actor sendingActor) {
VM.thisMethodNeedsToBeOptimized("not optimized for compilation");
args[0] = rcvr;
Actor finalTarget =
determineTargetAndWrapArguments(args, target, sendingActor, originalSender);
this.target = finalTarget; // for sends to far references, we need to adjust the target
this.finalSender = sendingActor;
if (VmSettings.SNAPSHOTS_ENABLED) {
this.messageId = Math.min(this.messageId,
ActorProcessingThread.currentThread().getSnapshotId());
}
}
@Override
public SSymbol getSelector() {
return selector;
}
@Override
public Actor getTarget() {
assert target != null;
return target;
}
public boolean isDelivered() {
return target != null;
}
@Override
public String toString() {
String t;
if (target == null) {
t = "null";
} else {
t = target.toString();
}
return "PSendMsg(" + selector.toString() + " " + Arrays.toString(args) + ", " + t
+ ", sender: " + (finalSender == null ? "" : finalSender.toString()) + ")";
}
@Override
public SPromise getPromise() {
return originalTarget;
}
@Override
public final void setPromise(final SPromise promise) {
assert VmSettings.SNAPSHOTS_ENABLED;
assert promise != null && originalTarget == null;
this.originalTarget = promise;
}
public Actor getFinalSender() {
return finalSender;
}
}
public static final class PromiseSendMessage extends AbstractPromiseSendMessage {
public PromiseSendMessage(final SSymbol selector, final Object[] arguments,
final Actor originalSender, final SResolver resolver, final RootCallTarget onReceive,
final boolean triggerMessageReceiverBreakpoint,
final boolean triggerPromiseResolverBreakpoint) {
super(selector, arguments, originalSender, resolver, onReceive,
triggerMessageReceiverBreakpoint, triggerPromiseResolverBreakpoint);
}
}
/** The callback message to be send after a promise is resolved. */
public abstract static class AbstractPromiseCallbackMessage extends PromiseMessage {
/**
* The promise on which this callback is registered on.
*/
@CompilationFinal protected SPromise promise;
protected AbstractPromiseCallbackMessage(final Actor owner, final SBlock callback,
final SResolver resolver, final RootCallTarget onReceive,
final boolean triggerMessageReceiverBreakpoint,
final boolean triggerPromiseResolverBreakpoint, final SPromise promiseRegisteredOn) {
super(new Object[] {callback, null}, owner, resolver, onReceive,
triggerMessageReceiverBreakpoint, triggerPromiseResolverBreakpoint);
this.promise = promiseRegisteredOn;
}
@Override
public void resolve(final Object rcvr, final Actor target, final Actor sendingActor) {
setPromiseValue(rcvr, sendingActor);
}
/**
* The value the promise was resolved to on which this callback is
* registered on.
*
* @param resolvingActor - the owner of the value, the promise was resolved to.
*/
private void setPromiseValue(final Object value, final Actor resolvingActor) {
args[1] = originalSender.wrapForUse(value, resolvingActor, null);
if (VmSettings.SNAPSHOTS_ENABLED) {
this.messageId = Math.min(this.messageId,
ActorProcessingThread.currentThread().getSnapshotId());
}
}
@Override
public SSymbol getSelector() {
return ((SBlock) args[0]).getMethod().getSignature();
}
@Override
public Actor getTarget() {
assert originalSender != null;
return originalSender;
}
@Override
public String toString() {
return "PCallbackMsg(" + Arrays.toString(args) + ")";
}
@Override
public SPromise getPromise() {
return promise;
}
/**
* Used for Fixup in deserialization.
*/
@Override
public final void setPromise(final SPromise promise) {
assert VmSettings.SNAPSHOTS_ENABLED;
assert promise != null && this.promise == null;
this.promise = promise;
}
}
public static final class PromiseCallbackMessage extends AbstractPromiseCallbackMessage {
public PromiseCallbackMessage(final Actor owner, final SBlock callback,
final SResolver resolver, final RootCallTarget onReceive,
final boolean triggerMessageReceiverBreakpoint,
final boolean triggerPromiseResolverBreakpoint, final SPromise promiseRegisteredOn) {
super(owner, callback, resolver, onReceive, triggerMessageReceiverBreakpoint,
triggerPromiseResolverBreakpoint, promiseRegisteredOn);
}
}
public final void execute() {
Object rcvrObj = args[0];
assert rcvrObj != null;
assert !(rcvrObj instanceof SFarReference);
assert !(rcvrObj instanceof SPromise);
assert onReceive.getRootNode() instanceof ReceivedMessage
|| onReceive.getRootNode() instanceof ReceivedCallback;
onReceive.call(this);
}
public static Actor getActorCurrentMessageIsExecutionOn() {
Thread t = Thread.currentThread();
return ((ActorProcessingThread) t).currentlyExecutingActor;
}
public static EventualMessage getCurrentExecutingMessage() {
Thread t = Thread.currentThread();
return ((ActorProcessingThread) t).currentMessage;
}
public Object[] getArgs() {
return args;
}
/**
* Indicates that execution should stop and yield to the debugger,
* before the message is processed.
*/
public boolean getHaltOnReceive() {
return haltOnReceive;
}
/**
* Sets the flag for the message receiver breakpoint.
*/
void enableHaltOnReceive() {
haltOnReceive = true;
}
/**
* Indicates that execution should stop and yield to the debugger,
* before the computed value is used to resolve the promise.
*/
boolean getHaltOnResolver() {
return haltOnResolver;
}
/**
* Indicates that a resolution breakpoint is set.
*/
boolean getHaltOnResolution() {
if (resolver == null) {
return false;
}
return resolver.getPromise().getHaltOnResolution();
}
/**
* Indicates that the message is a promise message and a resolution breakpoint
* is set.
*/
public abstract boolean getHaltOnPromiseMessageResolution();
}
|
package de.danoeh.antennapod.feed;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.util.Log;
import de.danoeh.antennapod.AppConfig;
import de.danoeh.antennapod.PodcastApp;
import de.danoeh.antennapod.asynctask.DownloadStatus;
import de.danoeh.antennapod.service.PlaybackService;
import de.danoeh.antennapod.storage.DownloadRequestException;
import de.danoeh.antennapod.storage.DownloadRequester;
import de.danoeh.antennapod.storage.PodDBAdapter;
import de.danoeh.antennapod.util.DownloadError;
import de.danoeh.antennapod.util.FeedtitleComparator;
import de.danoeh.antennapod.util.comparator.DownloadStatusComparator;
import de.danoeh.antennapod.util.comparator.FeedItemPubdateComparator;
/**
* Singleton class Manages all feeds, categories and feeditems
*
*
* */
public class FeedManager {
private static final String TAG = "FeedManager";
public static final String ACITON_FEED_LIST_UPDATE = "de.danoeh.antennapod.action.feed.feedlistUpdate";
public static final String ACTION_UNREAD_ITEMS_UPDATE = "de.danoeh.antennapod.action.feed.unreadItemsUpdate";
public static final String ACTION_QUEUE_UPDATE = "de.danoeh.antennapod.action.feed.queueUpdate";
public static final String ACTION_DOWNLOADLOG_UPDATE = "de.danoeh.antennapod.action.feed.downloadLogUpdate";
public static final String EXTRA_FEED_ITEM_ID = "de.danoeh.antennapod.extra.feed.feedItemId";
public static final String EXTRA_FEED_ID = "de.danoeh.antennapod.extra.feed.feedId";
/** Number of completed Download status entries to store. */
private static final int DOWNLOAD_LOG_SIZE = 50;
private static FeedManager singleton;
private List<Feed> feeds;
private ArrayList<FeedCategory> categories;
/** Contains all items where 'read' is false */
private List<FeedItem> unreadItems;
/** Contains completed Download status entries */
private ArrayList<DownloadStatus> downloadLog;
/** Contains the queue of items to be played. */
private List<FeedItem> queue;
private DownloadRequester requester;
/** Should be used to change the content of the arrays from another thread. */
private Handler contentChanger;
/** Ensures that there are no parallel db operations. */
private Executor dbExec;
/** Prevents user from starting several feed updates at the same time. */
private static boolean isStartingFeedRefresh = false;
private FeedManager() {
feeds = Collections.synchronizedList(new ArrayList<Feed>());
categories = new ArrayList<FeedCategory>();
unreadItems = Collections.synchronizedList(new ArrayList<FeedItem>());
requester = DownloadRequester.getInstance();
downloadLog = new ArrayList<DownloadStatus>();
queue = Collections.synchronizedList(new ArrayList<FeedItem>());
contentChanger = new Handler();
dbExec = Executors.newSingleThreadExecutor(new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setPriority(Thread.MIN_PRIORITY);
return t;
}
});
}
public static FeedManager getInstance() {
if (singleton == null) {
singleton = new FeedManager();
}
return singleton;
}
/**
* Play FeedMedia and start the playback service + launch Mediaplayer
* Activity.
*
* @param context
* for starting the playbackservice
* @param media
* that shall be played
* @param showPlayer
* if Mediaplayer activity shall be started
* @param startWhenPrepared
* if Mediaplayer shall be started after it has been prepared
*/
public void playMedia(Context context, FeedMedia media, boolean showPlayer,
boolean startWhenPrepared, boolean shouldStream) {
// Start playback Service
Intent launchIntent = new Intent(context, PlaybackService.class);
launchIntent.putExtra(PlaybackService.EXTRA_MEDIA_ID, media.getId());
launchIntent.putExtra(PlaybackService.EXTRA_FEED_ID, media.getItem()
.getFeed().getId());
launchIntent.putExtra(PlaybackService.EXTRA_START_WHEN_PREPARED,
startWhenPrepared);
launchIntent
.putExtra(PlaybackService.EXTRA_SHOULD_STREAM, shouldStream);
context.startService(launchIntent);
if (showPlayer) {
// Launch Mediaplayer
context.startActivity(PlaybackService.getPlayerActivityIntent(
context, media));
}
}
/** Remove media item that has been downloaded. */
public boolean deleteFeedMedia(Context context, FeedMedia media) {
boolean result = false;
if (media.isDownloaded()) {
File mediaFile = new File(media.file_url);
if (mediaFile.exists()) {
result = mediaFile.delete();
}
media.setDownloaded(false);
media.setFile_url(null);
setFeedMedia(context, media);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
final long lastPlayedId = prefs.getLong(PlaybackService.PREF_LAST_PLAYED_ID, -1);
if (media.getId() == lastPlayedId) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean(PlaybackService.PREF_LAST_IS_STREAM, true);
editor.commit();
}
}
if (AppConfig.DEBUG)
Log.d(TAG, "Deleting File. Result: " + result);
return result;
}
/** Remove a feed with all its items and media files and its image. */
public void deleteFeed(final Context context, final Feed feed) {
contentChanger.post(new Runnable() {
@Override
public void run() {
feeds.remove(feed);
sendFeedUpdateBroadcast(context);
}
});
dbExec.execute(new Runnable() {
@Override
public void run() {
PodDBAdapter adapter = new PodDBAdapter(context);
DownloadRequester requester = DownloadRequester.getInstance();
adapter.open();
// delete image file
if (feed.getImage() != null) {
if (feed.getImage().isDownloaded()
&& feed.getImage().getFile_url() != null) {
File imageFile = new File(feed.getImage().getFile_url());
imageFile.delete();
} else if (requester.isDownloadingFile(feed.getImage())) {
requester.cancelDownload(context, feed.getImage());
}
}
// delete stored media files and mark them as read
for (FeedItem item : feed.getItems()) {
if (!item.isRead()) {
unreadItems.remove(item);
}
if (queue.contains(item)) {
removeQueueItem(item, adapter);
}
if (item.getMedia() != null
&& item.getMedia().isDownloaded()) {
File mediaFile = new File(item.getMedia().getFile_url());
mediaFile.delete();
} else if (item.getMedia() != null
&& requester.isDownloadingFile(item.getMedia())) {
requester.cancelDownload(context, item.getMedia());
}
}
adapter.removeFeed(feed);
adapter.close();
}
});
}
private void sendUnreadItemsUpdateBroadcast(Context context, FeedItem item) {
Intent update = new Intent(ACTION_UNREAD_ITEMS_UPDATE);
if (item != null) {
update.putExtra(EXTRA_FEED_ID, item.getFeed().getId());
update.putExtra(EXTRA_FEED_ITEM_ID, item.getId());
}
context.sendBroadcast(update);
}
private void sendQueueUpdateBroadcast(Context context, FeedItem item) {
Intent update = new Intent(ACTION_QUEUE_UPDATE);
if (item != null) {
update.putExtra(EXTRA_FEED_ID, item.getFeed().getId());
update.putExtra(EXTRA_FEED_ITEM_ID, item.getId());
}
context.sendBroadcast(update);
}
private void sendFeedUpdateBroadcast(Context context) {
context.sendBroadcast(new Intent(ACITON_FEED_LIST_UPDATE));
}
/**
* Sets the 'read'-attribute of a FeedItem. Should be used by all Classes
* instead of the setters of FeedItem.
*/
public void markItemRead(final Context context, final FeedItem item,
final boolean read) {
if (AppConfig.DEBUG)
Log.d(TAG, "Setting item with title " + item.getTitle()
+ " as read/unread");
item.read = read;
setFeedItem(context, item);
contentChanger.post(new Runnable() {
@Override
public void run() {
if (read == true) {
unreadItems.remove(item);
} else {
unreadItems.add(item);
Collections.sort(unreadItems,
new FeedItemPubdateComparator());
}
sendUnreadItemsUpdateBroadcast(context, item);
}
});
}
/**
* Sets the 'read' attribute of all FeedItems of a specific feed to true
*
* @param context
*/
public void markFeedRead(Context context, Feed feed) {
for (FeedItem item : feed.getItems()) {
if (unreadItems.contains(item)) {
markItemRead(context, item, true);
}
}
}
/** Marks all items in the unread items list as read */
public void markAllItemsRead(final Context context) {
if (AppConfig.DEBUG)
Log.d(TAG, "marking all items as read");
for (FeedItem item : unreadItems) {
item.read = true;
}
final ArrayList<FeedItem> unreadItemsCopy = new ArrayList<FeedItem>(
unreadItems);
unreadItems.clear();
sendUnreadItemsUpdateBroadcast(context, null);
dbExec.execute(new Runnable() {
@Override
public void run() {
PodDBAdapter adapter = new PodDBAdapter(context);
adapter.open();
for (FeedItem item : unreadItemsCopy) {
setFeedItem(item, adapter);
}
adapter.close();
}
});
}
@SuppressLint("NewApi")
public void refreshAllFeeds(final Context context) {
if (AppConfig.DEBUG)
Log.d(TAG, "Refreshing all feeds.");
if (!isStartingFeedRefresh) {
isStartingFeedRefresh = true;
AsyncTask<Void, Void, Void> updateWorker = new AsyncTask<Void, Void, Void>() {
@Override
protected void onPostExecute(Void result) {
if (AppConfig.DEBUG)
Log.d(TAG,
"All feeds have been sent to the downloadmanager");
isStartingFeedRefresh = false;
}
@Override
protected Void doInBackground(Void... params) {
for (Feed feed : feeds) {
try {
refreshFeed(context, feed);
} catch (DownloadRequestException e) {
e.printStackTrace();
addDownloadStatus(
context,
new DownloadStatus(feed, feed
.getHumanReadableIdentifier(),
DownloadError.ERROR_REQUEST_ERROR,
false, e.getMessage()));
}
}
return null;
}
};
if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.GINGERBREAD_MR1) {
updateWorker.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else {
updateWorker.execute();
}
}
}
/**
* Notifies the feed manager that the an image file is invalid. It will try
* to redownload it
*/
public void notifyInvalidImageFile(Context context, FeedImage image) {
Log.i(TAG,
"The feedmanager was notified about an invalid image download. It will now try to redownload the image file");
try {
requester.downloadImage(context, image);
} catch (DownloadRequestException e) {
e.printStackTrace();
Log.w(TAG, "Failed to download invalid feed image");
}
}
public void refreshFeed(Context context, Feed feed)
throws DownloadRequestException {
requester.downloadFeed(context, new Feed(feed.getDownload_url(),
new Date(), feed.getTitle()));
}
public void addDownloadStatus(final Context context,
final DownloadStatus status) {
contentChanger.post(new Runnable() {
@Override
public void run() {
downloadLog.add(status);
Collections.sort(downloadLog, new DownloadStatusComparator());
final DownloadStatus removedStatus;
if (downloadLog.size() > DOWNLOAD_LOG_SIZE) {
removedStatus = downloadLog.remove(downloadLog.size() - 1);
} else {
removedStatus = null;
}
context.sendBroadcast(new Intent(ACTION_DOWNLOADLOG_UPDATE));
dbExec.execute(new Runnable() {
@Override
public void run() {
PodDBAdapter adapter = new PodDBAdapter(context);
adapter.open();
if (removedStatus != null) {
adapter.removeDownloadStatus(removedStatus);
}
adapter.setDownloadStatus(status);
adapter.close();
}
});
}
});
}
public void downloadAllItemsInQueue(final Context context) {
if (!queue.isEmpty()) {
try {
downloadFeedItem(context,
queue.toArray(new FeedItem[queue.size()]));
} catch (DownloadRequestException e) {
e.printStackTrace();
}
}
}
public void downloadFeedItem(final Context context, FeedItem... items)
throws DownloadRequestException {
boolean autoQueue = PreferenceManager.getDefaultSharedPreferences(
context.getApplicationContext()).getBoolean(
PodcastApp.PREF_AUTO_QUEUE, true);
List<FeedItem> addToQueue = new ArrayList<FeedItem>();
for (FeedItem item : items) {
if (item.getMedia() != null
&& !requester.isDownloadingFile(item.getMedia())
&& !item.getMedia().isDownloaded()) {
if (items.length > 1) {
try {
requester.downloadMedia(context, item.getMedia());
} catch (DownloadRequestException e) {
e.printStackTrace();
addDownloadStatus(context,
new DownloadStatus(item.getMedia(), item
.getMedia()
.getHumanReadableIdentifier(),
DownloadError.ERROR_REQUEST_ERROR,
false, e.getMessage()));
}
} else {
requester.downloadMedia(context, item.getMedia());
}
addToQueue.add(item);
}
}
if (autoQueue) {
addQueueItem(context,
addToQueue.toArray(new FeedItem[addToQueue.size()]));
}
}
public void enqueueAllNewItems(final Context context) {
if (!unreadItems.isEmpty()) {
addQueueItem(context,
unreadItems.toArray(new FeedItem[unreadItems.size()]));
markAllItemsRead(context);
}
}
public void addQueueItem(final Context context, final FeedItem... items) {
if (items.length > 0) {
contentChanger.post(new Runnable() {
@Override
public void run() {
for (FeedItem item : items) {
if (!queue.contains(item)) {
queue.add(item);
}
}
sendQueueUpdateBroadcast(context, items[0]);
dbExec.execute(new Runnable() {
@Override
public void run() {
PodDBAdapter adapter = new PodDBAdapter(context);
adapter.open();
adapter.setQueue(queue);
adapter.close();
}
});
}
});
}
}
/** Removes all items in queue */
public void clearQueue(final Context context) {
if (AppConfig.DEBUG)
Log.d(TAG, "Clearing queue");
queue.clear();
sendQueueUpdateBroadcast(context, null);
dbExec.execute(new Runnable() {
@Override
public void run() {
PodDBAdapter adapter = new PodDBAdapter(context);
adapter.open();
adapter.setQueue(queue);
adapter.close();
}
});
}
/** Uses external adapter. */
public void removeQueueItem(FeedItem item, PodDBAdapter adapter) {
boolean removed = queue.remove(item);
if (removed) {
adapter.setQueue(queue);
}
}
/** Uses its own adapter. */
public void removeQueueItem(final Context context, FeedItem item) {
boolean removed = queue.remove(item);
if (removed) {
autoDeleteIfPossible(context, item.getMedia());
dbExec.execute(new Runnable() {
@Override
public void run() {
PodDBAdapter adapter = new PodDBAdapter(context);
adapter.open();
adapter.setQueue(queue);
adapter.close();
}
});
}
sendQueueUpdateBroadcast(context, item);
}
/**
* Delete the episode of this FeedMedia object if auto-delete is enabled and
* it is not the last played media or it is the last played media and
* playback has been completed.
*/
public void autoDeleteIfPossible(Context context, FeedMedia media) {
if (media != null) {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(context
.getApplicationContext());
boolean autoDelete = prefs.getBoolean(PodcastApp.PREF_AUTO_DELETE,
false);
if (autoDelete) {
long lastPlayedId = prefs.getLong(
PlaybackService.PREF_LAST_PLAYED_ID, -1);
long autoDeleteId = prefs.getLong(
PlaybackService.PREF_AUTODELETE_MEDIA_ID, -1);
boolean playbackCompleted = prefs
.getBoolean(
PlaybackService.PREF_AUTO_DELETE_MEDIA_PLAYBACK_COMPLETED,
false);
if ((media.getId() != lastPlayedId)
&& ((media.getId() != autoDeleteId) || (media.getId() == autoDeleteId && playbackCompleted))) {
if (AppConfig.DEBUG)
Log.d(TAG, "Performing auto-cleanup");
deleteFeedMedia(context, media);
SharedPreferences.Editor editor = prefs.edit();
editor.putLong(PlaybackService.PREF_AUTODELETE_MEDIA_ID, -1);
editor.commit();
} else {
if (AppConfig.DEBUG)
Log.d(TAG, "Didn't do auto-cleanup");
}
} else {
if (AppConfig.DEBUG)
Log.d(TAG, "Auto-delete preference is disabled");
}
} else {
Log.e(TAG, "Could not do auto-cleanup: media was null");
}
}
public void moveQueueItem(final Context context, FeedItem item, int delta) {
if (AppConfig.DEBUG)
Log.d(TAG, "Moving queue item");
int itemIndex = queue.indexOf(item);
int newIndex = itemIndex + delta;
if (newIndex >= 0 && newIndex < queue.size()) {
FeedItem oldItem = queue.set(newIndex, item);
queue.set(itemIndex, oldItem);
dbExec.execute(new Runnable() {
@Override
public void run() {
PodDBAdapter adapter = new PodDBAdapter(context);
adapter.open();
adapter.setQueue(queue);
adapter.close();
}
});
}
sendQueueUpdateBroadcast(context, item);
}
public boolean isInQueue(FeedItem item) {
return queue.contains(item);
}
public FeedItem getFirstQueueItem() {
if (queue.isEmpty()) {
return null;
} else {
return queue.get(0);
}
}
private void addNewFeed(final Context context, final Feed feed) {
contentChanger.post(new Runnable() {
@Override
public void run() {
feeds.add(feed);
Collections.sort(feeds, new FeedtitleComparator());
sendFeedUpdateBroadcast(context);
}
});
dbExec.execute(new Runnable() {
@Override
public void run() {
PodDBAdapter adapter = new PodDBAdapter(context);
adapter.open();
adapter.setCompleteFeed(feed);
adapter.close();
}
});
}
/**
* Updates an existing feed or adds it as a new one if it doesn't exist.
*
* @return The saved Feed with a database ID
*/
public Feed updateFeed(Context context, final Feed newFeed) {
// Look up feed in the feedslist
final Feed savedFeed = searchFeedByIdentifyingValue(newFeed
.getIdentifyingValue());
if (savedFeed == null) {
if (AppConfig.DEBUG)
Log.d(TAG,
"Found no existing Feed with title "
+ newFeed.getTitle() + ". Adding as new one.");
// Add a new Feed
addNewFeed(context, newFeed);
return newFeed;
} else {
if (AppConfig.DEBUG)
Log.d(TAG, "Feed with title " + newFeed.getTitle()
+ " already exists. Syncing new with existing one.");
// Look for new or updated Items
for (int idx = 0; idx < newFeed.getItems().size(); idx++) {
final FeedItem item = newFeed.getItems().get(idx);
FeedItem oldItem = searchFeedItemByIdentifyingValue(savedFeed,
item.getIdentifyingValue());
if (oldItem == null) {
// item is new
final int i = idx;
item.setFeed(savedFeed);
contentChanger.post(new Runnable() {
@Override
public void run() {
savedFeed.getItems().add(i, item);
}
});
markItemRead(context, item, false);
}
}
// update attributes
savedFeed.setLastUpdate(newFeed.getLastUpdate());
savedFeed.setType(newFeed.getType());
setFeed(context, savedFeed);
return savedFeed;
}
}
/** Get a Feed by its link */
private Feed searchFeedByIdentifyingValue(String identifier) {
for (Feed feed : feeds) {
if (feed.getIdentifyingValue().equals(identifier)) {
return feed;
}
}
return null;
}
/**
* Returns true if a feed with the given download link is already in the
* feedlist.
*/
public boolean feedExists(String downloadUrl) {
for (Feed feed : feeds) {
if (feed.getDownload_url().equals(downloadUrl)) {
return true;
}
}
return false;
}
/** Get a FeedItem by its identifying value. */
private FeedItem searchFeedItemByIdentifyingValue(Feed feed,
String identifier) {
for (FeedItem item : feed.getItems()) {
if (item.getIdentifyingValue().equals(identifier)) {
return item;
}
}
return null;
}
/** Updates Information of an existing Feed. Uses external adapter. */
public void setFeed(Feed feed, PodDBAdapter adapter) {
if (adapter != null) {
adapter.setFeed(feed);
} else {
Log.w(TAG, "Adapter in setFeed was null");
}
}
/** Updates Information of an existing Feeditem. Uses external adapter. */
public void setFeedItem(FeedItem item, PodDBAdapter adapter) {
if (adapter != null) {
adapter.setSingleFeedItem(item);
} else {
Log.w(TAG, "Adapter in setFeedItem was null");
}
}
/** Updates Information of an existing Feedimage. Uses external adapter. */
public void setFeedImage(FeedImage image, PodDBAdapter adapter) {
if (adapter != null) {
adapter.setImage(image);
} else {
Log.w(TAG, "Adapter in setFeedImage was null");
}
}
/**
* Updates Information of an existing Feedmedia object. Uses external
* adapter.
*/
public void setFeedImage(FeedMedia media, PodDBAdapter adapter) {
if (adapter != null) {
adapter.setMedia(media);
} else {
Log.w(TAG, "Adapter in setFeedMedia was null");
}
}
/**
* Updates Information of an existing Feed. Creates and opens its own
* adapter.
*/
public void setFeed(final Context context, final Feed feed) {
dbExec.execute(new Runnable() {
@Override
public void run() {
PodDBAdapter adapter = new PodDBAdapter(context);
adapter.open();
adapter.setFeed(feed);
adapter.close();
}
});
}
/**
* Updates information of an existing FeedItem. Creates and opens its own
* adapter.
*/
public void setFeedItem(final Context context, final FeedItem item) {
dbExec.execute(new Runnable() {
@Override
public void run() {
PodDBAdapter adapter = new PodDBAdapter(context);
adapter.open();
adapter.setSingleFeedItem(item);
adapter.close();
}
});
}
/**
* Updates information of an existing FeedImage. Creates and opens its own
* adapter.
*/
public void setFeedImage(final Context context, final FeedImage image) {
dbExec.execute(new Runnable() {
@Override
public void run() {
PodDBAdapter adapter = new PodDBAdapter(context);
adapter.open();
adapter.setImage(image);
adapter.close();
}
});
}
/**
* Updates information of an existing FeedMedia object. Creates and opens
* its own adapter.
*/
public void setFeedMedia(final Context context, final FeedMedia media) {
dbExec.execute(new Runnable() {
@Override
public void run() {
PodDBAdapter adapter = new PodDBAdapter(context);
adapter.open();
adapter.setMedia(media);
adapter.close();
}
});
}
/** Get a Feed by its id */
public Feed getFeed(long id) {
for (Feed f : feeds) {
if (f.id == id) {
return f;
}
}
Log.e(TAG, "Couldn't find Feed with id " + id);
return null;
}
/** Get a Feed Image by its id */
public FeedImage getFeedImage(long id) {
for (Feed f : feeds) {
FeedImage image = f.getImage();
if (image != null && image.getId() == id) {
return image;
}
}
return null;
}
/** Get a Feed Item by its id and its feed */
public FeedItem getFeedItem(long id, Feed feed) {
if (feed != null) {
for (FeedItem item : feed.getItems()) {
if (item.getId() == id) {
return item;
}
}
}
Log.e(TAG, "Couldn't find FeedItem with id " + id);
return null;
}
/** Get a FeedMedia object by the id of the Media object and the feed object */
public FeedMedia getFeedMedia(long id, Feed feed) {
if (feed != null) {
for (FeedItem item : feed.getItems()) {
if (item.getMedia() != null && item.getMedia().getId() == id) {
return item.getMedia();
}
}
}
Log.e(TAG, "Couldn't find FeedMedia with id " + id);
if (feed == null)
Log.e(TAG, "Feed was null");
return null;
}
/** Get a FeedMedia object by the id of the Media object. */
public FeedMedia getFeedMedia(long id) {
for (Feed feed : feeds) {
for (FeedItem item : feed.getItems()) {
if (item.getMedia() != null && item.getMedia().getId() == id) {
return item.getMedia();
}
}
}
Log.w(TAG, "Couldn't find FeedMedia with id " + id);
return null;
}
public DownloadStatus getDownloadStatus(FeedFile feedFile) {
for (DownloadStatus status : downloadLog) {
if (status.getFeedFile() == feedFile) {
return status;
}
}
return null;
}
/** Reads the database */
public void loadDBData(Context context) {
updateArrays(context);
}
public void updateArrays(Context context) {
feeds.clear();
categories.clear();
PodDBAdapter adapter = new PodDBAdapter(context);
adapter.open();
extractFeedlistFromCursor(context, adapter);
extractDownloadLogFromCursor(context, adapter);
extractQueueFromCursor(context, adapter);
adapter.close();
Collections.sort(feeds, new FeedtitleComparator());
Collections.sort(unreadItems, new FeedItemPubdateComparator());
}
private void extractFeedlistFromCursor(Context context, PodDBAdapter adapter) {
if (AppConfig.DEBUG)
Log.d(TAG, "Extracting Feedlist");
Cursor feedlistCursor = adapter.getAllFeedsCursor();
if (feedlistCursor.moveToFirst()) {
do {
Date lastUpdate = new Date(
feedlistCursor
.getLong(PodDBAdapter.KEY_LAST_UPDATE_INDEX));
Feed feed = new Feed(lastUpdate);
feed.id = feedlistCursor.getLong(PodDBAdapter.KEY_ID_INDEX);
feed.setTitle(feedlistCursor
.getString(PodDBAdapter.KEY_TITLE_INDEX));
feed.setLink(feedlistCursor
.getString(PodDBAdapter.KEY_LINK_INDEX));
feed.setDescription(feedlistCursor
.getString(PodDBAdapter.KEY_DESCRIPTION_INDEX));
feed.setPaymentLink(feedlistCursor
.getString(PodDBAdapter.KEY_PAYMENT_LINK_INDEX));
feed.setAuthor(feedlistCursor
.getString(PodDBAdapter.KEY_AUTHOR_INDEX));
feed.setLanguage(feedlistCursor
.getString(PodDBAdapter.KEY_LANGUAGE_INDEX));
feed.setType(feedlistCursor
.getString(PodDBAdapter.KEY_TYPE_INDEX));
feed.setFeedIdentifier(feedlistCursor
.getString(PodDBAdapter.KEY_FEED_IDENTIFIER_INDEX));
long imageIndex = feedlistCursor
.getLong(PodDBAdapter.KEY_IMAGE_INDEX);
if (imageIndex != 0) {
feed.setImage(adapter.getFeedImage(imageIndex));
feed.getImage().setFeed(feed);
}
feed.file_url = feedlistCursor
.getString(PodDBAdapter.KEY_FILE_URL_INDEX);
feed.download_url = feedlistCursor
.getString(PodDBAdapter.KEY_DOWNLOAD_URL_INDEX);
feed.setDownloaded(feedlistCursor
.getInt(PodDBAdapter.KEY_DOWNLOADED_INDEX) > 0);
// Get FeedItem-Object
Cursor itemlistCursor = adapter.getAllItemsOfFeedCursor(feed);
feed.setItems(extractFeedItemsFromCursor(context, feed,
itemlistCursor, adapter));
itemlistCursor.close();
feeds.add(feed);
} while (feedlistCursor.moveToNext());
}
feedlistCursor.close();
}
private ArrayList<FeedItem> extractFeedItemsFromCursor(Context context,
Feed feed, Cursor itemlistCursor, PodDBAdapter adapter) {
if (AppConfig.DEBUG)
Log.d(TAG, "Extracting Feeditems of feed " + feed.getTitle());
ArrayList<FeedItem> items = new ArrayList<FeedItem>();
ArrayList<String> mediaIds = new ArrayList<String>();
if (itemlistCursor.moveToFirst()) {
do {
FeedItem item = new FeedItem();
item.id = itemlistCursor.getLong(PodDBAdapter.KEY_ID_INDEX);
item.setFeed(feed);
item.setTitle(itemlistCursor
.getString(PodDBAdapter.KEY_TITLE_INDEX));
item.setLink(itemlistCursor
.getString(PodDBAdapter.KEY_LINK_INDEX));
item.setDescription(itemlistCursor
.getString(PodDBAdapter.KEY_DESCRIPTION_INDEX));
item.setContentEncoded(itemlistCursor
.getString(PodDBAdapter.KEY_CONTENT_ENCODED_INDEX));
item.setPubDate(new Date(itemlistCursor
.getLong(PodDBAdapter.KEY_PUBDATE_INDEX)));
item.setPaymentLink(itemlistCursor
.getString(PodDBAdapter.KEY_PAYMENT_LINK_INDEX));
long mediaId = itemlistCursor
.getLong(PodDBAdapter.KEY_MEDIA_INDEX);
if (mediaId != 0) {
mediaIds.add(String.valueOf(mediaId));
item.setMedia(new FeedMedia(mediaId, item));
}
item.read = (itemlistCursor.getInt(PodDBAdapter.KEY_READ_INDEX) > 0) ? true
: false;
item.setItemIdentifier(itemlistCursor
.getString(PodDBAdapter.KEY_ITEM_IDENTIFIER_INDEX));
if (!item.read) {
unreadItems.add(item);
}
// extract chapters
boolean hasSimpleChapters = itemlistCursor
.getInt(PodDBAdapter.KEY_HAS_SIMPLECHAPTERS_INDEX) > 0;
if (hasSimpleChapters) {
Cursor chapterCursor = adapter
.getSimpleChaptersOfFeedItemCursor(item);
if (chapterCursor.moveToFirst()) {
item.setChapters(new ArrayList<Chapter>());
do {
int chapterType = chapterCursor
.getInt(PodDBAdapter.KEY_CHAPTER_TYPE_INDEX);
Chapter chapter = null;
long start = chapterCursor
.getLong(PodDBAdapter.KEY_CHAPTER_START_INDEX);
String title = chapterCursor
.getString(PodDBAdapter.KEY_TITLE_INDEX);
String link = chapterCursor
.getString(PodDBAdapter.KEY_CHAPTER_LINK_INDEX);
switch (chapterType) {
case SimpleChapter.CHAPTERTYPE_SIMPLECHAPTER:
chapter = new SimpleChapter(start, title, item,
link);
break;
case ID3Chapter.CHAPTERTYPE_ID3CHAPTER:
chapter = new ID3Chapter(start, title, item,
link);
break;
}
chapter.setId(chapterCursor
.getLong(PodDBAdapter.KEY_ID_INDEX));
item.getChapters().add(chapter);
} while (chapterCursor.moveToNext());
}
chapterCursor.close();
}
items.add(item);
} while (itemlistCursor.moveToNext());
}
extractMediafromFeedItemlist(adapter, items, mediaIds);
Collections.sort(items, new FeedItemPubdateComparator());
return items;
}
private void extractMediafromFeedItemlist(PodDBAdapter adapter,
ArrayList<FeedItem> items, ArrayList<String> mediaIds) {
ArrayList<FeedItem> itemsCopy = new ArrayList<FeedItem>(items);
Cursor cursor = adapter.getFeedMediaCursor(mediaIds
.toArray(new String[mediaIds.size()]));
if (cursor.moveToFirst()) {
do {
long mediaId = cursor.getLong(PodDBAdapter.KEY_ID_INDEX);
// find matching feed item
FeedItem item = getMatchingItemForMedia(mediaId, itemsCopy);
itemsCopy.remove(item);
if (item != null) {
item.setMedia(new FeedMedia(
mediaId,
item,
cursor.getInt(PodDBAdapter.KEY_DURATION_INDEX),
cursor.getInt(PodDBAdapter.KEY_POSITION_INDEX),
cursor.getLong(PodDBAdapter.KEY_SIZE_INDEX),
cursor.getString(PodDBAdapter.KEY_MIME_TYPE_INDEX),
cursor.getString(PodDBAdapter.KEY_FILE_URL_INDEX),
cursor.getString(PodDBAdapter.KEY_DOWNLOAD_URL_INDEX),
cursor.getInt(PodDBAdapter.KEY_DOWNLOADED_INDEX) > 0));
}
} while (cursor.moveToNext());
cursor.close();
}
}
private FeedItem getMatchingItemForMedia(long mediaId,
ArrayList<FeedItem> items) {
for (FeedItem item : items) {
if (item.getMedia() != null && item.getMedia().getId() == mediaId) {
return item;
}
}
return null;
}
private void extractDownloadLogFromCursor(Context context,
PodDBAdapter adapter) {
if (AppConfig.DEBUG)
Log.d(TAG, "Extracting DownloadLog");
Cursor logCursor = adapter.getDownloadLogCursor();
if (logCursor.moveToFirst()) {
do {
long id = logCursor.getLong(PodDBAdapter.KEY_ID_INDEX);
FeedFile feedfile = null;
long feedfileId = logCursor
.getLong(PodDBAdapter.KEY_FEEDFILE_INDEX);
int feedfileType = logCursor
.getInt(PodDBAdapter.KEY_FEEDFILETYPE_INDEX);
if (feedfileId != 0) {
switch (feedfileType) {
case Feed.FEEDFILETYPE_FEED:
feedfile = getFeed(feedfileId);
break;
case FeedImage.FEEDFILETYPE_FEEDIMAGE:
feedfile = getFeedImage(feedfileId);
break;
case FeedMedia.FEEDFILETYPE_FEEDMEDIA:
feedfile = getFeedMedia(feedfileId);
}
}
boolean successful = logCursor
.getInt(PodDBAdapter.KEY_SUCCESSFUL_INDEX) > 0;
int reason = logCursor.getInt(PodDBAdapter.KEY_REASON_INDEX);
String reasonDetailed = logCursor
.getString(PodDBAdapter.KEY_REASON_DETAILED_INDEX);
String title = logCursor
.getString(PodDBAdapter.KEY_DOWNLOADSTATUS_TITLE_INDEX);
Date completionDate = new Date(
logCursor
.getLong(PodDBAdapter.KEY_COMPLETION_DATE_INDEX));
downloadLog.add(new DownloadStatus(id, title, feedfile,
feedfileType, successful, reason, completionDate,
reasonDetailed));
} while (logCursor.moveToNext());
}
logCursor.close();
Collections.sort(downloadLog, new DownloadStatusComparator());
}
private void extractQueueFromCursor(Context context, PodDBAdapter adapter) {
if (AppConfig.DEBUG)
Log.d(TAG, "Extracting Queue");
Cursor cursor = adapter.getQueueCursor();
if (cursor.moveToFirst()) {
do {
int index = cursor.getInt(PodDBAdapter.KEY_ID_INDEX);
Feed feed = getFeed(cursor
.getLong(PodDBAdapter.KEY_QUEUE_FEED_INDEX));
if (feed != null) {
FeedItem item = getFeedItem(
cursor.getLong(PodDBAdapter.KEY_FEEDITEM_INDEX),
feed);
if (item != null) {
queue.add(index, item);
}
}
} while (cursor.moveToNext());
}
cursor.close();
}
public List<Feed> getFeeds() {
return feeds;
}
public List<FeedItem> getUnreadItems() {
return unreadItems;
}
public ArrayList<DownloadStatus> getDownloadLog() {
return downloadLog;
}
public List<FeedItem> getQueue() {
return queue;
}
}
|
package de.quaddy_services.ptc;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.StringTokenizer;
import javax.swing.Action;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Timer;
import javax.swing.border.Border;
import javax.swing.plaf.basic.BasicBorders;
import de.quaddy_services.ptc.edit.TaskEditor;
import de.quaddy_services.ptc.enterprise.EnterpriseUtil;
import de.quaddy_services.ptc.enterprise.EnterpriseUtilRemote;
import de.quaddy_services.ptc.log.Log;
import de.quaddy_services.ptc.preferences.PreferencesSelection;
import de.quaddy_services.ptc.store.BackupFile;
import de.quaddy_services.ptc.store.FileUtil;
import de.quaddy_services.ptc.store.PosAndContent;
import de.quaddy_services.ptc.store.Task;
import de.quaddy_services.ptc.store.TaskHistory;
import de.quaddy_services.ptc.store.TaskUpdater;
import de.quaddy_services.report.TaskReport;
import de.quaddy_services.report.groupby.GroupBy;
import de.quaddy_services.report.groupby.GroupByList;
import de.quaddy_services.report.gui.ReportSelection;
/**
* @author Stefan Cordes
*
*/
public class MainController {
private Log LOG = new Log(this.getClass());
private MainModel model;
private JFrame frame;
private Timer repeatingTimer;
private MainView mainView;
private boolean initialized = false;
private volatile boolean shutdownPending = false;
public void init() {
LOG.info("init");
LOG.info("java.runtime.name=" + System.getProperty("java.runtime.name"));
LOG.info("java.runtime.version=" + System.getProperty("java.runtime.version"));
loadModel();
mainView = new MainView();
mainView.setController(this);
initEnterpriseServer();
try {
taskHistory.backupFile();
taskHistory.updateLastTask(TaskHistory.TASK_STARTED);
setMainViewModel();
} catch (Throwable e) {
handleException(e);
}
initFrame("PTC", mainView);
repeatingTimer = new Timer(10000, new ActionListener() {
public void actionPerformed(ActionEvent aE) {
timerRepeats();
reminderFlash();
}
});
repeatingTimer.start();
Thread tempShutdownPendingDetector = new Thread() {
@Override
public void run() {
// Do nothing here but setting the variable. No logging etc!
shutdownPending = true;
}
};
tempShutdownPendingDetector.setName(tempShutdownPendingDetector.getName() + "ShutdownPendingDetector");
Runtime.getRuntime().addShutdownHook(tempShutdownPendingDetector);
}
private int lastReminderFlash = -1;
protected void reminderFlash() {
Short tempReminderFlashOnMinute = model.getReminderFlashOnMinute();
if (tempReminderFlashOnMinute != null) {
int tempCurrentHour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
if (lastReminderFlash == tempCurrentHour) {
return;
}
int tempCurrentMinute = Calendar.getInstance().get(Calendar.MINUTE);
if (tempCurrentMinute == tempReminderFlashOnMinute.intValue()) {
lastReminderFlash = tempCurrentHour;
reminderFlashNow();
}
}
}
private void reminderFlashNow() {
LOG.info("Reminder flash");
JFrame tempFrame = getFrame();
tempFrame.toFront();
tempFrame.setExtendedState(JFrame.ICONIFIED);
tempFrame.setExtendedState(JFrame.NORMAL);
}
private void setMainViewModel() throws IOException {
List<String> tempLastTasks = taskHistory.getLastTasks();
enterpriseUtil.filterWithFixedTasks(model, tempLastTasks);
if (tempLastTasks.size() == 0) {
// Very first start of PTC.
tempLastTasks.add(model.getDontSumChar().getChar() + "Enter your task here");
}
model.setCurrentTask(tempLastTasks.get(0));
mainView.setModel(model, tempLastTasks);
}
private void initEnterpriseServer() {
String tempServer = model.getEnterpriseServer();
try {
enterpriseUtil.initTaskNames(frame, model, tempServer);
} catch (Throwable e) {
handleException(e);
}
}
/**
* @param tempFrame
* @param tempMainView
*/
private void initFrame(String aStartTitle, JComponent tempMainView) {
JFrame tempFrame = new JFrame(aStartTitle);
tempFrame.setIconImage(loadImage("MainIcon.gif").getImage());
if (model.isFrameDecorated()) {
LOG.info("isFrameDecorated " + model.getFrameBounds());
tempFrame.setBounds(model.getFrameBounds());
tempMainView.setBorder(null);
} else {
tempFrame.setUndecorated(true);
Rectangle tempBounds = model.getFrameContentBounds();
Border tempBorder = BasicBorders.getInternalFrameBorder();
Insets tempInsets = tempBorder.getBorderInsets(tempFrame);
tempBounds.x -= tempInsets.left;
tempBounds.y -= tempInsets.top;
tempBounds.width += tempInsets.right + tempInsets.left;
tempBounds.height += tempInsets.bottom + tempInsets.top;
tempFrame.setBounds(tempBounds);
tempMainView.setBorder(tempBorder);
LOG.info("not isFrameDecorated Model=" + model.getFrameBounds() + " Frame=" + tempBounds);
}
// Check if frame is visible on Screen
Dimension tempScreen = Toolkit.getDefaultToolkit().getScreenSize();
if (model.isFrameDecorated()) {
// Frame must be visible
if (tempFrame.getX() > tempScreen.width - 20) {
tempFrame.setLocation(tempScreen.width - 20, tempFrame.getY());
}
} else {
// Button must be visible
if (tempFrame.getX() + tempFrame.getWidth() > tempScreen.width - 10) {
tempFrame.setLocation(tempScreen.width - 10 - tempFrame.getWidth(), tempFrame.getY());
}
}
if (tempFrame.getX() + tempFrame.getWidth() < 5) {
tempFrame.setLocation(0, tempFrame.getY());
}
if (tempFrame.getY() > tempScreen.height - 10) {
tempFrame.setLocation(tempFrame.getX(), tempScreen.height - 10);
}
if (tempFrame.getY() + tempFrame.getHeight() < 5) {
tempFrame.setLocation(tempFrame.getX(), 0);
}
tempFrame.setAlwaysOnTop(model.isAlwaysOnTop());
tempFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
initFrameListeners(tempFrame);
tempFrame.getContentPane().setLayout(new CardLayout());
tempFrame.getContentPane().add(tempMainView, "MainView");
tempFrame.invalidate();
tempFrame.setVisible(true);
if (frame != null) {
frame.dispose();
}
frame = tempFrame;
}
private void initFrameListeners(final JFrame aFrame) {
// aFrame.addWindowListener(new LoggingWindowAdapter());
aFrame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent aE) {
super.windowClosing(aE);
try {
LOG.info("windowClosing");
exitApplicationRequestedByUser();
} catch (Throwable e) {
handleException(e);
}
}
@Override
public void windowOpened(WindowEvent aE) {
super.windowOpened(aE);
initialized = true;
}
@Override
public void windowIconified(WindowEvent aE) {
super.windowIconified(aE);
// When Desktop is shown we get a Windows Iconified.
Timer tempTimer = new Timer(3000, new ActionListener() {
public void actionPerformed(ActionEvent aE) {
// DeIconify now.
int tempState = aFrame.getExtendedState();
tempState = tempState & ~Frame.ICONIFIED;
// aFrame.setExtendedState(tempState);
EventQueue.invokeLater(new Runnable() {
public void run() {
aFrame.setVisible(false);
}
});
EventQueue.invokeLater(new Runnable() {
public void run() {
aFrame.setVisible(true);
}
});
}
});
tempTimer.setRepeats(false);
tempTimer.start();
}
});
}
public void exitApplicationRequestedByUser() {
repeatingTimer.stop();
timerRepeats();
if (taskAcceptTimer != null) {
LOG.info("exitApplication: commit pending task");
taskAcceptTimer.stop();
taskAcceptActionListener.actionPerformed(null);
timerRepeats();
}
try {
saveApplicationStateToModel(true);
saveModel();
taskHistory.updateLastTask(TaskHistory.TASK_CLOSED);
} catch (Exception e) {
LOG.exception(e);
}
exitApplicationNow();
}
private void exitApplicationNow() {
LOG.info("Start exitThread");
Thread tempExitThread = new Thread() {
@Override
public void run() {
LOG.info("System.exit(0)");
System.exit(0);
}
};
tempExitThread.setName(tempExitThread.getName() + "-exitThread");
tempExitThread.start();
}
private void saveApplicationStateToModel(boolean aLogInfo) {
JFrame tempFrame = getFrame();
Container tempContentPane = tempFrame.getContentPane();
Point tempLocationOnScreen = tempContentPane.getLocationOnScreen();
Dimension tempFrameSize = tempContentPane.getSize();
Border tempBorder = BasicBorders.getInternalFrameBorder();
Rectangle tempCurrentLocationOnScreen = new Rectangle(tempLocationOnScreen, tempFrameSize);
Rectangle tempCurrentFrameBounds = tempFrame.getBounds();
Insets tempCurrentFrameInsets = tempBorder.getBorderInsets(tempFrame);
// Save the frame bounds.
if (tempCurrentLocationOnScreen != null) {
// Should always be != null
tempCurrentLocationOnScreen.x += tempCurrentFrameInsets.left;
tempCurrentLocationOnScreen.y += tempCurrentFrameInsets.top;
tempCurrentLocationOnScreen.width -= tempCurrentFrameInsets.right + tempCurrentFrameInsets.left;
tempCurrentLocationOnScreen.height -= tempCurrentFrameInsets.bottom + tempCurrentFrameInsets.top;
if (model.isFrameDecorated()) {
if (aLogInfo) {
LOG.info("isFrameDecorated Frame=" + tempCurrentFrameBounds + " " + tempCurrentLocationOnScreen);
}
model.setFrameBounds(getFrame().getBounds());
model.setFrameContentBounds(tempCurrentLocationOnScreen);
} else {
if (aLogInfo) {
LOG.info("not isFrameDecorated " + tempCurrentLocationOnScreen);
}
// see initFrame
model.setFrameContentBounds(tempCurrentLocationOnScreen);
}
}
}
public void saveModelNoException() {
try {
final Task tempCurrentTask = saveModel();
if (EventQueue.isDispatchThread()) {
updateFrame(tempCurrentTask);
} else {
EventQueue.invokeLater(new Runnable() {
public void run() {
updateFrame(tempCurrentTask);
}
});
}
} catch (Throwable e) {
handleException(e);
}
}
private Properties lastProperties;
private Task saveModel() throws MalformedURLException, FileNotFoundException, IOException {
File tempFile = getStoreFile();
Properties tempProperties = model.getProperties();
if (lastProperties == null || hasChanged(tempProperties, lastProperties)) {
lastProperties = new Properties();
savePropertiesSorted(tempFile, tempProperties);
lastProperties.putAll(tempProperties);
}
String tempActualTaskName = model.getCurrentTask();
Task tempCurrentTask = currentTaskUpdater.updateLastTask(tempActualTaskName);
return tempCurrentTask;
}
private boolean hasChanged(Properties aProperties, Properties aLastProperties) {
if (aProperties.size() != aLastProperties.size()) {
return true;
}
if (!aProperties.keySet().containsAll(aLastProperties.keySet())) {
return true;
}
if (!aProperties.values().containsAll(aLastProperties.values())) {
return true;
}
return false;
}
private void savePropertiesSorted(File aFile, Properties aProperties) throws IOException {
StringWriter tempWriter = new StringWriter();
aProperties.store(tempWriter, new Date().toString());
tempWriter.close();
BufferedReader tempReader = new BufferedReader(new StringReader(tempWriter.toString()));
List<String> tempLines = new ArrayList<String>();
while (tempReader.ready()) {
String tempLine = tempReader.readLine();
if (tempLine == null) {
break;
}
tempLines.add(tempLine);
}
Collections.sort(tempLines);
PrintWriter tempFileWriter = new PrintWriter(new FileWriter(aFile));
for (String tempLine : tempLines) {
tempFileWriter.println(tempLine);
}
tempFileWriter.close();
}
private static final Color[] COLORS = new Color[] { Color.RED, Color.BLUE, Color.CYAN, Color.MAGENTA, Color.DARK_GRAY, Color.WHITE, Color.GREEN,
Color.GRAY };
private void updateFrame(Task aCurrentTask) {
if (aCurrentTask == null) {
return;
}
String tempName = aCurrentTask.getName();
frame.setTitle(formatTitleTime(aCurrentTask) + " " + tempName);
BufferedImage tempBufferedImage = new BufferedImage(64, 64, BufferedImage.TYPE_INT_BGR);
Graphics g = tempBufferedImage.getGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, 64, 64);
String tempChars;
StringTokenizer tempTasks = new StringTokenizer(tempName, " -");
int tempCountTokens = tempTasks.countTokens();
tempChars = "";
if (tempCountTokens == 1) {
tempChars = tempName;
} else if (tempCountTokens == 2) {
tempChars += (tempTasks.nextToken() + " ").substring(0, 2).trim();
tempChars += (tempTasks.nextToken() + " ").substring(0, 2).trim();
} else if (tempCountTokens == 3) {
tempChars += (tempTasks.nextToken() + " ").substring(0, 1).trim();
tempChars += (tempTasks.nextToken() + " ").substring(0, 1).trim();
tempChars += (tempTasks.nextToken() + " ").substring(0, 2).trim();
} else {
while (tempChars.length() < 4 && tempTasks.hasMoreTokens()) {
tempChars += tempTasks.nextToken().charAt(0);
}
}
// System.out.println(tempName + " -> " + tempChars);
int x = 0;
int y = 0;
for (int i = 0; i < tempChars.length() && y < 64; i++) {
int c = tempChars.charAt(i);
g.setColor(COLORS[c % COLORS.length]);
g.fillRect(x, y, 32, 32);
x += 32;
if (x >= 64) {
x = 0;
y += 32;
}
}
g.setColor(Color.YELLOW);
g.fillOval(16, 16, 32, 32);
g.setColor(Color.BLACK);
g.fillOval(29, 29, 6, 6);
g.dispose();
frame.setIconImage(tempBufferedImage);
}
private static final DateFormat TIME_HOUR_FORMAT = new SimpleDateFormat("HH:mm");
private static final DateFormat TIME_MINUTE_FORMAT = new SimpleDateFormat("mm:ss");
private static final long ONE_HOUR_IN_MILLIS = 3600l * 1000l;
private String formatTitleTime(Task aCurrentTask) {
Calendar tempCal = Calendar.getInstance();
tempCal.clear();
tempCal.set(Calendar.HOUR_OF_DAY, 0);
tempCal.set(Calendar.MINUTE, 0);
tempCal.set(Calendar.SECOND, 0);
tempCal.add(Calendar.MILLISECOND, (int) aCurrentTask.getMillis());
if (tempCal.get(Calendar.HOUR_OF_DAY) > 0) {
return TIME_HOUR_FORMAT.format(tempCal.getTime());
}
return TIME_MINUTE_FORMAT.format(tempCal.getTime());
}
public void loadModel() {
MainModel tempMainModel = new MainModel();
Properties tempProperties = new Properties();
try {
// We are local
File tempFile = getStoreFile();
new BackupFile().backupFile(tempFile, 10);
if (tempFile.exists()) {
FileInputStream tempFileInputStream = new FileInputStream(tempFile);
tempProperties.load(tempFileInputStream);
tempFileInputStream.close();
}
} catch (Throwable e) {
handleException(e);
}
tempMainModel.setProperties(tempProperties);
model = tempMainModel;
}
/**
* @return
*/
private File getStoreFile() {
return new File(FileUtil.getDataFolder() + "/ptc.properties");
}
public void toggleFrameDecorator() {
if (model.isFrameDecorated()) {
model.setFrameBounds(getFrame().getBounds());
model.setFrameContentBounds(new Rectangle(getFrame().getLocationOnScreen(), getFrame().getContentPane().getSize()));
}
boolean tempNewIsFrameDecorated = !model.isFrameDecorated();
model.setFrameDecorated(tempNewIsFrameDecorated);
getFrame().setVisible(false);
initFrame(getFrame().getTitle(), (JComponent) frame.getContentPane().getComponent(0));
}
/**
* @return Returns the frame.
*/
public JFrame getFrame() {
return frame;
}
/**
* @param aFrame
* The frame to set.
*/
public void setFrame(JFrame aFrame) {
frame = aFrame;
}
private Timer taskAcceptTimer;
private ActionListener taskAcceptActionListener;
private boolean inTaskAccepting = false;
public void otherTaskName(final String aString) {
if (inTaskAccepting) {
LOG.info("Ignore because inTaskAccepting: " + aString);
return;
}
if (aString.trim().length() == 0) {
LOG.info("Ignore empty String inTaskAccepting: '" + aString + "'");
return;
}
LOG.info("Other Task requested: '" + aString + "'");
if (taskAcceptTimer != null) {
taskAcceptTimer.stop();
}
taskAcceptActionListener = new ActionListener() {
public void actionPerformed(ActionEvent aE) {
acceptNewTask(aString);
}
};
Timer tempTimer = new Timer(10000, taskAcceptActionListener);
mainView.newTaskPending();
tempTimer.setRepeats(false);
tempTimer.start();
taskAcceptTimer = tempTimer;
}
private TaskHistory taskHistory = new TaskHistory();
private TaskUpdater currentTaskUpdater = taskHistory;
private EnterpriseUtilRemote enterpriseUtil = new EnterpriseUtil();
private long lastTimerRepeats = System.currentTimeMillis();
private void timerRepeats() {
if (shutdownPending) {
LOG.info("Do not timerRepeats as shutdownPending");
return;
}
if (lastTimerRepeats + ONE_HOUR_IN_MILLIS < System.currentTimeMillis()) {
BigDecimal tempHours = new BigDecimal(System.currentTimeMillis() - lastTimerRepeats).divide(new BigDecimal(ONE_HOUR_IN_MILLIS), 2,
RoundingMode.HALF_UP);
String tempActualTaskName = model.getCurrentTask();
JLabel tempInfo = new JLabel("Add " + tempHours + " hours to " + tempActualTaskName + "?");
boolean tempContinue = DisplayHelper.displayComponent(frame, "Confirm Task", tempInfo);
if (tempContinue) {
} else {
String tempSuspendTaskName = model.getDontSumChar().getChar() + "suspended";
timerNewTask(tempSuspendTaskName);
timerNewTask(tempActualTaskName);
taskAcceptTimer = null;
}
}
lastTimerRepeats = System.currentTimeMillis();
saveApplicationStateToModel(false);
if (taskAcceptTimer == null) {
// Suspend save until new task is "commited"
saveModelNoException();
}
}
private void timerNewTask(String aNewTaskName) {
model.setCurrentTask(aNewTaskName);
saveModelNoException();
taskAcceptTimer = null;
taskAcceptActionListener = null;
}
private ImageIcon loadImage(String aString) {
URL tempURL = getClass().getResource("/" + aString);
return new ImageIcon(tempURL);
}
public void bringToFront() {
int tempState = frame.getExtendedState();
tempState = tempState & ~Frame.ICONIFIED;
frame.setExtendedState(tempState);
}
public boolean isInitialized() {
return initialized;
}
public void showLastWeek() {
try {
Calendar tempCal = Calendar.getInstance();
tempCal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
tempCal.set(Calendar.HOUR_OF_DAY, 0);
tempCal.set(Calendar.MINUTE, 0);
tempCal.set(Calendar.SECOND, 0);
tempCal.set(Calendar.MILLISECOND, 0);
long tempTo = tempCal.getTimeInMillis();
tempCal.add(Calendar.DAY_OF_YEAR, -7);
long tempFrom = tempCal.getTimeInMillis();
TaskReport tempTaskReport = new TaskReport(taskHistory, frame, model.getTaskDelimiter(), model.getDontSumChar(),
enterpriseUtil.getFixedTaskNames());
GroupBy[] tempGroupBy = new GroupBy[] { GroupByList.getGroupBy(GroupByList.DAY), GroupByList.getGroupBy(GroupByList.NONE) };
List<Action> tempActions = createAdditionalActions(tempTo, tempFrom);
tempTaskReport.showReport(tempFrom, tempTo, tempGroupBy, model.getTimeFormat(), tempActions);
} catch (Throwable e) {
handleException(e);
}
}
private List<Action> createAdditionalActions(long tempTo, long tempFrom) {
List<Action> tempActions = new ArrayList<Action>();
Action tempSaveReportAction = enterpriseUtil.createShowReportAction(this, tempFrom, tempTo);
tempActions.add(tempSaveReportAction);
Action tempShowBookingSystemAction = enterpriseUtil.createShowBookingSystemAction(this);
tempActions.add(tempShowBookingSystemAction);
return tempActions;
}
private void handleException(Throwable aE) {
LOG.exception(aE);
DisplayHelper.displayException(frame, aE);
}
public void about() {
DisplayHelper.displayAbout(frame);
}
public void showThisWeek() {
try {
Calendar tempCal = Calendar.getInstance();
tempCal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
tempCal.set(Calendar.HOUR_OF_DAY, 0);
tempCal.set(Calendar.MINUTE, 0);
tempCal.set(Calendar.SECOND, 0);
tempCal.set(Calendar.MILLISECOND, 0);
long tempFrom = tempCal.getTimeInMillis();
tempCal.add(Calendar.DAY_OF_YEAR, +7);
long tempTo = tempCal.getTimeInMillis();
TaskReport tempTaskReport = new TaskReport(taskHistory, frame, model.getTaskDelimiter(), model.getDontSumChar(),
enterpriseUtil.getFixedTaskNames());
GroupBy[] tempGroupBy = new GroupBy[] { GroupByList.getGroupBy(GroupByList.DAY), GroupByList.getGroupBy(GroupByList.NONE) };
List<Action> tempActions = createAdditionalActions(tempTo, tempFrom);
tempTaskReport.showReport(tempFrom, tempTo, tempGroupBy, model.getTimeFormat(), tempActions);
} catch (Throwable e) {
handleException(e);
}
}
public void showCustomReport() {
try {
ReportSelection tempReportSelection = new ReportSelection();
tempReportSelection.setGroupBy(model.getGroupBy());
tempReportSelection.setTimeFormat(model.getTimeFormat());
boolean tempOk = DisplayHelper.displayComponent(frame, "Select Report...", tempReportSelection);
if (tempOk) {
TaskReport tempTaskReport = new TaskReport(taskHistory, frame, model.getTaskDelimiter(), model.getDontSumChar(),
enterpriseUtil.getFixedTaskNames());
long tempFrom = tempReportSelection.getFrom();
long tempTo = tempReportSelection.getTo();
List<Action> tempActions = createAdditionalActions(tempTo, tempFrom);
tempTaskReport.showReport(tempFrom, tempTo, tempReportSelection.getGroupBys(), tempReportSelection.getTimeFormat(), tempActions);
}
} catch (Throwable e) {
handleException(e);
}
}
public void options() {
PreferencesSelection tempPreferencesSelection = new PreferencesSelection();
tempPreferencesSelection.setValues(model.getProperties());
boolean tempOk = DisplayHelper.displayComponent(frame, "Select Preferences...", tempPreferencesSelection);
if (tempOk) {
model.getProperties().putAll(tempPreferencesSelection.getValues());
saveModelNoException();
initEnterpriseServer();
try {
setMainViewModel();
} catch (IOException e) {
handleException(e);
}
frame.setAlwaysOnTop(model.isAlwaysOnTop());
}
}
public void editTasks() {
if (taskAcceptTimer != null) {
LOG.info("editTask: commit pending task");
taskAcceptTimer.stop();
taskAcceptTimer.setInitialDelay(0);
taskAcceptTimer.start();
waitForTaskTimerAndEditTasks();
} else {
editTasksNow();
}
}
private void waitForTaskTimerAndEditTasks() {
if (taskAcceptTimer == null) {
editTasksNow();
} else {
EventQueue.invokeLater(new Runnable() {
public void run() {
waitForTaskTimerAndEditTasks();
}
});
}
}
private void editTasksNow() {
saveModelNoException();
TaskEditor tempTaskEdtior = new TaskEditor();
long tempStartPos;
List<PosAndContent<Task>> tempTasks;
try {
tempTasks = taskHistory.getLastLinesForEdit();
tempStartPos = tempTasks.get(0).getPosInFile();
tempTaskEdtior.setTasks(tempTasks, enterpriseUtil);
} catch (Exception e) {
handleException(e);
return;
}
TaskUpdater tempOldTaskUpdater = currentTaskUpdater;
frame.setAlwaysOnTop(false);
try {
if (DisplayHelper.displayComponent(frame, "Edit Tasks", tempTaskEdtior)) {
for (Iterator<PosAndContent<Task>> i = tempTasks.iterator(); i.hasNext();) {
PosAndContent<Task> tempPosAndContent = i.next();
if (tempTaskEdtior.getDeletedTasks().contains(tempPosAndContent)) {
i.remove();
}
}
try {
taskHistory.saveTasks(tempStartPos, tempTasks);
} catch (IOException e) {
handleException(e);
}
}
} finally {
currentTaskUpdater = tempOldTaskUpdater;
frame.setAlwaysOnTop(model.isAlwaysOnTop());
}
}
public List<String> getFixedTaskNames() {
return enterpriseUtil.getFixedTaskNames();
}
/**
* @return the enterpriseUtil
*/
public EnterpriseUtilRemote getEnterpriseUtil() {
return enterpriseUtil;
}
/**
* @return the taskHistory
*/
public TaskHistory getTaskHistory() {
return taskHistory;
}
private void acceptNewTask(final String aString) {
if (shutdownPending) {
LOG.info("Do not acceptNewTask " + aString + " as shutdownPending");
return;
}
inTaskAccepting = true;
try {
timerNewTask(aString);
mainView.newTaskAccepted(aString);
LOG.info("newTaskAccepted: " + aString);
} finally {
inTaskAccepting = false;
}
}
public void setEnterpriseUtil(EnterpriseUtilRemote aEnterpriseUtil) {
enterpriseUtil = aEnterpriseUtil;
}
}
|
package de.sebhn.algorithm.excersise5;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
class DLXNode { // represents 1 element or header
DLXNode C; // reference to column-header
DLXNode L, R, U, D; // left, right, up, down references
int posH;
int posV;
static int indexLength;
static DLXNode[] headers;
static int matrixLine;
static int maxNumber;
static int n;
DLXNode() {
C = L = R = U = D = this;
} // supports circular lists
/**
* search tries to find and count all complete coverings of the DLX matrix. Is a recursive,
* depth-first, backtracking algorithm that finds all solutions to the exact cover problem encoded
* in the DLX matrix. each time all columns are covered, static long cnt is increased
*
* @param int k: number of level
*
*/
static int cnt;
static DLXNode h;
public static void search(int k) { // finds & counts solutions
if (h.R == h) {
cnt++;
return;
} // if empty: count & done
DLXNode c = h.R; // choose next column c
cover(c); // remove c from columns
for (DLXNode r = c.D; r != c; r = r.D) { // forall rows with 1 in c
for (DLXNode j = r.R; j != r; j = j.R) // forall 1-elements in row
cover(j.C); // remove column
search(k + 1); // recursion
for (DLXNode j = r.L; j != r; j = j.L) // forall 1-elements in row
uncover(j.C); // backtrack: un-remove
}
uncover(c); // un-remove c to columns
}
/**
* cover "covers" a column c of the DLX matrix column c will no longer be found in the column list
* rows i with 1 element in column c will no longer be found in other column lists than c so
* column c and rows i are invisible after execution of cover
*
* @param DLXNode c: header element of column that has to be covered
*
*/
public static void cover(DLXNode c) { // remove column c
c.R.L = c.L; // remove header
c.L.R = c.R; // .. from row list
for (DLXNode i = c.D; i != c; i = i.D) // forall rows with 1
for (DLXNode j = i.R; i != j; j = j.R) { // forall elem in row
j.D.U = j.U; // remove row element
j.U.D = j.D; // .. from column list
}
}
/**
* uncover "uncovers" a column c of the DLX matrix all operations of cover are undone so column c
* and rows i are visible again after execution of uncover
*
* @param DLXNode c: header element of column that has to be uncovered
*
*/
public static void uncover(DLXNode c) {// undo remove col c
for (DLXNode i = c.U; i != c; i = i.U) // forall rows with 1
for (DLXNode j = i.L; i != j; j = j.L) { // forall elem in row
j.D.U = j; // un-remove row elem
j.U.D = j; // .. to column list
}
c.R.L = c; // un-remove header
c.L.R = c; // .. to row list
}
public static void main(String[] args) {
cnt = 0; // set counter for solutions to zero
h = new DLXNode(); // create header
h.posH = 0;
h.posV = 0;
n = 3;
matrixLine = 1;
maxNumber = n * 6;
addHeader(maxNumber);
/*
* for (int i = 0; i < amountOfHeaders; i++) { DLXNodeOld columnNode = gotoIndex(i);
* System.out.println("Header-Column: " + columnNode.posH); System.out.println("Row x: " +
* columnNode.posV); DLXNodeOld verticaclNode = columnNode.D; System.out.println("Row o: " +
* verticaclNode.posV); do { verticaclNode = verticaclNode.D; // if (verticaclNode.posV != -1) {
* System.out.println("Row i: " + verticaclNode.posV); // } } while
* (!columnNode.equals(verticaclNode)); }
*/
long start = System.nanoTime();
calcCross();
calcMono();
calcU_UP();
calcU_DOWN();
calcU_LEFT();
calcU_RIGHT();
calcL_R0();
calcL_R1();
calcL_R2();
calcL_R3();
calcL_R4();
calcL_R5();
calcL_R6();
calcL_R7();
long ende = System.nanoTime();
System.out.println((ende - start) / 10000 + "ms for matrix generation");
// DLXNodeOld node = h.R;
// for (int i = 0; i < maxNumber + 1; i++) {
// System.out.print(node.posV + " " + node.posH + " | ");
// node = node.R;
start = System.nanoTime();
search(0);
ende = System.nanoTime();
System.out.println((ende - start) / 1000000000 + "s for search");
System.out.println(cnt);
}
/**
* create headers
*/
public static void addHeader(int n) {
indexLength = n;
headers = new DLXNode[n + 1];
headers[0] = h;
DLXNode tempNode;
int x = 0;
for (int i = 0; i < n; i++) {
DLXNode node = new DLXNode();
node.posH = ++x; // set index to header
node.posV = 0; // set vertical position to 0 to signal header
headers[x] = node;
if (h.L == h) {
// connect header to node
h.L = node;
h.R = node;
// connect node to header
node.L = h;
node.R = h;
} else {
tempNode = h.L; // goto last header
tempNode.R = node; // connect old last node to new node
node.L = tempNode; // connect new node to old last node
node.R = h; // connect last new node to header
h.L = node; // connect header to last new node
}
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + posH;
result = prime * result + posV;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
} else if (obj == null || getClass() != obj.getClass()) {
return false;
}
DLXNode other = (DLXNode) obj;
if (posH != other.posH) {
return false;
} else if (posV != other.posV) {
return false;
}
return true;
}
private static DLXNode gotoIndex(int posH) {
DLXNode node = new DLXNode();
node = h.R;
for (int i = 0; i < posH; i++) {
node = node.R;
}
return node;
}
private static DLXNode gotoHeaderIndex(int posH) {
return headers[posH];
}
private static void addNode(int posV, int posH) {
System.out.println("add node: posV=" + posV + " posH=" + posH);
DLXNode node = new DLXNode();
DLXNode temp = gotoHeaderIndex(posH); // goto header index
node.posH = posH;
node.posV = posV;
node.C = temp; // direct link to header
if (temp.D == node.C) { // add node if there are no other nodes
temp.U = node;
temp.D = node;
node.U = temp;
node.D = temp;
connectRight(node);
connectLeft(node);
return;
} else {
for (int i = 0; i < 6; i++) {
temp = temp.D;
if (temp.posV < posV) {
temp = temp.D;
if (temp == temp.C) { // add node if its the highest index
temp = temp.U;
temp.D = node;
node.U = temp;
node.D = node.C;
node.C.U = node;
connectRight(node);
connectLeft(node);
return;
}
}
if (temp.posV > posV) {
temp = temp.U;
node.D = temp.D; // connect node to higher node
temp.D.U = node; // connect higher node to node
temp.D = node; // connect lower node to node
node.U = temp; // connect node to lower node}
connectRight(node);
connectLeft(node);
return;
}
}
}
}
public static void connectRight(DLXNode node) {
// connection to the right
int posV = node.posV;
DLXNode temp = node;
for (int i = 0; i < indexLength; i++) {
temp = temp.C.R;
while (temp.D != temp.C) {
temp = temp.D;
if (temp.posV == posV) {
node.R = temp;
temp.L = node;
// System.out.println("connected right " + node.posV + " " + node.posH + " mit " +
// temp.posV
// + " " + temp.posH);
return;
} else {
}
}
}
}
public static void connectLeft(DLXNode node) {
// connection to the right
int posV = node.posV;
DLXNode temp = node;
for (int i = 0; i < indexLength; i++) {
temp = temp.C.L;
while (temp.D != temp.C) {
temp = temp.D;
if (temp.posV == posV) {
temp.R = node;
node.L = temp;
// System.out.println("connected left " + node.posV + " " + node.posH + " mit " +
// temp.posV
// + " " + temp.posH);
return;
} else {
}
}
}
}
public static void calcCross() {
int a = 2;
int b = 7;
int c = 8;
int d = 9;
int e = 14;
List<Integer> figure = Arrays.asList(a, b, c, d, e);
int width = 3;
int height = 3;
calculateFiguresPosition(figure, height, width);
}
public static void calcU_UP() {
calculateFiguresPosition(Arrays.asList(1, 2, 8, 13, 14), 4, 3);
}
public static void calcU_DOWN() {
calculateFiguresPosition(Arrays.asList(1, 2, 7, 13, 14), 4, 3);
}
public static void calcU_LEFT() {
calculateFiguresPosition(Arrays.asList(1, 3, 7, 9, 8), 3, 2);
}
public static void calcU_RIGHT() {
calculateFiguresPosition(Arrays.asList(1, 2, 3, 9, 7), 3, 2);
}
/**
* |<br>
* |<br>
* |_<br>
*/
public static void calcL_R0() {
calculateFiguresPosition(Arrays.asList(1, 2, 3, 4, 10), 2, 2);
}
public static void calcL_R1() {
calculateFiguresPosition(Arrays.asList(2, 8, 14, 20, 19), 4, 4);
}
/**
* _<br>
* .|<br>
* .|<br>
* .|<br>
* .|
*/
public static void calcL_R2() {
calculateFiguresPosition(Arrays.asList(1, 7, 8, 9, 10), 2, 2);
}
public static void calcL_R3() {
calculateFiguresPosition(Arrays.asList(1, 2, 13, 7, 19), 4, 4);
}
/**
* .|<br>
* .|<br>
* _|<br>
*/
public static void calcL_R4() {
calculateFiguresPosition(Arrays.asList(7, 8, 9, 10, 4), 2, 2);
}
public static void calcL_R5() {
calculateFiguresPosition(Arrays.asList(1, 7, 13, 19, 20), 4, 4);
}
public static void calcL_R6() {
calculateFiguresPosition(Arrays.asList(1, 2, 8, 14, 20), 4, 4);
}
/**
* ._<br>
* |<br>
* |<br>
* |
*/
public static void calcL_R7() {
calculateFiguresPosition(Arrays.asList(1, 2, 3, 4, 7), 2, 2);
}
public static void calcMono() {
for (int i = 0; i < maxNumber; i++) {
addNode(matrixLine, i + 1);
matrixLine++;
}
}
private static void calculateFiguresPosition(List<Integer> figures, int downShifts, int width) {
int shiftsRight = n - width;
if (shiftsRight > n || shiftsRight < 0) {
System.out.println("no positions, cant fit figure");
return;
}
insertFigure(figures);
for (int i = 0; i < downShifts; i++) {
List<Integer> plusSixFigures = new ArrayList<>(figures);
shiftRight(shiftsRight, plusSixFigures);
shiftDown(figures);
}
shiftRight(shiftsRight, figures);
}
private static void shiftRight(int shiftsRight, List<Integer> plusSixFigures) {
for (int g = 0; g < shiftsRight; g++) {
shiftOneRight(plusSixFigures);
}
}
private static void insertFigure(List<Integer> figures) {
DLXNode[] array = new DLXNode[5];
int arrayIndex = 0;
for (Integer integer : figures) {
// addNode(matrixLine, integer);
array[arrayIndex] = createNode(matrixLine, integer);
arrayIndex++;
}
createLine(array);
matrixLine++;
}
private static void shiftDown(List<Integer> figures) {
DLXNode[] array = new DLXNode[5];
int arrayIndex = 0;
for (int j = 0; j < figures.size(); j++) {
int elementPlusOne = figures.get(j) + 1;
figures.set(j, elementPlusOne);
// addNode(matrixLine, elementPlusOne);
array[arrayIndex] = createNode(matrixLine, elementPlusOne);
arrayIndex++;
}
createLine(array);
matrixLine++;
}
private static void shiftOneRight(List<Integer> plusSixFigures) {
DLXNode[] array = new DLXNode[5];
int arrayIndex = 0;
for (int j = 0; j < plusSixFigures.size(); j++) {
Integer current = plusSixFigures.get(j);
current += 6;
plusSixFigures.set(j, current);
// addNode(matrixLine, current);
array[arrayIndex] = createNode(matrixLine, current);
arrayIndex++;
}
createLine(array);
matrixLine++;
}
private static void calculateFiguresPosition(List<Integer> figures, int downShifts) {
insertFigure(figures);
DLXNode[] al = new DLXNode[5];
int arrayIndex = 0;
for (int i = 0; i <= downShifts; i++) {
ArrayList<Integer> plusSixFigures = new ArrayList<>(figures);
int currentMaxHorizontal = plusSixFigures.get(plusSixFigures.size() - 1) + 6;
while (currentMaxHorizontal <= maxNumber) {
shiftOneRight(plusSixFigures);
currentMaxHorizontal = plusSixFigures.get(plusSixFigures.size() - 1) + 6;
}
int currentMaxVertical = figures.get(figures.size() - 2) + 1;
boolean hasNotReachedVerticalEnd = currentMaxVertical < 13;
for (int j = 0; j < figures.size() && hasNotReachedVerticalEnd; j++) {
int elementPlusOne = figures.get(j) + 1;
figures.set(j, elementPlusOne);
// addNode(matrixLine, elementPlusOne);
al[arrayIndex] = createNode(matrixLine, elementPlusOne);
arrayIndex++;
}
if (hasNotReachedVerticalEnd) {
matrixLine++;
createLine(al);
}
al = new DLXNode[5];
}
}
private static DLXNode createNode(int posV, int posH) {
System.out.println("add node: posV=" + posV + " posH=" + posH);
DLXNode node = new DLXNode();
node.posV = posV;
node.posH = posH;
return node;
}
private static void createLine(DLXNode[] array) {
for (int i = 0; i < array.length; i++) {
array[i].C = gotoHeaderIndex(array[i].posH);
array[i].U = gotoHeaderIndex(array[i].posH).U;
gotoHeaderIndex(array[i].posH).U.D = array[i];
array[i].D = gotoHeaderIndex(array[i].posH);
gotoHeaderIndex(array[i].posH).U = array[i];
if (i == 0) {
array[i].L = array[array.length - 1];
array[i].R = array[i + 1];
} else if (i == array.length - 1) {
array[i].L = array[i - 1];
array[i].R = array[0];
} else {
array[i].L = array[i - 1];
array[i].R = array[i + 1];
}
}
}
}
|
package de.st_ddt.crazyplugin.data;
import java.util.Date;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import de.st_ddt.crazyplugin.CrazyPluginInterface;
import de.st_ddt.crazyutil.ChatHelper;
import de.st_ddt.crazyutil.locales.CrazyLocale;
public abstract class PlayerData<S extends PlayerData<S>> implements PlayerDataInterface
{
protected final String name;
public PlayerData(final String name)
{
super();
this.name = name;
}
protected abstract String getChatHeader();
public void show(final CommandSender target)
{
show(target, getChatHeader(), true);
}
public void show(final CommandSender target, String chatHeader, boolean showDetailed)
{
final CrazyLocale locale = CrazyLocale.getLocaleHead().getSecureLanguageEntry("CRAZYPLUGIN.PLAYERINFO");
final Player player = getPlayer();
ChatHelper.sendMessage(target, chatHeader, locale.getLanguageEntry("HEAD"), CrazyPluginInterface.DateFormat.format(new Date()));
if (player == null)
{
ChatHelper.sendMessage(target, chatHeader, locale.getLanguageEntry("USERNAME"), getName());
}
else
{
ChatHelper.sendMessage(target, chatHeader, locale.getLanguageEntry("USERNAME"), player.getName());
ChatHelper.sendMessage(target, chatHeader, locale.getLanguageEntry("DISPLAYNAME"), player.getDisplayName());
ChatHelper.sendMessage(target, chatHeader, locale.getLanguageEntry("IPADDRESS"), player.getAddress().getAddress().getHostAddress());
ChatHelper.sendMessage(target, chatHeader, locale.getLanguageEntry("CONNECTION"), player.getAddress().getHostName());
ChatHelper.sendMessage(target, chatHeader, locale.getLanguageEntry("URL"), player.getAddress().getAddress().getHostAddress());
}
final OfflinePlayer plr = getOfflinePlayer();
if (plr != null)
{
ChatHelper.sendMessage(target, chatHeader, locale.getLanguageEntry("OP"), plr.isOp() ? "True" : "False");
if (Bukkit.hasWhitelist())
ChatHelper.sendMessage(target, chatHeader, locale.getLanguageEntry("WHITELISTED"), plr.isWhitelisted() ? "True" : "False");
if (plr.isBanned())
ChatHelper.sendMessage(target, chatHeader, locale.getLanguageEntry("BANNED"), "True");
}
if (showDetailed)
{
ChatHelper.sendMessage(target, chatHeader, locale.getLanguageEntry("SEPERATOR"));
showDetailed(target, chatHeader);
}
}
public abstract void showDetailed(CommandSender target, String chatHeader);
@Override
public String getShortInfo()
{
return toString();
}
@Override
public Player getPlayer()
{
return Bukkit.getPlayerExact(getName());
}
@Override
public OfflinePlayer getOfflinePlayer()
{
return Bukkit.getOfflinePlayer(getName());
}
@Override
public String getName()
{
return name;
}
@Override
public boolean isOnline()
{
final Player player = getPlayer();
if (player == null)
return false;
return player.isOnline();
}
@Override
public String toString()
{
return "PlayerData " + getName();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.