answer
stringlengths 17
10.2M
|
|---|
package com.swabunga.spell.event;
import java.util.*;
import com.swabunga.spell.engine.*;
/** This is the main class for spell checking (using the new event based spell
* checking).
*
* @author Jason Height (jheight@chariot.net.au)
*/
public class SpellChecker {
private List eventListeners = new ArrayList();
private SpellDictionary dictionary;
private int threshold = 100;
/**This variable holds all of the words that are to be always ignored*/
private Set ignoredWords = new HashSet();
private Map autoReplaceWords = new HashMap();
/** Constructs the SpellChecker. The default threshold is used*/
public SpellChecker (SpellDictionary dictionary) {
if (dictionary == null)
throw new IllegalArgumentException("dictionary must no be null");
this.dictionary = dictionary;
}
/** Constructs the SpellChecker with a threshold*/
public SpellChecker (SpellDictionary dictionary, int threshold) {
this(dictionary);
this.threshold = threshold;
}
/**Adds a SpellCheckListener*/
public void addSpellCheckListener (SpellCheckListener listener) {
eventListeners.add(listener);
}
/**Removes a SpellCheckListener*/
public void removeSpellCheckListener (SpellCheckListener listener) {
eventListeners.remove(listener);
}
/**Alter the threshold*/
public void setThreshold (int threshold) {
this.threshold = threshold;
}
/**Returns the threshold*/
public int getThreshold () {
return threshold;
}
/** Fires off a spell check event to the listeners.
*/
protected void fireSpellCheckEvent (SpellCheckEvent event) {
for (int i = eventListeners.size() - 1; i >= 0; i
((SpellCheckListener)eventListeners.get(i)).spellingError(event);
}
}
/** This method clears the words that are currently being remembered as
* Ignore All words and Replace All words.
*/
public void reset() {
ignoredWords.clear();
autoReplaceWords.clear();
}
/** Checks the text string.
* <p>
* Returns the corrected string.
* @deprecated use checkSpelling(WordTokenizer)
*/
public String checkString (String text) {
StringWordTokenizer tokens = new StringWordTokenizer(text);
checkSpelling(tokens);
return tokens.getFinalText();
}
/** This method is called to check the spelling of the words that are returned
* by the WordTokenizer.
* <p>For each invalid word the action listeners will be informed with a new SpellCheckEvent</p>
*/
public final void checkSpelling(WordTokenizer tokenizer) {
//Dont bother to execute if no-one is listening ;-)
if (eventListeners.size() > 0) {
boolean terminated = false;
while (tokenizer.hasMoreWords() && !terminated) {
String word = tokenizer.nextWord();
//Check the spelling of the word
if (!dictionary.isCorrect(word)) {
//For this invalid word are we ignoreing the misspelling?
if (!ignoredWords.contains(word)) {
//Is this word being automagically replaced
if (autoReplaceWords.containsKey(word)) {
tokenizer.replaceWord((String)autoReplaceWords.get(word));
}
else {
System.out.println("Current word position="+tokenizer.getCurrentWordPosition());
//Fire the event.
SpellCheckEvent event = new BasicSpellCheckEvent(word, dictionary.getSuggestions(word,
threshold), tokenizer);
fireSpellCheckEvent(event);
//Work out what to do in response to the event.
switch (event.getAction()) {
case SpellCheckEvent.INITIAL:
break;
case SpellCheckEvent.IGNORE:
break;
case SpellCheckEvent.IGNOREALL:
if (!ignoredWords.contains(word))
ignoredWords.add(word);
break;
case SpellCheckEvent.REPLACE:
tokenizer.replaceWord(event.getReplaceWord());
break;
case SpellCheckEvent.REPLACEALL:
String replaceAllWord = event.getReplaceWord();
if (!autoReplaceWords.containsKey(word)) {
autoReplaceWords.put(word, replaceAllWord);
}
tokenizer.replaceWord(replaceAllWord);
break;
//JMH TBD case SpellCheckEvent.ADDTODICT:
case SpellCheckEvent.CANCEL:
terminated = true;
break;
default:
throw new IllegalArgumentException("Unhandled case.");
}
}
}
}
}
}
}
}
|
package com.virtualfactory.app;
import com.virtualfactory.utils.ScreenSettings;
import com.jme3.app.SimpleApplication;
/**
* Virtual Factory 2.0
*/
public final class VirtualFactory extends SimpleApplication {
public static void main(String[] args) {
VirtualFactory app = new VirtualFactory();
app.setSettings(ScreenSettings.generate());
app.setShowSettings(false);
app.setPauseOnLostFocus(false);
app.start(); // calls simpleInitApp()
}
@Override
public void simpleInitApp() {
disableJmonkeyHUD();
loadGame();
}
private void disableJmonkeyHUD() {
setDisplayFps(false);
setDisplayStatView(false);
}
private void loadGame() {
stateManager.attach(new GameEngine());
}
}
|
package com.wakatime.intellij.plugin;
import com.intellij.AppTopics;
import com.intellij.compiler.server.BuildManagerListener;
import com.intellij.ide.BrowserUtil;
import com.intellij.ide.plugins.PluginManager;
import com.intellij.ide.plugins.PluginManagerCore;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ApplicationInfo;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.compiler.CompilerTopics;
import com.intellij.openapi.components.ApplicationComponent;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.extensions.PluginId;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.StatusBar;
import com.intellij.openapi.wm.WindowManager;
import com.intellij.util.PlatformUtils;
import com.intellij.util.concurrency.AppExecutorUtil;
import com.intellij.util.messages.MessageBusConnection;
import org.apache.log4j.Level;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.awt.KeyboardFocusManager;
import java.io.*;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.concurrent.*;
public class WakaTime implements ApplicationComponent {
public static final BigDecimal FREQUENCY = new BigDecimal(2 * 60); // max secs between heartbeats for continuous coding
public static final Logger log = Logger.getInstance("WakaTime");
public static String VERSION;
public static String IDE_NAME;
public static String IDE_VERSION;
public static MessageBusConnection connection;
public static Boolean DEBUG = false;
public static Boolean DEBUG_CHECKED = false;
public static Boolean STATUS_BAR = false;
public static Boolean READY = false;
public static String lastFile = null;
public static BigDecimal lastTime = new BigDecimal(0);
public static Boolean isBuilding = false;
private final int queueTimeoutSeconds = 30;
private static ConcurrentLinkedQueue<Heartbeat> heartbeatsQueue = new ConcurrentLinkedQueue<Heartbeat>();
private static ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
private static ScheduledFuture<?> scheduledFixture;
public WakaTime() {
}
public void initComponent() {
try {
// support older IDE versions with deprecated PluginManager
VERSION = PluginManager.getPlugin(PluginId.getId("com.wakatime.intellij.plugin")).getVersion();
} catch (Exception e) {
// use PluginManagerCore if PluginManager deprecated
VERSION = PluginManagerCore.getPlugin(PluginId.getId("com.wakatime.intellij.plugin")).getVersion();
}
log.info("Initializing WakaTime plugin v" + VERSION + " (https://wakatime.com/)");
// Set runtime constants
IDE_NAME = PlatformUtils.getPlatformPrefix();
IDE_VERSION = ApplicationInfo.getInstance().getFullVersion();
setupDebugging();
setupStatusBar();
setLoggingLevel();
checkApiKey();
checkCli();
setupEventListeners();
setupQueueProcessor();
}
private void checkCli() {
ApplicationManager.getApplication().executeOnPooledThread(new Runnable() {
public void run() {
if (!Dependencies.isCLIInstalled()) {
log.info("Downloading and installing wakatime-cli...");
Dependencies.installCLI();
WakaTime.READY = true;
log.info("Finished downloading and installing wakatime-cli.");
} else if (Dependencies.isCLIOld()) {
if (System.getenv("WAKATIME_CLI_LOCATION") != null && !System.getenv("WAKATIME_CLI_LOCATION").trim().isEmpty()) {
File wakatimeCLI = new File(System.getenv("WAKATIME_CLI_LOCATION"));
if (wakatimeCLI.exists()) {
log.warn("$WAKATIME_CLI_LOCATION is out of date, please update it.");
}
} else {
log.info("Upgrading wakatime-cli ...");
Dependencies.installCLI();
WakaTime.READY = true;
log.info("Finished upgrading wakatime-cli.");
}
} else {
WakaTime.READY = true;
log.info("wakatime-cli is up to date.");
}
Dependencies.createSymlink(Dependencies.combinePaths(Dependencies.getResourcesLocation(), "wakatime-cli"), Dependencies.getCLILocation());
log.debug("wakatime-cli location: " + Dependencies.getCLILocation());
}
});
}
private static void checkApiKey() {
ApplicationManager.getApplication().invokeLater(new Runnable(){
public void run() {
// prompt for apiKey if it does not already exist
Project project = getCurrentProject();
if (project == null) return;
if (ConfigFile.getApiKey().equals("")) {
try {
ApiKey apiKey = new ApiKey(project);
apiKey.promptForApiKey();
} catch(Exception e) {
log.warn(e);
} catch (Throwable throwable) {
log.warn("Unable to prompt for api key because UI not ready.");
}
}
}
});
}
private void setupEventListeners() {
ApplicationManager.getApplication().invokeLater(new Runnable(){
public void run() {
Disposable disposable = Disposer.newDisposable((String) "WakaTimeListener");
MessageBusConnection connection = ApplicationManager.getApplication().getMessageBus().connect();
// save file
connection.subscribe(AppTopics.FILE_DOCUMENT_SYNC, new CustomSaveListener());
// edit document
EditorFactory.getInstance().getEventMulticaster().addDocumentListener(new CustomDocumentListener(), disposable);
// mouse press
EditorFactory.getInstance().getEventMulticaster().addEditorMouseListener(new CustomEditorMouseListener(), disposable);
// scroll document
EditorFactory.getInstance().getEventMulticaster().addVisibleAreaListener(new CustomVisibleAreaListener(), disposable);
// compiling
connection.subscribe(BuildManagerListener.TOPIC, new CustomBuildManagerListener());
connection.subscribe(CompilerTopics.COMPILATION_STATUS, new CustomBuildManagerListener());
}
});
}
private void setupQueueProcessor() {
final Runnable handler = new Runnable() {
public void run() {
processHeartbeatQueue();
}
};
long delay = queueTimeoutSeconds;
scheduledFixture = scheduler.scheduleAtFixedRate(handler, delay, delay, java.util.concurrent.TimeUnit.SECONDS);
}
private static void checkDebug() {
if (DEBUG_CHECKED) return;
DEBUG_CHECKED = true;
if (!DEBUG) return;
ApplicationManager.getApplication().invokeLater(new Runnable(){
public void run() {
Messages.showWarningDialog("Your IDE may respond slower. Disable debug mode from Tools -> WakaTime Settings.", "WakaTime Debug Mode Enabled");
}
});
}
public void disposeComponent() {
try {
connection.disconnect();
} catch(Exception e) { }
try {
scheduledFixture.cancel(true);
} catch (Exception e) { }
// make sure to send all heartbeats before exiting
processHeartbeatQueue();
}
public static BigDecimal getCurrentTimestamp() {
return new BigDecimal(String.valueOf(System.currentTimeMillis() / 1000.0)).setScale(4, BigDecimal.ROUND_HALF_UP);
}
public static void appendHeartbeat(final VirtualFile file, Project project, final boolean isWrite) {
checkDebug();
if (WakaTime.READY) {
updateStatusBarText();
if (project != null) {
StatusBar statusbar = WindowManager.getInstance().getStatusBar(project);
if (statusbar != null) statusbar.updateWidget("WakaTime");
}
}
if (!shouldLogFile(file)) return;
final BigDecimal time = WakaTime.getCurrentTimestamp();
if (!isWrite && file.getPath().equals(WakaTime.lastFile) && !enoughTimePassed(time)) {
return;
}
WakaTime.lastFile = file.getPath();
WakaTime.lastTime = time;
final String projectName = project != null ? project.getName() : null;
final String language = WakaTime.getLanguage(file);
ApplicationManager.getApplication().executeOnPooledThread(new Runnable() {
public void run() {
Heartbeat h = new Heartbeat();
h.entity = file.getPath();
h.timestamp = time;
h.isWrite = isWrite;
h.project = projectName;
h.language = language;
h.isBuilding = WakaTime.isBuilding;
heartbeatsQueue.add(h);
if (WakaTime.isBuilding) setBuildTimeout();
}
});
}
private static void setBuildTimeout() {
AppExecutorUtil.getAppScheduledExecutorService().schedule(new Runnable() {
@Override
public void run() {
if (!WakaTime.isBuilding) return;
Project project = getCurrentProject();
if (project == null) return;
if (!WakaTime.isProjectInitialized(project)) return;
VirtualFile file = WakaTime.getCurrentFile(project);
if (file == null) return;
WakaTime.appendHeartbeat(file, project, false);
}
}, 10, TimeUnit.SECONDS);
}
private static void processHeartbeatQueue() {
if (!WakaTime.READY) return;
checkApiKey();
// get single heartbeat from queue
Heartbeat heartbeat = heartbeatsQueue.poll();
if (heartbeat == null)
return;
// get all extra heartbeats from queue
ArrayList<Heartbeat> extraHeartbeats = new ArrayList<Heartbeat>();
while (true) {
Heartbeat h = heartbeatsQueue.poll();
if (h == null)
break;
extraHeartbeats.add(h);
}
sendHeartbeat(heartbeat, extraHeartbeats);
}
private static void sendHeartbeat(final Heartbeat heartbeat, final ArrayList<Heartbeat> extraHeartbeats) {
final String[] cmds = buildCliCommand(heartbeat, extraHeartbeats);
log.debug("Executing CLI: " + Arrays.toString(obfuscateKey(cmds)));
try {
Process proc = Runtime.getRuntime().exec(cmds);
if (extraHeartbeats.size() > 0) {
String json = toJSON(extraHeartbeats);
log.debug(json);
try {
BufferedWriter stdin = new BufferedWriter(new OutputStreamWriter(proc.getOutputStream()));
stdin.write(json);
stdin.write("\n");
try {
stdin.flush();
stdin.close();
} catch (IOException e) { /* ignored because wakatime-cli closes pipe after receiving \n */ }
} catch (IOException e) {
log.warn(e);
}
}
if (WakaTime.DEBUG) {
BufferedReader stdout = new BufferedReader(new
InputStreamReader(proc.getInputStream()));
BufferedReader stderr = new BufferedReader(new
InputStreamReader(proc.getErrorStream()));
proc.waitFor();
String s;
while ((s = stdout.readLine()) != null) {
log.debug(s);
}
while ((s = stderr.readLine()) != null) {
log.debug(s);
}
log.debug("Command finished with return value: " + proc.exitValue());
}
} catch (Exception e) {
log.warn(e);
if (Dependencies.isWindows() && e.toString().contains("Access is denied")) {
try {
Messages.showWarningDialog("Microsoft Defender is blocking WakaTime. Please allow " + Dependencies.getCLILocation() + " to run so WakaTime can upload code stats to your dashboard.", "Error");
} catch (Exception ex) { }
}
}
}
private static String toJSON(ArrayList<Heartbeat> extraHeartbeats) {
StringBuffer json = new StringBuffer();
json.append("[");
boolean first = true;
for (Heartbeat heartbeat : extraHeartbeats) {
StringBuffer h = new StringBuffer();
h.append("{\"entity\":\"");
h.append(jsonEscape(heartbeat.entity));
h.append("\",\"timestamp\":");
h.append(heartbeat.timestamp.toPlainString());
h.append(",\"is_write\":");
h.append(heartbeat.isWrite.toString());
if (heartbeat.isBuilding) {
h.append(",\"category\":\"building\"");
}
if (heartbeat.project != null) {
h.append(",\"project\":\"");
h.append(jsonEscape(heartbeat.project));
h.append("\"");
}
if (heartbeat.language != null) {
h.append(",\"language\":\"");
h.append(jsonEscape(heartbeat.language));
h.append("\"");
}
h.append("}");
if (!first)
json.append(",");
json.append(h.toString());
first = false;
}
json.append("]");
return json.toString();
}
private static String jsonEscape(String s) {
if (s == null)
return null;
StringBuffer escaped = new StringBuffer();
final int len = s.length();
for (int i = 0; i < len; i++) {
char c = s.charAt(i);
switch(c) {
case '\\': escaped.append("\\\\"); break;
case '"': escaped.append("\\\""); break;
case '\b': escaped.append("\\b"); break;
case '\f': escaped.append("\\f"); break;
case '\n': escaped.append("\\n"); break;
case '\r': escaped.append("\\r"); break;
case '\t': escaped.append("\\t"); break;
default:
boolean isUnicode = (c >= '\u0000' && c <= '\u001F') || (c >= '\u007F' && c <= '\u009F') || (c >= '\u2000' && c <= '\u20FF');
if (isUnicode){
escaped.append("\\u");
String hex = Integer.toHexString(c);
for (int k = 0; k < 4 - hex.length(); k++) {
escaped.append('0');
}
escaped.append(hex.toUpperCase());
} else {
escaped.append(c);
}
}
}
return escaped.toString();
}
private static String[] buildCliCommand(Heartbeat heartbeat, ArrayList<Heartbeat> extraHeartbeats) {
ArrayList<String> cmds = new ArrayList<String>();
cmds.add(Dependencies.getCLILocation());
cmds.add("--entity");
cmds.add(heartbeat.entity);
cmds.add("--time");
cmds.add(heartbeat.timestamp.toPlainString());
String apiKey = ConfigFile.getApiKey();
if (!apiKey.equals("")) {
cmds.add("--key");
cmds.add(apiKey);
}
if (heartbeat.project != null) {
cmds.add("--alternate-project");
cmds.add(heartbeat.project);
}
if (heartbeat.language != null) {
cmds.add("--alternate-language");
cmds.add(heartbeat.language);
}
cmds.add("--plugin");
cmds.add(IDE_NAME+"/"+IDE_VERSION+" "+IDE_NAME+"-wakatime/"+VERSION);
if (heartbeat.isWrite)
cmds.add("--write");
if (heartbeat.isBuilding) {
cmds.add("--category");
cmds.add("building");
}
if (extraHeartbeats.size() > 0)
cmds.add("--extra-heartbeats");
return cmds.toArray(new String[cmds.size()]);
}
public static boolean enoughTimePassed(BigDecimal currentTime) {
return WakaTime.lastTime.add(FREQUENCY).compareTo(currentTime) < 0;
}
public static boolean shouldLogFile(VirtualFile file) {
if (file == null || file.getUrl().startsWith("mock:
return false;
}
String filePath = file.getPath();
if (filePath.equals("atlassian-ide-plugin.xml") || filePath.contains("/.idea/workspace.xml")) {
return false;
}
return true;
}
public static boolean isAppActive() {
return KeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow() != null;
}
public static boolean isProjectInitialized(Project project) {
if (project == null) return true;
return project.isInitialized();
}
public static void setupDebugging() {
String debug = ConfigFile.get("settings", "debug", false);
WakaTime.DEBUG = debug != null && debug.trim().equals("true");
}
public static void setupStatusBar() {
String statusBarVal = ConfigFile.get("settings", "status_bar_enabled", false);
WakaTime.STATUS_BAR = statusBarVal == null || !statusBarVal.trim().equals("false");
if (WakaTime.READY) {
try {
updateStatusBarText();
Project project = getCurrentProject();
if (project == null) return;
StatusBar statusbar = WindowManager.getInstance().getStatusBar(project);
if (statusbar == null) return;
statusbar.updateWidget("WakaTime");
} catch (Exception e) {
log.warn(e);
}
}
}
public static void setLoggingLevel() {
if (WakaTime.DEBUG) {
log.setLevel(Level.DEBUG);
log.debug("Logging level set to DEBUG");
} else {
log.setLevel(Level.INFO);
}
}
public static Project getProject(Document document) {
Editor[] editors = EditorFactory.getInstance().getEditors(document);
if (editors.length > 0) {
return editors[0].getProject();
}
return null;
}
private static String getLanguage(final VirtualFile file) {
FileType type = file.getFileType();
if (type != null)
return type.getName();
return null;
}
@Nullable
public static VirtualFile getFile(Document document) {
if (document == null) return null;
FileDocumentManager instance = FileDocumentManager.getInstance();
if (instance == null) return null;
VirtualFile file = instance.getFile(document);
return file;
}
@Nullable
public static Project getCurrentProject() {
Project project = null;
try {
project = ProjectManager.getInstance().getDefaultProject();
} catch (Exception e) { }
return project;
}
@Nullable
public static VirtualFile getCurrentFile(Project project) {
if (project == null) return null;
Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor();
if (editor == null) return null;
Document document = editor.getDocument();
return WakaTime.getFile(document);
}
public static void openDashboardWebsite() {
BrowserUtil.browse("https://wakatime.com/dashboard");
}
private static String todayText = "initialized";
private static BigDecimal todayTextTime = new BigDecimal(0);
public static String getStatusBarText() {
if (!WakaTime.READY) return "";
if (!WakaTime.STATUS_BAR) return "";
return todayText;
}
public static void updateStatusBarText() {
// rate limit, to prevent from fetching Today's stats too frequently
BigDecimal now = getCurrentTimestamp();
if (todayTextTime.add(new BigDecimal(60)).compareTo(now) > 0) return;
todayTextTime = getCurrentTimestamp();
ApplicationManager.getApplication().executeOnPooledThread(new Runnable() {
public void run() {
final String[] cmds = new String[]{Dependencies.getCLILocation(), "--today", "--key", ConfigFile.getApiKey()};
log.debug("Executing CLI: " + Arrays.toString(obfuscateKey(cmds)));
try {
Process proc = Runtime.getRuntime().exec(cmds);
BufferedReader stdout = new BufferedReader(new
InputStreamReader(proc.getInputStream()));
BufferedReader stderr = new BufferedReader(new
InputStreamReader(proc.getErrorStream()));
proc.waitFor();
ArrayList<String> output = new ArrayList<String>();
String s;
while ((s = stdout.readLine()) != null) {
output.add(s);
}
while ((s = stderr.readLine()) != null) {
output.add(s);
}
log.debug("Command finished with return value: " + proc.exitValue());
todayText = " " + String.join("", output);
todayTextTime = getCurrentTimestamp();
} catch (InterruptedException interruptedException) {
interruptedException.printStackTrace();
} catch (Exception e) {
log.warn(e);
if (Dependencies.isWindows() && e.toString().contains("Access is denied")) {
try {
Messages.showWarningDialog("Microsoft Defender is blocking WakaTime. Please allow " + Dependencies.getCLILocation() + " to run so WakaTime can upload code stats to your dashboard.", "Error");
} catch (Exception ex) { }
}
}
}
});
}
private static String obfuscateKey(String key) {
String newKey = null;
if (key != null) {
newKey = key;
if (key.length() > 4)
newKey = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXX" + key.substring(key.length() - 4);
}
return newKey;
}
private static String[] obfuscateKey(String[] cmds) {
ArrayList<String> newCmds = new ArrayList<String>();
String lastCmd = "";
for (String cmd : cmds) {
if (lastCmd == "--key")
newCmds.add(obfuscateKey(cmd));
else
newCmds.add(cmd);
lastCmd = cmd;
}
return newCmds.toArray(new String[newCmds.size()]);
}
@NotNull
public String getComponentName() {
return "WakaTime";
}
}
|
package com.wikidreams.imageselection;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionAdapter;
import java.awt.image.BufferedImage;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
@SuppressWarnings("serial")
public class MyPanel extends JPanel {
//private File dir;
private File[] files;
//private ArrayList<File> result;
private JLabel screenLabel;
private Image image;
private BufferedImage screen;
private BufferedImage screenCopy;
private int currentSelectedImage;
private Rectangle captureRect;
private Rectangle captureRectCopy;
public MyPanel() {
this.captureRect = null;
this.captureRectCopy = null;
this.files = openDialog();
//this.dir = new File("C:\\Development\\data\\images\\");
//if (this.dir == null) {
//JOptionPane.showMessageDialog(null, "Select a folder with images.");
//return;
//this.result = new ArrayList<File>();
//this.displayDirectoryContents(this.dir, this.result);
this.image = null;
try {
//image = ImageIO.read(new File(this.result.get(0).getAbsolutePath()));
image = ImageIO.read(new File(this.files[0].getAbsolutePath()));
this.currentSelectedImage = 1;
} catch (IOException e) {
System.out.println(e.getMessage());
return;
}
this.screen = (BufferedImage) image;
this.screenCopy = new BufferedImage(this.screen.getWidth(), this.screen.getHeight(), this.screen.getType());
this.screenLabel = new JLabel(new ImageIcon(this.screenCopy));
this.screenLabel.setPreferredSize(new Dimension(this.screen.getWidth(), this.screen.getHeight()));
this.setLayout(new BorderLayout());
this.add(screenLabel, BorderLayout.CENTER);
final JLabel selectionLabel = new JLabel("Drag a rectangle in the image.");
this.add(selectionLabel, BorderLayout.SOUTH);
repaint(screen, screenCopy);
screenLabel.repaint();
screenLabel.addMouseMotionListener(new MouseMotionAdapter() {
Point start = new Point();
@Override
public void mouseMoved(MouseEvent me) {
if (captureRect == null) {
start = me.getPoint();
repaint(screen, screenCopy);
selectionLabel.setText("Start Point: " + start);
screenLabel.repaint();
}
}
@Override
public void mouseDragged(MouseEvent me) {
if (start != null) {
Point end = me.getPoint();
captureRect = new Rectangle(start, new Dimension(end.x-start.x, end.y-start.y));
repaint(screen, screenCopy);
screenLabel.repaint();
selectionLabel.setText("Rectangle: " + captureRect);
System.out.println(captureRect);
}
}
});
screenLabel.addMouseListener(new MouseListener() {
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent me) {
}
@Override
public void mouseExited(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseClicked(MouseEvent me) {
if (captureRect != null) {
Point start = me.getPoint();
captureRectCopy = new Rectangle(start, captureRect.getSize());
autoRepaint(screen, screenCopy);
screenLabel.repaint();
}
}
});
}
private void repaint(BufferedImage orig, BufferedImage copy) {
Graphics2D g = copy.createGraphics();
g.drawImage(orig,0,0, null);
if (captureRect!=null) {
g.setColor(Color.RED);
g.draw(captureRect);
g.setColor(new Color(255,255,255,150));
g.fill(captureRect);
}
g.dispose();
}
private void autoRepaint(BufferedImage orig, BufferedImage copy) {
Graphics2D g = copy.createGraphics();
g.drawImage(orig,0,0, null);
if (captureRectCopy!=null) {
g.setColor(Color.RED);
g.draw(captureRectCopy);
g.setColor(new Color(255,255,255,150));
g.fill(captureRectCopy);
}
g.dispose();
}
private void displayDirectoryContents(File dir, ArrayList<File> result) {
try {
File[] files = dir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
//System.out.println("directory:" + file.getAbsolutePath());
displayDirectoryContents(file, result);
} else {
//System.out.println(" file:" + file.getAbsolutePath());
result.add(new File(file.getAbsolutePath()));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void nextImage() {
if (this.captureRect != null) {
//if (this.currentSelectedImage != this.result.size()) {
if (this.currentSelectedImage != this.files.length) {
try {
//this.image = ImageIO.read(new File(this.result.get(this.currentSelectedImage).getAbsolutePath()));
this.image = ImageIO.read(new File(this.files[this.currentSelectedImage].getAbsolutePath()));
this.currentSelectedImage +=1;
this.screen = (BufferedImage) this.image;
this.screenCopy = new BufferedImage(this.screen.getWidth(), this.screen.getHeight(), this.screen.getType());
this.screenLabel.setIcon(new ImageIcon(this.screenCopy));
this.autoRepaint(this.screen, this.screenCopy);
this.screenLabel.repaint();
} catch (IOException e) {
e.printStackTrace();
}
} else {
JOptionPane.showMessageDialog(null, "There are no more images to display.");
}
} else {
JOptionPane.showMessageDialog(null, "Drag a rectangle in the image.");
}
}
public void saveCoordinatesFromSelectedRegion() {
try {
String content = "";
if (this.captureRectCopy == null) {
content = captureRect.toString();
} else {
content = captureRectCopy.toString();
}
File file = new File("C:\\Development\\data\\images\\info.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
JOptionPane.showMessageDialog(null, "File saved.");
} catch (HeadlessException e) {
e.printStackTrace();
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "The system cannot find the path specified");
}
}
public void createImageFromSelectedRegion() {
try {
BufferedImage selectedImage = this.screen.getSubimage(this.captureRect.x, this.captureRect.y, this.captureRect.width, this.captureRect.height);
ImageIO.write(selectedImage, "jpg", new File("c:\\output.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
}
private File[] openDialog() {
/*
File folder = null;
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
int returnVal = fc.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
folder = fc.getSelectedFile();
}
return folder;
*/
JFileChooser chooser = new JFileChooser();
chooser.setMultiSelectionEnabled(true);
chooser.showOpenDialog(this);
File[] files = chooser.getSelectedFiles();
return files;
}
private void saveDialog() {
final JFileChooser fc = new JFileChooser();
int returnVal = fc.showSaveDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
}
}
}
|
package bisq.core.util;
import bisq.core.app.BisqEnvironment;
import bisq.core.locale.CurrencyUtil;
import bisq.core.locale.GlobalSettings;
import bisq.core.locale.LanguageUtil;
import bisq.core.locale.Res;
import bisq.core.monetary.Altcoin;
import bisq.core.monetary.Price;
import bisq.core.monetary.Volume;
import bisq.core.offer.Offer;
import bisq.core.offer.OfferPayload;
import bisq.network.p2p.NodeAddress;
import bisq.common.util.MathUtils;
import org.bitcoinj.core.Coin;
import org.bitcoinj.core.Monetary;
import org.bitcoinj.utils.Fiat;
import org.bitcoinj.utils.MonetaryFormat;
import javax.inject.Inject;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.commons.lang3.time.DurationFormatUtils;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
@Slf4j
public class BSFormatter {
public final static String RANGE_SEPARATOR = " - ";
protected boolean useMilliBit;
protected int scale = 3;
// We don't support localized formatting. Format is always using "." as decimal mark and no grouping separator.
// Input of "," as decimal mark (like in german locale) will be replaced with ".".
// Input of a group separator (1,123,45) lead to an validation error.
// Note: BtcFormat was intended to be used, but it lead to many problems (automatic format to mBit,
// no way to remove grouping separator). It seems to be not optimal for user input formatting.
protected MonetaryFormat coinFormat;
// protected String currencyCode = CurrencyUtil.getDefaultFiatCurrencyAsCode();
protected final MonetaryFormat fiatPriceFormat = new MonetaryFormat().shift(0).minDecimals(4).repeatOptionalDecimals(0, 0);
protected final MonetaryFormat fiatVolumeFormat = new MonetaryFormat().shift(0).minDecimals(2).repeatOptionalDecimals(0, 0);
protected final MonetaryFormat altcoinFormat = new MonetaryFormat().shift(0).minDecimals(8).repeatOptionalDecimals(0, 0);
protected final DecimalFormat decimalFormat = new DecimalFormat("
@Inject
public BSFormatter() {
coinFormat = BisqEnvironment.getParameters().getMonetaryFormat();
}
// BTC
public String formatCoin(Coin coin) {
return formatCoin(coin, -1);
}
@NotNull
public String formatCoin(Coin coin, int decimalPlaces) {
return formatCoin(coin, decimalPlaces, false, 0);
}
public String formatCoin(long value, MonetaryFormat coinFormat) {
return formatCoin(Coin.valueOf(value), -1, false, 0, coinFormat);
}
public String formatCoin(Coin coin, int decimalPlaces, boolean decimalAligned, int maxNumberOfDigits) {
return formatCoin(coin, decimalPlaces, decimalAligned, maxNumberOfDigits, coinFormat);
}
public String formatCoin(Coin coin, int decimalPlaces, boolean decimalAligned, int maxNumberOfDigits, MonetaryFormat coinFormat) {
String formattedCoin = "";
if (coin != null) {
try {
if (decimalPlaces < 0 || decimalPlaces > 4) {
formattedCoin = coinFormat.noCode().format(coin).toString();
} else {
formattedCoin = coinFormat.noCode().minDecimals(decimalPlaces).repeatOptionalDecimals(1, decimalPlaces).format(coin).toString();
}
} catch (Throwable t) {
log.warn("Exception at formatBtc: " + t.toString());
}
}
if (decimalAligned) {
formattedCoin = fillUpPlacesWithEmptyStrings(formattedCoin, maxNumberOfDigits);
}
return formattedCoin;
}
public String formatCoinWithCode(Coin coin) {
return formatCoinWithCode(coin, coinFormat);
}
public String formatCoinWithCode(long value) {
return formatCoinWithCode(Coin.valueOf(value), coinFormat);
}
public String formatCoinWithCode(long value, MonetaryFormat coinFormat) {
return formatCoinWithCode(Coin.valueOf(value), coinFormat);
}
public String formatCoinWithCode(Coin coin, MonetaryFormat coinFormat) {
if (coin != null) {
try {
// we don't use the code feature from coinFormat as it does automatic switching between mBTC and BTC and
// pre and post fixing
return coinFormat.postfixCode().format(coin).toString();
} catch (Throwable t) {
log.warn("Exception at formatBtcWithCode: " + t.toString());
return "";
}
} else {
return "";
}
}
public Coin parseToCoin(String input) {
return parseToCoin(input, coinFormat);
}
public Coin parseToCoin(String input, MonetaryFormat coinFormat) {
if (input != null && input.length() > 0) {
try {
return coinFormat.parse(cleanDoubleInput(input));
} catch (Throwable t) {
log.warn("Exception at parseToBtc: " + t.toString());
return Coin.ZERO;
}
} else {
return Coin.ZERO;
}
}
/**
* Converts to a coin with max. 4 decimal places. Last place gets rounded.
* 0.01234 -> 0.0123
* 0.01235 -> 0.0124
*
* @param input
* @return
*/
public Coin parseToCoinWith4Decimals(String input) {
try {
return Coin.valueOf(new BigDecimal(parseToCoin(cleanDoubleInput(input)).value).setScale(-scale - 1,
BigDecimal.ROUND_HALF_UP).setScale(scale + 1, BigDecimal.ROUND_HALF_UP).toBigInteger().longValue());
} catch (Throwable t) {
if (input != null && input.length() > 0)
log.warn("Exception at parseToCoinWith4Decimals: " + t.toString());
return Coin.ZERO;
}
}
public boolean hasBtcValidDecimals(String input) {
return parseToCoin(input).equals(parseToCoinWith4Decimals(input));
}
/**
* Transform a coin with the properties defined in the format (used to reduce decimal places)
*
* @param coin The coin which should be transformed
* @return The transformed coin
*/
public Coin reduceTo4Decimals(Coin coin) {
return parseToCoin(formatCoin(coin));
}
// FIAT
public String formatFiat(Fiat fiat, MonetaryFormat format, boolean appendCurrencyCode) {
if (fiat != null) {
try {
final String res = format.noCode().format(fiat).toString();
if (appendCurrencyCode)
return res + " " + fiat.getCurrencyCode();
else
return res;
} catch (Throwable t) {
log.warn("Exception at formatFiatWithCode: " + t.toString());
return Res.get("shared.na") + " " + fiat.getCurrencyCode();
}
} else {
return Res.get("shared.na");
}
}
protected Fiat parseToFiat(String input, String currencyCode) {
if (input != null && input.length() > 0) {
try {
return Fiat.parseFiat(currencyCode, cleanDoubleInput(input));
} catch (Exception e) {
log.warn("Exception at parseToFiat: " + e.toString());
return Fiat.valueOf(currencyCode, 0);
}
} else {
return Fiat.valueOf(currencyCode, 0);
}
}
/**
* Converts to a fiat with max. 2 decimal places. Last place gets rounded.
* 0.234 -> 0.23
* 0.235 -> 0.24
*
* @param input
* @return
*/
public Fiat parseToFiatWithPrecision(String input, String currencyCode) {
if (input != null && input.length() > 0) {
try {
return parseToFiat(new BigDecimal(cleanDoubleInput(input)).setScale(2, BigDecimal.ROUND_HALF_UP).toString(),
currencyCode);
} catch (Throwable t) {
log.warn("Exception at parseToFiatWithPrecision: " + t.toString());
return Fiat.valueOf(currencyCode, 0);
}
}
return Fiat.valueOf(currencyCode, 0);
}
public boolean isFiatAlteredWhenPrecisionApplied(String input, String currencyCode) {
return parseToFiat(input, currencyCode).equals(parseToFiatWithPrecision(input, currencyCode));
}
// Altcoin
public String formatAltcoin(Altcoin altcoin) {
return formatAltcoin(altcoin, false);
}
public String formatAltcoinWithCode(Altcoin altcoin) {
return formatAltcoin(altcoin, true);
}
public String formatAltcoin(Altcoin altcoin, boolean appendCurrencyCode) {
if (altcoin != null) {
try {
String res = altcoinFormat.noCode().format(altcoin).toString();
if (appendCurrencyCode)
return res + " " + altcoin.getCurrencyCode();
else
return res;
} catch (Throwable t) {
log.warn("Exception at formatAltcoin: " + t.toString());
return Res.get("shared.na") + " " + altcoin.getCurrencyCode();
}
} else {
return Res.get("shared.na");
}
}
// Volume
public String formatVolume(Offer offer, Boolean decimalAligned, int maxNumberOfDigits) {
return formatVolume(offer, decimalAligned, maxNumberOfDigits, true);
}
public String formatVolume(Offer offer, Boolean decimalAligned, int maxNumberOfDigits, boolean showRange) {
String formattedVolume = offer.isRange() && showRange ? formatVolume(offer.getMinVolume()) + RANGE_SEPARATOR + formatVolume(offer.getVolume()) : formatVolume(offer.getVolume());
if (decimalAligned) {
formattedVolume = fillUpPlacesWithEmptyStrings(formattedVolume, maxNumberOfDigits);
}
return formattedVolume;
}
@NotNull
public String fillUpPlacesWithEmptyStrings(String formattedNumber, int maxNumberOfDigits) {
//FIXME: temporary deactivate adding spaces in front of numbers as we don't use a monospace font right now.
/*int numberOfPlacesToFill = maxNumberOfDigits - formattedNumber.length();
for (int i = 0; i < numberOfPlacesToFill; i++) {
formattedNumber = " " + formattedNumber;
}*/
return formattedNumber;
}
public String formatVolume(Volume volume) {
return formatVolume(volume, fiatVolumeFormat, false);
}
public String formatVolumeWithCode(Volume volume) {
return formatVolume(volume, fiatVolumeFormat, true);
}
public String formatVolume(Volume volume, MonetaryFormat fiatVolumeFormat, boolean appendCurrencyCode) {
if (volume != null) {
Monetary monetary = volume.getMonetary();
if (monetary instanceof Fiat)
return formatFiat((Fiat) monetary, fiatVolumeFormat, appendCurrencyCode);
else
return formatAltcoinVolume((Altcoin) monetary, appendCurrencyCode);
} else {
return "";
}
}
public String formatAltcoinVolume(Altcoin altcoin, boolean appendCurrencyCode) {
if (altcoin != null) {
try {
// TODO quick hack...
String res;
if (altcoin.getCurrencyCode().equals("BSQ"))
res = altcoinFormat.noCode().minDecimals(2).repeatOptionalDecimals(0, 0).format(altcoin).toString();
else
res = altcoinFormat.noCode().format(altcoin).toString();
if (appendCurrencyCode)
return res + " " + altcoin.getCurrencyCode();
else
return res;
} catch (Throwable t) {
log.warn("Exception at formatAltcoinVolume: " + t.toString());
return Res.get("shared.na") + " " + altcoin.getCurrencyCode();
}
} else {
return Res.get("shared.na");
}
}
public String formatVolumeLabel(String currencyCode) {
return formatVolumeLabel(currencyCode, "");
}
public String formatVolumeLabel(String currencyCode, String postFix) {
return Res.get("formatter.formatVolumeLabel",
currencyCode, postFix);
}
// Amount
public String formatAmount(Offer offer) {
return formatAmount(offer, false);
}
public String formatAmount(Offer offer, boolean decimalAligned) {
String formattedAmount = offer.isRange() ? formatCoin(offer.getMinAmount()) + RANGE_SEPARATOR + formatCoin(offer.getAmount()) : formatCoin(offer.getAmount());
if (decimalAligned) {
formattedAmount = fillUpPlacesWithEmptyStrings(formattedAmount, 15);
}
return formattedAmount;
}
public String formatAmount(Offer offer, int decimalPlaces, boolean decimalAligned, int maxPlaces) {
String formattedAmount = offer.isRange() ? formatCoin(offer.getMinAmount(), decimalPlaces) + RANGE_SEPARATOR + formatCoin(offer.getAmount(), decimalPlaces) : formatCoin(offer.getAmount(), decimalPlaces);
if (decimalAligned) {
formattedAmount = fillUpPlacesWithEmptyStrings(formattedAmount, maxPlaces);
}
return formattedAmount;
}
// Price
public String formatPrice(Price price, MonetaryFormat fiatPriceFormat, boolean appendCurrencyCode) {
if (price != null) {
Monetary monetary = price.getMonetary();
if (monetary instanceof Fiat)
return formatFiat((Fiat) monetary, fiatPriceFormat, appendCurrencyCode);
else
return formatAltcoin((Altcoin) monetary, appendCurrencyCode);
} else {
return Res.get("shared.na");
}
}
public String formatPrice(Price price) {
return formatPrice(price, fiatPriceFormat, false);
}
public String formatPrice(Price price, Boolean decimalAligned, int maxPlaces) {
String formattedPrice = formatPrice(price);
if (decimalAligned) {
formattedPrice = fillUpPlacesWithEmptyStrings(formattedPrice, maxPlaces);
}
return formattedPrice;
}
// Market price
public String formatMarketPrice(double price, String currencyCode) {
if (CurrencyUtil.isFiatCurrency(currencyCode))
return formatMarketPrice(price, 2);
else
return formatMarketPrice(price, 8);
}
public String formatMarketPrice(double price, int precision) {
return formatRoundedDoubleWithPrecision(price, precision);
}
// Other
public String formatRoundedDoubleWithPrecision(double value, int precision) {
decimalFormat.setMinimumFractionDigits(precision);
decimalFormat.setMaximumFractionDigits(precision);
return decimalFormat.format(MathUtils.roundDouble(value, precision)).replace(",", ".");
}
public String getDirectionWithCode(OfferPayload.Direction direction, String currencyCode) {
if (CurrencyUtil.isFiatCurrency(currencyCode))
return (direction == OfferPayload.Direction.BUY) ? Res.get("shared.buyCurrency", Res.getBaseCurrencyCode()) : Res.get("shared.sellCurrency", Res.getBaseCurrencyCode());
else
return (direction == OfferPayload.Direction.SELL) ? Res.get("shared.buyCurrency", currencyCode) : Res.get("shared.sellCurrency", currencyCode);
}
public String getDirectionWithCodeDetailed(OfferPayload.Direction direction, String currencyCode) {
if (CurrencyUtil.isFiatCurrency(currencyCode))
return (direction == OfferPayload.Direction.BUY) ? Res.get("shared.buyingBTCWith", currencyCode) : Res.get("shared.sellingBTCFor", currencyCode);
else
return (direction == OfferPayload.Direction.SELL) ? Res.get("shared.buyingCurrency", currencyCode) : Res.get("shared.sellingCurrency", currencyCode);
}
public String arbitratorAddressesToString(List<NodeAddress> nodeAddresses) {
return nodeAddresses.stream().map(NodeAddress::getFullAddress).collect(Collectors.joining(", "));
}
public String languageCodesToString(List<String> languageLocales) {
return languageLocales.stream().map(LanguageUtil::getDisplayName).collect(Collectors.joining(", "));
}
public String formatDateTime(Date date) {
return formatDateTime(date,
DateFormat.getDateInstance(DateFormat.DEFAULT, getLocale()),
DateFormat.getTimeInstance(DateFormat.DEFAULT, getLocale()));
}
public String formatDateTime(Date date, DateFormat dateFormatter, DateFormat timeFormatter) {
if (date != null) {
return dateFormatter.format(date) + " " + timeFormatter.format(date);
} else {
return "";
}
}
public String formatDateTimeSpan(Date dateFrom, Date dateTo) {
if (dateFrom != null && dateTo != null) {
DateFormat dateFormatter = DateFormat.getDateInstance(DateFormat.DEFAULT, getLocale());
DateFormat timeFormatter = DateFormat.getTimeInstance(DateFormat.DEFAULT, getLocale());
return dateFormatter.format(dateFrom) + " " + timeFormatter.format(dateFrom) + RANGE_SEPARATOR + timeFormatter.format(dateTo);
} else {
return "";
}
}
public String formatTime(Date date) {
if (date != null) {
DateFormat timeFormatter = DateFormat.getTimeInstance(DateFormat.DEFAULT, getLocale());
return timeFormatter.format(date);
} else {
return "";
}
}
public String formatDate(Date date) {
if (date != null) {
DateFormat dateFormatter = DateFormat.getDateInstance(DateFormat.DEFAULT, getLocale());
return dateFormatter.format(date);
} else {
return "";
}
}
public String formatToPercentWithSymbol(double value) {
return formatToPercent(value) + "%";
}
public String formatPercentagePrice(double value) {
return formatToPercentWithSymbol(value);
}
public String formatToPercent(double value) {
DecimalFormat decimalFormat = new DecimalFormat("
decimalFormat.setMinimumFractionDigits(2);
decimalFormat.setMaximumFractionDigits(2);
return decimalFormat.format(MathUtils.roundDouble(value * 100.0, 2)).replace(",", ".");
}
public double parseNumberStringToDouble(String input) throws NumberFormatException {
return Double.parseDouble(cleanDoubleInput(input));
}
public double parsePercentStringToDouble(String percentString) throws NumberFormatException {
String input = percentString.replace("%", "");
input = cleanDoubleInput(input);
double value = Double.parseDouble(input);
return value / 100d;
}
public long parsePriceStringToLong(String currencyCode, String amount, int precision) {
if (amount == null || amount.isEmpty())
return 0;
long value = 0;
try {
double amountValue = Double.parseDouble(amount);
amount = formatRoundedDoubleWithPrecision(amountValue, precision);
value = Price.parse(currencyCode, amount).getValue();
} catch (NumberFormatException ignore) {
// expected NumberFormatException if input is not a number
} catch (Throwable t) {
log.error("parsePriceStringToLong: " + t.toString());
}
return value;
}
public static String convertCharsForNumber(String input) {
// Some languages like finnish use the long dash for the minus
input = input.replace("−", "-");
input = StringUtils.deleteWhitespace(input);
return input.replace(",", ".");
}
protected String cleanDoubleInput(String input) {
input = convertCharsForNumber(input);
if (input.equals("."))
input = input.replace(".", "0.");
if (input.equals("-."))
input = input.replace("-.", "-0.");
// don't use String.valueOf(Double.parseDouble(input)) as return value as it gives scientific
// notation (1.0E-6) which screw up coinFormat.parse
//noinspection ResultOfMethodCallIgnored
// Just called to check if we have a valid double, throws exception otherwise
//noinspection ResultOfMethodCallIgnored
Double.parseDouble(input);
return input;
}
public String formatAccountAge(long durationMillis) {
durationMillis = Math.max(0, durationMillis);
String day = Res.get("time.day").toLowerCase();
String days = Res.get("time.days");
String format = "d\' " + days + "\'";
return StringUtils.replaceOnce(DurationFormatUtils.formatDuration(durationMillis, format), "1 " + days, "1 " + day);
}
public String formatDurationAsWords(long durationMillis) {
return formatDurationAsWords(durationMillis, false, true);
}
public String formatDurationAsWords(long durationMillis, boolean showSeconds, boolean showZeroValues) {
String format = "";
String second = Res.get("time.second");
String minute = Res.get("time.minute");
String hour = Res.get("time.hour").toLowerCase();
String day = Res.get("time.day").toLowerCase();
String days = Res.get("time.days");
String hours = Res.get("time.hours");
String minutes = Res.get("time.minutes");
String seconds = Res.get("time.seconds");
if (durationMillis >= DateUtils.MILLIS_PER_DAY) {
format = "d\' " + days + ", \'";
}
if (showSeconds) {
format += "H\' " + hours + ", \'m\' " + minutes + ", \'s\' " + seconds + "\'";
} else
format += "H\' " + hours + ", \'m\' " + minutes + "\'";
String duration = durationMillis > 0 ? DurationFormatUtils.formatDuration(durationMillis, format) : "";
duration = StringUtils.replacePattern(duration, "^1 " + seconds + "|\\b1 " + seconds, "1 " + second);
duration = StringUtils.replacePattern(duration, "^1 " + minutes + "|\\b1 " + minutes, "1 " + minute);
duration = StringUtils.replacePattern(duration, "^1 " + hours + "|\\b1 " + hours, "1 " + hour);
duration = StringUtils.replacePattern(duration, "^1 " + days + "|\\b1 " + days, "1 " + day);
if (!showZeroValues) {
duration = duration.replace(", 0 seconds", "");
duration = duration.replace(", 0 minutes", "");
duration = duration.replace(", 0 hours", "");
duration = duration.replace("0 days", "");
duration = duration.replace("0 hours, ", "");
duration = duration.replace("0 minutes, ", "");
duration = duration.replace("0 seconds", "");
}
return duration.trim();
}
public String booleanToYesNo(boolean value) {
return value ? Res.get("shared.yes") : Res.get("shared.no");
}
public String getDirectionBothSides(OfferPayload.Direction direction, String currencyCode) {
if (CurrencyUtil.isFiatCurrency(currencyCode)) {
currencyCode = Res.getBaseCurrencyCode();
return direction == OfferPayload.Direction.BUY ?
Res.get("formatter.makerTaker", currencyCode, Res.get("shared.buyer"), currencyCode, Res.get("shared.seller")) :
Res.get("formatter.makerTaker", currencyCode, Res.get("shared.seller"), currencyCode, Res.get("shared.buyer"));
} else {
return direction == OfferPayload.Direction.SELL ?
Res.get("formatter.makerTaker", currencyCode, Res.get("shared.buyer"), currencyCode, Res.get("shared.seller")) :
Res.get("formatter.makerTaker", currencyCode, Res.get("shared.seller"), currencyCode, Res.get("shared.buyer"));
}
}
public String getDirectionForBuyer(boolean isMyOffer, String currencyCode) {
if (CurrencyUtil.isFiatCurrency(currencyCode)) {
String code = Res.getBaseCurrencyCode();
return isMyOffer ?
Res.get("formatter.youAreAsMaker", Res.get("shared.buying"), code, Res.get("shared.selling"), code) :
Res.get("formatter.youAreAsTaker", Res.get("shared.buying"), code, Res.get("shared.selling"), code);
} else {
return isMyOffer ?
Res.get("formatter.youAreAsMaker", Res.get("shared.selling"), currencyCode, Res.get("shared.buying"), currencyCode) :
Res.get("formatter.youAreAsTaker", Res.get("shared.selling"), currencyCode, Res.get("shared.buying"), currencyCode);
}
}
public String getDirectionForSeller(boolean isMyOffer, String currencyCode) {
if (CurrencyUtil.isFiatCurrency(currencyCode)) {
String code = Res.getBaseCurrencyCode();
return isMyOffer ?
Res.get("formatter.youAreAsMaker", Res.get("shared.selling"), code, Res.get("shared.buying"), code) :
Res.get("formatter.youAreAsTaker", Res.get("shared.selling"), code, Res.get("shared.buying"), code);
} else {
return isMyOffer ?
Res.get("formatter.youAreAsMaker", Res.get("shared.buying"), currencyCode, Res.get("shared.selling"), currencyCode) :
Res.get("formatter.youAreAsTaker", Res.get("shared.buying"), currencyCode, Res.get("shared.selling"), currencyCode);
}
}
public String getDirectionForTakeOffer(OfferPayload.Direction direction, String currencyCode) {
String baseCurrencyCode = Res.getBaseCurrencyCode();
if (CurrencyUtil.isFiatCurrency(currencyCode)) {
return direction == OfferPayload.Direction.BUY ?
Res.get("formatter.youAre", Res.get("shared.selling"), baseCurrencyCode, Res.get("shared.buying"), currencyCode) :
Res.get("formatter.youAre", Res.get("shared.buying"), baseCurrencyCode, Res.get("shared.selling"), currencyCode);
} else {
return direction == OfferPayload.Direction.SELL ?
Res.get("formatter.youAre", Res.get("shared.selling"), currencyCode, Res.get("shared.buying"), baseCurrencyCode) :
Res.get("formatter.youAre", Res.get("shared.buying"), currencyCode, Res.get("shared.selling"), baseCurrencyCode);
}
}
public String getOfferDirectionForCreateOffer(OfferPayload.Direction direction, String currencyCode) {
String baseCurrencyCode = Res.getBaseCurrencyCode();
if (CurrencyUtil.isFiatCurrency(currencyCode)) {
return direction == OfferPayload.Direction.BUY ?
Res.get("formatter.youAreCreatingAnOffer.fiat", Res.get("shared.buy"), baseCurrencyCode) :
Res.get("formatter.youAreCreatingAnOffer.fiat", Res.get("shared.sell"), baseCurrencyCode);
} else {
return direction == OfferPayload.Direction.SELL ?
Res.get("formatter.youAreCreatingAnOffer.altcoin", Res.get("shared.buy"), currencyCode, Res.get("shared.selling"), baseCurrencyCode) :
Res.get("formatter.youAreCreatingAnOffer.altcoin", Res.get("shared.sell"), currencyCode, Res.get("shared.buying"), baseCurrencyCode);
}
}
public String getRole(boolean isBuyerMakerAndSellerTaker, boolean isMaker, String currencyCode) {
if (CurrencyUtil.isFiatCurrency(currencyCode)) {
String baseCurrencyCode = Res.getBaseCurrencyCode();
if (isBuyerMakerAndSellerTaker)
return isMaker ?
Res.get("formatter.asMaker", baseCurrencyCode, Res.get("shared.buyer")) :
Res.get("formatter.asTaker", baseCurrencyCode, Res.get("shared.seller"));
else
return isMaker ?
Res.get("formatter.asMaker", baseCurrencyCode, Res.get("shared.seller")) :
Res.get("formatter.asTaker", baseCurrencyCode, Res.get("shared.buyer"));
} else {
if (isBuyerMakerAndSellerTaker)
return isMaker ?
Res.get("formatter.asMaker", currencyCode, Res.get("shared.seller")) :
Res.get("formatter.asTaker", currencyCode, Res.get("shared.buyer"));
else
return isMaker ?
Res.get("formatter.asMaker", currencyCode, Res.get("shared.buyer")) :
Res.get("formatter.asTaker", currencyCode, Res.get("shared.seller"));
}
}
public String formatBytes(long bytes) {
double kb = 1024;
double mb = kb * kb;
DecimalFormat decimalFormat = new DecimalFormat("
if (bytes < kb)
return bytes + " bytes";
else if (bytes < mb)
return decimalFormat.format(bytes / kb) + " KB";
else
return decimalFormat.format(bytes / mb) + " MB";
}
public String getCurrencyPair(String currencyCode) {
if (CurrencyUtil.isFiatCurrency(currencyCode))
return Res.getBaseCurrencyCode() + "/" + currencyCode;
else
return currencyCode + "/" + Res.getBaseCurrencyCode();
}
public String getCounterCurrency(String currencyCode) {
if (CurrencyUtil.isFiatCurrency(currencyCode))
return currencyCode;
else
return Res.getBaseCurrencyCode();
}
public String getBaseCurrency(String currencyCode) {
if (CurrencyUtil.isCryptoCurrency(currencyCode))
return currencyCode;
else
return Res.getBaseCurrencyCode();
}
public String getCounterCurrencyAndCurrencyPair(String currencyCode) {
return getCounterCurrency(currencyCode) + " (" + getCurrencyPair(currencyCode) + ")";
}
public String getCurrencyNameAndCurrencyPair(String currencyCode) {
return CurrencyUtil.getNameByCode(currencyCode) + " (" + getCurrencyPair(currencyCode) + ")";
}
public String getPriceWithCurrencyCode(String currencyCode) {
return getPriceWithCurrencyCode(currencyCode, "shared.priceInCurForCur");
}
public String getPriceWithCurrencyCode(String currencyCode, String translationKey) {
if (CurrencyUtil.isCryptoCurrency(currencyCode))
return Res.get(translationKey, Res.getBaseCurrencyCode(), currencyCode);
else
return Res.get(translationKey, currencyCode, Res.getBaseCurrencyCode());
}
public Locale getLocale() {
return GlobalSettings.getLocale();
}
}
|
package com.questdb.std.time;
import com.questdb.ex.NumericException;
import com.questdb.misc.Chars;
import com.questdb.misc.Numbers;
import com.questdb.std.str.StringSink;
final public class Dates {
public static final long DAY_MILLIS = 86400000L;
public static final long HOUR_MILLIS = 3600000L;
public static final long MINUTE_MILLIS = 60000;
public static final long SECOND_MILLIS = 1000;
public static final int STATE_INIT = 0;
public static final int STATE_UTC = 1;
public static final int STATE_GMT = 2;
public static final int STATE_HOUR = 3;
public static final int STATE_DELIM = 4;
public static final int STATE_MINUTE = 5;
public static final int STATE_END = 6;
public static final int STATE_SIGN = 7;
private static final long AVG_YEAR_MILLIS = (long) (365.2425 * DAY_MILLIS);
private static final long YEAR_MILLIS = 365 * DAY_MILLIS;
private static final long LEAP_YEAR_MILLIS = 366 * DAY_MILLIS;
private static final long HALF_YEAR_MILLIS = AVG_YEAR_MILLIS / 2;
private static final long EPOCH_MILLIS = 1970L * AVG_YEAR_MILLIS;
private static final long HALF_EPOCH_MILLIS = EPOCH_MILLIS / 2;
private static final int DAY_HOURS = 24;
private static final int HOUR_MINUTES = 60;
private static final int MINUTE_SECONDS = 60;
private static final int DAYS_0000_TO_1970 = 719527;
private static final int[] DAYS_PER_MONTH = {
31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
};
private static final long[] MIN_MONTH_OF_YEAR_MILLIS = new long[12];
private static final long[] MAX_MONTH_OF_YEAR_MILLIS = new long[12];
private static final char BEFORE_ZERO = '0' - 1;
private static final char AFTER_NINE = '9' + 1;
private Dates() {
}
public static long addDays(long millis, int days) {
return millis + days * DAY_MILLIS;
}
public static long addHours(long millis, int hours) {
return millis + hours * HOUR_MILLIS;
}
public static long addMonths(final long millis, int months) {
if (months == 0) {
return millis;
}
int y = Dates.getYear(millis);
boolean l = Dates.isLeapYear(y);
int m = getMonthOfYear(millis, y, l);
int _y;
int _m = m - 1 + months;
if (_m > -1) {
_y = y + _m / 12;
_m = (_m % 12) + 1;
} else {
_y = y + _m / 12 - 1;
_m = -_m % 12;
if (_m == 0) {
_m = 12;
}
_m = 12 - _m + 1;
if (_m == 1) {
_y += 1;
}
}
int _d = getDayOfMonth(millis, y, m, l);
int maxDay = getDaysPerMonth(_m, isLeapYear(_y));
if (_d > maxDay) {
_d = maxDay;
}
return toMillis(_y, _m, _d) + getTime(millis) + (millis < 0 ? 1 : 0);
}
public static long addPeriod(long lo, char type, int period) throws NumericException {
switch (type) {
case 's':
return lo + period * Dates.SECOND_MILLIS;
case 'm':
return lo + period * Dates.MINUTE_MILLIS;
case 'h':
return Dates.addHours(lo, period);
case 'd':
return Dates.addDays(lo, period);
case 'M':
return Dates.addMonths(lo, period);
case 'y':
return Dates.addYear(lo, period);
default:
throw NumericException.INSTANCE;
}
}
public static long addYear(long millis, int years) {
if (years == 0) {
return millis;
}
int y = getYear(millis);
int m;
boolean leap1 = isLeapYear(y);
boolean leap2 = isLeapYear(y + years);
return yearMillis(y + years, leap2)
+ monthOfYearMillis(m = getMonthOfYear(millis, y, leap1), leap2)
+ (getDayOfMonth(millis, y, m, leap1) - 1) * DAY_MILLIS
+ getTime(millis)
+ (millis < 0 ? 1 : 0);
}
public static long ceilDD(long millis) {
int y, m;
boolean l;
return yearMillis(y = getYear(millis), l = isLeapYear(y))
+ monthOfYearMillis(m = getMonthOfYear(millis, y, l), l)
+ (getDayOfMonth(millis, y, m, l) - 1) * DAY_MILLIS
+ 23 * HOUR_MILLIS
+ 59 * MINUTE_MILLIS
+ 59 * SECOND_MILLIS
+ 999L
;
}
public static long ceilMM(long millis) {
int y, m;
boolean l;
return yearMillis(y = getYear(millis), l = isLeapYear(y))
+ monthOfYearMillis(m = getMonthOfYear(millis, y, l), l)
+ (getDaysPerMonth(m, l) - 1) * DAY_MILLIS
+ 23 * HOUR_MILLIS
+ 59 * MINUTE_MILLIS
+ 59 * SECOND_MILLIS
+ 999L
;
}
public static long ceilYYYY(long millis) {
int y;
boolean l;
return yearMillis(y = getYear(millis), l = isLeapYear(y))
+ monthOfYearMillis(12, l)
+ (DAYS_PER_MONTH[11] - 1) * DAY_MILLIS
+ 23 * HOUR_MILLIS
+ 59 * MINUTE_MILLIS
+ 59 * SECOND_MILLIS
+ 999L;
}
public static long endOfYear(int year) {
return toMillis(year, 12, 31, 23, 59) + 59 * 1000L + 999L;
}
public static long floorDD(long millis) {
return millis - getTime(millis);
}
public static long floorHH(long millis) {
return millis - millis % HOUR_MILLIS;
}
public static long floorMI(long millis) {
return millis - millis % MINUTE_MILLIS;
}
public static long floorMM(long millis) {
int y;
boolean l;
return yearMillis(y = getYear(millis), l = isLeapYear(y)) + monthOfYearMillis(getMonthOfYear(millis, y, l), l);
}
public static long floorYYYY(long millis) {
int y;
return yearMillis(y = getYear(millis), isLeapYear(y));
}
public static int getDayOfMonth(long millis, int year, int month, boolean leap) {
long dateMillis = yearMillis(year, leap);
dateMillis += monthOfYearMillis(month, leap);
return (int) ((millis - dateMillis) / DAY_MILLIS) + 1;
}
public static int getDayOfWeek(long millis) {
// 1970-01-01 is Thursday.
long d;
if (millis > -1) {
d = millis / DAY_MILLIS;
} else {
d = (millis - (DAY_MILLIS - 1)) / DAY_MILLIS;
if (d < -3) {
return 7 + (int) ((d + 4) % 7);
}
}
return 1 + (int) ((d + 3) % 7);
}
public static int getDayOfWeekSundayFirst(long millis) {
// 1970-01-01 is Thursday.
long d;
if (millis > -1) {
d = millis / DAY_MILLIS;
} else {
d = (millis - (DAY_MILLIS - 1)) / DAY_MILLIS;
if (d < -4) {
return 7 + (int) ((d + 5) % 7);
}
}
return 1 + (int) ((d + 4) % 7);
}
public static long getDaysBetween(long a, long b) {
if (b < a) {
return getDaysBetween(b, a);
} else {
return (b - a) / DAY_MILLIS;
}
}
/**
* Days in a given month. This method expects you to know if month is in leap year.
*
* @param m month from 1 to 12
* @param leap true if this is for leap year
* @return number of days in month.
*/
public static int getDaysPerMonth(int m, boolean leap) {
return leap & m == 2 ? 29 : DAYS_PER_MONTH[m - 1];
}
public static int getHourOfDay(long millis) {
if (millis > -1) {
return (int) ((millis / HOUR_MILLIS) % DAY_HOURS);
} else {
return DAY_HOURS - 1 + (int) (((millis + 1) / HOUR_MILLIS) % DAY_HOURS);
}
}
public static int getMillisOfSecond(long millis) {
if (millis > -1) {
return (int) (millis % 1000);
} else {
return 1000 - 1 + (int) ((millis + 1) % 1000);
}
}
public static int getMinuteOfHour(long millis) {
if (millis > -1) {
return (int) ((millis / MINUTE_MILLIS) % HOUR_MINUTES);
} else {
return HOUR_MINUTES - 1 + (int) (((millis + 1) / MINUTE_MILLIS) % HOUR_MINUTES);
}
}
/**
* Calculates month of year from absolute millis.
*
* @param millis millis since 1970
* @param year year of month
* @param leap true if year was leap
* @return month of year
*/
public static int getMonthOfYear(long millis, int year, boolean leap) {
int i = (int) ((millis - yearMillis(year, leap)) >> 10);
return leap
? ((i < 182 * 84375)
? ((i < 91 * 84375)
? ((i < 31 * 84375) ? 1 : (i < 60 * 84375) ? 2 : 3)
: ((i < 121 * 84375) ? 4 : (i < 152 * 84375) ? 5 : 6))
: ((i < 274 * 84375)
? ((i < 213 * 84375) ? 7 : (i < 244 * 84375) ? 8 : 9)
: ((i < 305 * 84375) ? 10 : (i < 335 * 84375) ? 11 : 12)))
: ((i < 181 * 84375)
? ((i < 90 * 84375)
? ((i < 31 * 84375) ? 1 : (i < 59 * 84375) ? 2 : 3)
: ((i < 120 * 84375) ? 4 : (i < 151 * 84375) ? 5 : 6))
: ((i < 273 * 84375)
? ((i < 212 * 84375) ? 7 : (i < 243 * 84375) ? 8 : 9)
: ((i < 304 * 84375) ? 10 : (i < 334 * 84375) ? 11 : 12)));
}
public static long getMonthsBetween(long a, long b) {
if (b < a) {
return getMonthsBetween(b, a);
}
int aYear = getYear(a);
int bYear = getYear(b);
boolean aLeap = isLeapYear(aYear);
boolean bLeap = isLeapYear(bYear);
int aMonth = getMonthOfYear(a, aYear, aLeap);
int bMonth = getMonthOfYear(b, bYear, bLeap);
long aResidual = a - yearMillis(aYear, aLeap) - monthOfYearMillis(aMonth, aLeap);
long bResidual = b - yearMillis(bYear, bLeap) - monthOfYearMillis(bMonth, bLeap);
long months = 12 * (bYear - aYear) + (bMonth - aMonth);
if (aResidual > bResidual) {
return months - 1;
} else {
return months;
}
}
public static int getSecondOfMinute(long millis) {
if (millis > -1) {
return (int) ((millis / SECOND_MILLIS) % MINUTE_SECONDS);
} else {
return MINUTE_SECONDS - 1 + (int) (((millis + 1) / SECOND_MILLIS) % MINUTE_SECONDS);
}
}
/**
* Calculates year number from millis.
*
* @param millis time millis.
* @return year
*/
public static int getYear(long millis) {
long mid = (millis >> 1) + HALF_EPOCH_MILLIS;
if (mid < 0) {
mid = mid - HALF_YEAR_MILLIS + 1;
}
int year = (int) (mid / HALF_YEAR_MILLIS);
boolean leap = isLeapYear(year);
long yearStart = yearMillis(year, leap);
long diff = millis - yearStart;
if (diff < 0) {
year
} else if (diff >= YEAR_MILLIS) {
yearStart += leap ? LEAP_YEAR_MILLIS : YEAR_MILLIS;
if (yearStart <= millis) {
year++;
}
}
return year;
}
public static long getYearsBetween(long a, long b) {
if (b < a) {
return getYearsBetween(b, a);
}
int aYear = getYear(a);
int bYear = getYear(b);
boolean aLeap = isLeapYear(aYear);
boolean bLeap = isLeapYear(bYear);
long aResidual = a - yearMillis(aYear, aLeap);
long bResidual = b - yearMillis(bYear, bLeap);
long months = bYear - aYear;
if (aResidual > bResidual) {
return months - 1;
} else {
return months;
}
}
public static boolean isLeapYear(int year) {
return ((year & 3) == 0) && ((year % 100) != 0 || (year % 400) == 0);
}
public static long monthOfYearMillis(int month, boolean leap) {
return leap ? MAX_MONTH_OF_YEAR_MILLIS[month - 1] : MIN_MONTH_OF_YEAR_MILLIS[month - 1];
}
public static long nextOrSameDayOfWeek(long millis, int dow) {
int thisDow = getDayOfWeek(millis);
if (thisDow == dow) {
return millis;
}
if (thisDow < dow) {
return millis + (dow - thisDow) * DAY_MILLIS;
} else {
return millis + (7 - (thisDow - dow)) * DAY_MILLIS;
}
}
public static long parseOffset(CharSequence in, int lo, int hi) {
int p = lo;
int state = STATE_INIT;
boolean negative = false;
int hour = 0;
int minute = 0;
try {
OUT:
while (p < hi) {
char c = in.charAt(p);
switch (state) {
case STATE_INIT:
switch (c) {
case 'U':
case 'u':
state = STATE_UTC;
break;
case 'G':
case 'g':
state = STATE_GMT;
break;
case 'Z':
case 'z':
state = STATE_END;
break;
case '+':
negative = false;
state = STATE_HOUR;
break;
case '-':
negative = true;
state = STATE_HOUR;
break;
default:
if (isDigit(c)) {
state = STATE_HOUR;
p
} else {
return Long.MIN_VALUE;
}
break;
}
p++;
break;
case STATE_UTC:
if (p > hi - 2 || !Chars.equalsIgnoreCase(in, p, p + 2, "tc", 0, 2)) {
return Long.MIN_VALUE;
}
state = STATE_SIGN;
p += 2;
break;
case STATE_GMT:
if (p > hi - 2 || !Chars.equalsIgnoreCase(in, p, p + 2, "mt", 0, 2)) {
return Long.MIN_VALUE;
}
state = STATE_SIGN;
p += 2;
break;
case STATE_SIGN:
switch (c) {
case '+':
negative = false;
break;
case '-':
negative = true;
break;
default:
return Long.MIN_VALUE;
}
p++;
state = STATE_HOUR;
break;
case STATE_HOUR:
if (isDigit(c) && p < hi - 1) {
hour = Numbers.parseInt(in, p, p + 2);
} else {
return Long.MIN_VALUE;
}
state = STATE_DELIM;
p += 2;
break;
case STATE_DELIM:
if (c == ':') {
state = STATE_MINUTE;
p++;
} else if (isDigit(c)) {
state = STATE_MINUTE;
} else {
return Long.MIN_VALUE;
}
break;
case STATE_MINUTE:
if (isDigit(c) && p < hi - 1) {
minute = Numbers.parseInt(in, p, p + 2);
} else {
return Long.MIN_VALUE;
}
p += 2;
state = STATE_END;
break OUT;
default:
throw new IllegalStateException("Unexpected state");
}
}
} catch (NumericException e) {
return Long.MIN_VALUE;
}
switch (state) {
case STATE_DELIM:
case STATE_END:
if (hour > 23 || minute > 59) {
return Long.MIN_VALUE;
}
int min = hour * 60 + minute;
long r = ((long) (p - lo) << 32) | min;
return negative ? -r : r;
default:
return Long.MIN_VALUE;
}
}
public static long previousOrSameDayOfWeek(long millis, int dow) {
int thisDow = getDayOfWeek(millis);
if (thisDow == dow) {
return millis;
}
if (thisDow < dow) {
return millis - (7 + (thisDow - dow)) * DAY_MILLIS;
} else {
return millis - (thisDow - dow) * DAY_MILLIS;
}
}
public static long toMillis(int y, int m, int d, int h, int mi) {
return toMillis(y, isLeapYear(y), m, d, h, mi);
}
public static long toMillis(int y, boolean leap, int m, int d, int h, int mi) {
return yearMillis(y, leap) + monthOfYearMillis(m, leap) + (d - 1) * DAY_MILLIS + h * HOUR_MILLIS + mi * MINUTE_MILLIS;
}
public static String toString(long millis) {
StringSink sink = new StringSink();
DateFormatUtils.appendDateTime(sink, millis);
return sink.toString();
}
/**
* Calculated start of year in millis. For example of year 2008 this is
* equivalent to parsing "2008-01-01T00:00:00.000Z", except this method is faster.
*
* @param year the year
* @param leap true if give year is leap year
* @return millis for start of year.
*/
public static long yearMillis(int year, boolean leap) {
int leapYears = year / 100;
if (year < 0) {
leapYears = ((year + 3) >> 2) - leapYears + ((leapYears + 3) >> 2) - 1;
} else {
leapYears = (year >> 2) - leapYears + (leapYears >> 2);
if (leap) {
leapYears
}
}
return (year * 365L + (leapYears - DAYS_0000_TO_1970)) * DAY_MILLIS;
}
private static boolean isDigit(char c) {
return c > BEFORE_ZERO && c < AFTER_NINE;
}
private static long getTime(long millis) {
return millis < 0 ? DAY_MILLIS - 1 + (millis % DAY_MILLIS) : millis % DAY_MILLIS;
}
private static long toMillis(int y, int m, int d) {
boolean l = isLeapYear(y);
return yearMillis(y, l) + monthOfYearMillis(m, l) + (d - 1) * DAY_MILLIS;
}
static {
long minSum = 0;
long maxSum = 0;
for (int i = 0; i < 11; i++) {
minSum += DAYS_PER_MONTH[i] * DAY_MILLIS;
MIN_MONTH_OF_YEAR_MILLIS[i + 1] = minSum;
maxSum += getDaysPerMonth(i + 1, true) * DAY_MILLIS;
MAX_MONTH_OF_YEAR_MILLIS[i + 1] = maxSum;
}
}
}
|
package hudson.util;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
/**
* Hex-binary encoding stream.
*
* TODO: use base64binary.
*
* @author Kohsuke Kawaguchi
* @see DecodingStream
*/
public class EncodingStream extends FilterOutputStream {
public EncodingStream(OutputStream out) {
super(out);
}
@Override
public void write(int b) throws IOException {
if (b < 0) b += 256;
out.write(chars.charAt(b/16));
out.write(chars.charAt(b%16));
}
private static final String chars = "0123456789ABCDEF";
}
|
package org.cache2k.impl;
import org.cache2k.BulkCacheSource;
import org.cache2k.CacheEntry;
import org.cache2k.CacheEntryProcessingException;
import org.cache2k.CacheEntryProcessor;
import org.cache2k.CacheException;
import org.cache2k.CacheManager;
import org.cache2k.CacheMisconfigurationException;
import org.cache2k.CacheWriter;
import org.cache2k.ClosableIterator;
import org.cache2k.EntryExpiryCalculator;
import org.cache2k.EntryProcessingResult;
import org.cache2k.ExceptionExpiryCalculator;
import org.cache2k.ExceptionPropagator;
import org.cache2k.ExperimentalBulkCacheSource;
import org.cache2k.Cache;
import org.cache2k.CacheConfig;
import org.cache2k.FetchCompletedListener;
import org.cache2k.RefreshController;
import org.cache2k.StorageConfiguration;
import org.cache2k.ValueWithExpiryTime;
import org.cache2k.impl.threading.Futures;
import org.cache2k.impl.threading.LimitedPooledExecutor;
import org.cache2k.impl.timer.GlobalTimerService;
import org.cache2k.impl.timer.TimerService;
import org.cache2k.impl.util.ThreadDump;
import org.cache2k.CacheSourceWithMetaInfo;
import org.cache2k.CacheSource;
import org.cache2k.PropagatedCacheException;
import org.cache2k.storage.PurgeableStorage;
import org.cache2k.storage.StorageEntry;
import org.cache2k.impl.util.Log;
import org.cache2k.impl.util.TunableConstants;
import org.cache2k.impl.util.TunableFactory;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.security.SecureRandom;
import java.util.AbstractList;
import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Random;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static org.cache2k.impl.util.Util.*;
/**
* Foundation for all cache variants. All common functionality is in here.
* For a (in-memory) cache we need three things: a fast hash table implementation, an
* LRU list (a simple double linked list), and a fast timer.
* The variants implement different eviction strategies.
*
* <p>Locking: The cache has a single structure lock obtained via {@link #lock} and also
* locks on each entry for operations on it. Though, mutation operations that happen on a
* single entry get serialized.
*
* @author Jens Wilke; created: 2013-07-09
*/
@SuppressWarnings({"unchecked", "SynchronizationOnLocalVariableOrMethodParameter"})
public abstract class BaseCache<E extends Entry, K, T>
implements Cache<K, T>, CanCheckIntegrity, Iterable<CacheEntry<K, T>>, StorageAdapter.Parent {
static final Random SEED_RANDOM = new Random(new SecureRandom().nextLong());
static int cacheCnt = 0;
protected static final Tunable TUNABLE = TunableFactory.get(Tunable.class);
/**
* Instance of expiry calculator that extracts the expiry time from the value.
*/
final static EntryExpiryCalculator<?, ValueWithExpiryTime> ENTRY_EXPIRY_CALCULATOR_FROM_VALUE = new
EntryExpiryCalculator<Object, ValueWithExpiryTime>() {
@Override
public long calculateExpiryTime(
Object _key, ValueWithExpiryTime _value, long _fetchTime,
CacheEntry<Object, ValueWithExpiryTime> _oldEntry) {
return _value.getCacheExpiryTime();
}
};
final static ExceptionPropagator DEFAULT_EXCEPTION_PROPAGATOR = new ExceptionPropagator() {
@Override
public void propagateException(String _additionalMessage, Throwable _originalException) {
throw new PropagatedCacheException(_additionalMessage, _originalException);
}
};
protected int hashSeed;
{
if (TUNABLE.disableHashRandomization) {
hashSeed = TUNABLE.hashSeed;
} else {
hashSeed = SEED_RANDOM.nextInt();
}
}
/** Maximum amount of elements in cache */
protected int maxSize = 5000;
protected String name;
protected CacheManagerImpl manager;
protected CacheSourceWithMetaInfo<K, T> source;
/** Statistics */
/** Time in milliseconds we keep an element */
protected long maxLinger = 10 * 60 * 1000;
protected long exceptionMaxLinger = 1 * 60 * 1000;
protected EntryExpiryCalculator<K, T> entryExpiryCalculator;
protected ExceptionExpiryCalculator<K> exceptionExpiryCalculator;
protected Info info;
protected long clearedTime = 0;
protected long startedTime;
protected long touchedTime;
protected int timerCancelCount = 0;
protected long keyMutationCount = 0;
protected long putCnt = 0;
protected long putButExpiredCnt = 0;
protected long putNewEntryCnt = 0;
protected long removedCnt = 0;
/** Number of entries removed by clear. */
protected long clearedCnt = 0;
protected long expiredKeptCnt = 0;
protected long expiredRemoveCnt = 0;
protected long evictedCnt = 0;
protected long refreshCnt = 0;
protected long suppressedExceptionCnt = 0;
protected long fetchExceptionCnt = 0;
/* that is a miss, but a hit was already counted. */
protected long peekHitNotFreshCnt = 0;
/* no heap hash hit */
protected long peekMissCnt = 0;
protected long fetchCnt = 0;
protected long fetchButHitCnt = 0;
protected long bulkGetCnt = 0;
protected long fetchMillis = 0;
protected long refreshHitCnt = 0;
protected long newEntryCnt = 0;
/**
* Entries created for processing via invoke, but no operation happened on it.
*/
protected long invokeNewEntryCnt = 0;
/**
* Loaded from storage, but the entry was not fresh and cannot be returned.
*/
protected long loadNonFreshCnt = 0;
/**
* Entry was loaded from storage and fresh.
*/
protected long loadHitCnt = 0;
/**
* Separate counter for loaded entries that needed a fetch.
*/
protected long loadNonFreshAndFetchedCnt;
protected long refreshSubmitFailedCnt = 0;
/**
* An exception that should not have happened and was not thrown to the
* application. Only used for the refresh thread yet.
*/
protected long internalExceptionCnt = 0;
/**
* Needed to correct the counter invariants, because during eviction the entry
* might be removed from the replacement list, but still in the hash.
*/
protected int evictedButInHashCnt = 0;
/**
* Storage did not contain the requested entry.
*/
protected long loadMissCnt = 0;
/**
* A newly inserted entry was removed by the eviction without the fetch to complete.
*/
protected long virginEvictCnt = 0;
protected int maximumBulkFetchSize = 100;
/**
* Structure lock of the cache. Every operation that needs a consistent structure
* of the cache or modifies it needs to synchronize on this. Since this is a global
* lock, locking on it should be avoided and any operation under the lock should be
* quick.
*/
protected final Object lock = new Object();
protected CacheRefreshThreadPool refreshPool;
protected Hash<E> mainHashCtrl;
protected E[] mainHash;
protected Hash<E> refreshHashCtrl;
protected E[] refreshHash;
protected ExperimentalBulkCacheSource<K, T> experimentalBulkCacheSource;
protected BulkCacheSource<K, T> bulkCacheSource;
protected Timer timer;
/** Stuff that we need to wait for before shutdown may complete */
protected Futures.WaitForAllFuture<?> shutdownWaitFuture;
protected boolean shutdownInitiated = false;
/**
* Flag during operation that indicates, that the cache is full and eviction needs
* to be done. Eviction is only allowed to happen after an entry is fetched, so
* at the end of an cache operation that increased the entry count we check whether
* something needs to be evicted.
*/
protected boolean evictionNeeded = false;
protected Class keyType;
protected Class valueType;
protected CacheWriter<K, T> writer;
protected ExceptionPropagator exceptionPropagator = DEFAULT_EXCEPTION_PROPAGATOR;
protected StorageAdapter storage;
protected TimerService timerService = GlobalTimerService.getInstance();
/**
* Stops creation of new entries when clear is ongoing.
*/
protected boolean waitForClear = false;
private int featureBits = 0;
private static final int SHARP_TIMEOUT_FEATURE = 1;
private static final int KEEP_AFTER_EXPIRED = 2;
private static final int SUPPRESS_EXCEPTIONS = 4;
private static final int NULL_VALUE_SUPPORT = 8;
protected final boolean hasSharpTimeout() {
return (featureBits & SHARP_TIMEOUT_FEATURE) > 0;
}
protected final boolean hasKeepAfterExpired() {
return (featureBits & KEEP_AFTER_EXPIRED) > 0;
}
protected final boolean hasNullValueSupport() {
return (featureBits & NULL_VALUE_SUPPORT) > 0;
}
protected final boolean hasSuppressExceptions() {
return (featureBits & SUPPRESS_EXCEPTIONS) > 0;
}
protected final void setFeatureBit(int _bitmask, boolean _flag) {
if (_flag) {
featureBits |= _bitmask;
} else {
featureBits &= ~_bitmask;
}
}
/**
* Enabling background refresh means also serving expired values.
*/
protected final boolean hasBackgroundRefreshAndServesExpiredValues() {
return refreshPool != null;
}
/**
* Returns name of the cache with manager name.
*/
protected String getCompleteName() {
if (manager != null) {
return manager.getName() + ":" + name;
}
return name;
}
/**
* Normally a cache itself logs nothing, so just construct when needed.
*/
protected Log getLog() {
return
Log.getLog(Cache.class.getName() + '/' + getCompleteName());
}
@Override
public void resetStorage(StorageAdapter _from, StorageAdapter to) {
synchronized (lock) {
storage = to;
}
}
/** called via reflection from CacheBuilder */
public void setCacheConfig(CacheConfig c) {
valueType = c.getValueType();
keyType = c.getKeyType();
if (name != null) {
throw new IllegalStateException("already configured");
}
setName(c.getName());
maxSize = c.getMaxSize();
if (c.getHeapEntryCapacity() >= 0) {
maxSize = c.getHeapEntryCapacity();
}
if (c.isBackgroundRefresh()) {
refreshPool = CacheRefreshThreadPool.getInstance();
}
long _expiryMillis = c.getExpiryMillis();
if (_expiryMillis == Long.MAX_VALUE || _expiryMillis < 0) {
maxLinger = -1;
} else if (_expiryMillis >= 0) {
maxLinger = _expiryMillis;
}
long _exceptionExpiryMillis = c.getExceptionExpiryMillis();
if (_exceptionExpiryMillis == -1) {
if (maxLinger == -1) {
exceptionMaxLinger = -1;
} else {
exceptionMaxLinger = maxLinger / 10;
}
} else {
exceptionMaxLinger = _exceptionExpiryMillis;
}
setFeatureBit(KEEP_AFTER_EXPIRED, c.isKeepDataAfterExpired());
setFeatureBit(SHARP_TIMEOUT_FEATURE, c.isSharpExpiry());
setFeatureBit(SUPPRESS_EXCEPTIONS, c.isSuppressExceptions());
/*
if (c.isPersistent()) {
storage = new PassingStorageAdapter();
}
-*/
List<StorageConfiguration> _stores = c.getStorageModules();
if (_stores.size() == 1) {
StorageConfiguration cfg = _stores.get(0);
if (cfg.getEntryCapacity() < 0) {
cfg.setEntryCapacity(c.getMaxSize());
}
storage = new PassingStorageAdapter(this, c, _stores.get(0));
} else if (_stores.size() > 1) {
throw new UnsupportedOperationException("no aggregation support yet");
}
if (ValueWithExpiryTime.class.isAssignableFrom(c.getValueType()) &&
entryExpiryCalculator == null) {
entryExpiryCalculator =
(EntryExpiryCalculator<K, T>)
ENTRY_EXPIRY_CALCULATOR_FROM_VALUE;
}
}
public void setEntryExpiryCalculator(EntryExpiryCalculator<K, T> v) {
entryExpiryCalculator = v;
}
public void setExceptionExpiryCalculator(ExceptionExpiryCalculator<K> v) {
exceptionExpiryCalculator = v;
}
/** called via reflection from CacheBuilder */
public void setRefreshController(final RefreshController<T> lc) {
entryExpiryCalculator = new EntryExpiryCalculator<K, T>() {
@Override
public long calculateExpiryTime(K _key, T _value, long _fetchTime, CacheEntry<K, T> _oldEntry) {
if (_oldEntry != null) {
return lc.calculateNextRefreshTime(_oldEntry.getValue(), _value, _oldEntry.getLastModification(), _fetchTime);
} else {
return lc.calculateNextRefreshTime(null, _value, 0L, _fetchTime);
}
}
};
}
public void setExceptionPropagator(ExceptionPropagator ep) {
exceptionPropagator = ep;
}
@SuppressWarnings("unused")
public void setSource(CacheSourceWithMetaInfo<K, T> eg) {
source = eg;
}
public void setWriter(CacheWriter<K, T> w) {
writer = w;
}
@SuppressWarnings("unused")
public void setSource(final CacheSource<K, T> g) {
if (g != null) {
source = new CacheSourceWithMetaInfo<K, T>() {
@Override
public T get(K key, long _currentTime, T _previousValue, long _timeLastFetched) throws Throwable {
return g.get(key);
}
};
}
}
@SuppressWarnings("unused")
public void setExperimentalBulkCacheSource(ExperimentalBulkCacheSource<K, T> g) {
experimentalBulkCacheSource = g;
if (source == null) {
source = new CacheSourceWithMetaInfo<K, T>() {
@Override
public T get(K key, long _currentTime, T _previousValue, long _timeLastFetched) throws Throwable {
K[] ka = (K[]) Array.newInstance(keyType, 1);
ka[0] = key;
T[] ra = (T[]) Array.newInstance(valueType, 1);
BitSet _fetched = new BitSet(1);
experimentalBulkCacheSource.getBulk(ka, ra, _fetched, 0, 1);
return ra[0];
}
};
}
}
public void setBulkCacheSource(BulkCacheSource<K, T> s) {
bulkCacheSource = s;
if (source == null) {
source = new CacheSourceWithMetaInfo<K, T>() {
@Override
public T get(final K key, final long _currentTime, final T _previousValue, final long _timeLastFetched) throws Throwable {
final CacheEntry<K, T> entry = new CacheEntry<K, T>() {
@Override
public K getKey() {
return key;
}
@Override
public T getValue() {
return _previousValue;
}
@Override
public Throwable getException() {
return null;
}
@Override
public long getLastModification() {
return _timeLastFetched;
}
};
List<CacheEntry<K, T>> _entryList = new AbstractList<CacheEntry<K, T>>() {
@Override
public CacheEntry<K, T> get(int index) {
return entry;
}
@Override
public int size() {
return 1;
}
};
return bulkCacheSource.getValues(_entryList, _currentTime).get(0);
}
};
}
}
/**
* Set the name and configure a logging, used within cache construction.
*/
public void setName(String n) {
if (n == null) {
n = this.getClass().getSimpleName() + "#" + cacheCnt++;
}
name = n;
}
/**
* Set the time in seconds after which the cache does an refresh of the
* element. -1 means the element will be hold forever.
* 0 means the element will not be cached at all.
*/
public void setExpirySeconds(int s) {
if (s < 0 || s == Integer.MAX_VALUE) {
maxLinger = -1;
return;
}
maxLinger = s * 1000;
}
public String getName() {
return name;
}
public void setCacheManager(CacheManagerImpl cm) {
manager = cm;
}
public StorageAdapter getStorage() { return storage; }
public Class<?> getKeyType() { return keyType; }
public Class<?> getValueType() { return valueType; }
/**
* Registers the cache in a global set for the clearAllCaches function and
* registers it with the resource monitor.
*/
public void init() {
synchronized (lock) {
if (name == null) {
name = "" + cacheCnt++;
}
if (storage == null && maxSize == 0) {
throw new IllegalArgumentException("maxElements must be >0");
}
if (storage != null) {
bulkCacheSource = null;
storage.open();
}
initializeHeapCache();
initTimer();
if (refreshPool != null &&
source == null) {
throw new CacheMisconfigurationException("backgroundRefresh, but no source");
}
if (refreshPool != null && timer == null) {
if (maxLinger == 0) {
getLog().warn("Background refresh is enabled, but elements are fetched always. Disable background refresh!");
} else {
getLog().warn("Background refresh is enabled, but elements are eternal. Disable background refresh!");
}
refreshPool.destroy();
refreshPool = null;
}
}
}
boolean isNeedingTimer() {
return
maxLinger > 0 || entryExpiryCalculator != null ||
exceptionMaxLinger > 0 || exceptionExpiryCalculator != null;
}
/**
* Either add a timer or remove the timer if needed or not needed.
*/
private void initTimer() {
if (isNeedingTimer()) {
if (timer == null) {
timer = new Timer(name, true);
}
} else {
if (timer != null) {
timer.cancel();
timer = null;
}
}
}
/**
* Clear may be called during operation, e.g. to reset all the cache content. We must make sure
* that there is no ongoing operation when we send the clear to the storage. That is because the
* storage implementation has a guarantee that there is only one storage operation ongoing for
* one entry or key at any time. Clear, of course, affects all entries.
*/
private void processClearWithStorage() {
StorageClearTask t = new StorageClearTask();
boolean _untouchedHeapCache;
synchronized (lock) {
checkClosed();
waitForClear = true;
_untouchedHeapCache = touchedTime == clearedTime && getLocalSize() == 0;
if (!storage.checkStorageStillDisconnectedForClear()) {
t.allLocalEntries = iterateAllHeapEntries();
t.allLocalEntries.setStopOnClear(false);
}
t.storage = storage;
t.storage.disconnectStorageForClear();
}
try {
if (_untouchedHeapCache) {
FutureTask<Void> f = new FutureTask<Void>(t);
updateShutdownWaitFuture(f);
f.run();
} else {
updateShutdownWaitFuture(manager.getThreadPool().execute(t));
}
} catch (Exception ex) {
throw new CacheStorageException(ex);
}
synchronized (lock) {
if (isClosed()) { throw new CacheClosedException(); }
clearLocalCache();
waitForClear = false;
lock.notifyAll();
}
}
protected void updateShutdownWaitFuture(Future<?> f) {
synchronized (lock) {
if (shutdownWaitFuture == null || shutdownWaitFuture.isDone()) {
shutdownWaitFuture = new Futures.WaitForAllFuture(f);
} else {
shutdownWaitFuture.add((Future) f);
}
}
}
class StorageClearTask implements LimitedPooledExecutor.NeverRunInCallingTask<Void> {
ClosableConcurrentHashEntryIterator<Entry> allLocalEntries;
StorageAdapter storage;
@Override
public Void call() {
try {
if (allLocalEntries != null) {
waitForEntryOperations();
}
storage.clearAndReconnect();
storage = null;
return null;
} catch (Throwable t) {
if (allLocalEntries != null) {
allLocalEntries.close();
}
getLog().warn("clear exception, when signalling storage", t);
storage.disable(t);
throw new CacheStorageException(t);
}
}
private void waitForEntryOperations() {
Iterator<Entry> it = allLocalEntries;
while (it.hasNext()) {
Entry e = it.next();
synchronized (e) { }
}
}
}
protected void checkClosed() {
if (isClosed()) {
throw new CacheClosedException();
}
while (waitForClear) {
try {
lock.wait();
} catch (InterruptedException ignore) { }
}
}
public final void clear() {
if (storage != null) {
processClearWithStorage();
return;
}
synchronized (lock) {
checkClosed();
clearLocalCache();
}
}
protected final void clearLocalCache() {
iterateAllEntriesRemoveAndCancelTimer();
clearedCnt += getLocalSize();
initializeHeapCache();
clearedTime = System.currentTimeMillis();
touchedTime = clearedTime;
}
protected void iterateAllEntriesRemoveAndCancelTimer() {
Iterator<Entry> it = iterateAllHeapEntries();
int _count = 0;
while (it.hasNext()) {
Entry e = it.next();
e.removedFromList();
cancelExpiryTimer(e);
_count++;
}
}
protected void initializeHeapCache() {
if (mainHashCtrl != null) {
mainHashCtrl.cleared();
refreshHashCtrl.cleared();
}
mainHashCtrl = new Hash<E>();
refreshHashCtrl = new Hash<E>();
mainHash = mainHashCtrl.init((Class<E>) newEntry().getClass());
refreshHash = refreshHashCtrl.init((Class<E>) newEntry().getClass());
if (startedTime == 0) {
startedTime = System.currentTimeMillis();
}
if (timer != null) {
timer.cancel();
timer = null;
initTimer();
}
}
public void clearTimingStatistics() {
synchronized (lock) {
fetchCnt = 0;
fetchMillis = 0;
}
}
/**
* Preparation for shutdown. Cancel all pending timer jobs e.g. for
* expiry/refresh or flushing the storage.
*/
Future<Void> cancelTimerJobs() {
synchronized (lock) {
if (timer != null) {
timer.cancel();
}
Future<Void> _waitFuture = new Futures.BusyWaitFuture<Void>() {
@Override
public boolean isDone() {
synchronized (lock) {
return getFetchesInFlight() == 0;
}
}
};
if (storage != null) {
Future<Void> f = storage.cancelTimerJobs();
if (f != null) {
_waitFuture = new Futures.WaitForAllFuture(_waitFuture, f);
}
}
return _waitFuture;
}
}
public void purge() {
if (storage != null) {
storage.purge();
}
}
public void flush() {
if (storage != null) {
storage.flush();
}
}
@Override
public boolean isClosed() {
return shutdownInitiated;
}
@Override
public void destroy() {
close();
}
@Override
public void close() {
synchronized (lock) {
if (shutdownInitiated) {
return;
}
shutdownInitiated = true;
}
Future<Void> _await = cancelTimerJobs();
try {
_await.get(TUNABLE.waitForTimerJobsSeconds, TimeUnit.SECONDS);
} catch (TimeoutException ex) {
int _fetchesInFlight;
synchronized (lock) {
_fetchesInFlight = getFetchesInFlight();
}
if (_fetchesInFlight > 0) {
getLog().warn(
"Fetches still in progress after " +
TUNABLE.waitForTimerJobsSeconds + " seconds. " +
"fetchesInFlight=" + _fetchesInFlight);
} else {
getLog().warn(
"timeout waiting for timer jobs termination" +
" (" + TUNABLE.waitForTimerJobsSeconds + " seconds)", ex);
getLog().warn("Thread dump:\n" + ThreadDump.generateThredDump());
}
getLog().warn("State: " + toString());
} catch (Exception ex) {
getLog().warn("exception waiting for timer jobs termination", ex);
}
synchronized (lock) {
mainHashCtrl.close();
refreshHashCtrl.close();
}
try {
Future<?> _future = shutdownWaitFuture;
if (_future != null) {
_future.get();
}
} catch (Exception ex) {
throw new CacheException(ex);
}
Future<Void> _waitForStorage = null;
if (storage != null) {
_waitForStorage = storage.shutdown();
}
if (_waitForStorage != null) {
try {
_waitForStorage.get();
} catch (Exception ex) {
StorageAdapter.rethrow("shutdown", ex);
}
}
synchronized (lock) {
storage = null;
}
synchronized (lock) {
if (timer != null) {
timer.cancel();
timer = null;
}
if (refreshPool != null) {
refreshPool.destroy();
refreshPool = null;
}
mainHash = refreshHash = null;
source = null;
if (manager != null) {
manager.cacheDestroyed(this);
manager = null;
}
}
}
@Override
public void removeAll() {
ClosableIterator<E> it;
if (storage == null) {
synchronized (lock) {
it = new IteratorFilterFresh((ClosableIterator<E>) iterateAllHeapEntries());
}
} else {
it = (ClosableIterator<E>) storage.iterateAll();
}
while (it.hasNext()) {
E e = it.next();
remove((K) e.getKey());
}
}
@Override
public ClosableIterator<CacheEntry<K, T>> iterator() {
if (storage == null) {
synchronized (lock) {
return new IteratorFilterEntry2Entry((ClosableIterator<E>) iterateAllHeapEntries(), true);
}
} else {
return new IteratorFilterEntry2Entry((ClosableIterator<E>) storage.iterateAll(), false);
}
}
/**
* Filter out non valid entries and wrap each entry with a cache
* entry object.
*/
class IteratorFilterEntry2Entry implements ClosableIterator<CacheEntry<K, T>> {
ClosableIterator<E> iterator;
E entry;
CacheEntry<K, T> lastEntry;
boolean filter = true;
IteratorFilterEntry2Entry(ClosableIterator<E> it) { iterator = it; }
IteratorFilterEntry2Entry(ClosableIterator<E> it, boolean _filter) {
iterator = it;
filter = _filter;
}
/**
* Between hasNext() and next() an entry may be evicted or expired.
* In practise we have to deliver a next entry if we return hasNext() with
* true, furthermore, there should be no big gap between the calls to
* hasNext() and next().
*/
@Override
public boolean hasNext() {
if (entry != null) {
return true;
}
if (iterator == null) {
return false;
}
while (iterator.hasNext()) {
E e = iterator.next();
if (filter) {
if (e.hasFreshData()) {
entry = e;
return true;
}
} else {
entry = e;
return true;
}
}
entry = null;
close();
return false;
}
@Override
public void close() {
if (iterator != null) {
iterator.close();
iterator = null;
}
}
@Override
public CacheEntry<K, T> next() {
if (entry == null && !hasNext()) {
throw new NoSuchElementException("not available");
}
recordHitLocked(entry);
lastEntry = returnEntry(entry);
entry = null;
return lastEntry;
}
@Override
public void remove() {
if (lastEntry == null) {
throw new IllegalStateException("hasNext() / next() not called or end of iteration reached");
}
BaseCache.this.remove((K) lastEntry.getKey());
}
}
/**
* Filter out non valid entries and wrap each entry with a cache
* entry object.
*/
class IteratorFilterFresh implements ClosableIterator<E> {
ClosableIterator<E> iterator;
E entry;
CacheEntry<K, T> lastEntry;
boolean filter = true;
IteratorFilterFresh(ClosableIterator<E> it) { iterator = it; }
/**
* Between hasNext() and next() an entry may be evicted or expired.
* In practise we have to deliver a next entry if we return hasNext() with
* true, furthermore, there should be no big gap between the calls to
* hasNext() and next().
*/
@Override
public boolean hasNext() {
if (entry != null) {
return true;
}
if (iterator == null) {
return false;
}
while (iterator.hasNext()) {
E e = iterator.next();
if (e.hasFreshData()) {
entry = e;
return true;
}
}
entry = null;
close();
return false;
}
@Override
public void close() {
if (iterator != null) {
iterator.close();
iterator = null;
}
}
@Override
public E next() {
if (entry == null && !hasNext()) {
throw new NoSuchElementException("not available");
}
E tmp = entry;
entry = null;
return tmp;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
protected static void removeFromList(final Entry e) {
e.prev.next = e.next;
e.next.prev = e.prev;
e.removedFromList();
}
protected static void insertInList(final Entry _head, final Entry e) {
e.prev = _head;
e.next = _head.next;
e.next.prev = e;
_head.next = e;
}
protected static final int getListEntryCount(final Entry _head) {
Entry e = _head.next;
int cnt = 0;
while (e != _head) {
cnt++;
if (e == null) {
return -cnt;
}
e = e.next;
}
return cnt;
}
protected static final <E extends Entry> void moveToFront(final E _head, final E e) {
removeFromList(e);
insertInList(_head, e);
}
protected static final <E extends Entry> E insertIntoTailCyclicList(final E _head, final E e) {
if (_head == null) {
return (E) e.shortCircuit();
}
e.next = _head;
e.prev = _head.prev;
_head.prev = e;
e.prev.next = e;
return _head;
}
/**
* Insert X into A B C, yields: A X B C.
*/
protected static final <E extends Entry> E insertAfterHeadCyclicList(final E _head, final E e) {
if (_head == null) {
return (E) e.shortCircuit();
}
e.prev = _head;
e.next = _head.next;
_head.next.prev = e;
_head.next = e;
return _head;
}
/** Insert element at the head of the list */
protected static final <E extends Entry> E insertIntoHeadCyclicList(final E _head, final E e) {
if (_head == null) {
return (E) e.shortCircuit();
}
e.next = _head;
e.prev = _head.prev;
_head.prev.next = e;
_head.prev = e;
return e;
}
protected static <E extends Entry> E removeFromCyclicList(final E _head, E e) {
if (e.next == e) {
e.removedFromList();
return null;
}
Entry _eNext = e.next;
e.prev.next = _eNext;
e.next.prev = e.prev;
e.removedFromList();
return e == _head ? (E) _eNext : _head;
}
protected static Entry removeFromCyclicList(final Entry e) {
Entry _eNext = e.next;
e.prev.next = _eNext;
e.next.prev = e.prev;
e.removedFromList();
return _eNext == e ? null : _eNext;
}
protected static int getCyclicListEntryCount(Entry e) {
if (e == null) { return 0; }
final Entry _head = e;
int cnt = 0;
do {
cnt++;
e = e.next;
if (e == null) {
return -cnt;
}
} while (e != _head);
return cnt;
}
protected static boolean checkCyclicListIntegrity(Entry e) {
if (e == null) { return true; }
Entry _head = e;
do {
if (e.next == null) {
return false;
}
if (e.next.prev == null) {
return false;
}
if (e.next.prev != e) {
return false;
}
e = e.next;
} while (e != _head);
return true;
}
/**
* Record an entry hit.
*/
protected abstract void recordHit(E e);
/**
* New cache entry, put it in the replacement algorithm structure
*/
protected abstract void insertIntoReplacementList(E e);
/**
* Entry object factory. Return an entry of the proper entry subtype for
* the replacement/eviction algorithm.
*/
protected abstract E newEntry();
/**
* Find an entry that should be evicted. Called within structure lock.
* After doing some checks the cache will call {@link #removeEntryFromReplacementList(Entry)}
* if this entry will be really evicted. Pinned entries may be skipped. A
* good eviction algorithm returns another candidate on sequential calls, even
* if the candidate was not removed.
*
* <p/>Rationale: Within the structure lock we can check for an eviction candidate
* and may remove it from the list. However, we cannot process additional operations or
* events which affect the entry. For this, we need to acquire the lock on the entry
* first.
*/
protected abstract E findEvictionCandidate();
protected void removeEntryFromReplacementList(E e) {
removeFromList(e);
}
/**
* Check whether we have an entry in the ghost table
* remove it from ghost and insert it into the replacement list.
* null if nothing there. This may also do an optional eviction
* if the size limit of the cache is reached, because some replacement
* algorithms (ARC) do this together.
*/
protected E checkForGhost(K key, int hc) { return null; }
/**
* Implement unsynchronized lookup if it is supported by the eviction.
* If a null is returned the lookup is redone synchronized.
*/
protected E lookupEntryUnsynchronized(K key, int hc) { return null; }
protected E lookupEntryUnsynchronizedNoHitRecord(K key, int hc) { return null; }
protected void recordHitLocked(E e) {
synchronized (lock) {
recordHit(e);
}
}
@Override
public T get(K key) {
return (T) returnValue(getEntryInternal(key));
}
/**
* Wrap entry in a separate object instance. We can return the entry directly, however we lock on
* the entry object.
*/
protected CacheEntry<K, T> returnEntry(final Entry<E, K, T> e) {
if (e == null) {
return null;
}
synchronized (e) {
final K _key = e.getKey();
final T _value = e.getValue();
final Throwable _exception = e.getException();
final long _lastModification = e.getLastModification();
return returnCacheEntry(_key, _value, _exception, _lastModification);
}
}
public String getEntryState(K key) {
E e = getEntryInternal(key);
return generateEntryStateString(e);
}
private String generateEntryStateString(E e) {
synchronized (e) {
String _timerState = "n/a";
if (e.task != null) {
_timerState = "<unavailable>";
try {
Field f = TimerTask.class.getDeclaredField("state");
f.setAccessible(true);
int _state = f.getInt(e.task);
_timerState = _state + "";
} catch (Exception x) {
_timerState = x.toString();
}
}
return
"Entry{" + System.identityHashCode(e) + "}, " +
"keyIdentityHashCode=" + System.identityHashCode(e.key) + ", " +
"valueIdentityHashCode=" + System.identityHashCode(e.value) + ", " +
"keyHashCode" + e.key.hashCode() + ", " +
"keyModifiedHashCode=" + e.hashCode + ", " +
"keyMutation=" + (modifiedHash(e.key.hashCode()) != e.hashCode) + ", " +
"modified=" + e.getLastModification() + ", " +
"nextRefreshTime(with state)=" + e.nextRefreshTime + ", " +
"hasTimer=" + (e.task != null ? "true" : "false") + ", " +
"timerState=" + _timerState;
}
}
private CacheEntry<K, T> returnCacheEntry(final K _key, final T _value, final Throwable _exception, final long _lastModification) {
CacheEntry<K, T> ce = new CacheEntry<K, T>() {
@Override
public K getKey() {
return _key;
}
@Override
public T getValue() {
return _value;
}
@Override
public Throwable getException() {
return _exception;
}
@Override
public long getLastModification() {
return _lastModification;
}
@Override
public String toString() {
return "CacheEntry(" +
"key=" + getKey() +
((getException() != null) ? ", exception=" + getException() + ", " : ", value=" + getValue()) +
", updated=" + formatMillis(getLastModification());
}
};
return ce;
}
@Override
public CacheEntry<K, T> getEntry(K key) {
return returnEntry(getEntryInternal(key));
}
protected E getEntryInternal(K key) {
long _previousNextRefreshTime;
E e;
for (;;) {
e = lookupOrNewEntrySynchronized(key);
if (e.hasFreshData()) {
return e;
}
synchronized (e) {
e.waitForFetch();
if (e.hasFreshData()) {
return e;
}
if (e.isRemovedState()) {
continue;
}
_previousNextRefreshTime = e.startFetch();
break;
}
}
boolean _finished = false;
try {
e.finishFetch(fetch(e, _previousNextRefreshTime));
_finished = true;
} finally {
e.ensureFetchAbort(_finished, _previousNextRefreshTime);
}
evictEventually();
return e;
}
/** Always fetch the value from the source. That is a copy of getEntryInternal without fresh checks. */
protected void fetchAndReplace(K key) {
long _previousNextRefreshTime;
E e;
for (;;) {
e = lookupOrNewEntrySynchronized(key);
synchronized (e) {
e.waitForFetch();
if (e.isRemovedState()) {
continue;
}
_previousNextRefreshTime = e.startFetch();
break;
}
}
boolean _finished = false;
try {
e.finishFetch(fetch(e, _previousNextRefreshTime));
_finished = true;
} finally {
e.ensureFetchAbort(_finished, _previousNextRefreshTime);
}
evictEventually();
}
/**
* Insert the storage entry in the heap cache and return it. Used when storage entries
* are queried. We need to check whether the entry is present meanwhile, get the entry lock
* and maybe fetch it from the source. Doubles with {@link #getEntryInternal(Object)}
* except we do not need to retrieve the data from the storage again.
*
* @param _needsFetch if true the entry is fetched from CacheSource when expired.
* @return a cache entry is always returned, however, it may be outdated
*/
protected Entry insertEntryFromStorage(StorageEntry se, boolean _needsFetch) {
int _spinCount = TUNABLE.maximumEntryLockSpins;
for (;;) {
if (_spinCount-- <= 0) { throw new CacheLockSpinsExceededError(); }
E e = lookupOrNewEntrySynchronized((K) se.getKey());
if (e.hasFreshData()) { return e; }
synchronized (e) {
if (!e.isDataValidState()) {
if (e.isRemovedState()) {
continue;
}
if (e.isFetchInProgress()) {
e.waitForFetch();
return e.hasFreshData() ? e : null;
}
e.startFetch();
}
}
boolean _fresh;
boolean _finished = false;
try {
long _nextRefresh = insertEntryFromStorage(se, e, _needsFetch);
_fresh = e.hasFreshData(System.currentTimeMillis(), _nextRefresh);
e.finishFetch(_nextRefresh);
_finished = true;
} finally {
e.ensureFetchAbort(_finished);
}
evictEventually();
return _fresh ? e : null;
}
}
/**
* Insert a cache entry for the given key and run action under the entry
* lock. If the cache entry has fresh data, we do not run the action.
* Called from storage. The entry referenced by the key is expired and
* will be purged.
*/
protected void lockAndRunForPurge(Object key, PurgeableStorage.PurgeAction _action) {
int _spinCount = TUNABLE.maximumEntryLockSpins;
E e;
boolean _virgin;
for (;;) {
if (_spinCount-- <= 0) { throw new CacheLockSpinsExceededError(); }
e = lookupOrNewEntrySynchronized((K) key);
if (e.hasFreshData()) { return; }
synchronized (e) {
e.waitForFetch();
if (e.isDataValidState()) {
return;
}
if (e.isRemovedState()) {
continue;
}
_virgin = e.isVirgin();
e.startFetch();
break;
}
}
boolean _finished = false;
try {
StorageEntry se = _action.checkAndPurge(key);
synchronized (e) {
if (_virgin) {
e.finishFetch(Entry.VIRGIN_STATE);
evictEntryFromHeap(e);
} else {
e.finishFetch(Entry.LOADED_NON_VALID);
evictEntryFromHeap(e);
}
}
_finished = true;
} finally {
e.ensureFetchAbort(_finished);
}
}
protected final void evictEventually() {
int _spinCount = TUNABLE.maximumEvictSpins;
E _previousCandidate = null;
while (evictionNeeded) {
if (_spinCount-- <= 0) { return; }
E e;
synchronized (lock) {
checkClosed();
if (getLocalSize() <= maxSize) {
evictionNeeded = false;
return;
}
e = findEvictionCandidate();
}
boolean _shouldStore;
synchronized (e) {
if (e.isRemovedState()) {
continue;
}
if (e.isPinned()) {
if (e != _previousCandidate) {
_previousCandidate = e;
continue;
} else {
return;
}
}
boolean _storeEvenImmediatelyExpired = hasKeepAfterExpired() && (e.isDataValidState() || e.isExpiredState() || e.nextRefreshTime == Entry.FETCH_NEXT_TIME_STATE);
_shouldStore =
(storage != null) && (_storeEvenImmediatelyExpired || e.hasFreshData());
if (_shouldStore) {
e.startFetch();
} else {
evictEntryFromHeap(e);
}
}
if (_shouldStore) {
try {
storage.evict(e);
} finally {
synchronized (e) {
e.finishFetch(Entry.FETCH_ABORT);
evictEntryFromHeap(e);
}
}
}
}
}
private void evictEntryFromHeap(E e) {
synchronized (lock) {
if (e.isRemovedFromReplacementList()) {
if (removeEntryFromHash(e)) {
evictedButInHashCnt
evictedCnt++;
}
} else {
if (removeEntry(e)) {
evictedCnt++;
}
}
evictionNeeded = getLocalSize() > maxSize;
}
e.notifyAll();
}
/**
* Remove the entry from the hash and the replacement list.
* There is a race condition to catch: The eviction may run
* in a parallel thread and may have already selected this
* entry.
*/
protected boolean removeEntry(E e) {
if (!e.isRemovedFromReplacementList()) {
removeEntryFromReplacementList(e);
}
return removeEntryFromHash(e);
}
@Override
public T peekAndPut(K key, T _value) {
final int hc = modifiedHash(key.hashCode());
boolean _hasFreshData = false;
E e;
long _previousNextRefreshTime;
for (;;) {
e = lookupEntryUnsynchronized(key, hc);
if (e == null) {
synchronized (lock) {
e = lookupEntry(key, hc);
if (e == null) {
e = newEntry(key, hc);
}
}
}
synchronized (e) {
e.waitForFetch();
if (e.isRemovedState()) {
continue;
}
_hasFreshData = e.hasFreshData();
_previousNextRefreshTime = e.startFetch();
break;
}
}
boolean _finished = false;
try {
T _previousValue = null;
if (storage != null && e.isVirgin()) {
long t = fetchWithStorage(e, false, _previousNextRefreshTime);
_hasFreshData = e.hasFreshData(System.currentTimeMillis(), t);
}
if (_hasFreshData) {
_previousValue = (T) e.getValue();
recordHitLocked(e);
} else {
synchronized (lock) {
peekMissCnt++;
}
}
long t = System.currentTimeMillis();
e.finishFetch(insertOnPut(e, _value, t, t, _previousNextRefreshTime));
_finished = true;
return _previousValue;
} finally {
e.ensureFetchAbort(_finished, _previousNextRefreshTime);
}
}
@Override
public T peekAndReplace(K key, T _value) {
final int hc = modifiedHash(key.hashCode());
boolean _hasFreshData = false;
boolean _newEntry = false;
E e;
long _previousNextRefreshTime;
for (;;) {
e = lookupEntryUnsynchronized(key, hc);
if (e == null) {
synchronized (lock) {
e = lookupEntry(key, hc);
if (e == null && storage != null) {
e = newEntry(key, hc);
_newEntry = true;
}
}
}
if (e == null) {
synchronized (lock) {
peekMissCnt++;
}
return null;
}
synchronized (e) {
e.waitForFetch();
if (e.isRemovedState()) {
continue;
}
_hasFreshData = e.hasFreshData();
_previousNextRefreshTime = e.startFetch();
break;
}
}
boolean _finished = false;
try {
if (storage != null && e.isVirgin()) {
long t = fetchWithStorage(e, false, _previousNextRefreshTime);
_hasFreshData = e.hasFreshData(System.currentTimeMillis(), t);
}
long t = System.currentTimeMillis();
if (_hasFreshData) {
recordHitLocked(e);
T _previousValue = (T) e.getValue();
e.finishFetch(insertOnPut(e, _value, t, t, _previousNextRefreshTime));
_finished = true;
return _previousValue;
} else {
synchronized (lock) {
if (_newEntry) {
putNewEntryCnt++;
}
peekMissCnt++;
}
e.finishFetch(Entry.LOADED_NON_VALID);
_finished = true;
return null;
}
} finally {
e.ensureFetchAbort(_finished, _previousNextRefreshTime);
}
}
@Override
public boolean replace(K key, T _newValue) {
return replace(key, false, null, _newValue) == null;
}
@Override
public boolean replace(K key, T _oldValue, T _newValue) {
return replace(key, true, _oldValue, _newValue) == null;
}
public CacheEntry<K, T> replaceOrGet(K key, T _oldValue, T _newValue, CacheEntry<K, T> _dummyEntry) {
E e = replace(key, true, _oldValue, _newValue);
if (e == DUMMY_ENTRY_NO_REPLACE) {
return _dummyEntry;
} else if (e != null) {
return returnEntry(e);
}
return null;
}
final Entry DUMMY_ENTRY_NO_REPLACE = new Entry();
/**
* replace if value matches. if value not matches, return the existing entry or the dummy entry.
*/
protected E replace(K key, boolean _compare, T _oldValue, T _newValue) {
final int hc = modifiedHash(key.hashCode());
long _previousNextRefreshTime;
if (storage == null) {
E e = lookupEntrySynchronized(key);
if (e == null) {
synchronized (lock) {
peekMissCnt++;
}
return (E) DUMMY_ENTRY_NO_REPLACE;
}
synchronized (e) {
e.waitForFetch();
if (e.isRemovedState() || !e.hasFreshData()) {
return (E) DUMMY_ENTRY_NO_REPLACE;
}
if (_compare && !e.equalsValue(_oldValue)) {
return e;
}
_previousNextRefreshTime = e.startFetch();
}
boolean _finished = false;
recordHitLocked(e);
try {
long t = System.currentTimeMillis();
e.finishFetch(insertOnPut(e, _newValue, t, t, _previousNextRefreshTime));
_finished = true;
return null;
} finally {
e.ensureFetchAbort(_finished, _previousNextRefreshTime);
}
}
boolean _hasFreshData = false;
E e;
for (;;) {
e = lookupEntryUnsynchronized(key, hc);
if (e == null) {
synchronized (lock) {
e = lookupEntry(key, hc);
if (e == null) {
e = newEntry(key, hc);
}
}
}
synchronized (e) {
e.waitForFetch();
if (e.isRemovedState()) {
continue;
}
if (!e.hasFreshData()) {
return (E) DUMMY_ENTRY_NO_REPLACE;
}
if (_compare && !e.equalsValue(_oldValue)) {
return e;
}
_previousNextRefreshTime = e.startFetch();
break;
}
}
boolean _finished = false;
try {
if (e.isVirgin()) {
long t = fetchWithStorage(e, false, _previousNextRefreshTime);
_hasFreshData = e.hasFreshData(System.currentTimeMillis(), t);
if (!_hasFreshData) {
e.finishFetch(t);
_finished = true;
return (E) DUMMY_ENTRY_NO_REPLACE;
}
if (_compare && !e.equalsValue(_oldValue)) {
e.finishFetch(t);
_finished = true;
return e;
}
}
long t = System.currentTimeMillis();
e.finishFetch(insertOnPut(e, _newValue, t, t, _previousNextRefreshTime));
_finished = true;
return null;
} finally {
e.ensureFetchAbort(_finished, _previousNextRefreshTime);
}
}
/**
* Return the entry, if it is in the cache, without invoking the
* cache source.
*
* <p>The cache storage is asked whether the entry is present.
* If the entry is not present, this result is cached in the local
* cache.
*/
protected E peekEntryInternal(K key) {
final int hc = modifiedHash(key.hashCode());
long _previousNextRefreshTime;
int _spinCount = TUNABLE.maximumEntryLockSpins;
for (;;) {
if (_spinCount-- <= 0) { throw new CacheLockSpinsExceededError(); }
E e = lookupEntryUnsynchronized(key, hc);
if (e == null) {
synchronized (lock) {
e = lookupEntry(key, hc);
if (e == null && storage != null) {
e = newEntry(key, hc);
}
}
}
if (e == null) {
peekMissCnt++;
return null;
}
if (e.hasFreshData()) { return e; }
boolean _hasFreshData = false;
if (storage != null) {
boolean _needsLoad;
synchronized (e) {
e.waitForFetch();
if (e.isRemovedState()) {
continue;
}
if (e.hasFreshData()) {
return e;
}
_previousNextRefreshTime = e.nextRefreshTime;
_needsLoad = conditionallyStartProcess(e);
}
if (_needsLoad) {
boolean _finished = false;
try {
long t = fetchWithStorage(e, false, _previousNextRefreshTime);
e.finishFetch(t);
_hasFreshData = e.hasFreshData(System.currentTimeMillis(), t);
_finished = true;
} finally {
e.ensureFetchAbort(_finished, _previousNextRefreshTime);
}
}
}
evictEventually();
if (_hasFreshData) {
return e;
}
peekHitNotFreshCnt++;
return null;
}
}
@Override
public boolean contains(K key) {
if (storage == null) {
E e = lookupEntrySynchronizedNoHitRecord(key);
return e != null && e.hasFreshData();
}
E e = peekEntryInternal(key);
if (e != null) {
return true;
}
return false;
}
@Override
public T peek(K key) {
E e = peekEntryInternal(key);
if (e != null) {
return (T) returnValue(e);
}
return null;
}
@Override
public CacheEntry<K, T> peekEntry(K key) {
return returnEntry(peekEntryInternal(key));
}
@Override
public boolean putIfAbsent(K key, T value) {
long _previousNextRefreshTime;
long now;
if (storage == null) {
int _spinCount = TUNABLE.maximumEntryLockSpins;
E e;
for (;;) {
if (_spinCount
throw new CacheLockSpinsExceededError();
}
e = lookupOrNewEntrySynchronizedNoHitRecord(key);
synchronized (e) {
if (e.isRemovedState()) {
continue;
}
now = System.currentTimeMillis();
if (e.hasFreshData(now)) {
return false;
}
synchronized (lock) {
if (!e.isVirgin()) {
recordHit(e);
peekHitNotFreshCnt++;
}
}
_previousNextRefreshTime = e.startFetch();
}
boolean _finished = false;
try {
e.finishFetch(insertOnPut(e, value, now, now, _previousNextRefreshTime));
_finished = true;
return true;
} finally {
e.ensureFetchAbort(_finished, _previousNextRefreshTime);
}
}
}
int _spinCount = TUNABLE.maximumEntryLockSpins;
E e; long t;
for (;;) {
if (_spinCount-- <= 0) { throw new CacheLockSpinsExceededError(); }
e = lookupOrNewEntrySynchronized(key);
synchronized (e) {
e.waitForFetch();
if (e.isRemovedState()) {
continue;
}
t = System.currentTimeMillis();
if (e.hasFreshData(t)) {
return false;
}
_previousNextRefreshTime = e.startFetch();
break;
}
}
if (e.isVirgin()) {
long _result = _previousNextRefreshTime = fetchWithStorage(e, false, _previousNextRefreshTime);
now = System.currentTimeMillis();
if (e.hasFreshData(now, _result)) {
e.finishFetch(_result);
return false;
}
e.nextRefreshTime = Entry.LOADED_NON_VALID_AND_PUT;
}
boolean _finished = false;
try {
e.finishFetch(insertOnPut(e, value, t, t, _previousNextRefreshTime));
_finished = true;
evictEventually();
return true;
} finally {
e.ensureFetchAbort(_finished, _previousNextRefreshTime);
}
}
@Override
public void put(K key, T value) {
long _previousNextRefreshTime;
int _spinCount = TUNABLE.maximumEntryLockSpins;
E e;
for (;;) {
if (_spinCount-- <= 0) { throw new CacheLockSpinsExceededError(); }
e = lookupOrNewEntrySynchronized(key);
synchronized (e) {
if (e.isRemovedState()) {
continue;
}
if (e.isFetchInProgress()) {
e.waitForFetch();
continue;
} else {
_previousNextRefreshTime = e.startFetch();
break;
}
}
}
boolean _finished = false;
try {
long t = System.currentTimeMillis();
e.finishFetch(insertOnPut(e, value, t, t, _previousNextRefreshTime));
_finished = true;
} finally {
e.ensureFetchAbort(_finished, _previousNextRefreshTime);
}
evictEventually();
}
@Override
public boolean remove(K key, T _value) {
return removeWithFlag(key, true, _value);
}
public boolean removeWithFlag(K key) {
return removeWithFlag(key, false, null);
}
/**
* Remove the object mapped to a key from the cache.
*
* <p>Operation with storage: If there is no entry within the cache there may
* be one in the storage, so we need to send the remove to the storage. However,
* if a remove() and a get() is going on in parallel it may happen that the entry
* gets removed from the storage and added again by the tail part of get(). To
* keep the cache and the storage consistent it must be ensured that this thread
* is the only one working on the entry.
*/
public boolean removeWithFlag(K key, boolean _checkValue, T _value) {
if (!_checkValue) {
eventuallyCallWriterDelete(key);
}
if (storage == null) {
E e = lookupEntrySynchronized(key);
if (e != null) {
synchronized (e) {
e.waitForFetch();
if (!e.isRemovedState()) {
synchronized (lock) {
boolean f = e.hasFreshData();
if (_checkValue) {
if (!f || !e.equalsValue(_value)) {
return false;
}
eventuallyCallWriterDelete(key);
}
if (removeEntry(e)) {
removedCnt++;
return f;
}
return false;
}
}
}
}
return false;
}
int _spinCount = TUNABLE.maximumEntryLockSpins;
E e;
boolean _hasFreshData;
for (;;) {
if (_spinCount
throw new CacheLockSpinsExceededError();
}
e = lookupOrNewEntrySynchronized(key);
synchronized (e) {
e.waitForFetch();
if (e.isRemovedState()) {
continue;
}
_hasFreshData = e.hasFreshData();
e.startFetch();
break;
}
}
boolean _finished = false;
try {
long t;
if (!_hasFreshData && e.isVirgin()) {
t = fetchWithStorage(e, false, 0);
_hasFreshData = e.hasFreshData(System.currentTimeMillis(), t);
if (_checkValue && _hasFreshData && !e.equalsValue(_value)) {
e.finishFetch(t);
_finished = true;
return false;
}
}
if (_checkValue && _hasFreshData && !e.equalsValue(_value)) {
_hasFreshData = false;
}
if (_hasFreshData) {
eventuallyCallWriterDelete(key);
storage.remove(key);
}
synchronized (e) {
e.finishFetch(Entry.LOADED_NON_VALID);
if (_hasFreshData) {
synchronized (lock) {
if (removeEntry(e)) {
removedCnt++;
}
}
}
}
_finished = true;
} finally {
e.ensureFetchAbort(_finished);
}
return _hasFreshData;
}
private void eventuallyCallWriterDelete(K key) {
if (writer != null) {
try {
writer.delete(key);
} catch (RuntimeException ex) {
throw ex;
} catch (Exception ex) {
throw new CacheException(ex);
}
}
}
@Override
public void remove(K key) {
removeWithFlag(key);
}
public T peekAndRemove(K key) {
eventuallyCallWriterDelete(key);
if (storage == null) {
E e = lookupEntrySynchronized(key);
if (e != null) {
synchronized (e) {
e.waitForFetch();
if (!e.isRemovedState()) {
synchronized (lock) {
T _value = null;
boolean f = e.hasFreshData();
if (f) {
_value = (T) e.getValue();
recordHit(e);
} else {
peekMissCnt++;
}
if (removeEntry(e)) {
removedCnt++;
}
return _value;
}
}
}
}
synchronized (lock) {
peekMissCnt++;
}
return null;
} // end if (storage == null) ....
int _spinCount = TUNABLE.maximumEntryLockSpins;
E e;
boolean _hasFreshData;
for (;;) {
if (_spinCount
throw new CacheLockSpinsExceededError();
}
e = lookupOrNewEntrySynchronized(key);
synchronized (e) {
e.waitForFetch();
if (e.isRemovedState()) {
continue;
}
_hasFreshData = e.hasFreshData();
e.startFetch();
break;
}
}
boolean _finished = false;
T _value = null;
try {
long t;
if (!_hasFreshData && e.isVirgin()) {
t = fetchWithStorage(e, false, 0);
_hasFreshData = e.hasFreshData(System.currentTimeMillis(), t);
}
if (_hasFreshData) {
_value = (T) e.getValue();
storage.remove(key);
}
synchronized (e) {
e.finishFetch(Entry.LOADED_NON_VALID);
if (_hasFreshData) {
synchronized (lock) {
if (removeEntry(e)) {
removedCnt++;
}
}
}
}
_finished = true;
} finally {
e.ensureFetchAbort(_finished);
}
return _value;
}
@Override
public void prefetch(final K key) {
if (refreshPool == null ||
lookupEntrySynchronized(key) != null) {
return;
}
Runnable r = new Runnable() {
@Override
public void run() {
get(key);
}
};
refreshPool.submit(r);
}
public void prefetch(final List<K> keys, final int _startIndex, final int _endIndexExclusive) {
if (keys.size() == 0 || _startIndex == _endIndexExclusive) {
return;
}
if (keys.size() <= _endIndexExclusive) {
throw new IndexOutOfBoundsException("end > size");
}
if (_startIndex > _endIndexExclusive) {
throw new IndexOutOfBoundsException("start > end");
}
if (_startIndex > 0) {
throw new IndexOutOfBoundsException("end < 0");
}
Set<K> ks = new AbstractSet<K>() {
@Override
public Iterator<K> iterator() {
return new Iterator<K>() {
int idx = _startIndex;
@Override
public boolean hasNext() {
return idx < _endIndexExclusive;
}
@Override
public K next() {
return keys.get(idx++);
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
@Override
public int size() {
return _endIndexExclusive - _startIndex;
}
};
prefetch(ks);
}
@Override
public void fetchAll(Set<? extends K> _keys, boolean replaceExistingValues, FetchCompletedListener l) {
if (replaceExistingValues) {
for (K k : _keys) {
fetchAndReplace(k);
}
if (l != null) {
l.fetchCompleted();
}
} else {
prefetch(_keys, l);
}
}
@Override
public void prefetch(final Set<K> keys) {
prefetch(keys, null);
}
void prefetch(final Set<? extends K> keys, final FetchCompletedListener l) {
if (refreshPool == null) {
getAll(keys);
if (l != null) {
l.fetchCompleted();
}
return;
}
boolean _complete = true;
for (K k : keys) {
if (lookupEntryUnsynchronized(k, modifiedHash(k.hashCode())) == null) {
_complete = false; break;
}
}
if (_complete) {
if (l != null) {
l.fetchCompleted();
}
return;
}
Runnable r = new Runnable() {
@Override
public void run() {
getAll(keys);
if (l != null) {
l.fetchCompleted();
}
}
};
refreshPool.submit(r);
}
/**
* Lookup or create a new entry. The new entry is created, because we need
* it for locking within the data fetch.
*/
protected E lookupOrNewEntrySynchronized(K key) {
int hc = modifiedHash(key.hashCode());
return lookupOrNewEntrySynchronized(key, hc);
}
protected E lookupOrNewEntrySynchronized(K key, int hc) {
E e = lookupEntryUnsynchronized(key, hc);
if (e == null) {
synchronized (lock) {
checkClosed();
e = lookupEntry(key, hc);
if (e == null) {
e = newEntry(key, hc);
}
}
}
return e;
}
protected E lookupOrNewEntrySynchronizedNoHitRecord(K key) {
int hc = modifiedHash(key.hashCode());
E e = lookupEntryUnsynchronizedNoHitRecord(key, hc);
if (e == null) {
synchronized (lock) {
checkClosed();
e = lookupEntryNoHitRecord(key, hc);
if (e == null) {
e = newEntry(key, hc);
}
}
}
return e;
}
protected T returnValue(Entry<E, K,T> e) {
T v = e.value;
if (v instanceof ExceptionWrapper) {
ExceptionWrapper w = (ExceptionWrapper) v;
if (w.additionalExceptionMessage == null) {
synchronized (e) {
long t = e.getValueExpiryTime();
w.additionalExceptionMessage = "(expiry=" + (t > 0 ? formatMillis(t) : "none") + ") " + w.getException();
}
}
exceptionPropagator.propagateException(w.additionalExceptionMessage, w.getException());
}
return v;
}
protected E lookupEntrySynchronized(K key) {
int hc = modifiedHash(key.hashCode());
E e = lookupEntryUnsynchronized(key, hc);
if (e == null) {
synchronized (lock) {
e = lookupEntry(key, hc);
}
}
return e;
}
protected E lookupEntrySynchronizedNoHitRecord(K key) {
int hc = modifiedHash(key.hashCode());
E e = lookupEntryUnsynchronizedNoHitRecord(key, hc);
if (e == null) {
synchronized (lock) {
e = lookupEntryNoHitRecord(key, hc);
}
}
return e;
}
protected final E lookupEntry(K key, int hc) {
E e = Hash.lookup(mainHash, key, hc);
if (e != null) {
recordHit(e);
return e;
}
e = refreshHashCtrl.remove(refreshHash, key, hc);
if (e != null) {
refreshHitCnt++;
mainHash = mainHashCtrl.insert(mainHash, e);
recordHit(e);
return e;
}
return null;
}
protected final E lookupEntryNoHitRecord(K key, int hc) {
E e = Hash.lookup(mainHash, key, hc);
if (e != null) {
return e;
}
e = refreshHashCtrl.remove(refreshHash, key, hc);
if (e != null) {
refreshHitCnt++;
mainHash = mainHashCtrl.insert(mainHash, e);
return e;
}
return null;
}
/**
* Insert new entry in all structures (hash and replacement list). May evict an
* entry if the maximum capacity is reached.
*/
protected E newEntry(K key, int hc) {
if (getLocalSize() >= maxSize) {
evictionNeeded = true;
}
E e = checkForGhost(key, hc);
if (e == null) {
e = newEntry();
e.key = key;
e.hashCode = hc;
insertIntoReplacementList(e);
}
mainHash = mainHashCtrl.insert(mainHash, e);
newEntryCnt++;
return e;
}
/**
* Called when expiry of an entry happens. Remove it from the
* main cache, refresh cache and from the (lru) list. Also cancel the timer.
* Called under big lock.
*/
/**
* The entry is already removed from the replacement list. stop/reset timer, if needed.
* Called under big lock.
*/
private boolean removeEntryFromHash(E e) {
boolean f = mainHashCtrl.remove(mainHash, e) || refreshHashCtrl.remove(refreshHash, e);
checkForHashCodeChange(e);
cancelExpiryTimer(e);
if (e.isVirgin()) {
virginEvictCnt++;
}
e.setRemovedState();
return f;
}
protected final void cancelExpiryTimer(Entry e) {
if (e.task != null) {
e.task.cancel();
timerCancelCount++;
if (timerCancelCount >= 10000) {
timer.purge();
timerCancelCount = 0;
}
e.task = null;
}
}
/**
* Check whether the key was modified during the stay of the entry in the cache.
* We only need to check this when the entry is removed, since we expect that if
* the key has changed, the stored hash code in the cache will not match any more and
* the item is evicted very fast.
*/
private void checkForHashCodeChange(Entry e) {
if (modifiedHash(e.key.hashCode()) != e.hashCode && !e.isStale()) {
if (keyMutationCount == 0) {
getLog().warn("Key mismatch! Key hashcode changed! keyClass=" + e.key.getClass().getName());
String s;
try {
s = e.key.toString();
if (s != null) {
getLog().warn("Key mismatch! key.toString(): " + s);
}
} catch (Throwable t) {
getLog().warn("Key mismatch! key.toString() threw exception", t);
}
}
keyMutationCount++;
}
}
/**
* Time when the element should be fetched again from the underlying storage.
* If 0 then the object should not be cached at all. -1 means no expiry.
*
* @param _newObject might be a fetched value or an exception wrapped into the {@link ExceptionWrapper}
*/
static <K, T> long calcNextRefreshTime(
K _key, T _newObject, long now, Entry _entry,
EntryExpiryCalculator<K, T> ec, long _maxLinger,
ExceptionExpiryCalculator<K> _exceptionEc, long _exceptionMaxLinger) {
if (!(_newObject instanceof ExceptionWrapper)) {
if (_maxLinger == 0) {
return 0;
}
if (ec != null) {
long t = ec.calculateExpiryTime(_key, _newObject, now, _entry);
return limitExpiryToMaxLinger(now, _maxLinger, t);
}
if (_maxLinger > 0) {
return _maxLinger + now;
}
return -1;
}
if (_exceptionMaxLinger == 0) {
return 0;
}
if (_exceptionEc != null) {
ExceptionWrapper _wrapper = (ExceptionWrapper) _newObject;
long t = _exceptionEc.calculateExpiryTime(_key, _wrapper.getException(), now);
t = limitExpiryToMaxLinger(now, _exceptionMaxLinger, t);
return t;
}
if (_exceptionMaxLinger > 0) {
return _exceptionMaxLinger + now;
} else {
return _exceptionMaxLinger;
}
}
static long limitExpiryToMaxLinger(long now, long _maxLinger, long t) {
if (_maxLinger > 0) {
long _tMaximum = _maxLinger + now;
if (t > _tMaximum) {
return _tMaximum;
}
if (t < -1 && -t > _tMaximum) {
return -_tMaximum;
}
}
return t;
}
protected long calcNextRefreshTime(K _key, T _newObject, long now, Entry _entry) {
return calcNextRefreshTime(
_key, _newObject, now, _entry,
entryExpiryCalculator, maxLinger,
exceptionExpiryCalculator, exceptionMaxLinger);
}
protected long fetch(final E e, long _previousNextRefreshTime) {
if (storage != null) {
return fetchWithStorage(e, true, _previousNextRefreshTime);
} else {
return fetchFromSource(e, _previousNextRefreshTime);
}
}
protected boolean conditionallyStartProcess(E e) {
if (!e.isVirgin()) {
return false;
}
e.startFetch();
return true;
}
/**
*
* @param e
* @param _needsFetch true if value needs to be fetched from the cache source.
* This is false, when the we only need to peek for an value already mapped.
*/
protected long fetchWithStorage(E e, boolean _needsFetch, long _previousNextRefreshTime) {
if (!e.isVirgin()) {
if (_needsFetch) {
return fetchFromSource(e, _previousNextRefreshTime);
}
return Entry.LOADED_NON_VALID;
}
StorageEntry se = storage.get(e.key);
if (se == null) {
if (_needsFetch) {
synchronized (lock) {
loadMissCnt++;
}
return fetchFromSource(e, _previousNextRefreshTime);
}
synchronized (lock) {
touchedTime = System.currentTimeMillis();
loadNonFreshCnt++;
}
return Entry.LOADED_NON_VALID;
}
return insertEntryFromStorage(se, e, _needsFetch);
}
protected long insertEntryFromStorage(StorageEntry se, E e, boolean _needsFetch) {
e.setLastModificationFromStorage(se.getCreatedOrUpdated());
T _valueOrException = (T) se.getValueOrException();
long now = System.currentTimeMillis();
T v = (T) se.getValueOrException();
long _nextRefreshTime = maxLinger == 0 ? 0 : Long.MAX_VALUE;
long _expiryTimeFromStorage = se.getValueExpiryTime();
boolean _expired = _expiryTimeFromStorage != 0 && _expiryTimeFromStorage <= now;
if (!_expired && timer != null) {
_nextRefreshTime = calcNextRefreshTime((K) se.getKey(), v, se.getCreatedOrUpdated(), null);
_expired = _nextRefreshTime > Entry.EXPIRY_TIME_MIN && _nextRefreshTime <= now;
}
boolean _fetchAlways = timer == null && maxLinger == 0;
if (_expired || _fetchAlways) {
if (_needsFetch) {
e.value = _valueOrException;
e.setLoadedNonValidAndFetch();
return fetchFromSource(e, 0);
} else {
synchronized (lock) {
touchedTime = now;
loadNonFreshCnt++;
}
return Entry.LOADED_NON_VALID;
}
}
return insert(e, _valueOrException, 0, now, INSERT_STAT_UPDATE, _nextRefreshTime);
}
protected long fetchFromSource(E e, long _previousNextRefreshValue) {
T v;
long t0 = System.currentTimeMillis();
try {
if (source == null) {
throw new CacheUsageExcpetion("source not set");
}
if (e.isVirgin() || e.hasException()) {
v = source.get((K) e.key, t0, null, e.getLastModification());
} else {
v = source.get((K) e.key, t0, (T) e.getValue(), e.getLastModification());
}
e.setLastModification(t0);
} catch (Throwable _ouch) {
v = (T) new ExceptionWrapper(_ouch);
}
long t = System.currentTimeMillis();
return insertOrUpdateAndCalculateExpiry(e, v, t0, t, INSERT_STAT_UPDATE, _previousNextRefreshValue);
}
protected final long insertOnPut(E e, T v, long t0, long t, long _previousNextRefreshValue) {
if (writer != null) {
try {
CacheEntry<K, T> ce;
ce = returnCacheEntry((K) e.getKey(), v, null, t0);
writer.write(ce);
} catch (RuntimeException ex) {
cleanupAfterWriterException(e);
throw ex;
} catch (Exception ex) {
cleanupAfterWriterException(e);
throw new CacheException("writer exception", ex);
}
}
e.setLastModification(t0);
return insertOrUpdateAndCalculateExpiry(e, v, t0, t, INSERT_STAT_PUT, _previousNextRefreshValue);
}
/**
* Calculate the next refresh time if a timer / expiry is needed and call insert.
*/
protected final long insertOrUpdateAndCalculateExpiry(E e, T v, long t0, long t, byte _updateStatistics, long _previousNextRefreshTime) {
long _nextRefreshTime = maxLinger == 0 ? 0 : Long.MAX_VALUE;
if (timer != null) {
try {
_nextRefreshTime = calculateNextRefreshTime(e, v, t0, _previousNextRefreshTime);
} catch (Exception ex) {
updateStatistics(e, v, t0, t, _updateStatistics, false);
throw new CacheException("exception in expiry calculation", ex);
}
}
return insert(e, v, t0, t, _updateStatistics, _nextRefreshTime);
}
/**
* @throws Exception any exception from the ExpiryCalculator
*/
private long calculateNextRefreshTime(E _entry, T _newValue, long t0, long _previousNextRefreshTime) {
long _nextRefreshTime;
if (Entry.isDataValidState(_previousNextRefreshTime) || Entry.isExpiredState(_previousNextRefreshTime)) {
_nextRefreshTime = calcNextRefreshTime((K) _entry.getKey(), _newValue, t0, _entry);
} else {
_nextRefreshTime = calcNextRefreshTime((K) _entry.getKey(), _newValue, t0, null);
}
return _nextRefreshTime;
}
final static byte INSERT_STAT_NO_UPDATE = 0;
final static byte INSERT_STAT_UPDATE = 1;
final static byte INSERT_STAT_PUT = 2;
/**
* @param _nextRefreshTime -1/MAXVAL: eternal, 0: expires immediately
*/
protected final long insert(E e, T _value, long t0, long t, byte _updateStatistics, long _nextRefreshTime) {
final boolean _justLoadedFromStorage = (storage != null) && t0 == 0;
if (_nextRefreshTime == -1) {
_nextRefreshTime = Long.MAX_VALUE;
}
final boolean _suppressException =
_value instanceof ExceptionWrapper && hasSuppressExceptions() && e.getValue() != Entry.INITIAL_VALUE && !e.hasException();
if (!_suppressException) {
e.value = _value;
}
if (_value instanceof ExceptionWrapper && !_suppressException && !_justLoadedFromStorage) {
Log log = getLog();
if (log.isDebugEnabled()) {
log.debug(
"source caught exception, expires at: " + formatMillis(_nextRefreshTime),
((ExceptionWrapper) _value).getException());
}
}
CacheStorageException _storageException = null;
if (storage != null && e.isDirty() && (_nextRefreshTime != 0 || hasKeepAfterExpired())) {
try {
storage.put(e, _nextRefreshTime);
} catch (CacheStorageException ex) {
_storageException = ex;
} catch (Throwable ex) {
_storageException = new CacheStorageException(ex);
}
}
long _nextRefreshTimeWithState;
synchronized (lock) {
checkClosed();
updateStatisticsNeedsLock(e, _value, t0, t, _updateStatistics, _suppressException);
if (_storageException != null) {
throw _storageException;
}
_nextRefreshTimeWithState = stopStartTimer(_nextRefreshTime, e, t);
if (_updateStatistics == INSERT_STAT_PUT && !e.hasFreshData(t, _nextRefreshTimeWithState)) {
putButExpiredCnt++;
}
} // synchronized (lock)
return _nextRefreshTimeWithState;
}
private void updateStatistics(E e, T _value, long t0, long t, byte _updateStatistics, boolean _suppressException) {
synchronized (lock) {
updateStatisticsNeedsLock(e, _value, t0, t, _updateStatistics, _suppressException);
}
}
private void updateStatisticsNeedsLock(E e, T _value, long t0, long t, byte _updateStatistics, boolean _suppressException) {
boolean _justLoadedFromStorage = storage != null && t0 == 0;
touchedTime = t;
if (_updateStatistics == INSERT_STAT_UPDATE) {
if (_justLoadedFromStorage) {
loadHitCnt++;
} else {
if (_suppressException) {
suppressedExceptionCnt++;
fetchExceptionCnt++;
} else {
if (_value instanceof ExceptionWrapper) {
fetchExceptionCnt++;
}
}
fetchCnt++;
fetchMillis += t - t0;
if (e.isGettingRefresh()) {
refreshCnt++;
}
if (e.isLoadedNonValidAndFetch()) {
loadNonFreshAndFetchedCnt++;
} else if (!e.isVirgin()) {
fetchButHitCnt++;
}
}
} else if (_updateStatistics == INSERT_STAT_PUT) {
putCnt++;
eventuallyAdjustPutNewEntryCount(e);
if (e.nextRefreshTime == Entry.LOADED_NON_VALID_AND_PUT) {
peekHitNotFreshCnt++;
}
}
}
private void eventuallyAdjustPutNewEntryCount(E e) {
if (e.isVirgin()) {
putNewEntryCnt++;
}
}
private void cleanupAfterWriterException(E e) {
if (e.isVirgin()) {
synchronized (lock) {
putNewEntryCnt++;
}
}
}
protected long stopStartTimer(long _nextRefreshTime, E e, long now) {
if (e.task != null) {
e.task.cancel();
}
if (hasSharpTimeout() && _nextRefreshTime > Entry.EXPIRY_TIME_MIN && _nextRefreshTime != Long.MAX_VALUE) {
_nextRefreshTime = -_nextRefreshTime;
}
if (timer != null &&
(_nextRefreshTime > Entry.EXPIRY_TIME_MIN || _nextRefreshTime < -1)) {
if (_nextRefreshTime < -1) {
long _timerTime =
-_nextRefreshTime - TUNABLE.sharpExpirySafetyGapMillis;
if (_timerTime >= now) {
MyTimerTask tt = new MyTimerTask();
tt.entry = e;
timer.schedule(tt, new Date(_timerTime));
e.task = tt;
_nextRefreshTime = -_nextRefreshTime;
}
} else {
MyTimerTask tt = new MyTimerTask();
tt.entry = e;
timer.schedule(tt, new Date(_nextRefreshTime));
e.task = tt;
}
} else {
_nextRefreshTime = _nextRefreshTime == Long.MAX_VALUE ? Entry.FETCHED_STATE : Entry.FETCH_NEXT_TIME_STATE;
}
return _nextRefreshTime;
}
/**
* When the time has come remove the entry from the cache.
*/
protected void timerEvent(final E e, long _executionTime) {
if (e.isRemovedFromReplacementList()) {
return;
}
if (refreshPool != null) {
synchronized (lock) {
if (isClosed()) { return; }
if (e.task == null) {
return;
}
if (e.isRemovedFromReplacementList()) {
return;
}
if (mainHashCtrl.remove(mainHash, e)) {
refreshHash = refreshHashCtrl.insert(refreshHash, e);
if (e.hashCode != modifiedHash(e.key.hashCode())) {
synchronized (lock) {
synchronized (e) {
if (!e.isRemovedState() && removeEntryFromHash(e)) {
expiredRemoveCnt++;
}
}
}
return;
}
Runnable r = new Runnable() {
@Override
public void run() {
long _previousNextRefreshTime;
synchronized (e) {
if (e.isRemovedFromReplacementList() || e.isRemovedState() || e.isFetchInProgress()) {
return;
}
_previousNextRefreshTime = e.nextRefreshTime;
e.setGettingRefresh();
}
try {
long t = fetch(e, _previousNextRefreshTime);
e.finishFetch(t);
} catch (CacheClosedException ignore) {
} catch (Throwable ex) {
e.ensureFetchAbort(false);
synchronized (lock) {
internalExceptionCnt++;
}
getLog().warn("Refresh exception", ex);
try {
expireEntry(e);
} catch (CacheClosedException ignore) { }
}
}
};
boolean _submitOkay = refreshPool.submit(r);
if (_submitOkay) {
return;
}
refreshSubmitFailedCnt++;
}
}
} else {
if (_executionTime < e.nextRefreshTime) {
synchronized (e) {
if (!e.isRemovedState()) {
long t = System.currentTimeMillis();
if (t < e.nextRefreshTime) {
e.nextRefreshTime = -e.nextRefreshTime;
return;
} else {
try {
expireEntry(e);
} catch (CacheClosedException ignore) { }
}
}
}
return;
}
}
synchronized (e) {
long t = System.currentTimeMillis();
if (t >= e.nextRefreshTime) {
try {
expireEntry(e);
} catch (CacheClosedException ignore) { }
}
}
}
protected void expireEntry(E e) {
synchronized (e) {
if (e.isRemovedState() || e.isExpiredState()) {
return;
}
if (e.isFetchInProgress()) {
e.nextRefreshTime = Entry.FETCH_IN_PROGRESS_NON_VALID;
return;
}
e.setExpiredState();
synchronized (lock) {
checkClosed();
if (hasKeepAfterExpired()) {
expiredKeptCnt++;
} else {
if (removeEntry(e)) {
expiredRemoveCnt++;
}
}
}
}
}
/**
* Returns all cache entries within the heap cache. Entries that
* are expired or contain no valid data are not filtered out.
*/
final protected ClosableConcurrentHashEntryIterator<Entry> iterateAllHeapEntries() {
return
new ClosableConcurrentHashEntryIterator(
mainHashCtrl, mainHash, refreshHashCtrl, refreshHash);
}
@Override
public void removeAllAtOnce(Set<K> _keys) {
}
/** JSR107 convenience getAll from array */
public Map<K, T> getAll(K[] _keys) {
return getAll(new HashSet<K>(Arrays.asList(_keys)));
}
/**
* JSR107 bulk interface. The behaviour is compatible to the JSR107 TCK. We also need
* to be compatible to the exception handling policy, which says that the exception
* is to be thrown when most specific. So exceptions are only thrown, when the value
* which has produced an exception is requested from the map.
*/
public Map<K, T> getAll(final Set<? extends K> _inputKeys) {
final Set<K> _keys = new HashSet<K>();
for (K k : _inputKeys) {
E e = getEntryInternal(k);
if (e != null) {
_keys.add(k);
}
}
final Set<Map.Entry<K, T>> set =
new AbstractSet<Map.Entry<K, T>>() {
@Override
public Iterator<Map.Entry<K, T>> iterator() {
return new Iterator<Map.Entry<K, T>>() {
Iterator<? extends K> keyIterator = _keys.iterator();
@Override
public boolean hasNext() {
return keyIterator.hasNext();
}
@Override
public Map.Entry<K, T> next() {
final K key = keyIterator.next();
return new Map.Entry<K, T>(){
@Override
public K getKey() {
return key;
}
@Override
public T getValue() {
return get(key);
}
@Override
public T setValue(T value) {
throw new UnsupportedOperationException();
}
};
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
@Override
public int size() {
return _keys.size();
}
};
return new AbstractMap<K, T>() {
@Override
public T get(Object key) {
if (containsKey(key)) {
return BaseCache.this.get((K) key);
}
return null;
}
@Override
public boolean containsKey(Object key) {
return _keys.contains(key);
}
@Override
public Set<Entry<K, T>> entrySet() {
return set;
}
};
}
public Map<K, T> peekAll(final Set<? extends K> _inputKeys) {
Map<K, T> map = new HashMap<K, T>();
for (K k : _inputKeys) {
CacheEntry<K, T> e = peekEntry(k);
if (e != null) {
map.put(k, e.getValue());
}
}
return map;
}
/**
* Retrieve
*/
@SuppressWarnings("unused")
public void getBulk(K[] _keys, T[] _result, BitSet _fetched, int s, int e) {
sequentialGetFallBack(_keys, _result, _fetched, s, e);
}
final void sequentialGetFallBack(K[] _keys, T[] _result, BitSet _fetched, int s, int e) {
for (int i = s; i < e; i++) {
if (!_fetched.get(i)) {
try {
_result[i] = get(_keys[i]);
} catch (Exception ignore) {
}
}
}
}
public void putAll(Map<? extends K, ? extends T> valueMap) {
if (valueMap.containsKey(null)) {
throw new NullPointerException("map contains null key");
}
for (Map.Entry<? extends K, ? extends T> e : valueMap.entrySet()) {
put(e.getKey(), e.getValue());
}
}
/**
* We need the hash code multiple times. Calculate all hash codes.
*/
void calcHashCodes(K[] _keys, int[] _hashCodes) {
for (int i = _keys.length - 1; i >= 0; i
_hashCodes[i] = modifiedHash(_keys[i].hashCode());
}
}
int startOperationForExistingEntriesNoWait(K[] _keys, int[] _hashCodes, E[] _entries, long[] _pNrt) {
int cnt = 0;
for (int i = _keys.length - 1; i >= 0; i
E e = _entries[i];
if (e != null) { continue; }
K key = _keys[i];
e = lookupEntryUnsynchronized(key, _hashCodes[i]);
if (e == null) { continue; }
synchronized (e) {
if (!e.isRemovedState() && !e.isFetchInProgress()) {
_pNrt[i] = e.startFetch();
_entries[i] = e;
cnt++;
}
}
}
return cnt;
}
int startOperationNewEntries(K[] _keys, int[] _hashCodes, E[] _entries, long[] _pNrt) {
int cnt = 0;
for (int i = _keys.length - 1; i >= 0; i
E e = _entries[i];
if (e != null) { continue; }
K key = _keys[i];
e = lookupOrNewEntrySynchronized(key, _hashCodes[i]);
synchronized (e) {
if (!e.isRemovedState() && !e.isFetchInProgress()) {
_pNrt[i] = e.startFetch();
_entries[i] = e;
cnt++;
}
}
}
return cnt;
}
int startOperationNewEntriesAndWait(K[] _keys, int[] _hashCodes, E[] _entries, long[] _pNrt) {
int cnt = 0;
for (int i = _keys.length - 1; i >= 0; i
E e = _entries[i];
if (e != null) { continue; }
K key = _keys[i];
e = lookupOrNewEntrySynchronized(key, _hashCodes[i]);
synchronized (e) {
e.waitForFetch();
if (!e.isRemovedState()) {
_pNrt[i] = e.startFetch();
_entries[i] = e;
cnt++;
}
}
}
return cnt;
}
void startBulkOperation(K[] _keys, int[] _hashCodes, E[] _entries, long[] _pNrt) {
calcHashCodes(_keys, _hashCodes);
int cnt = 0;
cnt = startOperationForExistingEntriesNoWait(_keys, _hashCodes, _entries, _pNrt);
if (cnt == _keys.length) { return; }
cnt += startOperationNewEntries(_keys, _hashCodes, _entries, _pNrt);
if (cnt == _keys.length) { return; }
cnt += startOperationNewEntries(_keys, _hashCodes, _entries, _pNrt);
if (cnt == _keys.length) { return; }
int _spinCount = TUNABLE.maximumEntryLockSpins;
do {
if (_spinCount
throw new CacheLockSpinsExceededError();
}
cnt += startOperationNewEntriesAndWait(_keys, _hashCodes, _entries, _pNrt);
} while (cnt != _keys.length);
if (storage != null) {
throw new UnsupportedOperationException("storage load must happen here");
}
}
void initializeEntries(BulkOperation op, long now, K[] _keys, E[] _entries, long[] _pNrt, EntryForProcessor<K, T>[] _pEntries) {
for (int i = _keys.length - 1; i >= 0; i
E e = _entries[i];
EntryForProcessor<K, T> ep;
_pEntries[i] = ep = new EntryForProcessor<K, T>();
ep.index = i;
ep.lastModification = e.getLastModification();
ep.key = _keys[i];
ep.operation = op;
if (e.hasFreshData(now, _pNrt[i])) {
ep.value = (T) e.getValueOrException();
} else {
ep.removed = true;
if (storage != null || source != null) {
ep.needsLoadOrFetch = true;
}
}
}
}
@Override
public <R> R invoke(K key, CacheEntryProcessor<K, T, R> entryProcessor, Object... _args) {
Map<K, EntryProcessingResult<R>> m = invokeAll(Collections.singleton(key), entryProcessor, _args);
return m.size() > 0 ? m.values().iterator().next().getResult() : null;
}
@Override
public <R> Map<K, EntryProcessingResult<R>> invokeAll(Set<? extends K> _inputKeys, CacheEntryProcessor<K ,T, R> p, Object... _args) {
checkClosed();
K[] _keys = _inputKeys.toArray((K[]) Array.newInstance(keyType, 0));
int[] _hashCodes = new int[_keys.length];
E[] _entries = (E[]) Array.newInstance(newEntry().getClass(), _keys.length);
long[] _pNrt = new long[_keys.length];
long t0 = System.currentTimeMillis();
startBulkOperation(_keys, _hashCodes, _entries, _pNrt);
EntryForProcessor<K, T>[] _pEntries = new EntryForProcessor[_keys.length];
BulkOperation op = new BulkOperation(_entries, _pNrt);
initializeEntries(op, t0, _keys, _entries, _pNrt, _pEntries);
Map<K, EntryProcessingResult<R>> _results = new HashMap<K, EntryProcessingResult<R>>();
boolean _gotException = false;
for (int i = _keys.length - 1; i >= 0; i
EntryProcessingResult<R> _result;
try {
R r = p.process(_pEntries[i], _args);
_result = r != null ? new ProcessingResultImpl<R>(r) : null;
} catch (Throwable t) {
_result = new ProcessingResultImpl<R>(t);
_gotException = true;
}
if (_result != null) {
_results.put(_keys[i], _result);
}
}
long[] _newExpiry = new long[_keys.length];
Exception _propagateException = null;
if (!_gotException && timer != null) {
try {
for (int i = _keys.length - 1; i >= 0; i
if (_pEntries[i].updated && !_pEntries[i].removed) {
_newExpiry[i] = calculateNextRefreshTime(_entries[i], (T) _pEntries[i].value, t0, _pNrt[i]);
}
}
} catch (Exception ex) {
_gotException = true;
_propagateException = ex;
}
}
if (!_gotException && writer != null) {
try {
for (int i = _keys.length - 1; i >= 0; i
if (!_pEntries[i].updated) {
continue;
}
if (_pEntries[i].removed) {
if (_entries[i].hasFreshData(System.currentTimeMillis(), _pNrt[i])) {
writer.delete(_keys[i]);
}
} else {
CacheEntry<K, T> ce = returnCacheEntry(_keys[i], _pEntries[i].getValue(), _pEntries[i].getException(), _pEntries[i].getLastModification());
writer.write(ce);
}
}
} catch (Exception ex) {
_gotException = true;
_propagateException = ex;
}
}
if (_gotException) {
for (int i = _keys.length - 1; i >= 0; i
if (_pNrt[i] == Entry.VIRGIN_STATE) {
synchronized (lock) {
invokeNewEntryCnt++;
}
}
_entries[i].finishFetch(_pNrt[i]);
}
} else {
for (int i = _keys.length - 1; i >= 0; i
E e = _entries[i];
if (!_pEntries[i].updated) {
if (_pNrt[i] == Entry.VIRGIN_STATE) {
synchronized (lock) {
invokeNewEntryCnt++;
}
}
e.finishFetch(_pNrt[i]);
continue;
}
if (_pEntries[i].removed) {
if (e.hasFreshData(System.currentTimeMillis(), _pNrt[i])) {
synchronized (e) {
e.finishFetch(Entry.LOADED_NON_VALID);
synchronized (lock) {
removeEntry(e);
removedCnt++;
}
}
} else {
synchronized (lock) {
invokeNewEntryCnt++;
}
e.finishFetch(_pNrt[i]);
}
continue;
}
long t = System.currentTimeMillis();
long _expiry;
if (timer == null) {
_expiry = maxLinger == 0 ? 0 : Long.MAX_VALUE;
} else {
_expiry = _newExpiry[i];
}
e.setLastModification(_pEntries[i].getLastModification());
e.finishFetch(insert(e, (T) _pEntries[i].value, t0, t, INSERT_STAT_PUT, _expiry));
}
}
if (_propagateException != null) {
throw new CacheEntryProcessingException(_propagateException);
}
return _results;
}
class BulkOperation {
E[] entries;
long[] pNrt;
public BulkOperation(E[] entries, long[] pNrt) {
this.entries = entries;
this.pNrt = pNrt;
}
void loadOrFetch(EntryForProcessor<K, T> ep) {
int idx = ep.index;
E e = entries[idx];
if (storage != null) {
pNrt[idx] = fetchWithStorage(e, ep.removed, pNrt[idx]);
} else {
pNrt[idx] = fetch(e, pNrt[idx]);
}
if (e.isVirgin()) {
e.setLoadedNonValidAndFetch();
}
ep.needsLoadOrFetch = false;
if (e.hasFreshData(System.currentTimeMillis(), pNrt[idx])) {
ep.value = (T) e.getValue();
ep.lastModification = e.getLastModification();
} else {
ep.removed = true;
}
}
/*
void loadAndFetch(EntryForProcessor<K, T> ep) {
int idx = ep.index;
E e = entries[idx];
pNrt[idx] = fetch(e, pNrt[idx]);
if (e.isVirgin()) {
e.setLoadedNonValidAndFetch();
}
ep.needsLoad = false;
ep.needsFetch = false;
if (e.hasFreshData(System.currentTimeMillis(), pNrt[idx])) {
ep.value = (T) e.getValue();
ep.lastModification = e.getLastModification();
} else {
ep.removed = true;
}
}
*/
}
public abstract long getHitCnt();
protected final int calculateHashEntryCount() {
return Hash.calcEntryCount(mainHash) + Hash.calcEntryCount(refreshHash);
}
protected final int getLocalSize() {
return mainHashCtrl.size + refreshHashCtrl.size;
}
public final int getTotalEntryCount() {
synchronized (lock) {
if (storage != null) {
return storage.getTotalEntryCount();
}
return getLocalSize();
}
}
public long getExpiredCnt() {
return expiredRemoveCnt + expiredKeptCnt;
}
/**
* For peek no fetch is counted if there is a storage miss, hence the extra counter.
*/
public long getFetchesBecauseOfNewEntries() {
return fetchCnt - fetchButHitCnt;
}
protected int getFetchesInFlight() {
long _fetchesBecauseOfNoEntries = getFetchesBecauseOfNewEntries();
return (int) (newEntryCnt - putNewEntryCnt - virginEvictCnt
- loadNonFreshCnt
- loadHitCnt
- _fetchesBecauseOfNoEntries
- invokeNewEntryCnt
);
}
protected IntegrityState getIntegrityState() {
synchronized (lock) {
return new IntegrityState()
.checkEquals(
"newEntryCnt - virginEvictCnt == " +
"getFetchesBecauseOfNewEntries() + getFetchesInFlight() + putNewEntryCnt + loadNonFreshCnt + loadHitCnt",
newEntryCnt - virginEvictCnt,
getFetchesBecauseOfNewEntries() + getFetchesInFlight() + putNewEntryCnt + loadNonFreshCnt + loadHitCnt)
.checkLessOrEquals("getFetchesInFlight() <= 100", getFetchesInFlight(), 100)
.checkEquals("newEntryCnt == getSize() + evictedCnt + expiredRemoveCnt + removeCnt + clearedCnt", newEntryCnt, getLocalSize() + evictedCnt + expiredRemoveCnt + removedCnt + clearedCnt)
.checkEquals("newEntryCnt == getSize() + evictedCnt + getExpiredCnt() - expiredKeptCnt + removeCnt + clearedCnt", newEntryCnt, getLocalSize() + evictedCnt + getExpiredCnt() - expiredKeptCnt + removedCnt + clearedCnt)
.checkEquals("mainHashCtrl.size == Hash.calcEntryCount(mainHash)", mainHashCtrl.size, Hash.calcEntryCount(mainHash))
.checkEquals("refreshHashCtrl.size == Hash.calcEntryCount(refreshHash)", refreshHashCtrl.size, Hash.calcEntryCount(refreshHash))
.check("!!evictionNeeded | (getSize() <= maxSize)", !!evictionNeeded | (getLocalSize() <= maxSize))
.check("storage => storage.getAlert() < 2", storage == null || storage.getAlert() < 2);
}
}
/** Check internal data structures and throw and exception if something is wrong, used for unit testing */
public final void checkIntegrity() {
synchronized (lock) {
IntegrityState is = getIntegrityState();
if (is.getStateFlags() > 0) {
throw new CacheIntegrityError(is.getStateDescriptor(), is.getFailingChecks(), toString());
}
}
}
public final Info getInfo() {
synchronized (lock) {
long t = System.currentTimeMillis();
if (info != null &&
(info.creationTime + info.creationDeltaMs * TUNABLE.minimumStatisticsCreationTimeDeltaFactor + TUNABLE.minimumStatisticsCreationDeltaMillis > t)) {
return info;
}
info = getLatestInfo(t);
}
return info;
}
public final Info getLatestInfo() {
return getLatestInfo(System.currentTimeMillis());
}
private Info getLatestInfo(long t) {
synchronized (lock) {
info = new Info();
info.creationTime = t;
info.creationDeltaMs = (int) (System.currentTimeMillis() - t);
return info;
}
}
protected String getExtraStatistics() { return ""; }
static String timestampToString(long t) {
if (t == 0) {
return "-";
}
return formatMillis(t);
}
@Override
public CacheManager getCacheManager() {
return manager;
}
/**
* Return status information. The status collection is time consuming, so this
* is an expensive operation.
*/
@Override
public String toString() {
synchronized (lock) {
Info fo = getLatestInfo();
return "Cache{" + name + "}"
+ "("
+ "size=" + fo.getSize() + ", "
+ "maxSize=" + fo.getMaxSize() + ", "
+ "usageCnt=" + fo.getUsageCnt() + ", "
+ "missCnt=" + fo.getMissCnt() + ", "
+ "fetchCnt=" + fo.getFetchCnt() + ", "
+ "fetchButHitCnt=" + fetchButHitCnt + ", "
+ "heapHitCnt=" + fo.hitCnt + ", "
+ "virginEvictCnt=" + virginEvictCnt + ", "
+ "fetchesInFlightCnt=" + fo.getFetchesInFlightCnt() + ", "
+ "newEntryCnt=" + fo.getNewEntryCnt() + ", "
+ "bulkGetCnt=" + fo.getBulkGetCnt() + ", "
+ "refreshCnt=" + fo.getRefreshCnt() + ", "
+ "refreshSubmitFailedCnt=" + fo.getRefreshSubmitFailedCnt() + ", "
+ "refreshHitCnt=" + fo.getRefreshHitCnt() + ", "
+ "putCnt=" + fo.getPutCnt() + ", "
+ "putNewEntryCnt=" + fo.getPutNewEntryCnt() + ", "
+ "expiredCnt=" + fo.getExpiredCnt() + ", "
+ "evictedCnt=" + fo.getEvictedCnt() + ", "
+ "removedCnt=" + fo.getRemovedCnt() + ", "
+ "storageLoadCnt=" + fo.getStorageLoadCnt() + ", "
+ "storageMissCnt=" + fo.getStorageMissCnt() + ", "
+ "storageHitCnt=" + fo.getStorageHitCnt() + ", "
+ "hitRate=" + fo.getDataHitString() + ", "
+ "collisionCnt=" + fo.getCollisionCnt() + ", "
+ "collisionSlotCnt=" + fo.getCollisionSlotCnt() + ", "
+ "longestCollisionSize=" + fo.getLongestCollisionSize() + ", "
+ "hashQuality=" + fo.getHashQualityInteger() + ", "
+ "msecs/fetch=" + (fo.getMillisPerFetch() >= 0 ? fo.getMillisPerFetch() : "-") + ", "
+ "created=" + timestampToString(fo.getStarted()) + ", "
+ "cleared=" + timestampToString(fo.getCleared()) + ", "
+ "touched=" + timestampToString(fo.getTouched()) + ", "
+ "fetchExceptionCnt=" + fo.getFetchExceptionCnt() + ", "
+ "suppressedExceptionCnt=" + fo.getSuppressedExceptionCnt() + ", "
+ "internalExceptionCnt=" + fo.getInternalExceptionCnt() + ", "
+ "keyMutationCnt=" + fo.getKeyMutationCnt() + ", "
+ "infoCreated=" + timestampToString(fo.getInfoCreated()) + ", "
+ "infoCreationDeltaMs=" + fo.getInfoCreationDeltaMs() + ", "
+ "impl=\"" + getClass().getSimpleName() + "\""
+ getExtraStatistics() + ", "
+ "integrityState=" + fo.getIntegrityDescriptor() + ")";
}
}
/**
* Stable interface to request information from the cache, the object
* safes values that need a longer calculation time, other values are
* requested directly.
*/
public class Info {
int size = BaseCache.this.getLocalSize();
long creationTime;
int creationDeltaMs;
long missCnt = fetchCnt - refreshCnt + peekHitNotFreshCnt + peekMissCnt;
long storageMissCnt = loadMissCnt + loadNonFreshCnt + loadNonFreshAndFetchedCnt;
long storageLoadCnt = storageMissCnt + loadHitCnt;
long newEntryCnt = BaseCache.this.newEntryCnt - virginEvictCnt;
long hitCnt = getHitCnt();
long correctedPutCnt = putCnt - putButExpiredCnt;
long usageCnt =
hitCnt + newEntryCnt + peekMissCnt;
CollisionInfo collisionInfo;
String extraStatistics;
int fetchesInFlight = BaseCache.this.getFetchesInFlight();
{
collisionInfo = new CollisionInfo();
Hash.calcHashCollisionInfo(collisionInfo, mainHash);
Hash.calcHashCollisionInfo(collisionInfo, refreshHash);
extraStatistics = BaseCache.this.getExtraStatistics();
if (extraStatistics.startsWith(", ")) {
extraStatistics = extraStatistics.substring(2);
}
}
IntegrityState integrityState = getIntegrityState();
String percentString(double d) {
String s = Double.toString(d);
return (s.length() > 5 ? s.substring(0, 5) : s) + "%";
}
public String getName() { return name; }
public String getImplementation() { return BaseCache.this.getClass().getSimpleName(); }
public int getSize() { return size; }
public int getMaxSize() { return maxSize; }
public long getStorageHitCnt() { return loadHitCnt; }
public long getStorageLoadCnt() { return storageLoadCnt; }
public long getStorageMissCnt() { return storageMissCnt; }
public long getReadUsageCnt() { return usageCnt - putCnt - removedCnt - invokeNewEntryCnt; }
public long getUsageCnt() { return usageCnt; }
public long getMissCnt() { return missCnt; }
public long getNewEntryCnt() { return newEntryCnt; }
public long getFetchCnt() { return fetchCnt; }
public int getFetchesInFlightCnt() { return fetchesInFlight; }
public long getBulkGetCnt() { return bulkGetCnt; }
public long getRefreshCnt() { return refreshCnt; }
public long getInternalExceptionCnt() { return internalExceptionCnt; }
public long getRefreshSubmitFailedCnt() { return refreshSubmitFailedCnt; }
public long getSuppressedExceptionCnt() { return suppressedExceptionCnt; }
public long getFetchExceptionCnt() { return fetchExceptionCnt; }
public long getRefreshHitCnt() { return refreshHitCnt; }
public long getExpiredCnt() { return BaseCache.this.getExpiredCnt(); }
public long getEvictedCnt() { return evictedCnt - virginEvictCnt; }
public long getRemovedCnt() { return BaseCache.this.removedCnt; }
public long getPutNewEntryCnt() { return putNewEntryCnt; }
public long getPutCnt() { return correctedPutCnt; }
public long getKeyMutationCnt() { return keyMutationCount; }
public double getDataHitRate() {
long cnt = getReadUsageCnt();
return cnt == 0 ? 0.0 : ((cnt - missCnt) * 100D / cnt);
}
public String getDataHitString() { return percentString(getDataHitRate()); }
public double getEntryHitRate() { return usageCnt == 0 ? 100 : (usageCnt - newEntryCnt + putCnt) * 100D / usageCnt; }
public String getEntryHitString() { return percentString(getEntryHitRate()); }
/** How many items will be accessed with collision */
public int getCollisionPercentage() {
return
(size - collisionInfo.collisionCnt) * 100 / size;
}
/** 100 means each collision has its own slot */
public int getSlotsPercentage() {
return collisionInfo.collisionSlotCnt * 100 / collisionInfo.collisionCnt;
}
public int getHq0() {
return Math.max(0, 105 - collisionInfo.longestCollisionSize * 5) ;
}
public int getHq1() {
final int _metricPercentageBase = 60;
int m =
getCollisionPercentage() * ( 100 - _metricPercentageBase) / 100 + _metricPercentageBase;
m = Math.min(100, m);
m = Math.max(0, m);
return m;
}
public int getHq2() {
final int _metricPercentageBase = 80;
int m =
getSlotsPercentage() * ( 100 - _metricPercentageBase) / 100 + _metricPercentageBase;
m = Math.min(100, m);
m = Math.max(0, m);
return m;
}
public int getHashQualityInteger() {
if (size == 0 || collisionInfo.collisionSlotCnt == 0) {
return 100;
}
int _metric0 = getHq0();
int _metric1 = getHq1();
int _metric2 = getHq2();
if (_metric1 < _metric0) {
int v = _metric0;
_metric0 = _metric1;
_metric1 = v;
}
if (_metric2 < _metric0) {
int v = _metric0;
_metric0 = _metric2;
_metric2 = v;
}
if (_metric2 < _metric1) {
int v = _metric1;
_metric1 = _metric2;
_metric2 = v;
}
if (_metric0 <= 0) {
return 0;
}
_metric0 = _metric0 + ((_metric1 - 50) * 5 / _metric0);
_metric0 = _metric0 + ((_metric2 - 50) * 2 / _metric0);
_metric0 = Math.max(0, _metric0);
_metric0 = Math.min(100, _metric0);
return _metric0;
}
public double getMillisPerFetch() { return fetchCnt == 0 ? 0 : (fetchMillis * 1D / fetchCnt); }
public long getFetchMillis() { return fetchMillis; }
public int getCollisionCnt() { return collisionInfo.collisionCnt; }
public int getCollisionSlotCnt() { return collisionInfo.collisionSlotCnt; }
public int getLongestCollisionSize() { return collisionInfo.longestCollisionSize; }
public String getIntegrityDescriptor() { return integrityState.getStateDescriptor(); }
public long getStarted() { return startedTime; }
public long getCleared() { return clearedTime; }
public long getTouched() { return touchedTime; }
public long getInfoCreated() { return creationTime; }
public int getInfoCreationDeltaMs() { return creationDeltaMs; }
public int getHealth() {
if (storage != null && storage.getAlert() == 2) {
return 2;
}
if (integrityState.getStateFlags() > 0 ||
getHashQualityInteger() < 5) {
return 2;
}
if (storage != null && storage.getAlert() == 1) {
return 1;
}
if (getHashQualityInteger() < 30 ||
getKeyMutationCnt() > 0 ||
getInternalExceptionCnt() > 0) {
return 1;
}
return 0;
}
public String getExtraStatistics() {
return extraStatistics;
}
}
static class CollisionInfo {
int collisionCnt; int collisionSlotCnt; int longestCollisionSize;
}
/**
* This function calculates a modified hash code. The intention is to
* "rehash" the incoming integer hash codes to overcome weak hash code
* implementations. We expect good results for integers also.
* Also add a random seed to the hash to protect against attacks on hashes.
* This is actually a slightly reduced version of the java.util.HashMap
* hash modification.
*/
protected final int modifiedHash(int h) {
h ^= hashSeed;
h ^= h >>> 7;
h ^= h >>> 15;
return h;
}
protected class MyTimerTask extends java.util.TimerTask {
E entry;
public void run() {
timerEvent(entry, scheduledExecutionTime());
}
}
public static class Tunable extends TunableConstants {
/**
* Implementation class to use by default.
*/
public Class<? extends BaseCache> defaultImplementation = ClockProPlusCache.class;
/**
* Log exceptions from the source just as they happen. The log goes to the debug output
* of the cache log, debug level of the cache log must be enabled also.
*/
public boolean logSourceExceptions = false;
public int waitForTimerJobsSeconds = 5;
/**
* Limits the number of spins until an entry lock is expected to
* succeed. The limit is to detect deadlock issues during development
* and testing. It is set to an arbitrary high value to result in
* an exception after about one second of spinning.
*/
public int maximumEntryLockSpins = 333333;
/**
* Maximum number of tries to find an entry for eviction if maximum size
* is reached.
*/
public int maximumEvictSpins = 5;
/**
* Size of the hash table before inserting the first entry. Must be power
* of two. Default: 64.
*/
public int initialHashSize = 64;
/**
* Fill percentage limit. When this is reached the hash table will get
* expanded. Default: 64.
*/
public int hashLoadPercent = 64;
/**
* The hash code will randomized by default. This is a countermeasure
* against from outside that know the hash function.
*/
public boolean disableHashRandomization = false;
/**
* Seed used when randomization is disabled. Default: 0.
*/
public int hashSeed = 0;
/**
* When sharp expiry is enabled, the expiry timer goes
* before the actual expiry to switch back to a time checking
* scheme when the get method is invoked. This prevents
* that an expired value gets served by the cache if the time
* is too late. A recent GC should not produce more then 200
* milliseconds stall. If longer GC stalls are expected, this
* value needs to be changed. A value of LONG.MaxValue
* suppresses the timer usage completely.
*/
public long sharpExpirySafetyGapMillis = 666;
/**
* Some statistic values need processing time to gather and compute it. This is a safety
* time delta, to ensure that the machine is not busy due to statistics generation. Default: 333.
*/
public int minimumStatisticsCreationDeltaMillis = 333;
/**
* Factor of the statistics creation time, that determines the time difference when new
* statistics are generated.
*/
public int minimumStatisticsCreationTimeDeltaFactor = 17;
}
}
|
package cucumber.runner;
import cucumber.api.Scenario;
import cucumber.runtime.Argument;
import cucumber.runtime.Backend;
import cucumber.runtime.HookDefinition;
import cucumber.runtime.Runtime;
import cucumber.runtime.RuntimeOptions;
import cucumber.runtime.StepDefinition;
import cucumber.runtime.io.ClasspathResourceLoader;
import cucumber.runtime.snippets.FunctionNameGenerator;
import gherkin.events.PickleEvent;
import gherkin.pickles.Pickle;
import gherkin.pickles.PickleLocation;
import gherkin.pickles.PickleStep;
import gherkin.pickles.PickleTag;
import org.junit.Test;
import org.mockito.InOrder;
import org.mockito.Matchers;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static java.util.Arrays.asList;
import static org.mockito.Matchers.anyListOf;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class RunnerTest {
private static final String ENGLISH = "en";
private static final String NAME = "name";
private static final List<PickleStep> NO_STEPS = Collections.<PickleStep>emptyList();
private static final List<PickleTag> NO_TAGS = Collections.<PickleTag>emptyList();
private static final List<PickleLocation> MOCK_LOCATIONS = asList(mock(PickleLocation.class));
private final Backend backend = mock(Backend.class);
private final Runtime runtime = createRuntime(backend);
private final Runner runner = runtime.getRunner();
@Test
public void hooks_execute_when_world_exist() throws Throwable {
HookDefinition beforeHook = addBeforeHook(runtime);
HookDefinition afterHook = addAfterHook(runtime);
runner.runPickle(createEmptyPickleEvent());
InOrder inOrder = inOrder(beforeHook, afterHook, backend);
inOrder.verify(backend).buildWorld();
inOrder.verify(beforeHook).execute(Matchers.<Scenario>any());
inOrder.verify(afterHook).execute(Matchers.<Scenario>any());
inOrder.verify(backend).disposeWorld();
}
@Test
public void steps_are_skipped_after_failure() throws Throwable {
HookDefinition failingBeforeHook = addBeforeHook(runtime);
doThrow(RuntimeException.class).when(failingBeforeHook).execute(Matchers.<Scenario>any());
StepDefinition stepDefinition = mock(StepDefinition.class);
runner.runPickle(createPickleEventMatchingStepDefinitions(asList(stepDefinition), runtime));
InOrder inOrder = inOrder(failingBeforeHook, stepDefinition);
inOrder.verify(failingBeforeHook).execute(Matchers.<Scenario>any());
inOrder.verify(stepDefinition, never()).execute(Matchers.anyString(), Matchers.<Object[]>any());
}
@Test
public void hooks_execute_also_after_failure() throws Throwable {
HookDefinition failingBeforeHook = addBeforeHook(runtime);
doThrow(RuntimeException.class).when(failingBeforeHook).execute(Matchers.<Scenario>any());
HookDefinition beforeHook = addBeforeHook(runtime);
HookDefinition afterHook = addAfterHook(runtime);
runner.runPickle(createEmptyPickleEvent());
InOrder inOrder = inOrder(failingBeforeHook, beforeHook, afterHook);
inOrder.verify(failingBeforeHook).execute(Matchers.<Scenario>any());
inOrder.verify(beforeHook).execute(Matchers.<Scenario>any());
inOrder.verify(afterHook).execute(Matchers.<Scenario>any());
}
@Test
public void steps_are_executed() throws Throwable {
final StepDefinition stepDefinition = mock(StepDefinition.class);
runtime.getRunner().runPickle(createPickleEventMatchingStepDefinitions(asList(stepDefinition), runtime));
verify(stepDefinition).execute(Matchers.anyString(), Matchers.<Object[]>any());
}
@Test
public void steps_are_not_executed_on_dry_run() throws Throwable {
final StepDefinition stepDefinition = mock(StepDefinition.class);
final Runtime dryRuntime = createRuntime(backend, "--dry-run");
dryRuntime.getRunner().runPickle(createPickleEventMatchingStepDefinitions(asList(stepDefinition), dryRuntime));
verify(stepDefinition, never()).execute(Matchers.anyString(), Matchers.<Object[]>any());
}
@Test
public void hooks_not_executed_in_dry_run_mode() throws Throwable {
Runtime runtime = createRuntime(backend, "--dry-run");
Runner runner = runtime.getRunner();
HookDefinition beforeHook = addBeforeHook(runtime);
HookDefinition afterHook = addAfterHook(runtime);
runner.runPickle(createEmptyPickleEvent());
verify(beforeHook, never()).execute(Matchers.<Scenario>any());
verify(afterHook, never()).execute(Matchers.<Scenario>any());
}
@Test
public void backends_are_asked_for_snippets_for_undefined_steps() throws Throwable {
PickleStep step = mock(PickleStep.class);
runner.runPickle(createPickleEventWithSteps(asList(step)));
verify(backend).getSnippet(Matchers.eq(step), Matchers.anyString(), Matchers.<FunctionNameGenerator>any());
}
private Runtime createRuntime(Backend backend) {
return createRuntime(backend, "-p null");
}
private Runtime createRuntime(Backend backend, String options) {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
RuntimeOptions runtimeOptions = new RuntimeOptions(options);
return new Runtime(new ClasspathResourceLoader(classLoader), classLoader, asList(backend), runtimeOptions);
}
private boolean isBefore(boolean value) {
return value;
}
private HookDefinition addBeforeHook(Runtime runtime) {
return addHook(runtime, isBefore(true));
}
private HookDefinition addAfterHook(Runtime runtime) {
return addHook(runtime, isBefore(false));
}
private HookDefinition addHook(Runtime runtime, boolean isBefore) {
HookDefinition hook = mock(HookDefinition.class);
when(hook.matches(anyListOf(PickleTag.class))).thenReturn(true);
if (isBefore) {
runtime.getGlue().addBeforeHook(hook);
} else {
runtime.getGlue().addAfterHook(hook);
}
return hook;
}
private PickleEvent createEmptyPickleEvent() {
return new PickleEvent("uri", new Pickle(NAME, ENGLISH, NO_STEPS, NO_TAGS, MOCK_LOCATIONS));
}
private PickleEvent createPickleEventMatchingStepDefinitions(List<StepDefinition> stepDefinitions, Runtime runtime) {
List<PickleStep> steps = new ArrayList<PickleStep>(stepDefinitions.size());
int i = 0;
for (StepDefinition stepDefinition : stepDefinitions) {
PickleStep step = mock(PickleStep.class);
steps.add(step);
when(stepDefinition.matchedArguments(step)).thenReturn(Collections.<Argument>emptyList());
when(stepDefinition.getPattern()).thenReturn("pattern" + Integer.toString(++i));
runtime.getGlue().addStepDefinition(stepDefinition);
}
return new PickleEvent("uri", new Pickle(NAME, ENGLISH, steps, NO_TAGS, MOCK_LOCATIONS));
}
private PickleEvent createPickleEventWithSteps(List<PickleStep> steps) {
return new PickleEvent("uri", new Pickle(NAME, ENGLISH, steps, NO_TAGS, MOCK_LOCATIONS));
}
}
|
package com.couchbase.cblite.phonegap;
import android.content.Context;
import android.text.TextUtils;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import com.couchbase.lite.DatabaseOptions;
import com.couchbase.lite.Document;
import com.couchbase.lite.DocumentChange;
import com.couchbase.lite.Query;
import com.couchbase.lite.QueryEnumerator;
import com.couchbase.lite.QueryRow;
import com.couchbase.lite.UnsavedRevision;
import com.couchbase.lite.android.AndroidContext;
import com.couchbase.lite.Database;
import com.couchbase.lite.Manager;
import com.couchbase.lite.auth.Authenticator;
import com.couchbase.lite.auth.AuthenticatorFactory;
import com.couchbase.lite.replicator.Replication;
import com.couchbase.lite.View;
import com.couchbase.lite.javascript.JavaScriptReplicationFilterCompiler;
import com.couchbase.lite.javascript.JavaScriptViewCompiler;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class CBLite extends CordovaPlugin {
private static Manager dbmgr = null;
private static HashMap<String, Database> dbs = null;
private static HashMap<String, Replication> replications = null;
private static HashMap<String, Database.ChangeListener> changeListeners = null;
private static HashMap<String, Replication.ChangeListener> replicationListeners = null;
private static int runnerCount = 0;
final static int MAX_THREADS = 3;
private static ObjectMapper mapper = new ObjectMapper();
public CBLite() {
super();
System.out.println("CBLite() constructor called");
}
@Override
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
System.out.println("initialize() called");
super.initialize(cordova, webView);
try {
View.setCompiler(new JavaScriptViewCompiler());
Database.setFilterCompiler(new JavaScriptReplicationFilterCompiler());
dbmgr = startCBLite(this.cordova.getActivity());
} catch (final Exception e) {
e.printStackTrace();
}
}
@Override
public void onReset() {
//cancel change listeners
if(changeListeners != null){
for (String dbName : changeListeners.keySet()) {
for (Database.ChangeListener listener : changeListeners.values()) {
dbs.get(dbName).removeChangeListener(listener);
}
}
}
if(replicationListeners != null){
for (String dbName : replicationListeners.keySet()) {
for (Replication.ChangeListener listener : replicationListeners.values()) {
replications.get(dbName).removeChangeListener(listener);
}
}
}
//cancel replications
if(replications != null){
for (Replication replication : replications.values()) {
replication.stop();
}
}
if (dbs != null) dbs.clear();
if (changeListeners != null) changeListeners.clear();
if (replicationListeners != null) replicationListeners.clear();
if (replications != null) replications.clear();
runnerCount = 0;
}
@Override
public boolean execute(String action, JSONArray args, CallbackContext callback) {
//UTIL
if (action.equals("changesDatabase")) changesDatabase(args, callback);
else if (action.equals("changesReplication")) changesReplication(args, callback);
else if (action.equals("compact")) compact(args, callback);
else if (action.equals("info")) info(args, callback);
else if (action.equals("initDb")) initDb(args, callback);
else if (action.equals("replicateFrom")) replicateFrom(args, callback);
else if (action.equals("replicateTo")) replicateTo(args, callback);
else if (action.equals("reset")) reset(args, callback);
else if (action.equals("stopReplication")) stopReplication(args, callback);
else if (action.equals("sync")) sync(args, callback);
//READ
else if (action.equals("allDocs")) allDocs(args, callback);
else if (action.equals("get")) get(args, callback);
//WRITE
else if (action.equals("putAttachment")) putAttachment(args, callback);
else if (action.equals("upsert")) upsert(args, callback);
return true;
}
private void changesDatabase(final JSONArray args, final CallbackContext callback) {
PluginResult result = new PluginResult(PluginResult.Status.NO_RESULT);
result.setKeepCallback(true);
callback.sendPluginResult(result);
cordova.getThreadPool().execute(new Runnable() {
public void run() {
try {
String dbName = args.getString(0);
if (changeListeners == null) {
changeListeners = new HashMap<String, Database.ChangeListener>();
}
if (dbs.get(dbName) != null) {
changeListeners.put(dbName, new Database.ChangeListener() {
public void changed(Database.ChangeEvent event) {
List<DocumentChange> changes = event.getChanges();
for (DocumentChange change : changes) {
PluginResult result = new PluginResult(PluginResult.Status.OK, change.getDocumentId());
result.setKeepCallback(true);
callback.sendPluginResult(result);
}
}
});
dbs.get(dbName).addChangeListener(changeListeners.get(dbName));
}
} catch (final Exception e) {
callback.error(e.getMessage());
}
}
});
}
private void changesReplication(final JSONArray args, final CallbackContext callback) {
PluginResult result = new PluginResult(PluginResult.Status.NO_RESULT);
result.setKeepCallback(true);
callback.sendPluginResult(result);
cordova.getThreadPool().execute(new Runnable() {
public void run() {
try {
String dbName = args.getString(0);
if (replicationListeners == null) {
replicationListeners = new HashMap<String, Replication.ChangeListener>();
}
if (dbs.get(dbName) != null) {
replicationListeners.put(dbName, new Replication.ChangeListener() {
public void changed(Replication.ChangeEvent event) {
Replication.ReplicationStatus status = event.getStatus();
PluginResult result = new PluginResult(PluginResult.Status.OK, status.toString());
result.setKeepCallback(true);
callback.sendPluginResult(result);
}
});
replications.get(dbName).addChangeListener(replicationListeners.get(dbName));
}
} catch (final Exception e) {
callback.error(e.getMessage());
}
}
});
}
private void compact(final JSONArray args, final CallbackContext callback) {
cordova.getThreadPool().execute(new Runnable() {
public void run() {
try {
String dbName = args.getString(0);
dbs.get(dbName).compact();
callback.success("attachment saved!");
} catch (final Exception e) {
callback.error(e.getMessage());
}
}
});
}
private void info(final JSONArray args, final CallbackContext callback) {
cordova.getThreadPool().execute(new Runnable() {
public void run() {
try {
String dbName = args.getString(0);
callback.success(dbs.get(dbName).getDocumentCount());
} catch (final Exception e) {
callback.error(e.getMessage());
}
}
});
}
private void initDb(final JSONArray args, final CallbackContext callback) {
cordova.getThreadPool().execute(new Runnable() {
public void run() {
try {
String dbName = args.getString(0);
if (dbs == null) dbs = new HashMap<String, Database>();
DatabaseOptions options = new DatabaseOptions();
options.setCreate(true);
options.setStorageType(Manager.FORESTDB_STORAGE);
dbs.put(dbName, dbmgr.openDatabase(dbName, options));
callback.success("CBL db init success");
} catch (final Exception e) {
callback.error(e.getMessage());
}
}
});
}
private void replicateFrom(JSONArray args, CallbackContext callback) {
}
private void replicateTo(JSONArray args, CallbackContext callback) {
}
private void reset(JSONArray args, CallbackContext callback) {
this.onReset();
}
private void stopReplication(final JSONArray args, final CallbackContext callback) {
cordova.getThreadPool().execute(new Runnable() {
public void run() {
try {
String dbName = args.getString(0);
Database db = dbs.get(dbName);
if (db != null) {
for (Replication replication : db.getAllReplications()) replication.stop();
callback.success("true");
} else callback.error("false");
} catch (final Exception e) {
callback.error(e.getMessage());
}
}
});
}
private void sync(final JSONArray args, final CallbackContext callback) {
cordova.getThreadPool().execute(new Runnable() {
public void run() {
try {
String dbName = args.getString(0);
URL syncUrl = new URL(args.getString(1));
String user = args.getString(2);
String pass = args.getString(3);
if(replications == null) replications = new HashMap<String, Replication>();
Replication push = dbs.get(dbName).createPushReplication(syncUrl);
Replication pull = dbs.get(dbName).createPullReplication(syncUrl);
Authenticator auth = AuthenticatorFactory.createBasicAuthenticator(user, pass);
push.setAuthenticator(auth);
pull.setAuthenticator(auth);
push.start();
pull.start();
replications.put(dbName + "_push",push);
replications.put(dbName + "_pull", pull);
callback.success("true");
} catch (Exception e) {
callback.error(e.getMessage());
}
}
});
}
private void allDocs(final JSONArray args, final CallbackContext callback) {
PluginResult firstResult = new PluginResult(PluginResult.Status.NO_RESULT);
firstResult.setKeepCallback(true);
callback.sendPluginResult(firstResult);
cordova.getThreadPool().execute(new Runnable() {
public void run() {
//create batch queries
try{
final String dbName = args.getString(0);
final int totalDocs = dbs.get(dbName).getDocumentCount();
final int batch = 500;
final int segments = batch > totalDocs ? 1 : totalDocs / batch;
ArrayList<Integer> skipList = new ArrayList<Integer>();
for(int i = 1; i <= segments; i++) skipList.add(i * batch);
for(Integer skipCount: skipList){
final int innerSkip = skipCount;
ExecutorService executor = Executors.newFixedThreadPool(MAX_THREADS);
Future<Boolean> isComplete = executor.submit(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
Query query = dbs.get(dbName).createAllDocumentsQuery();
query.setAllDocsMode(Query.AllDocsMode.ALL_DOCS);
query.setPrefetch(true);
query.setLimit(batch);
query.setSkip(innerSkip);
try{
QueryEnumerator allDocsQuery = query.run();
final ArrayList<String> responseBuffer = new ArrayList<String>();
for (Iterator<QueryRow> it = allDocsQuery; it.hasNext(); ) {
QueryRow row = it.next();
responseBuffer.add(mapper.writeValueAsString(row.asJSONDictionary()));
}
PluginResult result = new PluginResult(PluginResult.Status.OK, "[" + TextUtils.join(",",responseBuffer) + "]");
result.setKeepCallback(true);
callback.sendPluginResult(result);
if(totalDocs - innerSkip < batch){
//close callback
PluginResult finalResult = new PluginResult(PluginResult.Status.OK, "");
finalResult.setKeepCallback(false);
callback.sendPluginResult(finalResult);
runnerCount = 0;
}
}
catch(Exception e){
PluginResult result = new PluginResult(PluginResult.Status.ERROR,e.getMessage());
result.setKeepCallback(false);
callback.sendPluginResult(result);
return false;
}
return true;
}
});
runnerCount += 1;
if(runnerCount >= MAX_THREADS) {
isComplete.get();
runnerCount = 0;
}
}
}
catch(Exception e){
PluginResult result = new PluginResult(PluginResult.Status.ERROR,e.getMessage());
result.setKeepCallback(false);
callback.sendPluginResult(result);
}
}
});
}
private void get(final JSONArray args, final CallbackContext callback) {
cordova.getThreadPool().execute(new Runnable() {
public void run() {
try{
String dbName = args.getString(0);
String id = args.getString(1);
Boolean isLocal = args.getBoolean(2);
if(isLocal){
Map<String, Object> localDoc = dbs.get(dbName).getExistingLocalDocument(id);
if(localDoc != null) {
callback.success(mapper.writeValueAsString(localDoc));
}
else callback.error("null");
}
else {
Document doc = dbs.get(dbName).getExistingDocument(id);
if(doc != null){
String jsonString = mapper.writeValueAsString(doc.getProperties());
callback.success(jsonString);
}
else callback.error("null");
}
}
catch(final Exception e){
callback.error(e.getMessage());
}
}
});
}
private void putAttachment(final JSONArray args, final CallbackContext callback) {
cordova.getThreadPool().execute(new Runnable() {
public void run() {
try {
String dbName = args.getString(0);
String filePath = cordova.getActivity().getApplicationContext().getFilesDir() + "/" + args.getString(5) + "/" + args.getString(2);
FileInputStream stream = new FileInputStream(filePath);
Document doc = dbs.get(dbName).getDocument(args.getString(1));
UnsavedRevision newRev = doc.getCurrentRevision().createRevision();
newRev.setAttachment(args.getString(3), args.getString(4), stream);
newRev.save();
callback.success("attachment saved!");
} catch (final Exception e) {
callback.error(e.getMessage());
}
}
});
}
private void upsert(final JSONArray args, final CallbackContext callback) {
cordova.getThreadPool().execute(new Runnable() {
public void run() {
try{
String dbName = args.getString(0);
String id = args.getString(1);
String jsonString = args.getString(2);
Boolean isLocal = args.getBoolean(3);
ObjectMapper mapper = new ObjectMapper();
if (isLocal) {
Map<String, Object> mapDoc = mapper.readValue(jsonString, new TypeReference<Map<String, Object>>() {});
dbs.get(dbName).putLocalDocument(id, mapDoc);
callback.success("local upsert successful");
}
else {
Document doc = dbs.get(dbName).getExistingDocument(id);
Map<String, Object> mapDoc = mapper.readValue(jsonString, new TypeReference<Map<String, Object>>() {});
if(doc != null) doc.putProperties(mapDoc);
else{
Document newDoc = dbs.get(dbName).getDocument(id);
newDoc.putProperties(mapDoc);
}
callback.success("upsert successful");
}
}
catch(final Exception e){
callback.error(e.getMessage());
}
}
});
}
//PLUGIN BOILER PLATE
private Manager startCBLite(Context context) {
try {
// Manager.enableLogging(Log.TAG, Log.VERBOSE);
// Manager.enableLogging(Log.TAG_SYNC, Log.VERBOSE);
// Manager.enableLogging(Log.TAG_QUERY, Log.VERBOSE);
// Manager.enableLogging(Log.TAG_VIEW, Log.VERBOSE);
// Manager.enableLogging(Log.TAG_CHANGE_TRACKER, Log.VERBOSE);
// Manager.enableLogging(Log.TAG_BLOB_STORE, Log.VERBOSE);
// Manager.enableLogging(Log.TAG_DATABASE, Log.VERBOSE);
// Manager.enableLogging(Log.TAG_LISTENER, Log.VERBOSE);
// Manager.enableLogging(Log.TAG_MULTI_STREAM_WRITER, Log.VERBOSE);
// Manager.enableLogging(Log.TAG_REMOTE_REQUEST, Log.VERBOSE);
// Manager.enableLogging(Log.TAG_ROUTER, Log.VERBOSE);
dbmgr = new Manager(new AndroidContext(context), Manager.DEFAULT_OPTIONS);
} catch (IOException e) {
throw new RuntimeException(e);
}
return dbmgr;
}
@Override
public void onResume(boolean multitasking) {
System.out.println("CBLite.onResume() called");
}
@Override
public void onPause(boolean multitasking) {
System.out.println("CBLite.onPause() called");
}
}
|
package org.intermine.dwr;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Constructor;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeSet;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.lucene.queryParser.ParseException;
import org.apache.struts.Globals;
import org.apache.struts.util.MessageResources;
import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;
import org.intermine.InterMineException;
import org.intermine.api.InterMineAPI;
import org.intermine.api.bag.BagManager;
import org.intermine.api.bag.TypeConverter;
import org.intermine.api.mines.FriendlyMineManager;
import org.intermine.api.profile.InterMineBag;
import org.intermine.api.profile.Profile;
import org.intermine.api.profile.ProfileAlreadyExistsException;
import org.intermine.api.profile.ProfileManager;
import org.intermine.api.profile.SavedQuery;
import org.intermine.api.profile.TagManager;
import org.intermine.api.query.WebResultsExecutor;
import org.intermine.api.results.WebTable;
import org.intermine.api.search.Scope;
import org.intermine.api.search.SearchFilterEngine;
import org.intermine.api.search.SearchRepository;
import org.intermine.api.search.WebSearchable;
import org.intermine.api.tag.TagNames;
import org.intermine.api.template.TemplateManager;
import org.intermine.api.template.TemplateQuery;
import org.intermine.api.template.TemplateSummariser;
import org.intermine.api.util.NameUtil;
import org.intermine.metadata.FieldDescriptor;
import org.intermine.metadata.Model;
import org.intermine.objectstore.ObjectStore;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.objectstore.query.Query;
import org.intermine.objectstore.query.ResultsRow;
import org.intermine.pathquery.OrderDirection;
import org.intermine.pathquery.Path;
import org.intermine.pathquery.PathConstraint;
import org.intermine.pathquery.PathException;
import org.intermine.pathquery.PathQuery;
import org.intermine.util.StringUtil;
import org.intermine.util.TypeUtil;
import org.intermine.web.autocompletion.AutoCompleter;
import org.intermine.web.logic.Constants;
import org.intermine.web.logic.config.Type;
import org.intermine.web.logic.config.WebConfig;
import org.intermine.web.logic.query.PageTableQueryMonitor;
import org.intermine.web.logic.query.QueryMonitorTimeout;
import org.intermine.web.logic.results.PagedTable;
import org.intermine.web.logic.results.WebState;
import org.intermine.web.logic.session.QueryCountQueryMonitor;
import org.intermine.web.logic.session.SessionMethods;
import org.intermine.web.logic.widget.EnrichmentWidget;
import org.intermine.web.logic.widget.GraphWidget;
import org.intermine.web.logic.widget.HTMLWidget;
import org.intermine.web.logic.widget.TableWidget;
import org.intermine.web.logic.widget.config.EnrichmentWidgetConfig;
import org.intermine.web.logic.widget.config.GraphWidgetConfig;
import org.intermine.web.logic.widget.config.HTMLWidgetConfig;
import org.intermine.web.logic.widget.config.TableWidgetConfig;
import org.intermine.web.logic.widget.config.WidgetConfig;
import org.intermine.web.util.InterMineLinkGenerator;
import org.json.JSONObject;
/**
* This class contains the methods called through DWR Ajax
*
* @author Xavier Watkins
*
*/
public class AjaxServices
{
protected static final Logger LOG = Logger.getLogger(AjaxServices.class);
private static final Object ERROR_MSG = "Error happened during DWR ajax service.";
private static final String INVALID_NAME_MSG = "Invalid name. Names may only contain letters, "
+ "numbers, spaces, and underscores.";
/**
* Creates a favourite Tag for the given templateName
*
* @param name the name of the template we want to set as a favourite
* @param type type of tag (bag or template)
* @param isFavourite whether or not this item is currently a favourite
*/
public void setFavourite(String name, String type, boolean isFavourite) {
try {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
Profile profile = SessionMethods.getProfile(session);
String nameCopy = name.replaceAll("#039;", "'");
TagManager tagManager = getTagManager();
// already a favourite. turning off.
if (isFavourite) {
tagManager.deleteTag(TagNames.IM_FAVOURITE, nameCopy, type, profile.getUsername());
// not a favourite. turning on.
} else {
tagManager.addTag(TagNames.IM_FAVOURITE, nameCopy, type, profile.getUsername());
}
} catch (RuntimeException e) {
processException(e);
}
}
private static void processWidgetException(Exception e, String widgetId) {
String msg = "Failed to render widget: " + widgetId;
LOG.error(msg, e);
}
private static void processException(Exception e) {
LOG.error(ERROR_MSG, e);
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
}
throw new RuntimeException(e);
}
/**
* Precomputes the given template query
* @param templateName the template query name
* @return a String to guarantee the service ran properly
*/
public String preCompute(String templateName) {
try {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
Profile profile = SessionMethods.getProfile(session);
Map<String, TemplateQuery> templates = profile.getSavedTemplates();
TemplateQuery t = templates.get(templateName);
WebResultsExecutor executor = im.getWebResultsExecutor(profile);
try {
session.setAttribute("precomputing_" + templateName, "true");
executor.precomputeTemplate(t);
} catch (ObjectStoreException e) {
LOG.error("Error while precomputing", e);
} finally {
session.removeAttribute("precomputing_" + templateName);
}
} catch (RuntimeException e) {
processException(e);
}
return "precomputed";
}
/**
* Summarises the given template query.
*
* @param templateName the template query name
* @return a String to guarantee the service ran properly
*/
public String summarise(String templateName) {
try {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
Profile profile = SessionMethods.getProfile(session);
Map<String, TemplateQuery> templates = profile.getSavedTemplates();
TemplateQuery template = templates.get(templateName);
TemplateSummariser summariser = im.getTemplateSummariser();
try {
session.setAttribute("summarising_" + templateName, "true");
summariser.summarise(template);
} catch (ObjectStoreException e) {
LOG.error("Failed to summarise " + templateName, e);
} catch (NullPointerException e) {
NullPointerException e2 = new NullPointerException("No such template "
+ templateName);
e2.initCause(e);
throw e2;
} finally {
session.removeAttribute("summarising_" + templateName);
}
} catch (RuntimeException e) {
processException(e);
}
return "summarised";
}
/**
* Rename a element such as history, name, bag
* @param name the name of the element
* @param type history, saved, bag
* @param reName the new name for the element
* @return the new name of the element as a String
* @exception Exception if the application business logic throws
* an exception
*/
public String rename(String name, String type, String reName)
throws Exception {
String newName;
try {
newName = reName.trim();
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
Profile profile = SessionMethods.getProfile(session);
SavedQuery sq;
if (name.equals(newName) || StringUtils.isEmpty(newName)) {
return name;
}
// TODO get error text from properties file
if (!NameUtil.isValidName(newName)) {
return INVALID_NAME_MSG;
}
if ("history".equals(type)) {
if (profile.getHistory().get(name) == null) {
return "<i>" + name + " does not exist</i>";
}
if (profile.getHistory().get(newName) != null) {
return "<i>" + newName + " already exists</i>";
}
profile.renameHistory(name, newName);
} else if ("saved".equals(type)) {
if (profile.getSavedQueries().get(name) == null) {
return "<i>" + name + " does not exist</i>";
}
if (profile.getSavedQueries().get(newName) != null) {
return "<i>" + newName + " already exists</i>";
}
sq = profile.getSavedQueries().get(name);
profile.deleteQuery(sq.getName());
sq = new SavedQuery(newName, sq.getDateCreated(), sq.getPathQuery());
profile.saveQuery(sq.getName(), sq);
} else if ("bag".equals(type)) {
try {
profile.renameBag(name, newName);
} catch (IllegalArgumentException e) {
return "<i>" + name + " does not exist</i>";
} catch (ProfileAlreadyExistsException e) {
return "<i>" + newName + " already exists</i>";
}
} else {
return "Type unknown";
}
return newName;
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* Generate a new API key for a given user.
* @param username the user to generate the key for.
* @return A new API key, or null if something untoward happens.
* @throws Exception an exception.
*/
public String generateApiKey(String username) throws Exception {
try {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
final ProfileManager pm = im.getProfileManager();
Profile p = pm.getProfile(username);
return pm.generateApiKey(p);
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* Delete a user's API key, thus disabling webservice access. A message "deleted"
* is returned to confirm success.
* @param username The user whose key we should delete.
* @return A confirmation string.
* @throws Exception
*/
public String deleteApiKey(String username) throws Exception {
try {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
final ProfileManager pm = im.getProfileManager();
Profile p = pm.getProfile(username);
p.setApiKey(null);
return "deleted";
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* For a given bag, set its description
* @param bagName the bag
* @param description the description as entered by the user
* @return the description for display on the jsp page
* @throws Exception an exception
*/
public String saveBagDescription(String bagName, String description) throws Exception {
try {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
Profile profile = SessionMethods.getProfile(session);
InterMineBag bag = profile.getSavedBags().get(bagName);
if (bag == null) {
throw new InterMineException("List \"" + bagName + "\" not found.");
}
bag.setDescription(description);
profile.getSearchRepository().descriptionChanged(bag);
return description;
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* Set the description of a view path.
* @param pathString the string representation of the path
* @param description the new description
* @return the description, or null if the description was empty
*/
public String changeViewPathDescription(String pathString, String description) {
try {
String descr = description;
if (description.trim().length() == 0) {
descr = null;
}
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
PathQuery query = SessionMethods.getQuery(session);
Path path = query.makePath(pathString);
Path prefixPath = path.getPrefix();
if (descr == null) {
// setting to null removes the description
query.setDescription(prefixPath.getNoConstraintsString(), null);
} else {
query.setDescription(prefixPath.getNoConstraintsString(), descr);
}
if (descr == null) {
return null;
}
return descr.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">");
} catch (RuntimeException e) {
processException(e);
return null;
} catch (PathException e) {
processException(e);
return null;
}
}
/*
* Cannot be refactored from AjaxServices, else WebContextFactory.get() returns null
*/
private static WebState getWebState() {
HttpSession session = WebContextFactory.get().getSession();
return SessionMethods.getWebState(session);
}
/**
* Get the summary for the given column
* @param summaryPath the path for the column as a String
* @param tableName name of column-owning table
* @return a collection of rows
* @throws Exception an exception
*/
public static List getColumnSummary(String tableName, String summaryPath) throws Exception {
try {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
Profile profile = SessionMethods.getProfile(session);
WebResultsExecutor webResultsExecutor = im.getWebResultsExecutor(profile);
WebTable webTable = (SessionMethods.getResultsTable(session, tableName))
.getWebTable();
PathQuery pathQuery = webTable.getPathQuery();
List<ResultsRow> results = (List) webResultsExecutor.summariseQuery(pathQuery,
summaryPath);
// Start the count of results
Query countQuery = webResultsExecutor.makeSummaryQuery(pathQuery, summaryPath);
QueryCountQueryMonitor clientState
= new QueryCountQueryMonitor(Constants.QUERY_TIMEOUT_SECONDS * 1000, countQuery);
MessageResources messages = (MessageResources) ctx.getHttpServletRequest()
.getAttribute(Globals.MESSAGES_KEY);
String qid = SessionMethods.startQueryCount(clientState, session, messages);
List<ResultsRow> pageSizeResults = new ArrayList<ResultsRow>();
int rowCount = 0;
for (ResultsRow row : results) {
rowCount++;
if (rowCount > 10) {
break;
}
pageSizeResults.add(row);
}
return Arrays.asList(new Object[] {pageSizeResults, qid, new Integer(rowCount)});
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* Return the number of rows of results from the query with the given query id. If the size
* isn't yet available, return null. The query must be started with
* SessionMethods.startPagedTableCount().
* @param qid the id
* @return the row count or null if not yet available
*/
public static Integer getResultsSize(String qid) {
try {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
QueryMonitorTimeout controller = (QueryMonitorTimeout)
SessionMethods.getRunningQueryController(qid, session);
// this could happen if the user navigates away then back to the page
if (controller == null) {
return null;
}
// First tickle the controller to avoid timeout
controller.tickle();
if (controller.isCancelledWithError()) {
LOG.debug("query qid " + qid + " error");
return null;
} else if (controller.isCancelled()) {
LOG.debug("query qid " + qid + " cancelled");
return null;
} else if (controller.isCompleted()) {
LOG.debug("query qid " + qid + " complete");
if (controller instanceof PageTableQueryMonitor) {
PagedTable pt = ((PageTableQueryMonitor) controller).getPagedTable();
return new Integer(pt.getExactSize());
}
if (controller instanceof QueryCountQueryMonitor) {
return new Integer(((QueryCountQueryMonitor) controller).getCount());
}
LOG.debug("query qid " + qid + " - unknown controller type");
return null;
} else {
// query still running
LOG.debug("query qid " + qid + " still running, making client wait");
return null;
}
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* Given a scope, type, tags and some filter text, produce a list of matching WebSearchable, in
* a format useful in JavaScript. Each element of the returned List is a List containing a
* WebSearchable name, a score (from Lucene) and a string with the matching parts of the
* description highlighted.
* @param scope the scope (from TemplateHelper.GLOBAL_TEMPLATE or TemplateHelper.USER_TEMPLATE,
* even though not all WebSearchables are templates)
* @param type the type (from TagTypes)
* @param tags the tags to filter on
* @param filterText the text to pass to Lucene
* @param filterAction toggles favourites filter off an on; will be blank or 'favourites'
* @param callId unique id
* @return a List of Lists
*/
public static List<String> filterWebSearchables(String scope, String type,
List<String> tags, String filterText,
String filterAction, String callId) {
try {
ServletContext servletContext = WebContextFactory.get().getServletContext();
HttpSession session = WebContextFactory.get().getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
ProfileManager pm = im.getProfileManager();
Profile profile = SessionMethods.getProfile(session);
Map<String, WebSearchable> wsMap;
Map<WebSearchable, Float> hitMap = new LinkedHashMap<WebSearchable, Float>();
Map<WebSearchable, String> highlightedDescMap = new HashMap<WebSearchable, String>();
if (filterText != null && filterText.length() > 1) {
wsMap = new LinkedHashMap<String, WebSearchable>();
//Map<WebSearchable, String> scopeMap = new LinkedHashMap<WebSearchable, String>();
SearchRepository globalSearchRepository =
SessionMethods.getGlobalSearchRepository(servletContext);
try {
long time =
SearchRepository.runLeuceneSearch(filterText, scope, type, profile,
globalSearchRepository,
hitMap, null, highlightedDescMap);
LOG.info("Lucene search took " + time + " milliseconds");
} catch (ParseException e) {
LOG.error("couldn't run lucene filter", e);
ArrayList<String> emptyList = new ArrayList<String>();
emptyList.add(callId);
return emptyList;
} catch (IOException e) {
LOG.error("couldn't run lucene filter", e);
ArrayList<String> emptyList = new ArrayList<String>();
emptyList.add(callId);
return emptyList;
}
//long time = System.currentTimeMillis();
for (WebSearchable ws: hitMap.keySet()) {
wsMap.put(ws.getName(), ws);
}
} else {
if (scope.equals(Scope.USER)) {
SearchRepository searchRepository = profile.getSearchRepository();
wsMap = (Map<String, WebSearchable>) searchRepository.getWebSearchableMap(type);
} else {
SearchRepository globalRepository = SessionMethods
.getGlobalSearchRepository(servletContext);
if (scope.equals(Scope.GLOBAL)) {
wsMap = (Map<String, WebSearchable>) globalRepository.
getWebSearchableMap(type);
} else {
// must be "all"
SearchRepository userSearchRepository = profile.getSearchRepository();
Map<String, ? extends WebSearchable> userWsMap =
userSearchRepository.getWebSearchableMap(type);
Map<String, ? extends WebSearchable> globalWsMap =
globalRepository.getWebSearchableMap(type);
wsMap = new HashMap<String, WebSearchable>(userWsMap);
wsMap.putAll(globalWsMap);
}
}
}
Map<String, ? extends WebSearchable> filteredWsMap
= new LinkedHashMap<String, WebSearchable>();
//Filter by aspects (defined in superuser account)
List<String> aspectTags = new ArrayList<String>();
List<String> userTags = new ArrayList<String>();
for (String tag :tags) {
if (tag.startsWith(TagNames.IM_ASPECT_PREFIX)) {
aspectTags.add(tag);
} else {
userTags.add(tag);
}
}
if (aspectTags.size() > 0) {
wsMap = new SearchFilterEngine().filterByTags(wsMap, aspectTags, type,
pm.getSuperuser(), getTagManager());
}
if (profile.getUsername() != null && userTags.size() > 0) {
filteredWsMap = new SearchFilterEngine().filterByTags(wsMap, userTags, type,
profile.getUsername(), getTagManager());
} else {
filteredWsMap = wsMap;
}
List returnList = new ArrayList<String>();
returnList.add(callId);
// We need a modifiable map so we can filter out invalid templates
LinkedHashMap<String, ? extends WebSearchable> modifiableWsMap =
new LinkedHashMap(filteredWsMap);
SearchRepository.filterOutInvalidTemplates(modifiableWsMap);
for (WebSearchable ws: modifiableWsMap.values()) {
List row = new ArrayList();
row.add(ws.getName());
if (filterText != null && filterText.length() > 1) {
row.add(highlightedDescMap.get(ws));
row.add(hitMap.get(ws));
} else {
row.add(ws.getDescription());
}
returnList.add(row);
}
return returnList;
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* For a given bag name and a type different from the bag type, give the number of
* converted objects
*
* @param bagName the name of the bag
* @param type the type to convert to
* @return the number of converted objects
*/
public static int getConvertCountForBag(String bagName, String type) {
try {
HttpSession session = WebContextFactory.get().getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
String pckName = im.getModel().getPackageName();
Profile profile = SessionMethods.getProfile(session);
BagManager bagManager = im.getBagManager();
TemplateManager templateManager = im.getTemplateManager();
WebResultsExecutor webResultsExecutor = im.getWebResultsExecutor(profile);
InterMineBag imBag = null;
int count = 0;
try {
imBag = bagManager.getUserOrGlobalBag(profile, bagName);
List<TemplateQuery> conversionTemplates = templateManager.getConversionTemplates();
PathQuery pathQuery = TypeConverter.getConversionQuery(conversionTemplates,
TypeUtil.instantiate(pckName + "." + imBag.getType()),
TypeUtil.instantiate(pckName + "." + type), imBag);
count = webResultsExecutor.count(pathQuery);
} catch (Exception e) {
throw new RuntimeException(e);
}
return count;
} catch (RuntimeException e) {
processException(e);
return 0;
}
}
/**
* used on REPORT page
*
* For a gene, generate links to other intermines. Include gene and orthologues.
*
* Returns NULL if no values found. It's possible that the identifier in the local mine will
* match more than one entry in the remote mine but this will be handled by the portal of the
* remote mine.
*
* @param organismName gene.organism
* @param primaryIdentifier identifier for gene
* @param symbol identifier for gene or NULL
* @return the links to friendly intermines
*/
public static String getFriendlyMineReportLinks(String organismName,
String primaryIdentifier, String symbol) {
ServletContext servletContext = WebContextFactory.get().getServletContext();
HttpSession session = WebContextFactory.get().getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
Properties webProperties = SessionMethods.getWebProperties(servletContext);
FriendlyMineManager olm = FriendlyMineManager.getInstance(im, webProperties);
InterMineLinkGenerator linkGen = null;
Class<?> clazz
= TypeUtil.instantiate("org.intermine.bio.web.util.FriendlyMineReportLinkGenerator");
Constructor<?> constructor;
try {
constructor = clazz.getConstructor(new Class[] {});
linkGen = (InterMineLinkGenerator) constructor.newInstance(new Object[] {});
} catch (Exception e) {
LOG.error("Failed to instantiate FriendlyMineReportLinkGenerator because: " + e);
return null;
}
return linkGen.getLinks(olm, null, organismName, primaryIdentifier).toString();
}
/**
* For LIST ANALYSIS page - For a mine, test if that mine has orthologues
*
* @param mineName name of a friendly mine
* @param organisms list of organisms for genes in this list
* @param identifiers list of identifiers of genes in this list
* @return the links to friendly intermines or an error message
*/
public static String getFriendlyMineListLinks(String mineName, String organisms,
String identifiers) {
if (StringUtils.isEmpty(mineName) || StringUtils.isEmpty(organisms)
|| StringUtils.isEmpty(identifiers)) {
return null;
}
ServletContext servletContext = WebContextFactory.get().getServletContext();
HttpSession session = WebContextFactory.get().getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
Properties webProperties = SessionMethods.getWebProperties(servletContext);
FriendlyMineManager linkManager = FriendlyMineManager.getInstance(im, webProperties);
InterMineLinkGenerator linkGen = null;
Class<?> clazz
= TypeUtil.instantiate("org.intermine.bio.web.util.FriendlyMineListLinkGenerator");
Constructor<?> constructor;
Collection<JSONObject> results = null;
try {
constructor = clazz.getConstructor(new Class[] {});
linkGen = (InterMineLinkGenerator) constructor.newInstance(new Object[] {});
// runs remote templates (possibly)
results = linkGen.getLinks(linkManager, mineName, organisms, identifiers);
} catch (Exception e) {
LOG.error("Failed to instantiate FriendlyMineListLinkGenerator because: " + e);
return null;
}
if (results == null || results.isEmpty()) {
return null;
}
return results.toString();
}
/**
* Saves information, that some element was toggled - displayed or hidden.
*
* @param elementId element id
* @param opened new aspect state
*/
public static void saveToggleState(String elementId, boolean opened) {
try {
AjaxServices.getWebState().getToggledElements().put(elementId,
Boolean.valueOf(opened));
} catch (RuntimeException e) {
processException(e);
}
}
/**
* Set state that should be saved during the session.
* @param name name of state
* @param value value of state
*/
public static void setState(String name, String value) {
try {
AjaxServices.getWebState().setState(name, value);
} catch (RuntimeException e) {
processException(e);
}
}
/**
* validate bag upload
* @param bagName name of new bag to be validated
* @return error msg to display, if any
*/
public static String validateBagName(String bagName) {
try {
HttpSession session = WebContextFactory.get().getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
Profile profile = SessionMethods.getProfile(session);
BagManager bagManager = im.getBagManager();
bagName = bagName.trim();
// TODO get message text from the properties file
if ("".equals(bagName)) {
return "You cannot save a list with a blank name";
}
if (!NameUtil.isValidName(bagName)) {
return INVALID_NAME_MSG;
}
if (profile.getSavedBags().get(bagName) != null) {
return "The list name you have chosen is already in use";
}
if (bagManager.getGlobalBag(bagName) != null) {
return "The list name you have chosen is already in use -"
+ " there is a public list called " + bagName;
}
return "";
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* validation that happens before new bag is saved
* @param bagName name of new bag
* @param selectedBags bags involved in operation
* @param operation which operation is taking place - delete, union, intersect or subtract
* @return error msg, if any
*/
public static String validateBagOperations(String bagName, String[] selectedBags,
String operation) {
try {
ServletContext servletContext = WebContextFactory.get().getServletContext();
HttpSession session = WebContextFactory.get().getSession();
Profile profile = SessionMethods.getProfile(session);
// TODO get error text from the properties file
if (selectedBags.length == 0) {
return "No lists are selected";
}
if ("delete".equals(operation)) {
for (int i = 0; i < selectedBags.length; i++) {
Set<String> queries = new HashSet<String>();
queries.addAll(queriesThatMentionBag(profile.getSavedQueries(),
selectedBags[i]));
queries.addAll(queriesThatMentionBag(profile.getHistory(), selectedBags[i]));
if (queries.size() > 0) {
return "List " + selectedBags[i] + " cannot be deleted as it is referenced "
+ "by other queries " + queries;
}
}
for (int i = 0; i < selectedBags.length; i++) {
if (profile.getSavedBags().get(selectedBags[i]) == null) {
return "List " + selectedBags[i] + " cannot be deleted as it is a shared "
+ "list";
}
}
} else if (!"copy".equals(operation)) {
Properties properties = SessionMethods.getWebProperties(servletContext);
String defaultName = properties.getProperty("lists.input.example");
if (("".equals(bagName) || (bagName.equalsIgnoreCase(defaultName)))) {
return "New list name is required";
} else if (!NameUtil.isValidName(bagName)) {
return INVALID_NAME_MSG;
}
}
return "";
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* Provide a list of queries that mention a named bag
* @param savedQueries a saved queries map (name -> query)
* @param bagName the name of a bag
* @return the list of queries
*/
private static List<String> queriesThatMentionBag(Map<String, SavedQuery> savedQueries,
String bagName) {
try {
List<String> queries = new ArrayList<String>();
for (Iterator<String> i = savedQueries.keySet().iterator(); i.hasNext();) {
String queryName = (String) i.next();
SavedQuery query = (SavedQuery) savedQueries.get(queryName);
if (query.getPathQuery().getBagNames().contains(bagName)) {
queries.add(queryName);
}
}
return queries;
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* @param widgetId unique id for this widget
* @param bagName name of list
* @param selectedExtraAttribute extra attribute (like organism)
* @return graph widget
*/
public static GraphWidget getProcessGraphWidget(String widgetId, String bagName,
String selectedExtraAttribute) {
try {
ServletContext servletContext = WebContextFactory.get().getServletContext();
HttpSession session = WebContextFactory.get().getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
WebConfig webConfig = SessionMethods.getWebConfig(servletContext);
ObjectStore os = im.getObjectStore();
Model model = os.getModel();
Profile profile = SessionMethods.getProfile(session);
BagManager bagManager = im.getBagManager();
InterMineBag imBag = bagManager.getUserOrGlobalBag(profile, bagName);
Type type = webConfig.getTypes().get(model.getPackageName()
+ "." + imBag.getType());
List<WidgetConfig> widgets = type.getWidgets();
for (WidgetConfig widget: widgets) {
if (widget.getId().equals(widgetId)) {
GraphWidgetConfig graphWidgetConf = (GraphWidgetConfig) widget;
graphWidgetConf.setSession(session);
GraphWidget graphWidget = new GraphWidget(graphWidgetConf, imBag, os,
selectedExtraAttribute);
return graphWidget;
}
}
} catch (RuntimeException e) {
processWidgetException(e, widgetId);
}
return null;
}
/**
* @param widgetId unique id for this widget
* @param bagName name of list
* @return graph widget
*/
public static HTMLWidget getProcessHTMLWidget(String widgetId, String bagName) {
try {
ServletContext servletContext = WebContextFactory.get().getServletContext();
HttpSession session = WebContextFactory.get().getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
WebConfig webConfig = SessionMethods.getWebConfig(servletContext);
Model model = im.getModel();
Profile profile = SessionMethods.getProfile(session);
BagManager bagManager = im.getBagManager();
InterMineBag imBag = bagManager.getUserOrGlobalBag(profile, bagName);
Type type = webConfig.getTypes().get(model.getPackageName()
+ "." + imBag.getType());
List<WidgetConfig> widgets = type.getWidgets();
for (WidgetConfig widget: widgets) {
if (widget.getId().equals(widgetId)) {
HTMLWidgetConfig htmlWidgetConf = (HTMLWidgetConfig) widget;
HTMLWidget htmlWidget = new HTMLWidget(htmlWidgetConf);
return htmlWidget;
}
}
} catch (RuntimeException e) {
processWidgetException(e, widgetId);
}
return null;
}
/**
*
* @param widgetId unique ID for this widget
* @param bagName name of list
* @return table widget
*/
public static TableWidget getProcessTableWidget(String widgetId, String bagName) {
try {
ServletContext servletContext = WebContextFactory.get().getServletContext();
HttpSession session = WebContextFactory.get().getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
WebConfig webConfig = SessionMethods.getWebConfig(servletContext);
ObjectStore os = im.getObjectStore();
Model model = os.getModel();
Profile profile = SessionMethods.getProfile(session);
BagManager bagManager = im.getBagManager();
InterMineBag imBag = bagManager.getUserOrGlobalBag(profile, bagName);
Map<String, List<FieldDescriptor>> classKeys = im.getClassKeys();
Type type = webConfig.getTypes().get(model.getPackageName()
+ "." + imBag.getType());
List<WidgetConfig> widgets = type.getWidgets();
for (WidgetConfig widgetConfig: widgets) {
if (widgetConfig.getId().equals(widgetId)) {
TableWidgetConfig tableWidgetConfig = (TableWidgetConfig) widgetConfig;
tableWidgetConfig.setClassKeys(classKeys);
tableWidgetConfig.setWebConfig(webConfig);
TableWidget tableWidget = new TableWidget(tableWidgetConfig, imBag, os, null);
return tableWidget;
}
}
} catch (RuntimeException e) {
processWidgetException(e, widgetId);
}
return null;
}
/**
*
* @param widgetId unique ID for each widget
* @param bagName name of list
* @param errorCorrection error correction method to use
* @param max maximum value to display
* @param filters list of strings used to filter widget results, ie Ontology
* @param externalLink link to external datasource
* @param externalLinkLabel name of external datasource.
* @return enrichment widget
*/
public static EnrichmentWidget getProcessEnrichmentWidget(String widgetId, String bagName,
String errorCorrection, String max, String filters, String externalLink,
String externalLinkLabel) {
try {
ServletContext servletContext = WebContextFactory.get().getServletContext();
HttpSession session = WebContextFactory.get().getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
WebConfig webConfig = SessionMethods.getWebConfig(servletContext);
ObjectStore os = im.getObjectStore();
Model model = os.getModel();
Profile profile = SessionMethods.getProfile(session);
BagManager bagManager = im.getBagManager();
InterMineBag imBag = bagManager.getUserOrGlobalBag(profile, bagName);
Type type = webConfig.getTypes().get(model.getPackageName()
+ "." + imBag.getType());
List<WidgetConfig> widgets = type.getWidgets();
for (WidgetConfig widgetConfig : widgets) {
if (widgetConfig.getId().equals(widgetId)) {
EnrichmentWidgetConfig enrichmentWidgetConfig =
(EnrichmentWidgetConfig) widgetConfig;
enrichmentWidgetConfig.setExternalLink(externalLink);
enrichmentWidgetConfig.setExternalLinkLabel(externalLinkLabel);
EnrichmentWidget enrichmentWidget = new EnrichmentWidget(
enrichmentWidgetConfig, imBag, os, filters, max,
errorCorrection);
return enrichmentWidget;
}
}
} catch (RuntimeException e) {
processWidgetException(e, widgetId);
}
return null;
}
/**
* Add an ID to the PagedTable selection
* @param selectedId the id
* @param tableId the identifier for the PagedTable
* @param columnIndex the column of the selected id
* @return the field values of the first selected objects
*/
public static List<String> selectId(String selectedId, String tableId, String columnIndex) {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
PagedTable pt = SessionMethods.getResultsTable(session, tableId);
pt.selectId(new Integer(selectedId), (new Integer(columnIndex)).intValue());
Map<String, List<FieldDescriptor>> classKeys = im.getClassKeys();
ObjectStore os = im.getObjectStore();
return pt.getFirstSelectedFields(os, classKeys);
}
/**
* remove an Id from the PagedTable
* @param deSelectId the ID to remove from the selection
* @param tableId the PagedTable identifier
* @return the field values of the first selected objects
*/
public static List<String> deSelectId(String deSelectId, String tableId) {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
PagedTable pt = SessionMethods.getResultsTable(session, tableId);
pt.deSelectId(new Integer(deSelectId));
Map<String, List<FieldDescriptor>> classKeys = im.getClassKeys();
ObjectStore os = im.getObjectStore();
return pt.getFirstSelectedFields(os, classKeys);
}
/**
* Select all the elements in a PagedTable
* @param index the index of the selected column
* @param tableId the PagedTable identifier
*/
public static void selectAll(int index, String tableId) {
HttpSession session = WebContextFactory.get().getSession();
PagedTable pt = SessionMethods.getResultsTable(session, tableId);
pt.clearSelectIds();
pt.setAllSelectedColumn(index);
}
/**
* AJAX request - reorder view.
* @param newOrder the new order as a String
* @param oldOrder the previous order as a String
*/
public void reorder(String newOrder, String oldOrder) {
HttpSession session = WebContextFactory.get().getSession();
List<String> newOrderList =
new LinkedList<String>(StringUtil.serializedSortOrderToMap(newOrder).values());
List<String> oldOrderList =
new LinkedList<String>(StringUtil.serializedSortOrderToMap(oldOrder).values());
List<String> view = SessionMethods.getEditingView(session);
ArrayList<String> newView = new ArrayList<String>();
for (int i = 0; i < view.size(); i++) {
String newi = newOrderList.get(i);
int oldi = oldOrderList.indexOf(newi);
newView.add(view.get(oldi));
}
PathQuery query = SessionMethods.getQuery(session);
query.clearView();
query.addViews(newView);
}
/**
* AJAX request - reorder the constraints.
* @param newOrder the new order as a String
* @param oldOrder the previous order as a String
*/
public void reorderConstraints(String newOrder, String oldOrder) {
HttpSession session = WebContextFactory.get().getSession();
List<String> newOrderList =
new LinkedList<String>(StringUtil.serializedSortOrderToMap(newOrder).values());
List<String> oldOrderList =
new LinkedList<String>(StringUtil.serializedSortOrderToMap(oldOrder).values());
PathQuery query = SessionMethods.getQuery(session);
if (query instanceof TemplateQuery) {
TemplateQuery template = (TemplateQuery) query;
for (int index = 0; index < newOrderList.size() - 1; index++) {
String newi = newOrderList.get(index);
int oldi = oldOrderList.indexOf(newi);
if (index != oldi) {
List<PathConstraint> editableConstraints =
template.getModifiableEditableConstraints();
PathConstraint editableConstraint = editableConstraints.remove(oldi);
editableConstraints.add(index, editableConstraint);
template.setEditableConstraints(editableConstraints);
break;
}
}
}
}
/**
* Add a Node from the sort order
* @param path the Path as a String
* @param direction the direction to sort by
* @exception Exception if the application business logic throws
*/
public void addToSortOrder(String path, String direction)
throws Exception {
HttpSession session = WebContextFactory.get().getSession();
PathQuery query = SessionMethods.getQuery(session);
OrderDirection orderDirection = OrderDirection.ASC;
if ("DESC".equals(direction.toUpperCase())) {
orderDirection = OrderDirection.DESC;
}
query.clearOrderBy();
query.addOrderBy(path, orderDirection);
}
/**
* Work as a proxy for fetching remote file (RSS)
* @param rssURL the url
* @return String representation of a file
*/
public static String getNewsPreview(String rssURL) {
try {
URL url = new URL(rssURL);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
StringBuffer sb = new StringBuffer();
// append to string buffer
while ((str = in.readLine()) != null) {
sb.append(str);
}
in.close();
return sb.toString();
} catch (MalformedURLException e) {
return "";
} catch (IOException e) {
return "";
}
}
/**
* Adds tag and assures that there is only one tag for this combination of tag name, tagged
* Object and type.
* @param tag tag name
* @param taggedObject object id that is tagged by this tag
* @param type tag type
* @return 'ok' string if succeeded else error string
*/
public static String addTag(String tag, String taggedObject, String type) {
String tagName = tag;
LOG.info("Called addTag(). tagName:" + tagName + " taggedObject:"
+ taggedObject + " type: " + type);
try {
HttpServletRequest request = getRequest();
Profile profile = getProfile(request);
tagName = tagName.trim();
HttpSession session = request.getSession();
if (profile.getUsername() != null
&& !StringUtils.isEmpty(tagName)
&& !StringUtils.isEmpty(type)
&& !StringUtils.isEmpty(taggedObject)) {
if (tagExists(tagName, taggedObject, type)) {
return "Already tagged with this tag.";
}
if (!TagManager.isValidTagName(tagName)) {
return INVALID_NAME_MSG;
}
if (tagName.startsWith(TagNames.IM_PREFIX)
&& !SessionMethods.isSuperUser(session)) {
return "You cannot add a tag starting with " + TagNames.IM_PREFIX + ", "
+ "that is a reserved word.";
}
TagManager tagManager = getTagManager();
tagManager.addTag(tagName, taggedObject, type, profile.getUsername());
ServletContext servletContext = session.getServletContext();
if (SessionMethods.isSuperUser(session)) {
SearchRepository tr = SessionMethods.
getGlobalSearchRepository(servletContext);
tr.webSearchableTagChange(type, tagName);
}
return "ok";
}
return "Adding tag failed.";
} catch (Throwable e) {
LOG.error("Adding tag failed", e);
return "Adding tag failed.";
}
}
/**
* Deletes tag.
* @param tagName tag name
* @param tagged id of tagged object
* @param type tag type
* @return 'ok' string if succeeded else error string
*/
public static String deleteTag(String tagName, String tagged, String type) {
LOG.info("Called deleteTag(). tagName:" + tagName + " taggedObject:"
+ tagged + " type: " + type);
try {
HttpServletRequest request = getRequest();
HttpSession session = request.getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
Profile profile = getProfile(request);
TagManager manager = im.getTagManager();
manager.deleteTag(tagName, tagged, type, profile.getUsername());
ServletContext servletContext = session.getServletContext();
if (SessionMethods.isSuperUser(session)) {
SearchRepository tr =
SessionMethods.getGlobalSearchRepository(servletContext);
tr.webSearchableTagChange(type, tagName);
}
return "ok";
} catch (Throwable e) {
LOG.error("Deleting tag failed", e);
return "Deleting tag failed.";
}
}
/**
* Returns all tags of specified tag type together with prefixes of these tags.
* For instance: for tag 'bio:experiment' it automatically adds 'bio' tag.
* @param type tag type
* @return tags
*/
public static Set<String> getTags(String type) {
HttpServletRequest request = getRequest();
final InterMineAPI im = SessionMethods.getInterMineAPI(request.getSession());
TagManager tagManager = im.getTagManager();
Profile profile = getProfile(request);
if (profile.isLoggedIn()) {
return tagManager.getUserTagNames(type, profile.getUsername());
}
return new TreeSet<String>();
}
/**
* Returns all tags by which is specified object tagged.
* @param type tag type
* @param tagged id of tagged object
* @return tags
*/
public static Set<String> getObjectTags(String type, String tagged) {
HttpServletRequest request = getRequest();
final InterMineAPI im = SessionMethods.getInterMineAPI(request.getSession());
TagManager tagManager = im.getTagManager();
Profile profile = getProfile(request);
if (profile.isLoggedIn()) {
return tagManager.getObjectTagNames(tagged, type, profile.getUsername());
}
return new TreeSet<String>();
}
private static boolean tagExists(String tag, String taggedObject, String type) {
HttpServletRequest request = getRequest();
final InterMineAPI im = SessionMethods.getInterMineAPI(request.getSession());
TagManager tagManager = im.getTagManager();
String userName = getProfile(request).getUsername();
return tagManager.getObjectTagNames(taggedObject, type, userName).contains(tag);
}
private static Profile getProfile(HttpServletRequest request) {
return SessionMethods.getProfile(request.getSession());
}
private static HttpServletRequest getRequest() {
return WebContextFactory.get().getHttpServletRequest();
}
private static TagManager getTagManager() {
HttpServletRequest request = getRequest();
final InterMineAPI im = SessionMethods.getInterMineAPI(request.getSession());
return im.getTagManager();
}
/**
* Set the constraint logic on a query to be the given expression.
*
* @param expression the constraint logic for the query
* @throws PathException if the query is invalid
*/
public static void setConstraintLogic(String expression) throws PathException {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
PathQuery query = SessionMethods.getQuery(session);
query.setConstraintLogic(expression);
List<String> messages = query.fixUpForJoinStyle();
for (String message : messages) {
SessionMethods.recordMessage(message, session);
}
}
/**
* Get the grouped constraint logic
* @return a list representing the grouped constraint logic
*/
public static String getConstraintLogic() {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
PathQuery query = SessionMethods.getQuery(session);
return (query.getConstraintLogic());
}
/**
* @param suffix string of input before request for more results
* @param wholeList whether or not to show the entire list or a truncated version
* @param field field name from the table for the lucene search
* @param className class name (table in the database) for lucene search
* @return an array of values for this classname.field
*/
public String[] getContent(String suffix, boolean wholeList, String field, String className) {
ServletContext servletContext = WebContextFactory.get().getServletContext();
AutoCompleter ac = SessionMethods.getAutoCompleter(servletContext);
ac.createRAMIndex(className + "." + field);
if (!wholeList && suffix.length() > 0) {
String[] shortList = ac.getFastList(suffix, field, 31);
return shortList;
} else if (suffix.length() > 2 && wholeList) {
String[] longList = ac.getList(suffix, field);
return longList;
}
String[] defaultList = {""};
return defaultList;
}
}
|
package org.intermine.dwr;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Constructor;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeSet;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.lucene.queryParser.ParseException;
import org.apache.struts.Globals;
import org.apache.struts.util.MessageResources;
import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;
import org.intermine.InterMineException;
import org.intermine.api.InterMineAPI;
import org.intermine.api.bag.BagManager;
import org.intermine.api.bag.TypeConverter;
import org.intermine.api.mines.FriendlyMineManager;
import org.intermine.api.mines.FriendlyMineQueryRunner;
import org.intermine.api.mines.Mine;
import org.intermine.api.profile.BagState;
import org.intermine.api.profile.InterMineBag;
import org.intermine.api.profile.Profile;
import org.intermine.api.profile.ProfileAlreadyExistsException;
import org.intermine.api.profile.ProfileManager;
import org.intermine.api.profile.SavedQuery;
import org.intermine.api.profile.TagManager;
import org.intermine.api.query.WebResultsExecutor;
import org.intermine.api.results.WebTable;
import org.intermine.api.search.Scope;
import org.intermine.api.search.SearchFilterEngine;
import org.intermine.api.search.SearchRepository;
import org.intermine.api.search.WebSearchable;
import org.intermine.api.tag.TagNames;
import org.intermine.api.template.ApiTemplate;
import org.intermine.api.template.TemplateManager;
import org.intermine.api.template.TemplateSummariser;
import org.intermine.api.util.NameUtil;
import org.intermine.metadata.FieldDescriptor;
import org.intermine.metadata.Model;
import org.intermine.objectstore.ObjectStore;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.objectstore.query.Query;
import org.intermine.objectstore.query.ResultsRow;
import org.intermine.pathquery.OrderDirection;
import org.intermine.pathquery.Path;
import org.intermine.pathquery.PathConstraint;
import org.intermine.pathquery.PathException;
import org.intermine.pathquery.PathQuery;
import org.intermine.template.TemplateQuery;
import org.intermine.util.StringUtil;
import org.intermine.util.TypeUtil;
import org.intermine.web.autocompletion.AutoCompleter;
import org.intermine.web.displayer.InterMineLinkGenerator;
import org.intermine.web.logic.Constants;
import org.intermine.web.logic.config.Type;
import org.intermine.web.logic.config.WebConfig;
import org.intermine.web.logic.query.PageTableQueryMonitor;
import org.intermine.web.logic.query.QueryMonitorTimeout;
import org.intermine.web.logic.results.PagedTable;
import org.intermine.web.logic.results.WebState;
import org.intermine.web.logic.session.QueryCountQueryMonitor;
import org.intermine.web.logic.session.SessionMethods;
import org.intermine.web.logic.widget.EnrichmentWidget;
import org.intermine.web.logic.widget.GraphWidget;
import org.intermine.web.logic.widget.HTMLWidget;
import org.intermine.web.logic.widget.TableWidget;
import org.intermine.web.logic.widget.config.EnrichmentWidgetConfig;
import org.intermine.web.logic.widget.config.GraphWidgetConfig;
import org.intermine.web.logic.widget.config.HTMLWidgetConfig;
import org.intermine.web.logic.widget.config.TableWidgetConfig;
import org.intermine.web.logic.widget.config.WidgetConfig;
import org.json.JSONException;
import org.json.JSONObject;
/**
* This class contains the methods called through DWR Ajax
*
* @author Xavier Watkins
*
*/
public class AjaxServices
{
protected static final Logger LOG = Logger.getLogger(AjaxServices.class);
private static final Object ERROR_MSG = "Error happened during DWR ajax service.";
/**
* Creates a favourite Tag for the given templateName
*
* @param name the name of the template we want to set as a favourite
* @param type type of tag (bag or template)
* @param isFavourite whether or not this item is currently a favourite
*/
public void setFavourite(String name, String type, boolean isFavourite) {
try {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
Profile profile = SessionMethods.getProfile(session);
String nameCopy = name.replaceAll("#039;", "'");
TagManager tagManager = getTagManager();
// already a favourite. turning off.
if (isFavourite) {
tagManager.deleteTag(TagNames.IM_FAVOURITE, nameCopy, type, profile.getUsername());
// not a favourite. turning on.
} else {
try {
tagManager.addTag(TagNames.IM_FAVOURITE, nameCopy, type, profile);
} catch (TagManager.TagException e) {
throw new RuntimeException(e);
}
}
} catch (RuntimeException e) {
processException(e);
}
}
private static void processWidgetException(Exception e, String widgetId) {
String msg = "Failed to render widget: " + widgetId;
LOG.error(msg, e);
}
private static void processException(Exception e) {
LOG.error(ERROR_MSG, e);
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
}
throw new RuntimeException(e);
}
/**
* Precomputes the given template query
* @param templateName the template query name
* @return a String to guarantee the service ran properly
*/
public String preCompute(String templateName) {
try {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
Profile profile = SessionMethods.getProfile(session);
Map<String, ApiTemplate> templates = profile.getSavedTemplates();
TemplateQuery t = templates.get(templateName);
WebResultsExecutor executor = im.getWebResultsExecutor(profile);
try {
session.setAttribute("precomputing_" + templateName, "true");
executor.precomputeTemplate(t);
} catch (ObjectStoreException e) {
LOG.error("Error while precomputing", e);
} finally {
session.removeAttribute("precomputing_" + templateName);
}
} catch (RuntimeException e) {
processException(e);
}
return "precomputed";
}
/**
* Summarises the given template query.
*
* @param templateName the template query name
* @return a String to guarantee the service ran properly
*/
public String summarise(String templateName) {
try {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
Profile profile = SessionMethods.getProfile(session);
Map<String, ApiTemplate> templates = profile.getSavedTemplates();
ApiTemplate template = templates.get(templateName);
TemplateSummariser summariser = im.getTemplateSummariser();
try {
session.setAttribute("summarising_" + templateName, "true");
summariser.summarise(template);
} catch (ObjectStoreException e) {
LOG.error("Failed to summarise " + templateName, e);
} catch (NullPointerException e) {
NullPointerException e2 = new NullPointerException("No such template "
+ templateName);
e2.initCause(e);
throw e2;
} finally {
session.removeAttribute("summarising_" + templateName);
}
} catch (RuntimeException e) {
processException(e);
}
return "summarised";
}
/**
* Rename a element such as history, name, bag
* @param name the name of the element
* @param type history, saved, bag
* @param reName the new name for the element
* @return the new name of the element as a String
* @exception Exception if the application business logic throws
* an exception
*/
public String rename(String name, String type, String reName)
throws Exception {
String newName;
try {
newName = reName.trim();
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
Profile profile = SessionMethods.getProfile(session);
SavedQuery sq;
if (name.equals(newName) || StringUtils.isEmpty(newName)) {
return name;
}
// TODO get error text from properties file
if (!NameUtil.isValidName(newName)) {
return NameUtil.INVALID_NAME_MSG;
}
if ("history".equals(type)) {
if (profile.getHistory().get(name) == null) {
return "<i>" + name + " does not exist</i>";
}
if (profile.getHistory().get(newName) != null) {
return "<i>" + newName + " already exists</i>";
}
profile.renameHistory(name, newName);
} else if ("saved".equals(type)) {
if (profile.getSavedQueries().get(name) == null) {
return "<i>" + name + " does not exist</i>";
}
if (profile.getSavedQueries().get(newName) != null) {
return "<i>" + newName + " already exists</i>";
}
sq = profile.getSavedQueries().get(name);
profile.deleteQuery(sq.getName());
sq = new SavedQuery(newName, sq.getDateCreated(), sq.getPathQuery());
profile.saveQuery(sq.getName(), sq);
} else if ("bag".equals(type)) {
try {
profile.renameBag(name, newName);
} catch (IllegalArgumentException e) {
return "<i>" + name + " does not exist</i>";
} catch (ProfileAlreadyExistsException e) {
return "<i>" + newName + " already exists</i>";
}
} else {
return "Type unknown";
}
return newName;
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* Generate a new API key for a given user.
* @param username the user to generate the key for.
* @return A new API key, or null if something untoward happens.
* @throws Exception an exception.
*/
public String generateApiKey(String username) throws Exception {
try {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
final ProfileManager pm = im.getProfileManager();
Profile p = pm.getProfile(username);
return pm.generateApiKey(p);
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* Delete a user's API key, thus disabling webservice access. A message "deleted"
* is returned to confirm success.
* @param username The user whose key we should delete.
* @return A confirmation string.
* @throws Exception if somethign bad happens
*/
public String deleteApiKey(String username)
throws Exception {
try {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
final ProfileManager pm = im.getProfileManager();
Profile p = pm.getProfile(username);
p.setApiKey(null);
return "deleted";
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* For a given bag, set its description
* @param bagName the bag
* @param description the description as entered by the user
* @return the description for display on the jsp page
* @throws Exception an exception
*/
public String saveBagDescription(String bagName, String description) throws Exception {
try {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
Profile profile = SessionMethods.getProfile(session);
InterMineBag bag = profile.getSavedBags().get(bagName);
if (bag == null) {
throw new InterMineException("List \"" + bagName + "\" not found.");
}
bag.setDescription(description);
profile.getSearchRepository().descriptionChanged(bag);
return description;
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* Set the description of a view path.
* @param pathString the string representation of the path
* @param description the new description
* @return the description, or null if the description was empty
*/
public String changeViewPathDescription(String pathString, String description) {
try {
String descr = description;
if (description.trim().length() == 0) {
descr = null;
}
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
PathQuery query = SessionMethods.getQuery(session);
Path path = query.makePath(pathString);
Path prefixPath = path.getPrefix();
if (descr == null) {
// setting to null removes the description
query.setDescription(prefixPath.getNoConstraintsString(), null);
} else {
query.setDescription(prefixPath.getNoConstraintsString(), descr);
}
if (descr == null) {
return null;
}
return descr.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">");
} catch (RuntimeException e) {
processException(e);
return null;
} catch (PathException e) {
processException(e);
return null;
}
}
/*
* Cannot be refactored from AjaxServices, else WebContextFactory.get() returns null
*/
private static WebState getWebState() {
HttpSession session = WebContextFactory.get().getSession();
return SessionMethods.getWebState(session);
}
/**
* This method gets a map of ids of elements that were in the past (during session) toggled and
* returns them in JSON
* @return JSON serialized to a String
* @throws JSONException
*/
public static String getToggledElements() {
HttpSession session = WebContextFactory.get().getSession();
WebState webState = SessionMethods.getWebState(session);
Collection<JSONObject> lists = new HashSet<JSONObject>();
try {
for (Map.Entry<String, Boolean> entry : webState.getToggledElements().entrySet()) {
JSONObject list = new JSONObject();
list.put("id", entry.getKey());
list.put("opened", entry.getValue().toString());
lists.add(list);
}
} catch (JSONException jse) {
LOG.error("Errors generating json objects", jse);
}
return lists.toString();
}
/**
* Get the summary for the given column
* @param summaryPath the path for the column as a String
* @param tableName name of column-owning table
* @return a collection of rows
* @throws Exception an exception
*/
public static List getColumnSummary(String tableName, String summaryPath) throws Exception {
try {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
Profile profile = SessionMethods.getProfile(session);
WebResultsExecutor webResultsExecutor = im.getWebResultsExecutor(profile);
WebTable webTable = (SessionMethods.getResultsTable(session, tableName))
.getWebTable();
PathQuery pathQuery = webTable.getPathQuery();
List<ResultsRow> results = (List) webResultsExecutor.summariseQuery(pathQuery,
summaryPath);
// Start the count of results
Query countQuery = webResultsExecutor.makeSummaryQuery(pathQuery, summaryPath);
QueryCountQueryMonitor clientState
= new QueryCountQueryMonitor(Constants.QUERY_TIMEOUT_SECONDS * 1000, countQuery);
MessageResources messages = (MessageResources) ctx.getHttpServletRequest()
.getAttribute(Globals.MESSAGES_KEY);
String qid = SessionMethods.startQueryCount(clientState, session, messages);
List<ResultsRow> pageSizeResults = new ArrayList<ResultsRow>();
int rowCount = 0;
for (ResultsRow row : results) {
rowCount++;
if (rowCount > 10) {
break;
}
pageSizeResults.add(row);
}
return Arrays.asList(new Object[] {pageSizeResults, qid, new Integer(rowCount)});
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* Return the number of rows of results from the query with the given query id. If the size
* isn't yet available, return null. The query must be started with
* SessionMethods.startPagedTableCount().
* @param qid the id
* @return the row count or null if not yet available
*/
public static Integer getResultsSize(String qid) {
try {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
QueryMonitorTimeout controller = (QueryMonitorTimeout)
SessionMethods.getRunningQueryController(qid, session);
// this could happen if the user navigates away then back to the page
if (controller == null) {
return null;
}
// First tickle the controller to avoid timeout
controller.tickle();
if (controller.isCancelledWithError()) {
LOG.debug("query qid " + qid + " error");
return null;
} else if (controller.isCancelled()) {
LOG.debug("query qid " + qid + " cancelled");
return null;
} else if (controller.isCompleted()) {
LOG.debug("query qid " + qid + " complete");
if (controller instanceof PageTableQueryMonitor) {
PagedTable pt = ((PageTableQueryMonitor) controller).getPagedTable();
return new Integer(pt.getExactSize());
}
if (controller instanceof QueryCountQueryMonitor) {
return new Integer(((QueryCountQueryMonitor) controller).getCount());
}
LOG.debug("query qid " + qid + " - unknown controller type");
return null;
} else {
// query still running
LOG.debug("query qid " + qid + " still running, making client wait");
return null;
}
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* Given a scope, type, tags and some filter text, produce a list of matching WebSearchable, in
* a format useful in JavaScript. Each element of the returned List is a List containing a
* WebSearchable name, a score (from Lucene) and a string with the matching parts of the
* description highlighted.
* @param scope the scope (from TemplateHelper.GLOBAL_TEMPLATE or TemplateHelper.USER_TEMPLATE,
* even though not all WebSearchables are templates)
* @param type the type (from TagTypes)
* @param tags the tags to filter on
* @param filterText the text to pass to Lucene
* @param filterAction toggles favourites filter off an on; will be blank or 'favourites'
* @param callId unique id
* @return a List of Lists
*/
public static List<String> filterWebSearchables(String scope, String type,
List<String> tags, String filterText,
String filterAction, String callId) {
try {
ServletContext servletContext = WebContextFactory.get().getServletContext();
HttpSession session = WebContextFactory.get().getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
ProfileManager pm = im.getProfileManager();
Profile profile = SessionMethods.getProfile(session);
Map<String, WebSearchable> wsMap;
Map<WebSearchable, Float> hitMap = new LinkedHashMap<WebSearchable, Float>();
Map<WebSearchable, String> highlightedDescMap = new HashMap<WebSearchable, String>();
if (filterText != null && filterText.length() > 1) {
wsMap = new LinkedHashMap<String, WebSearchable>();
//Map<WebSearchable, String> scopeMap = new LinkedHashMap<WebSearchable, String>();
SearchRepository globalSearchRepository =
SessionMethods.getGlobalSearchRepository(servletContext);
try {
long time =
SearchRepository.runLeuceneSearch(filterText, scope, type, profile,
globalSearchRepository,
hitMap, null, highlightedDescMap);
LOG.info("Lucene search took " + time + " milliseconds");
} catch (ParseException e) {
LOG.error("couldn't run lucene filter", e);
ArrayList<String> emptyList = new ArrayList<String>();
emptyList.add(callId);
return emptyList;
} catch (IOException e) {
LOG.error("couldn't run lucene filter", e);
ArrayList<String> emptyList = new ArrayList<String>();
emptyList.add(callId);
return emptyList;
}
//long time = System.currentTimeMillis();
for (WebSearchable ws: hitMap.keySet()) {
wsMap.put(ws.getName(), ws);
}
} else {
if (scope.equals(Scope.USER)) {
SearchRepository searchRepository = profile.getSearchRepository();
wsMap = (Map<String, WebSearchable>) searchRepository.getWebSearchableMap(type);
} else {
SearchRepository globalRepository = SessionMethods
.getGlobalSearchRepository(servletContext);
if (scope.equals(Scope.GLOBAL)) {
wsMap = (Map<String, WebSearchable>) globalRepository.
getWebSearchableMap(type);
} else {
// must be "all"
SearchRepository userSearchRepository = profile.getSearchRepository();
Map<String, ? extends WebSearchable> userWsMap =
userSearchRepository.getWebSearchableMap(type);
Map<String, ? extends WebSearchable> globalWsMap =
globalRepository.getWebSearchableMap(type);
wsMap = new HashMap<String, WebSearchable>(userWsMap);
wsMap.putAll(globalWsMap);
}
}
}
Map<String, ? extends WebSearchable> filteredWsMap
= new LinkedHashMap<String, WebSearchable>();
//Filter by aspects (defined in superuser account)
List<String> aspectTags = new ArrayList<String>();
List<String> userTags = new ArrayList<String>();
for (String tag :tags) {
if (tag.startsWith(TagNames.IM_ASPECT_PREFIX)) {
aspectTags.add(tag);
} else {
userTags.add(tag);
}
}
if (aspectTags.size() > 0) {
wsMap = new SearchFilterEngine().filterByTags(wsMap, aspectTags, type,
pm.getSuperuser(), getTagManager());
}
if (profile.getUsername() != null && userTags.size() > 0) {
filteredWsMap = new SearchFilterEngine().filterByTags(wsMap, userTags, type,
profile.getUsername(), getTagManager());
} else {
filteredWsMap = wsMap;
}
List returnList = new ArrayList<String>();
returnList.add(callId);
// We need a modifiable map so we can filter out invalid templates
LinkedHashMap<String, ? extends WebSearchable> modifiableWsMap =
new LinkedHashMap(filteredWsMap);
SearchRepository.filterOutInvalidTemplates(modifiableWsMap);
for (WebSearchable ws: modifiableWsMap.values()) {
List row = new ArrayList();
row.add(ws.getName());
if (filterText != null && filterText.length() > 1) {
row.add(highlightedDescMap.get(ws));
row.add(hitMap.get(ws));
} else {
row.add(ws.getDescription());
}
returnList.add(row);
}
return returnList;
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* For a given bag name and a type different from the bag type, give the number of
* converted objects
*
* @param bagName the name of the bag
* @param type the type to convert to
* @return the number of converted objects
*/
public static int getConvertCountForBag(String bagName, String type) {
try {
HttpSession session = WebContextFactory.get().getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
String pckName = im.getModel().getPackageName();
Profile profile = SessionMethods.getProfile(session);
BagManager bagManager = im.getBagManager();
TemplateManager templateManager = im.getTemplateManager();
WebResultsExecutor webResultsExecutor = im.getWebResultsExecutor(profile);
InterMineBag imBag = null;
int count = 0;
try {
imBag = bagManager.getUserOrGlobalBag(profile, bagName);
List<ApiTemplate> conversionTemplates = templateManager.getConversionTemplates();
PathQuery pathQuery = TypeConverter.getConversionQuery(conversionTemplates,
TypeUtil.instantiate(pckName + "." + imBag.getType()),
TypeUtil.instantiate(pckName + "." + type), imBag);
count = webResultsExecutor.count(pathQuery);
} catch (Exception e) {
throw new RuntimeException(e);
}
return count;
} catch (RuntimeException e) {
processException(e);
return 0;
}
}
/**
* used on REPORT page
*
* For a gene, generate links to other intermines. Include gene and orthologues.
*
* Returns NULL if no values found. It's possible that the identifier in the local mine will
* match more than one entry in the remote mine but this will be handled by the portal of the
* remote mine.
*
* @param mineName name of mine to query
* @param organisms gene.organism
* @param identifiers identifiers for gene
* @return the links to friendly intermines
*/
public static String getFriendlyMineLinks(String mineName, String organisms,
String identifiers) {
if (StringUtils.isEmpty(mineName) || StringUtils.isEmpty(organisms)
|| StringUtils.isEmpty(identifiers)) {
return null;
}
HttpSession session = WebContextFactory.get().getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
FriendlyMineManager fmm = im.getFriendlyMineManager();
InterMineLinkGenerator linkGen = null;
Class<?> clazz
= TypeUtil.instantiate("org.intermine.bio.web.displayer.FriendlyMineLinkGenerator");
Constructor<?> constructor;
try {
constructor = clazz.getConstructor(new Class[] {});
linkGen = (InterMineLinkGenerator) constructor.newInstance(new Object[] {});
} catch (Exception e) {
LOG.error("Failed to instantiate FriendlyMineLinkGenerator because: " + e);
return null;
}
Collection<JSONObject> results = linkGen.getLinks(fmm, mineName, organisms, identifiers);
if (results == null || results.isEmpty()) {
return null;
}
return results.toString();
}
/**
* used on REPORT page
*
* For a gene, display pathways found in other mines for orthologous genes
*
* @param mineName mine to query
* @param orthologues list of genes to query for
* @return the links to friendly intermines
*/
public static String getFriendlyMinePathways(String mineName, String orthologues) {
if (StringUtils.isEmpty(orthologues)) {
return null;
}
HttpSession session = WebContextFactory.get().getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
FriendlyMineManager linkManager = im.getFriendlyMineManager();
Mine mine = linkManager.getMine(mineName);
if (mine == null || mine.getReleaseVersion() == null) {
// mine is dead
return null;
}
final String xmlQuery = "<query name=\"\" model=\"genomic\" view=\"Gene.pathways.id "
+ "Gene.pathways.name\" sortOrder=\"Gene.pathways.name asc\"><constraint path=\"Gene\" "
+ "op=\"LOOKUP\" value=\"" + orthologues + "\" extraValue=\"\"/></query>";
try {
JSONObject results
= FriendlyMineQueryRunner.runJSONWebServiceQuery(mine, xmlQuery);
if (results == null) {
LOG.error("Couldn't query " + mine.getName() + " for pathways");
return null;
}
results.put("mineURL", mine.getUrl());
return results.toString();
} catch (IOException e) {
LOG.error("Couldn't query " + mine.getName() + " for pathways", e);
return null;
} catch (JSONException e) {
LOG.error("Error adding Mine URL to pathways results", e);
return null;
}
}
/**
* Return list of disease ontology terms associated with list of provided rat genes. Returns
* JSONObject as string with ID (intermine ID) and name (ontologyTerm.name)
*
* @param orthologues list of rat genes
* @return JSONobject.toString of JSON object
*/
public static String getRatDiseases(String orthologues) {
if (StringUtils.isEmpty(orthologues)) {
return null;
}
HttpSession session = WebContextFactory.get().getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
FriendlyMineManager linkManager = im.getFriendlyMineManager();
Mine mine = linkManager.getMine("RatMine");
if (mine == null || mine.getReleaseVersion() == null) {
// mine is dead
return null;
}
final String xmlQuery = "<query name=\"rat_disease\" model=\"genomic\" view="
+ "\"Gene.doAnnotation.ontologyTerm.id Gene.doAnnotation.ontologyTerm.name\" "
+ "sortOrder=\"Gene.doAnnotation.ontologyTerm.name asc\"> "
+ "<pathDescription pathString=\"Gene.doAnnotation.ontologyTerm\" "
+ "description=\"Disease Ontology Term\"/> "
+ "<constraint path=\"Gene\" op=\"LOOKUP\" value=\"" + orthologues
+ "\" extraValue=\"\"/></query>";
try {
JSONObject results
= FriendlyMineQueryRunner.runJSONWebServiceQuery(mine, xmlQuery);
if (results != null) {
results.put("mineURL", mine.getUrl());
return results.toString();
}
} catch (IOException e) {
LOG.error("Couldn't query ratmine for diseases", e);
} catch (JSONException e) {
LOG.error("Couldn't process ratmine disease results", e);
}
return null;
}
/**
* Saves information, that some element was toggled - displayed or hidden.
*
* @param elementId element id
* @param opened new aspect state
*/
public static void saveToggleState(String elementId, boolean opened) {
try {
AjaxServices.getWebState().getToggledElements().put(elementId,
Boolean.valueOf(opened));
} catch (RuntimeException e) {
processException(e);
}
}
/**
* Set state that should be saved during the session.
* @param name name of state
* @param value value of state
*/
public static void setState(String name, String value) {
try {
AjaxServices.getWebState().setState(name, value);
} catch (RuntimeException e) {
processException(e);
}
}
/**
* validate bag upload
* @param bagName name of new bag to be validated
* @return error msg to display, if any
*/
public static String validateBagName(String bagName) {
try {
HttpSession session = WebContextFactory.get().getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
Profile profile = SessionMethods.getProfile(session);
BagManager bagManager = im.getBagManager();
bagName = bagName.trim();
// TODO get message text from the properties file
if ("".equals(bagName)) {
return "You cannot save a list with a blank name";
}
if (!NameUtil.isValidName(bagName)) {
return TagManager.INVALID_NAME_MSG;
}
if (profile.getSavedBags().get(bagName) != null) {
return "The list name you have chosen is already in use";
}
if (bagManager.getGlobalBag(bagName) != null) {
return "The list name you have chosen is already in use -"
+ " there is a public list called " + bagName;
}
return "";
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* validation that happens before new bag is saved
* @param bagName name of new list
* @param selectedBags bags involved in operation
* @param operation which operation is taking place - delete, union, intersect or subtract
* @return error msg, if any
*/
public static String validateBagOperations(String bagName, String[] selectedBags,
String operation) {
try {
ServletContext servletContext = WebContextFactory.get().getServletContext();
HttpSession session = WebContextFactory.get().getSession();
Profile profile = SessionMethods.getProfile(session);
// TODO get error text from the properties file
if (selectedBags.length == 0) {
return "No lists are selected";
}
if ("delete".equals(operation)) {
for (int i = 0; i < selectedBags.length; i++) {
Set<String> queries = new HashSet<String>();
queries.addAll(queriesThatMentionBag(profile.getSavedQueries(),
selectedBags[i]));
queries.addAll(queriesThatMentionBag(profile.getHistory(), selectedBags[i]));
if (queries.size() > 0) {
return "List " + selectedBags[i] + " cannot be deleted as it is referenced "
+ "by other queries " + queries;
}
}
for (int i = 0; i < selectedBags.length; i++) {
if (profile.getSavedBags().get(selectedBags[i]) == null) {
return "List " + selectedBags[i] + " cannot be deleted as it is a shared "
+ "list";
}
}
} else if (!"copy".equals(operation)) {
Properties properties = SessionMethods.getWebProperties(servletContext);
String defaultName = properties.getProperty("lists.input.example");
if (bagName.equalsIgnoreCase(defaultName)) {
return "New list name is required";
} else if (!NameUtil.isValidName(bagName)) {
return NameUtil.INVALID_NAME_MSG;
}
}
return "";
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* Provide a list of queries that mention a named bag
* @param savedQueries a saved queries map (name -> query)
* @param bagName the name of a bag
* @return the list of queries
*/
private static List<String> queriesThatMentionBag(Map<String, SavedQuery> savedQueries,
String bagName) {
try {
List<String> queries = new ArrayList<String>();
for (Iterator<String> i = savedQueries.keySet().iterator(); i.hasNext();) {
String queryName = (String) i.next();
SavedQuery query = (SavedQuery) savedQueries.get(queryName);
if (query.getPathQuery().getBagNames().contains(bagName)) {
queries.add(queryName);
}
}
return queries;
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* @param widgetId unique id for this widget
* @param bagName name of list
* @param selectedExtraAttribute extra attribute (like organism)
* @return graph widget
*/
public static GraphWidget getProcessGraphWidget(String widgetId, String bagName,
String selectedExtraAttribute) {
try {
ServletContext servletContext = WebContextFactory.get().getServletContext();
HttpSession session = WebContextFactory.get().getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
WebConfig webConfig = SessionMethods.getWebConfig(servletContext);
ObjectStore os = im.getObjectStore();
Model model = os.getModel();
Profile profile = SessionMethods.getProfile(session);
BagManager bagManager = im.getBagManager();
InterMineBag imBag = bagManager.getUserOrGlobalBag(profile, bagName);
Type type = webConfig.getTypes().get(model.getPackageName()
+ "." + imBag.getType());
List<WidgetConfig> widgets = type.getWidgets();
for (WidgetConfig widget: widgets) {
if (widget.getId().equals(widgetId)) {
GraphWidgetConfig graphWidgetConf = (GraphWidgetConfig) widget;
graphWidgetConf.setSession(session);
GraphWidget graphWidget = new GraphWidget(graphWidgetConf, imBag, os,
selectedExtraAttribute);
if (!graphWidget.getResults().isEmpty()) {
return graphWidget;
}
}
}
} catch (RuntimeException e) {
processWidgetException(e, widgetId);
}
return null;
}
/**
* @param widgetId unique id for this widget
* @param bagName name of list
* @return graph widget
*/
public static HTMLWidget getProcessHTMLWidget(String widgetId, String bagName) {
try {
ServletContext servletContext = WebContextFactory.get().getServletContext();
HttpSession session = WebContextFactory.get().getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
WebConfig webConfig = SessionMethods.getWebConfig(servletContext);
Model model = im.getModel();
Profile profile = SessionMethods.getProfile(session);
BagManager bagManager = im.getBagManager();
InterMineBag imBag = bagManager.getUserOrGlobalBag(profile, bagName);
Type type = webConfig.getTypes().get(model.getPackageName()
+ "." + imBag.getType());
List<WidgetConfig> widgets = type.getWidgets();
for (WidgetConfig widget: widgets) {
if (widget.getId().equals(widgetId)) {
HTMLWidgetConfig htmlWidgetConf = (HTMLWidgetConfig) widget;
HTMLWidget htmlWidget = new HTMLWidget(htmlWidgetConf);
return htmlWidget;
}
}
} catch (RuntimeException e) {
processWidgetException(e, widgetId);
}
return null;
}
/**
*
* @param widgetId unique ID for this widget
* @param bagName name of list
* @return table widget
*/
public static TableWidget getProcessTableWidget(String widgetId, String bagName) {
try {
ServletContext servletContext = WebContextFactory.get().getServletContext();
HttpSession session = WebContextFactory.get().getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
WebConfig webConfig = SessionMethods.getWebConfig(servletContext);
ObjectStore os = im.getObjectStore();
Model model = os.getModel();
Profile profile = SessionMethods.getProfile(session);
BagManager bagManager = im.getBagManager();
InterMineBag imBag = bagManager.getUserOrGlobalBag(profile, bagName);
Map<String, List<FieldDescriptor>> classKeys = im.getClassKeys();
Type type = webConfig.getTypes().get(model.getPackageName()
+ "." + imBag.getType());
List<WidgetConfig> widgets = type.getWidgets();
for (WidgetConfig widgetConfig: widgets) {
if (widgetConfig.getId().equals(widgetId)) {
TableWidgetConfig tableWidgetConfig = (TableWidgetConfig) widgetConfig;
tableWidgetConfig.setClassKeys(classKeys);
tableWidgetConfig.setWebConfig(webConfig);
TableWidget tableWidget = new TableWidget(tableWidgetConfig, imBag, os, null);
return tableWidget;
}
}
} catch (RuntimeException e) {
processWidgetException(e, widgetId);
}
return null;
}
/**
*
* @param widgetId unique ID for each widget
* @param bagName name of list
* @param errorCorrection error correction method to use
* @param max maximum value to display
* @param filters list of strings used to filter widget results, ie Ontology
* @param externalLink link to external datasource
* @param externalLinkLabel name of external datasource.
* @return enrichment widget
*/
public static EnrichmentWidget getProcessEnrichmentWidget(String widgetId, String bagName,
String errorCorrection, String max, String filters, String externalLink,
String externalLinkLabel) {
try {
ServletContext servletContext = WebContextFactory.get().getServletContext();
HttpSession session = WebContextFactory.get().getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
WebConfig webConfig = SessionMethods.getWebConfig(servletContext);
ObjectStore os = im.getObjectStore();
Model model = os.getModel();
Profile profile = SessionMethods.getProfile(session);
BagManager bagManager = im.getBagManager();
InterMineBag imBag = bagManager.getUserOrGlobalBag(profile, bagName);
Type type = webConfig.getTypes().get(model.getPackageName()
+ "." + imBag.getType());
List<WidgetConfig> widgets = type.getWidgets();
for (WidgetConfig widgetConfig : widgets) {
if (widgetConfig.getId().equals(widgetId)) {
EnrichmentWidgetConfig enrichmentWidgetConfig =
(EnrichmentWidgetConfig) widgetConfig;
enrichmentWidgetConfig.setExternalLink(externalLink);
enrichmentWidgetConfig.setExternalLinkLabel(externalLinkLabel);
EnrichmentWidget enrichmentWidget = new EnrichmentWidget(
enrichmentWidgetConfig, imBag, os, filters, max,
errorCorrection);
return enrichmentWidget;
}
}
} catch (RuntimeException e) {
processWidgetException(e, widgetId);
}
return null;
}
/**
* Add an ID to the PagedTable selection
* @param selectedId the id
* @param tableId the identifier for the PagedTable
* @param columnIndex the column of the selected id
* @return the field values of the first selected objects
*/
public static List<String> selectId(String selectedId, String tableId, String columnIndex) {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
PagedTable pt = SessionMethods.getResultsTable(session, tableId);
pt.selectId(new Integer(selectedId), (new Integer(columnIndex)).intValue());
Map<String, List<FieldDescriptor>> classKeys = im.getClassKeys();
ObjectStore os = im.getObjectStore();
return pt.getFirstSelectedFields(os, classKeys);
}
/**
* remove an Id from the PagedTable
* @param deSelectId the ID to remove from the selection
* @param tableId the PagedTable identifier
* @return the field values of the first selected objects
*/
public static List<String> deSelectId(String deSelectId, String tableId) {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
PagedTable pt = SessionMethods.getResultsTable(session, tableId);
pt.deSelectId(new Integer(deSelectId));
Map<String, List<FieldDescriptor>> classKeys = im.getClassKeys();
ObjectStore os = im.getObjectStore();
return pt.getFirstSelectedFields(os, classKeys);
}
/**
* Select all the elements in a PagedTable
* @param index the index of the selected column
* @param tableId the PagedTable identifier
*/
public static void selectAll(int index, String tableId) {
HttpSession session = WebContextFactory.get().getSession();
PagedTable pt = SessionMethods.getResultsTable(session, tableId);
pt.clearSelectIds();
pt.setAllSelectedColumn(index);
}
/**
* AJAX request - reorder view.
* @param newOrder the new order as a String
* @param oldOrder the previous order as a String
*/
public void reorder(String newOrder, String oldOrder) {
HttpSession session = WebContextFactory.get().getSession();
List<String> newOrderList =
new LinkedList<String>(StringUtil.serializedSortOrderToMap(newOrder).values());
List<String> oldOrderList =
new LinkedList<String>(StringUtil.serializedSortOrderToMap(oldOrder).values());
List<String> view = SessionMethods.getEditingView(session);
ArrayList<String> newView = new ArrayList<String>();
for (int i = 0; i < view.size(); i++) {
String newi = newOrderList.get(i);
int oldi = oldOrderList.indexOf(newi);
newView.add(view.get(oldi));
}
PathQuery query = SessionMethods.getQuery(session);
query.clearView();
query.addViews(newView);
}
/**
* AJAX request - reorder the constraints.
* @param newOrder the new order as a String
* @param oldOrder the previous order as a String
*/
public void reorderConstraints(String newOrder, String oldOrder) {
HttpSession session = WebContextFactory.get().getSession();
List<String> newOrderList =
new LinkedList<String>(StringUtil.serializedSortOrderToMap(newOrder).values());
List<String> oldOrderList =
new LinkedList<String>(StringUtil.serializedSortOrderToMap(oldOrder).values());
PathQuery query = SessionMethods.getQuery(session);
if (query instanceof TemplateQuery) {
TemplateQuery template = (TemplateQuery) query;
for (int index = 0; index < newOrderList.size() - 1; index++) {
String newi = newOrderList.get(index);
int oldi = oldOrderList.indexOf(newi);
if (index != oldi) {
List<PathConstraint> editableConstraints =
template.getModifiableEditableConstraints();
PathConstraint editableConstraint = editableConstraints.remove(oldi);
editableConstraints.add(index, editableConstraint);
template.setEditableConstraints(editableConstraints);
break;
}
}
}
}
/**
* Add a Node from the sort order
* @param path the Path as a String
* @param direction the direction to sort by
* @exception Exception if the application business logic throws
*/
public void addToSortOrder(String path, String direction)
throws Exception {
HttpSession session = WebContextFactory.get().getSession();
PathQuery query = SessionMethods.getQuery(session);
OrderDirection orderDirection = OrderDirection.ASC;
if ("DESC".equals(direction.toUpperCase())) {
orderDirection = OrderDirection.DESC;
}
query.clearOrderBy();
query.addOrderBy(path, orderDirection);
}
/**
* Work as a proxy for fetching remote file (RSS)
* @param rssURL the url
* @return String representation of a file
*/
public static String getNewsPreview(String rssURL) {
try {
URL url = new URL(rssURL);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
StringBuffer sb = new StringBuffer();
// append to string buffer
while ((str = in.readLine()) != null) {
sb.append(str);
}
in.close();
return sb.toString();
} catch (MalformedURLException e) {
return "";
} catch (IOException e) {
return "";
}
}
/**
* Adds tag and assures that there is only one tag for this combination of tag name, tagged
* Object and type.
* @param tag tag name
* @param taggedObject object id that is tagged by this tag
* @param type tag type
* @return 'ok' string if succeeded else error string
*/
public static String addTag(String tag, String taggedObject, String type) {
String tagName = tag;
LOG.info("Called addTag(). tagName:" + tagName + " taggedObject:"
+ taggedObject + " type: " + type);
try {
HttpServletRequest request = getRequest();
Profile profile = getProfile(request);
tagName = tagName.trim();
HttpSession session = request.getSession();
if (profile.getUsername() != null
&& !StringUtils.isEmpty(tagName)
&& !StringUtils.isEmpty(type)
&& !StringUtils.isEmpty(taggedObject)) {
if (tagExists(tagName, taggedObject, type)) {
return "Already tagged with this tag.";
}
TagManager tagManager = getTagManager();
try {
tagManager.addTag(tagName, taggedObject, type, profile);
} catch (TagManager.TagNameException e) {
LOG.error("Adding tag failed", e);
return e.getMessage();
} catch (TagManager.TagNamePermissionException e) {
LOG.error("Adding tag failed", e);
return e.getMessage();
}
ServletContext servletContext = session.getServletContext();
if (SessionMethods.isSuperUser(session)) {
SearchRepository tr = SessionMethods.
getGlobalSearchRepository(servletContext);
tr.webSearchableTagChange(type, tagName);
}
return "ok";
}
return "Adding tag failed.";
} catch (Throwable e) {
LOG.error("Adding tag failed", e);
return "Adding tag failed.";
}
}
/**
* Deletes tag.
* @param tagName tag name
* @param tagged id of tagged object
* @param type tag type
* @return 'ok' string if succeeded else error string
*/
public static String deleteTag(String tagName, String tagged, String type) {
LOG.info("Called deleteTag(). tagName:" + tagName + " taggedObject:"
+ tagged + " type: " + type);
try {
HttpServletRequest request = getRequest();
HttpSession session = request.getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
Profile profile = getProfile(request);
TagManager manager = im.getTagManager();
manager.deleteTag(tagName, tagged, type, profile.getUsername());
ServletContext servletContext = session.getServletContext();
if (SessionMethods.isSuperUser(session)) {
SearchRepository tr =
SessionMethods.getGlobalSearchRepository(servletContext);
tr.webSearchableTagChange(type, tagName);
}
return "ok";
} catch (Throwable e) {
LOG.error("Deleting tag failed", e);
return "Deleting tag failed.";
}
}
/**
* Returns all tags of specified tag type together with prefixes of these tags.
* For instance: for tag 'bio:experiment' it automatically adds 'bio' tag.
* @param type tag type
* @return tags
*/
public static Set<String> getTags(String type) {
HttpServletRequest request = getRequest();
final InterMineAPI im = SessionMethods.getInterMineAPI(request.getSession());
TagManager tagManager = im.getTagManager();
Profile profile = getProfile(request);
if (profile.isLoggedIn()) {
return tagManager.getUserTagNames(type, profile.getUsername());
}
return new TreeSet<String>();
}
/**
* Returns all tags by which is specified object tagged.
* @param type tag type
* @param tagged id of tagged object
* @return tags
*/
public static Set<String> getObjectTags(String type, String tagged) {
HttpServletRequest request = getRequest();
final InterMineAPI im = SessionMethods.getInterMineAPI(request.getSession());
TagManager tagManager = im.getTagManager();
Profile profile = getProfile(request);
if (profile.isLoggedIn()) {
return tagManager.getObjectTagNames(tagged, type, profile.getUsername());
}
return new TreeSet<String>();
}
private static boolean tagExists(String tag, String taggedObject, String type) {
HttpServletRequest request = getRequest();
final InterMineAPI im = SessionMethods.getInterMineAPI(request.getSession());
TagManager tagManager = im.getTagManager();
String userName = getProfile(request).getUsername();
return tagManager.getObjectTagNames(taggedObject, type, userName).contains(tag);
}
private static Profile getProfile(HttpServletRequest request) {
return SessionMethods.getProfile(request.getSession());
}
private static HttpServletRequest getRequest() {
return WebContextFactory.get().getHttpServletRequest();
}
private static TagManager getTagManager() {
HttpServletRequest request = getRequest();
final InterMineAPI im = SessionMethods.getInterMineAPI(request.getSession());
return im.getTagManager();
}
/**
* Set the constraint logic on a query to be the given expression.
*
* @param expression the constraint logic for the query
* @throws PathException if the query is invalid
*/
public static void setConstraintLogic(String expression) throws PathException {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
PathQuery query = SessionMethods.getQuery(session);
query.setConstraintLogic(expression);
List<String> messages = query.fixUpForJoinStyle();
for (String message : messages) {
SessionMethods.recordMessage(message, session);
}
}
/**
* Get the grouped constraint logic
* @return a list representing the grouped constraint logic
*/
public static String getConstraintLogic() {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
PathQuery query = SessionMethods.getQuery(session);
return (query.getConstraintLogic());
}
/**
* @param suffix string of input before request for more results
* @param wholeList whether or not to show the entire list or a truncated version
* @param field field name from the table for the lucene search
* @param className class name (table in the database) for lucene search
* @return an array of values for this classname.field
*/
public String[] getContent(String suffix, boolean wholeList, String field, String className) {
ServletContext servletContext = WebContextFactory.get().getServletContext();
AutoCompleter ac = SessionMethods.getAutoCompleter(servletContext);
ac.createRAMIndex(className + "." + field);
// swap "-" for spaces, ticket #2357
suffix = suffix.replace("-", " ");
if (!wholeList && suffix.length() > 0) {
String[] shortList = ac.getFastList(suffix, field, 31);
return shortList;
} else if (suffix.length() > 2 && wholeList) {
String[] longList = ac.getList(suffix, field);
return longList;
}
String[] defaultList = {""};
return defaultList;
}
/**
* This method gets the latest bags from the session (SessionMethods) and returns them in JSON
* @return JSON serialized to a String
* @throws JSONException
*/
@SuppressWarnings("unchecked")
public String getSavedBagStatus() throws JSONException {
HttpSession session = WebContextFactory.get().getSession();
@SuppressWarnings("unchecked")
Map<String, Map<String, Object>> savedBagStatus =
(Map<String, Map<String, Object>>) session.getAttribute(Constants.SAVED_BAG_STATUS);
// this is where my lists go
Collection<JSONObject> lists = new HashSet<JSONObject>();
try {
for (Map.Entry<String, Map<String, Object>> entry : savedBagStatus.entrySet()) {
Map<String, Object> listAttributes = entry.getValue();
// save to the resulting JSON object only if these are 'actionable' lists
if (listAttributes.get("status").equals(BagState.CURRENT.toString()) ||
listAttributes.get("status").equals(BagState.TO_UPGRADE.toString())) {
JSONObject list = new JSONObject();
list.put("name", entry.getKey());
list.put("status", listAttributes.get("status"));
if (listAttributes.containsKey("size")) {
list.put("size", listAttributes.get("size"));
}
lists.add(list);
}
}
} catch (JSONException jse) {
LOG.error("Errors generating json objects", jse);
}
return lists.toString();
}
}
|
package com.exedio.cope;
import com.exedio.cope.util.CacheInfo;
public class HierarchyTest extends AbstractLibTest
{
public HierarchyTest()
{
super(Main.hierarchyModel);
}
public void testHierarchy()
throws IntegrityViolationException, UniqueViolationException
{
// model HierarchySuper
assertEquals(null, HierarchySuper.TYPE.getSupertype());
assertEqualsUnmodifiable(list(HierarchyFirstSub.TYPE, HierarchySecondSub.TYPE), HierarchySuper.TYPE.getSubTypes());
assertEqualsUnmodifiable(list(HierarchyFirstSub.TYPE, HierarchySecondSub.TYPE), HierarchySuper.TYPE.getTypesOfInstances());
assertTrue(HierarchySuper.TYPE.isAssignableFrom(HierarchySuper.TYPE));
assertTrue(HierarchySuper.TYPE.isAssignableFrom(HierarchyFirstSub.TYPE));
assertEqualsUnmodifiable(list(HierarchySuper.superInt, HierarchySuper.superString), HierarchySuper.TYPE.getDeclaredAttributes());
assertEqualsUnmodifiable(list(HierarchySuper.superInt, HierarchySuper.superString), HierarchySuper.TYPE.getAttributes());
assertEqualsUnmodifiable(list(
HierarchySuper.superInt.getSingleUniqueConstraint()
), HierarchySuper.TYPE.getDeclaredUniqueConstraints());
assertEqualsUnmodifiable(list(
HierarchySuper.superInt.getSingleUniqueConstraint()
), HierarchySuper.TYPE.getUniqueConstraints());
assertEqualsUnmodifiable(list(
HierarchySuper.superInt,
HierarchySuper.superInt.getSingleUniqueConstraint(),
HierarchySuper.superString,
HierarchySuper.superStringUpper
), HierarchySuper.TYPE.getDeclaredFeatures());
assertEqualsUnmodifiable(list(
HierarchySuper.superInt,
HierarchySuper.superInt.getSingleUniqueConstraint(),
HierarchySuper.superString,
HierarchySuper.superStringUpper
), HierarchySuper.TYPE.getFeatures());
assertEquals(HierarchySuper.superInt, HierarchySuper.TYPE.getDeclaredFeature("superInt"));
assertEquals(HierarchySuper.superString, HierarchySuper.TYPE.getDeclaredFeature("superString"));
assertEquals(null, HierarchySuper.TYPE.getDeclaredFeature("firstSubString"));
assertEquals(null, HierarchySuper.TYPE.getDeclaredFeature("zack"));
assertEquals(HierarchySuper.superInt, HierarchySuper.TYPE.getFeature("superInt"));
assertEquals(HierarchySuper.superString, HierarchySuper.TYPE.getFeature("superString"));
assertEquals(null, HierarchySuper.TYPE.getFeature("firstSubString"));
assertEquals(null, HierarchySuper.TYPE.getFeature("zack"));
assertTrue(HierarchySuper.TYPE.isAbstract());
assertEquals(HierarchySuper.TYPE, HierarchySuper.superInt.getType());
// model HierarchyFirstSub
assertEquals(HierarchySuper.TYPE, HierarchyFirstSub.TYPE.getSupertype());
assertEqualsUnmodifiable(list(), HierarchyFirstSub.TYPE.getSubTypes());
assertEqualsUnmodifiable(list(HierarchyFirstSub.TYPE), HierarchyFirstSub.TYPE.getTypesOfInstances());
assertFalse(HierarchyFirstSub.TYPE.isAssignableFrom(HierarchySuper.TYPE));
assertTrue(HierarchyFirstSub.TYPE.isAssignableFrom(HierarchyFirstSub.TYPE));
assertFalse(HierarchyFirstSub.TYPE.isAssignableFrom(HierarchySecondSub.TYPE));
assertFalse(HierarchySecondSub.TYPE.isAssignableFrom(HierarchyFirstSub.TYPE));
assertEqualsUnmodifiable(list(HierarchyFirstSub.firstSubString), HierarchyFirstSub.TYPE.getDeclaredAttributes());
assertEqualsUnmodifiable(list(HierarchySuper.superInt, HierarchySuper.superString, HierarchyFirstSub.firstSubString), HierarchyFirstSub.TYPE.getAttributes());
assertEqualsUnmodifiable(list(
HierarchyFirstSub.firstSubString.getSingleUniqueConstraint()
), HierarchyFirstSub.TYPE.getDeclaredUniqueConstraints());
assertEqualsUnmodifiable(list(
HierarchyFirstSub.superInt.getSingleUniqueConstraint(),
HierarchyFirstSub.firstSubString.getSingleUniqueConstraint()
), HierarchyFirstSub.TYPE.getUniqueConstraints());
assertEqualsUnmodifiable(list(
HierarchyFirstSub.firstSubString,
HierarchyFirstSub.firstSubString.getSingleUniqueConstraint(),
HierarchyFirstSub.firstSubStringUpper
), HierarchyFirstSub.TYPE.getDeclaredFeatures());
assertEqualsUnmodifiable(list(
HierarchySuper.superInt,
HierarchySuper.superInt.getSingleUniqueConstraint(),
HierarchySuper.superString,
HierarchySuper.superStringUpper,
HierarchyFirstSub.firstSubString,
HierarchyFirstSub.firstSubString.getSingleUniqueConstraint(),
HierarchyFirstSub.firstSubStringUpper
), HierarchyFirstSub.TYPE.getFeatures());
assertEquals(null, HierarchyFirstSub.TYPE.getDeclaredFeature("superInt"));
assertEquals(null, HierarchyFirstSub.TYPE.getDeclaredFeature("superString"));
assertEquals(HierarchyFirstSub.firstSubString, HierarchyFirstSub.TYPE.getDeclaredFeature("firstSubString"));
assertEquals(null, HierarchyFirstSub.TYPE.getDeclaredFeature("zack"));
assertEquals(HierarchyFirstSub.superInt, HierarchyFirstSub.TYPE.getFeature("superInt"));
assertEquals(HierarchyFirstSub.superString, HierarchyFirstSub.TYPE.getFeature("superString"));
assertEquals(HierarchyFirstSub.firstSubString, HierarchyFirstSub.TYPE.getFeature("firstSubString"));
assertEquals(null, HierarchyFirstSub.TYPE.getFeature("zack"));
assertFalse(HierarchyFirstSub.TYPE.isAbstract());
assertEquals(HierarchyFirstSub.TYPE, HierarchyFirstSub.firstSubString.getType());
final HierarchyFirstSub firstItem = new HierarchyFirstSub(0);
deleteOnTearDown(firstItem);
assertID(0, firstItem);
assertEquals(0, firstItem.getSuperInt());
assertEquals(null, firstItem.getFirstSubString());
firstItem.setSuperInt(2);
assertEquals(2, firstItem.getSuperInt());
assertEquals(null, firstItem.getFirstSubString());
firstItem.setFirstSubString("firstSubString");
assertEquals(2, firstItem.getSuperInt());
assertEquals("firstSubString", firstItem.getFirstSubString());
restartTransaction();
assertEquals(2, firstItem.getSuperInt());
assertEquals("firstSubString", firstItem.getFirstSubString());
firstItem.setSuperInt(0);
final HierarchySecondSub secondItem = new HierarchySecondSub(2);
deleteOnTearDown(secondItem);
assertID(1, secondItem);
assertEquals(2, secondItem.getSuperInt());
assertEquals(null, secondItem.getFirstSubString());
final HierarchySecondSub secondItem2 = new HierarchySecondSub(3);
deleteOnTearDown(secondItem2);
assertID(2, secondItem2);
final HierarchyFirstSub firstItem2 = new HierarchyFirstSub(4);
deleteOnTearDown(firstItem2);
assertID(3, firstItem2);
assertEquals(list(firstItem), firstItem.TYPE.search(firstItem.firstSubString.equal("firstSubString")));
assertEquals(list(), firstItem.TYPE.search(firstItem.firstSubString.equal("firstSubStringX")));
assertContains(firstItem, secondItem, firstItem2, secondItem2, HierarchySuper.TYPE.search(null));
// model HierarchySingle
assertEquals(list(HierarchySingleSub.TYPE), HierarchySingleSuper.TYPE.getSubTypes());
assertEquals(list(HierarchySingleSub.TYPE), HierarchySingleSuper.TYPE.getTypesOfInstances());
assertEquals(list(), HierarchySingleSub.TYPE.getSubTypes());
assertEquals(list(HierarchySingleSub.TYPE), HierarchySingleSub.TYPE.getTypesOfInstances());
assertTrue(HierarchySingleSuper.TYPE.isAbstract());
assertFalse(HierarchySingleSub.TYPE.isAbstract());
final HierarchySingleSub singleSub1a = new HierarchySingleSub();
deleteOnTearDown(singleSub1a);
singleSub1a.setSubString("a");
singleSub1a.setSuperInt(new Integer(1));
final HierarchySingleSub singleSub1b = new HierarchySingleSub(1, "b");
deleteOnTearDown(singleSub1b);
final HierarchySingleSub singleSub2a = new HierarchySingleSub(2, "a");
deleteOnTearDown(singleSub2a);
assertContains(singleSub1a, singleSub1b, singleSub1a.TYPE.search(HierarchySingleSuper.superInt.equal(1)));
assertContains(singleSub1a, singleSub1b, HierarchySingleSuper.TYPE.search(HierarchySingleSuper.superInt.equal(1)));
assertContains(singleSub1a, singleSub2a, singleSub1a.TYPE.search(singleSub1a.subString.equal("a")));
assertContains(singleSub1a, singleSub1a.TYPE.search(HierarchySingleSuper.superInt.equal(1).and(singleSub1a.subString.equal("a"))));
restartTransaction();
assertContains(singleSub1a, singleSub1a.TYPE.search(HierarchySingleSuper.superInt.equal(1).and(singleSub1a.subString.equal("a"))));
assertEquals("a", singleSub2a.getSubString());
assertEquals(new Integer(1), singleSub1b.getSuperInt());
// test polymorphic pointers
assertEquals(null, singleSub1a.getHierarchySuper());
assertEquals(list(null), new Query(singleSub1a.hierarchySuper, singleSub1a.TYPE, singleSub1a.superInt.equal(1).and(singleSub1a.subString.equal("a"))).search());
singleSub1a.setHierarchySuper( firstItem );
assertEquals(firstItem, singleSub1a.getHierarchySuper());
assertEquals(list(firstItem), new Query(singleSub1a.hierarchySuper, singleSub1a.TYPE, singleSub1a.superInt.equal(1).and(singleSub1a.subString.equal("a"))).search());
assertEquals(list(singleSub1a), singleSub1a.TYPE.search(singleSub1a.hierarchySuper.equal(firstItem)));
restartTransaction();
assertEquals(firstItem, singleSub1a.getHierarchySuper());
assertEquals(list(firstItem), new Query(singleSub1a.hierarchySuper, singleSub1a.TYPE, singleSub1a.superInt.equal(1).and(singleSub1a.subString.equal("a"))).search());
assertEquals(list(singleSub1a), singleSub1a.TYPE.search(singleSub1a.hierarchySuper.equal(firstItem)));
singleSub1a.setHierarchySuper(secondItem2);
assertEquals(secondItem2, singleSub1a.getHierarchySuper());
assertEquals(list(secondItem2), new Query(singleSub1a.hierarchySuper, singleSub1a.TYPE, singleSub1a.superInt.equal(1).and(singleSub1a.subString.equal("a"))).search());
assertEquals(list(singleSub1a), singleSub1a.TYPE.search(singleSub1a.hierarchySuper.equal(secondItem2)));
restartTransaction();
assertEquals(secondItem2, singleSub1a.getHierarchySuper());
assertEquals(list(secondItem2), new Query(singleSub1a.hierarchySuper, singleSub1a.TYPE, singleSub1a.superInt.equal(1).and(singleSub1a.subString.equal("a"))).search());
assertEquals(list(singleSub1a), singleSub1a.TYPE.search(singleSub1a.hierarchySuper.equal(secondItem2)));
singleSub1a.setHierarchySuper(null);
assertEquals(null, singleSub1a.getHierarchySuper());
assertEquals(list(null), new Query(singleSub1a.hierarchySuper, singleSub1a.TYPE, singleSub1a.superInt.equal(1).and(singleSub1a.subString.equal("a"))).search());
restartTransaction();
assertEquals(null, singleSub1a.getHierarchySuper());
assertEquals(list(null), new Query(singleSub1a.hierarchySuper, singleSub1a.TYPE, singleSub1a.superInt.equal(1).and(singleSub1a.subString.equal("a"))).search());
}
public void testPolymorphicQueryInvalidation() throws UniqueViolationException
{
final HierarchyFirstSub item = new HierarchyFirstSub(10);
deleteOnTearDown(item);
final Query q1 = new Query(HierarchySuper.TYPE, item.superInt.equal(10));
final Query q2 = new Query(HierarchySuper.TYPE, item.superInt.equal(20));
assertEquals(list(item), q1.search());
assertEquals(list(), q2.search());
item.setSuperInt(20);
assertEquals(list(), q1.search());
assertEquals(list(item), q2.search());
}
public void testModel()
{
model.checkDatabase();
model.dropDatabaseConstraints();
model.createDatabaseConstraints();
assertEquals(list(
HierarchyFirstSub.TYPE,
HierarchySecondSub.TYPE,
HierarchySuper.TYPE,
HierarchySingleSuper.TYPE,
HierarchySingleSub.TYPE
), model.getTypes());
assertEquals(list(
HierarchyFirstSub.TYPE,
HierarchySecondSub.TYPE,
HierarchySingleSub.TYPE
), model.getConcreteTypes());
final CacheInfo[] cacheInfo = model.getCacheInfo();
assertEquals(HierarchyFirstSub.TYPE, cacheInfo[0].getType());
assertEquals(HierarchySecondSub.TYPE, cacheInfo[1].getType());
assertEquals(HierarchySingleSub.TYPE, cacheInfo[2].getType());
assertNotNull(model.getCacheQueryInfo());
model.getCacheQueryHistogram();
assertNotNull(model.getConnectionPoolInfo());
assertNotNull(model.getConnectionPoolInfo().getCounter());
}
}
|
package io.digdag.cli;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.ArrayList;
import java.util.HashMap;
import java.time.Instant;
import java.time.ZoneId;
import java.time.LocalDate;
import java.time.DateTimeException;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.temporal.TemporalAccessor;
import java.util.stream.Collectors;
import java.io.File;
import java.nio.file.Path;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.DynamicParameter;
import com.google.common.base.Optional;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Module;
import com.google.inject.Scopes;
import com.google.inject.util.Modules;
import io.digdag.core.DigdagEmbed;
import io.digdag.core.LocalSite;
import io.digdag.core.repository.Dagfile;
import io.digdag.core.repository.ArchiveMetadata;
import io.digdag.core.repository.WorkflowDefinition;
import io.digdag.core.repository.WorkflowDefinitionList;
import io.digdag.core.session.ArchivedTask;
import io.digdag.core.session.StoredTask;
import io.digdag.core.session.StoredSessionAttemptWithSession;
import io.digdag.core.session.TaskStateCode;
import io.digdag.core.agent.OperatorManager;
import io.digdag.core.agent.TaskCallbackApi;
import io.digdag.core.agent.SetThreadName;
import io.digdag.core.agent.ConfigEvalEngine;
import io.digdag.core.agent.ArchiveManager;
import io.digdag.core.agent.AgentId;
import io.digdag.core.agent.AgentConfig;
import io.digdag.core.workflow.TaskMatchPattern;
import io.digdag.core.workflow.WorkflowCompiler;
import io.digdag.core.config.ConfigLoaderManager;
import io.digdag.spi.TaskRequest;
import io.digdag.spi.TaskResult;
import io.digdag.spi.OperatorFactory;
import io.digdag.spi.ScheduleTime;
import io.digdag.client.config.Config;
import io.digdag.client.config.ConfigException;
import io.digdag.client.config.ConfigFactory;
import static io.digdag.cli.Main.systemExit;
import static io.digdag.server.TempFileManager.deleteFilesIfExistsRecursively;
import static java.util.Locale.ENGLISH;
public class Run
extends Command
{
public static final String DEFAULT_DAGFILE = "digdag.yml";
private static final Logger logger = LoggerFactory.getLogger(Run.class);
@Parameter(names = {"-f", "--file"})
String dagfilePath = null;
@Parameter(names = {"-s", "--status"})
String sessionStatusPath = null;
@DynamicParameter(names = {"-p", "--param"})
Map<String, String> params = new HashMap<>();
@Parameter(names = {"-P", "--params-file"})
String paramsFile = null;
@Parameter(names = {"-t", "--session-time"})
String sessionTime = null;
@Parameter(names = {"-d", "--dry-run"})
boolean dryRun = false;
@Parameter(names = {"-e", "--show-params"})
boolean showParams = false;
@Parameter(names = {"-de"})
boolean dryRunAndShowParams = false;
//@Parameter(names = {"-G", "--graph"})
//String visualizePath = null;
private boolean runAsImplicit = false;
// used by Main
static Run asImplicit()
{
Run command = new Run();
command.runAsImplicit = true;
return command;
}
@Override
public void main()
throws Exception
{
if (dryRunAndShowParams) {
dryRun = showParams = true;
}
if (runAsImplicit && args.isEmpty() && dagfilePath == null) {
throw Main.usage(null);
}
if (dagfilePath == null) {
dagfilePath = DEFAULT_DAGFILE;
}
String taskNamePattern;
switch (args.size()) {
case 0:
taskNamePattern = null;
break;
case 1:
taskNamePattern = args.get(0);
if (!taskNamePattern.startsWith("+")) {
throw usage("Task name must begin with '+': " + taskNamePattern);
}
break;
default:
throw usage(null);
}
run(taskNamePattern);
}
public SystemExitException usage(String error)
{
System.err.println("Usage: digdag run [+task] [options...]");
System.err.println(" Options:");
System.err.println(" -f, --file PATH use this file to load tasks (default: digdag.yml)");
System.err.println(" -s, --status DIR use this directory to read and write session status");
System.err.println(" -p, --param KEY=VALUE overwrite a parameter (use multiple times to set many parameters)");
System.err.println(" -P, --params-file PATH.yml read parameters from a YAML file");
System.err.println(" -d, --dry-run dry-run mode doesn't execute tasks");
System.err.println(" -e, --show-params show task parameters before running a task");
System.err.println(" -t, --session-time \"yyyy-MM-dd[ HH:mm:ss]\" set session_time to this time");
//System.err.println(" -g, --graph OUTPUT.png visualize a task and exit");
Main.showCommonOptions();
return systemExit(error);
}
private final DateTimeFormatter sessionTimeParser =
DateTimeFormatter.ofPattern("yyyy-MM-dd[ HH:mm:ss]", ENGLISH);
public void run(String taskNamePattern) throws Exception
{
Injector injector = new DigdagEmbed.Bootstrap()
.addModules(binder -> {
binder.bind(ResumeStateManager.class).in(Scopes.SINGLETON);
binder.bind(YamlMapper.class).in(Scopes.SINGLETON); // used by ResumeStateManager
binder.bind(Run.class).toInstance(this); // used by OperatorManagerWithSkip
})
.overrideModules((list) -> ImmutableList.of(Modules.override(list).with((binder) -> {
binder.bind(OperatorManager.class).to(OperatorManagerWithSkip.class).in(Scopes.SINGLETON);
})))
.initialize()
.getInjector();
LocalSite localSite = injector.getInstance(LocalSite.class);
localSite.initialize();
final ConfigFactory cf = injector.getInstance(ConfigFactory.class);
final ConfigLoaderManager loader = injector.getInstance(ConfigLoaderManager.class);
final ResumeStateManager rsm = injector.getInstance(ResumeStateManager.class);
Config overwriteParams = cf.create();
if (paramsFile != null) {
overwriteParams.setAll(loader.loadParameterizedFile(new File(paramsFile), cf.create()));
}
for (Map.Entry<String, String> pair : params.entrySet()) {
overwriteParams.set(pair.getKey(), pair.getValue());
}
if (sessionStatusPath != null) {
this.skipTaskReports = (fullName) -> rsm.readSuccessfulTaskReport(new File(sessionStatusPath), fullName);
}
Dagfile dagfile = loader.loadParameterizedFile(new File(dagfilePath), overwriteParams).convert(Dagfile.class);
if (taskNamePattern == null) {
if (dagfile.getDefaultTaskName().isPresent()) {
taskNamePattern = dagfile.getDefaultTaskName().get();
}
else {
throw new ConfigException(String.format(
"run: option is not written at %s file. Please add run: option or add +NAME option to command line", dagfilePath));
}
}
StoredSessionAttemptWithSession attempt = localSite.storeAndStartLocalWorkflows(
ArchiveMetadata.of(
dagfile.getWorkflowList(),
dagfile.getDefaultParams(),
dagfile.getDefaultTimeZone().or(ZoneId.systemDefault())), // TODO should this systemDefault be configurable by cmdline argument?
TaskMatchPattern.compile(taskNamePattern),
overwriteParams,
(sr, timeZone) -> {
Instant time;
if (sessionTime != null) {
TemporalAccessor parsed;
try {
parsed = sessionTimeParser
.withZone(timeZone)
.parse(sessionTime);
}
catch (DateTimeParseException ex) {
throw new ConfigException("-t, --session-time must be \"yyyy-MM-dd\" or \"yyyy-MM-dd HH:mm:SS\" format: " + sessionTime);
}
try {
time = Instant.from(parsed);
}
catch (DateTimeException ex) {
time = LocalDate.from(parsed)
.atStartOfDay(timeZone)
.toInstant();
}
}
else if (sr.isPresent()) {
time = sr.get().lastScheduleTime(Instant.now()).getTime();
}
else {
logger.warn("-t, --session-time option is not set and _schedule in yaml file is not set. Using current time as ${session_time}.");
time = ScheduleTime.alignedNow();
}
return ScheduleTime.runNow(time);
});
logger.debug("Submitting {}", attempt);
localSite.startLocalAgent();
localSite.startMonitor();
// if sessionStatusPath is not set, use workflow.yml.resume.yml
File resumeResultPath = new File(Optional.fromNullable(sessionStatusPath).or("digdag.status"));
rsm.startUpdate(resumeResultPath, attempt);
localSite.runUntilAny();
ArrayList<ArchivedTask> failedTasks = new ArrayList<>();
for (ArchivedTask task : localSite.getSessionStore().getTasksOfAttempt(attempt.getId())) {
if (task.getState() == TaskStateCode.ERROR) {
failedTasks.add(task);
}
logger.debug(" Task["+task.getId()+"]: "+task.getFullName());
logger.debug(" parent: "+task.getParentId().transform(it -> Long.toString(it)).or("(root)"));
logger.debug(" upstreams: "+task.getUpstreams().stream().map(it -> Long.toString(it)).collect(Collectors.joining(",")));
logger.debug(" state: "+task.getState());
logger.debug(" retryAt: "+task.getRetryAt());
logger.debug(" config: "+task.getConfig());
logger.debug(" taskType: "+task.getTaskType());
logger.debug(" exported: "+task.getExportParams());
logger.debug(" stored: "+task.getStoreParams());
logger.debug(" stateParams: "+task.getStateParams());
logger.debug(" in: "+task.getReport().transform(report -> report.getInputs()).or(ImmutableList.of()));
logger.debug(" out: "+task.getReport().transform(report -> report.getOutputs()).or(ImmutableList.of()));
logger.debug(" error: "+task.getError());
}
//if (visualizePath != null) {
// List<WorkflowVisualizerNode> nodes = localSite.getSessionStore().getTasks(attempt.getId(), 1024, Optional.absent())
// .stream()
// .map(it -> WorkflowVisualizerNode.of(it))
// .collect(Collectors.toList());
// Show.show(nodes, new File(visualizePath));
if (!failedTasks.isEmpty()) {
StringBuilder sb = new StringBuilder();
sb.append(String.format("%n"));
for (ArchivedTask task : failedTasks) {
sb.append(String.format(" * %s:%n", task.getFullName()));
String message = task.getError().get("message", String.class, "");
if (message.isEmpty()) {
sb.append(" " + task.getError());
}
else {
int i = message.indexOf("Exception: ");
if (i > 0) {
message = message.substring(i + "Exception: ".length());
}
sb.append(" " + message);
}
sb.append(String.format("%n"));
}
sb.append(String.format("%n"));
sb.append(String.format("Task state is stored at %s directory.%n", resumeResultPath));
sb.append(String.format("Run the workflow again using `-s %s` option to retry this workflow.",
resumeResultPath));
throw systemExit(sb.toString());
}
else if (sessionStatusPath == null) {
rsm.shutdown();
deleteFilesIfExistsRecursively(resumeResultPath);
}
}
private Function<String, TaskResult> skipTaskReports = (fullName) -> null;
public static class OperatorManagerWithSkip
extends OperatorManager
{
private final ConfigFactory cf;
private final Run cmd;
private final YamlMapper yamlMapper;
@Inject
public OperatorManagerWithSkip(
AgentConfig config, AgentId agentId,
TaskCallbackApi callback, ArchiveManager archiveManager,
ConfigLoaderManager configLoader, WorkflowCompiler compiler, ConfigFactory cf,
ConfigEvalEngine evalEngine, Set<OperatorFactory> factories,
Run cmd, YamlMapper yamlMapper)
{
super(config, agentId, callback, archiveManager, configLoader, compiler, cf, evalEngine, factories);
this.cf = cf;
this.cmd = cmd;
this.yamlMapper = yamlMapper;
}
@Override
public void run(TaskRequest request)
{
String fullName = request.getTaskName();
TaskResult result = cmd.skipTaskReports.apply(fullName);
if (result != null) {
try (SetThreadName threadName = new SetThreadName(fullName)) {
logger.info("Skipped");
}
callback.taskSucceeded(
request.getTaskId(), request.getLockId(), agentId,
result);
}
else {
super.run(request);
}
}
@Override
protected TaskResult callExecutor(Path archivePath, String type, TaskRequest mergedRequest)
{
if (cmd.showParams) {
StringBuilder sb = new StringBuilder();
for (String line : yamlMapper.toYaml(mergedRequest.getConfig()).split("\n")) {
sb.append(" ").append(line).append("\n");
}
logger.warn("\n{}", sb.toString());
}
if (cmd.dryRun) {
return TaskResult.empty(cf);
}
else {
return super.callExecutor(archivePath, type, mergedRequest);
}
}
}
}
|
package se.raddo.raddose3D;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* This class defines the absorption properties of the container
* encasing the irradiated sample. In this class the container material
* is defined as a list of its component elements.
* The container introduces an additional attenuation factor to the
* beam before it reaches the sample.
*/
public class ContainerElemental extends Container{
/**
* Conversion of beam energy from MeV to KeV
*/
private static final double MEV_TO_KEV = 1e3;
/**
* Conversion from microns to centimeters
*/
private static final double MICRONS_TO_CENTIMETERS = 1e-4;
/**
* The material that the container is made from
*/
private String material;
/**
* The thickness of the container in microns
*/
private final double thickness;
/**
* The density of the material in grams per centimetre cubed
*/
private final double density;
/**
* The mass attenuation coefficient of the sample
*/
private double massAttenuationCoefficient;
/**
* The mass thickness of the sample. On the NIST website the mass
* thickness is defined as the mass per unit area.
*/
private double massThickness;
/**
* The total fraction attenuation of the X-ray beam due to the container
*/
private double containerAttenuationFraction;
/**
* A list of the elements from which the container is composed
*/
private final List<String> elementNamesList;
/**
* A list of the corresponding element occurrences
*/
private final List<Double> elementNumsList;
/**
* Element database keeping the coefficients of all elements.
*/
private final ElementDatabase elementDB;
/**
* Constructor for the ContainerMixture class.
*
* @param conThickness
* Double type argument giving the thickness of the
* container in microns.
* @param conDensity
* Double type argument giving the density of the
* container in grams per centimetre cubed.
*/
public ContainerElemental(Double conThickness, Double conDensity,
List<String> containerElementNames,
List<Double> containerElementNums) {
/**
* Initialise the instance variables
*/
this.thickness = conThickness;
this.density = conDensity;
this.elementNamesList = containerElementNames;
this.elementNumsList = containerElementNums;
this.elementDB = ElementDatabase.getInstance();
//Loop through elements in the element list and return the full compound as a
//String
this.material = "";
for (int i = 0; i < containerElementNames.size(); i++) {
this.material += containerElementNames.get(i);
int elementAtomNum = (int) Math.round(containerElementNums.get(i));
if (elementAtomNum > 1) {
this.material += String.valueOf(elementAtomNum);
}
}
}
/**
* Calculate the fraction by which the beam is attenuated by the container
*
* @param beam
* The beam object that is used to irradiate the sample
*/
@Override
public void calculateContainerAttenuation(Beam beam) {
extractMassAttenuationCoef(beam);
calculateMassThickness();
this.containerAttenuationFraction = 1 - Math
.exp(-this.massAttenuationCoefficient
* this.massThickness);
}
public void extractMassAttenuationCoef(Beam beam) {
if (this.material == null) {
this.massAttenuationCoefficient = 0;
} else {
//Define/Initialise the local variables
URL nistURL = null;
URLConnection nistConnection = null;
BufferedReader br = null;
String inputLine;
double nistBeamEnergyInMeV = 0;
double nistBeamEnergyInKeV = 0;
double massAttenCoeff = 0;
double nistBeamEnergyInKeVPrevious = 0;
double massAttenCoeffPrevious = 0;
double totalWeight = 0;
//Create arrays to store the mass attenuation coeffcients and the atomic weights
//of each element in the container material.
double[] elementMassAttCoeffs = new double[this.elementNamesList.size()];
double[] elementAtomicWeights = new double[this.elementNamesList.size()];
double[] relativeAtomicWeights = new double[this.elementNamesList.size()];
// Regular expressions used in parsing
Pattern openTag = Pattern.compile("<PRE>");
Pattern closeTag = Pattern.compile("</PRE>");
Pattern scientificNotation = Pattern.compile("[0-9]E[-+][0-9]");
for (int i = 0; i < this.elementNamesList.size(); i++) {
boolean readLine = false;
int indexOfEnergyCol = -1;
//create an element object from the element name using information in the
//ElementDatabase.
Element containerAtom = getParser().getElement(this.elementNamesList.get(i));
//Get the URL string
String urlString = getNISTURL(containerAtom.getAtomicNumber());
//Create a URL object for the relevant NIST table
try {
nistURL = new URL(urlString);
} catch (MalformedURLException e) {
System.out.println("URL " + urlString + " is malformed");
e.printStackTrace();
}
//Open a URL connection
try {
nistConnection = nistURL.openConnection();
} catch (IOException e) {
System.out.print("Cannot read from URL: " + urlString);
e.printStackTrace();
}
//Read the data from the NIST table webpage into a buffered reader
try {
br = new BufferedReader(
new InputStreamReader(nistConnection.getInputStream()));
} catch (IOException e) {
System.out.println("Cannot read from URL: " + urlString);
e.printStackTrace();
}
//Read and parse the data from the buffered reader
try {
//While we haven't reached the end of the file read each line
while ((inputLine = br.readLine()) != null) {
//Check if the line contains the "<PRE>" and "<\PRE>" tags
Matcher openTagMatcher = openTag.matcher(inputLine);
Matcher closeTagMatcher = closeTag.matcher(inputLine);
if (openTagMatcher.find()) {
readLine = true;
} else if (closeTagMatcher.find()) {
readLine = false;
}
//If we are in inside the "<PRE>" tag block then check for
//mass coefficient table
if (readLine) {
//Look for scientific notation in the current line
Matcher scientificNotationotationMatcher =
scientificNotation.matcher(inputLine);
if (scientificNotationotationMatcher.find()) {
//Split the string by whitespace
String[] splitLine = inputLine.split("\\s+");
for (int j = 0; j < splitLine.length; j++) {
if(splitLine[j].indexOf("E") != -1) {
indexOfEnergyCol = j;
break;
}
}
//Extract the beam energy and the mass attenuation coefficient from
//the current line.
nistBeamEnergyInMeV = Double.parseDouble(splitLine[indexOfEnergyCol]);
massAttenCoeff = Double.parseDouble(splitLine[indexOfEnergyCol + 1]);
//Convert the beam energy from MeV to KeV
nistBeamEnergyInKeV = nistBeamEnergyInMeV * MEV_TO_KEV;
//Check if the beam energy on this line of the NIST table
//is bigger than the beam energy of the input beam
if (nistBeamEnergyInKeV > beam.getPhotonEnergy()) {
break;
} else {
nistBeamEnergyInKeVPrevious = nistBeamEnergyInKeV;
massAttenCoeffPrevious = massAttenCoeff;
}
}
}
}
} catch (IOException e) {
System.out.println("Cannot read from URL: " + urlString);
e.printStackTrace();
}
//Get the mass attenuation coefficient given by a linear interpolation
//between the values in the NIST table.
double elementMassAttenuationCoefficient = massAttenCoeffPrevious +
(massAttenCoeff - massAttenCoeffPrevious) *
((beam.getPhotonEnergy() - nistBeamEnergyInKeVPrevious) /
(nistBeamEnergyInKeV - nistBeamEnergyInKeVPrevious));
//Store the interpolated value and the atomic weights.
elementMassAttCoeffs[i] = elementMassAttenuationCoefficient;
elementAtomicWeights[i] = containerAtom.getAtomicWeight();
//Add this element's contribution to the total weight
totalWeight += containerAtom.getAtomicWeight() *
this.elementNumsList.get(i);
}
//Calculate the relative atomic weights and use the weighted average
//to give the overall mass attenuation coefficient.
for (int k = 0; k < this.elementNamesList.size(); k++) {
relativeAtomicWeights[k] = (this.elementNumsList.get(k) *
elementAtomicWeights[k]) / totalWeight;
this.massAttenuationCoefficient += (relativeAtomicWeights[k] *
elementMassAttCoeffs[k]);
}
}
}
/**
* Uses the container atoms (explicitly it uses their atomic numbers) to
* generate the URL to the NIST table with the corresponding mass
* attenuation coefficients.
*
* @param atomicNumber
* The atomic number of the element.
*
* @return
* String of the URL pointing to the location of the mass attenuation
* coefficients.
*/
private String getNISTURL(int atomicNumber) {
return String.format("http://physics.nist.gov/PhysRefData/XrayMassCoef"
+ "/ElemTab/z%s.html", String.format("%02d", atomicNumber));
}
/**
* Calculate the mass thickness of the container. The mass thickness is
* defined as the mass per unit area.
*/
private void calculateMassThickness() {
//Convert container thickness units from microns to centimeters.
double thicknessInCentimeters = MICRONS_TO_CENTIMETERS * this.thickness;
this.massThickness = this.density * thicknessInCentimeters;
}
/**
* Return the mass thickness of the container
*
* @return
* Mass thickness of the sample
*/
public double getMassThickness() {
return this.massThickness;
}
/**
* Return the mass attenuation coefficient of the container
*
* @return
* Mass attenuation coefficient
*/
public double getMassAttenuationCoefficient() {
return this.massAttenuationCoefficient;
}
/**
* Return the attenuation factor of the container
*
* @return
* Attenuation factor
*/
@Override
public double getContainerAttenuationFraction() {
return this.containerAttenuationFraction;
}
/**
* Return the material from which the container is made
*
* @return
* Container material
*/
@Override
public String getContainerMaterial() {
return this.material;
}
/**
* @return the parser
*/
public ElementDatabase getParser() {
return elementDB;
}
/**
* Construct a string that prints details about the sample container.
*/
@Override
public void containerInformation() {
if (this.material != null) {
String s = String.format(
"The mass attenuation coefficient of the %s container "
+ "is %.2f centimetres^2 per gram.%n"
+ "The attenuation fraction of the beam due to the sample"
+ " container of thickness %.2f microns is: %.2f.%n"
, this.material, this.massAttenuationCoefficient
, this.thickness, this.containerAttenuationFraction);
System.out.printf(s);
}
}
}
|
package com.parc.ccn.security.access;
import java.security.Key;
import java.security.PrivateKey;
import java.util.HashMap;
import com.parc.ccn.data.ContentName;
import com.parc.ccn.security.crypto.CCNDigestHelper;
import com.parc.ccn.security.keys.KeyManager;
/**
* A cache for decrypted symmetric keys for access control.
* @author smetters
*
*/
public class KeyCache {
private HashMap<byte [], Key> _keyMap = new HashMap<byte [], Key>();
private HashMap<byte [], PrivateKey> _myKeyMap = new HashMap<byte [], PrivateKey>();
private HashMap<byte [], PrivateKey> _privateKeyMap = new HashMap<byte [], PrivateKey>();
private HashMap<byte [], byte []> _privateKeyIdentifierMap = new HashMap<byte [], byte[]>();
private HashMap<byte [], ContentName> _keyNameMap = new HashMap<byte [], ContentName>();
public KeyCache() {
this(KeyManager.getKeyManager());
}
public KeyCache(KeyManager keyManagerToLoadFrom) {
PrivateKey [] pks = keyManagerToLoadFrom.getSigningKeys();
for (PrivateKey pk : pks) {
addMyPrivateKey(keyManagerToLoadFrom.getPublisherKeyID(pk).digest(), pk);
}
}
Key getKey(byte [] desiredKeyIdentifier) {
Key theKey = _keyMap.get(desiredKeyIdentifier);
if (null == theKey) {
theKey = _privateKeyMap.get(desiredKeyIdentifier);
}
if (null == theKey) {
theKey = _myKeyMap.get(desiredKeyIdentifier);
}
return theKey;
}
public boolean containsKey(byte [] keyIdentifier) {
if ((_keyMap.containsKey(keyIdentifier)) || (_myKeyMap.containsKey(keyIdentifier)) ||
(_privateKeyMap.containsKey(keyIdentifier))) {
return true;
}
return false;
}
public ContentName getKeyName(byte [] keyIdentifier) {
return _keyNameMap.get(keyIdentifier);
}
public ContentName getKeyName(Key key) {
return getKeyName(getKeyIdentifier(key));
}
PrivateKey getPrivateKey(byte [] desiredPublicKeyIdentifier) {
PrivateKey key = _myKeyMap.get(desiredPublicKeyIdentifier);
if (null == key) {
_privateKeyMap.get(desiredPublicKeyIdentifier);
}
return key;
}
void addPrivateKey(ContentName keyName, byte [] publicKeyIdentifier, PrivateKey pk) {
_privateKeyMap.put(publicKeyIdentifier, pk);
_privateKeyIdentifierMap.put(getKeyIdentifier(pk), publicKeyIdentifier);
if (null != keyName)
_keyNameMap.put(publicKeyIdentifier, keyName);
}
void addMyPrivateKey(byte [] publicKeyIdentifier, PrivateKey pk) {
_privateKeyIdentifierMap.put(getKeyIdentifier(pk), publicKeyIdentifier);
_myKeyMap.put(publicKeyIdentifier, pk);
}
public void addKey(ContentName name, Key key) {
byte [] id = getKeyIdentifier(key);
_keyMap.put(id, key);
_keyNameMap.put(id, name);
}
public byte [] getKeyIdentifier(Key key) {
// Works on symmetric and public.
return CCNDigestHelper.digest(key.getEncoded());
}
}
|
package CodeMonkey.project;
import java.util.ArrayList;
import java.util.Random;
import CodeMonkey.genetic.Evaluator;
import CodeMonkey.genetic.Gene;
import CodeMonkey.genetic.GeneFactory;
import CodeMonkey.genetic.Genome;
import CodeMonkey.genetic.Population;
import CodeMonkey.genetic.breed.Breeder;
import CodeMonkey.genetic.champ.ChampionSelector;
import CodeMonkey.genetic.mutate.Mutator;
import processing.core.PApplet;
import processing.core.PGraphics;
import processing.core.PImage;
public class PluggablePluto extends ProjectBase {
public static void main( String[ ] args ) {
PApplet.main( "CodeMonkey.project.PluggablePluto" );
}
private static Random rng = new Random( );
private static class Circle implements Gene {
public int x, y;
public int color;
public int alpha;
public int rad;
public Circle( int x, int y, int color, int alpha, int rad ) {
this.x = x;
this.y = y;
this.color = color;
this.alpha = alpha;
this.rad = rad;
}
public Circle( Circle c ) {
this.x = c.x;
this.y = c.y;
this.color = c.color;
this.alpha = c.alpha;
this.rad = c.rad;
}
}
private class CircleGenetics implements GeneFactory<Circle>, Evaluator<Circle>, ChampionSelector<Circle>, Breeder<Circle>, Mutator<Circle> {
private Random rng = new Random( );
private PGraphics canvas;
private PImage target;
private int nChamp;
private float mChance;
public CircleGenetics( PApplet context, PImage target, int nChamp, float mChance ) {
this.canvas = context.createGraphics( target.width, target.height );
this.target = target;
this.nChamp = nChamp;
this.mChance = mChance;
}
public int makeX( ) {
return this.rng.nextInt( this.target.width );
}
public int makeY( ) {
return this.rng.nextInt( this.target.height );
}
public int makeC( ) {
return this.rng.nextInt( 255 );
}
public int makeA( ) {
return this.rng.nextInt( 50 ) + 50;
}
public int makeR( ) {
return this.rng.nextInt( 8 ) + 2;
}
@Override
public Circle make( ) {
return new Circle(
this.makeX( ),
this.makeY( ),
this.makeC( ),
this.makeA( ),
this.makeR( ) );
}
@Override
public float eval( ArrayList<Circle> genome ) {
float f = 0;
this.canvas.beginDraw( );
this.canvas.background( 0 );
for( Circle c : genome ) {
this.canvas.color( c.color, c.alpha );
this.canvas.ellipse( c.x, c.y, c.rad, c.rad );
}
this.canvas.loadPixels( );
this.target.loadPixels( );
for( int ydx = 0; ydx < this.canvas.height; ++ydx ) {
for( int xdx = 0; xdx < this.canvas.width; ++ xdx ) {
int pdx = xdx + ydx * this.canvas.width;
f += 1.0f - Math.abs( ( this.target.pixels[ pdx ] & 0xFF ) - ( this.canvas.pixels[ pdx ] & 0xFF ) ) / 255f;
}
}
this.canvas.endDraw( );
return f / ( this.canvas.width * this.canvas.height );
}
@Override
public ArrayList<Genome<Circle>> filter( ArrayList<Genome<Circle>> population ) {
ArrayList<Genome<Circle>> champs = new ArrayList<Genome<Circle>>( );
for( int cdx = 0; cdx < this.nChamp; ++cdx )
champs.add( population.get( cdx ) );
return champs;
}
@Override
public ArrayList<Circle> breed( ArrayList<Circle> a, ArrayList<Circle> b ) {
ArrayList<Circle> child = new ArrayList<Circle>( );
for( int gdx = 0; gdx < a.size( ); ++gdx ) {
if( this.rng.nextFloat( ) < 0.5 )
child.add( new Circle( a.get( gdx ) ) );
else
child.add( new Circle( b.get( gdx ) ) );
}
return child;
}
@Override
public void mutate( ArrayList<Circle> genome ) {
for( Circle c : genome ) {
if( this.rng.nextFloat( ) < this.mChance ) {
switch( this.rng.nextInt( 5 ) ) {
case 0:
c.x = this.makeX( );
break;
case 1:
c.y = this.makeY( );
break;
case 2:
c.color = this.makeC( );
break;
case 3:
c.alpha = this.makeA( );
break;
case 4:
c.rad = this.makeR( );
break;
}
}
}
}
}
private PGraphics canvas;
private static int cWidth = 200;
private static int cHeigh = 200;
private PImage tgtImg;
private CircleGenetics cg;
private Population<Circle> genetic;
@Override
public void settings( ) {
this.size( 720, 640 );
this.setName( );
}
@Override
public void setup( ) {
this.canvas = this.createGraphics( cWidth, cHeigh );
this.tgtImg = this.loadImage( dataDir + "Darwin.jpg" );
this.tgtImg.resize( cWidth, cHeigh );
this.tgtImg.filter( POSTERIZE, 8 );
this.tgtImg.filter( GRAY );
this.cg = new CircleGenetics( this, this.tgtImg, 5, 0.03f );
this.genetic = new Population<Circle>( 16, 1024, this.cg );
// DEBUG: Show target image
// this.canvas.beginDraw( );
// this.canvas.image( this.tgtImg, 0, 0, cWidth, cHeigh );
// this.canvas.endDraw( );
}
@Override
public void draw( ) {
// Evaluate all genomes, sort by best fitness
this.genetic.eval( this.cg );
// Pick champions and rebreed
this.genetic.rebreed( this.cg, this.cg, this.cg );
// Draw the best (Assumed 0-index)
ArrayList<Circle> champion = this.genetic.get( 0 );
this.canvas.beginDraw( );
this.canvas.background( 0 );
for( Circle c : champion ) {
this.canvas.fill( c.color, c.alpha );
this.canvas.noStroke( );
this.canvas.ellipse( c.x, c.y, c.rad, c.rad );
}
this.canvas.endDraw( );
this.image( this.canvas, 0, 0, this.pixelWidth, this.pixelHeight );
}
@Override
public void keyPressed( ) {
if( this.key == 'w' )
this.save( this.canvas );
}
}
|
package net.silentchaos512.gems.block;
import java.util.List;
import net.minecraft.block.SoundType;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.item.EnumRarity;
import net.minecraft.item.ItemStack;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.oredict.OreDictionary;
import net.silentchaos512.gems.SilentGems;
import net.silentchaos512.gems.lib.EnumGem;
import net.silentchaos512.gems.lib.Names;
import net.silentchaos512.lib.registry.RecipeMaker;
public class BlockGem extends BlockGemSubtypes {
public final boolean supercharged;
public BlockGem(EnumGem.Set set, boolean supercharged) {
super(set, nameForSet(set, Names.GEM_BLOCK + (supercharged ? "Super" : "")));
this.supercharged = supercharged;
setHardness(supercharged ? 7.0f : 3.0f);
setResistance(supercharged ? 6000000.0F : 30.0f);
setSoundType(SoundType.METAL);
setHarvestLevel("pickaxe", supercharged ? 3 : 1);
}
@Override
public void addRecipes(RecipeMaker recipes) {
for (int i = 0; i < 16; ++i) {
EnumGem gem = getGem(i);
if (supercharged) {
recipes.addShapedOre(gem.name() + "_block_super", gem.getBlockSuper(), " g ", "gog", " g ",
'g', gem.getItemSuperOreName(), 'o', Blocks.OBSIDIAN);
} else {
recipes.addCompression(gem.name() + "_block", gem.getItem(), gem.getBlock(), 9);
}
}
}
@Override
public void addOreDict() {
for (int i = 0; i < 16; ++i) {
EnumGem gem = getGem(i);
if (supercharged) {
OreDictionary.registerOre(gem.getBlockSuperOreName(), gem.getBlockSuper());
} else {
OreDictionary.registerOre(gem.getBlockOreName(), gem.getBlock());
}
}
}
@Override
public void clAddInformation(ItemStack stack, World world, List<String> list, boolean advanced) {
String str = blockName.replaceFirst("Dark", "");
list.addAll(SilentGems.localizationHelper.getBlockDescriptionLines(str));
}
@Override
public EnumRarity getRarity(int meta) {
return supercharged ? EnumRarity.RARE : EnumRarity.COMMON;
}
@Override
public boolean canEntityDestroy(IBlockState state, IBlockAccess world, BlockPos pos,
Entity entity) {
// Does not prevent Withers from breaking. Only the Ender Dragon seems to call this...
if (supercharged) {
return entity instanceof EntityPlayer;
}
return super.canEntityDestroy(state, world, pos, entity);
}
@Override
public boolean isBeaconBase(IBlockAccess worldObj, BlockPos pos, BlockPos beacon) {
return true;
}
}
|
package dwriter;
import dwriter.core.WorkFile;
import dwriter.core.WorkFileV1;
import dwriter.ctrl.WorkFileFactory;
import dwriter.ui.FileChooser;
import dwriter.ui.Frame;
import java.awt.List;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Scanner;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
public class Dwriter {
/**
* The filename of the default properties, loaded from the directory of the
* class
*/
private static final String DEFAULT_PROPERTIES_FILENAME = "defaults.xml";
/**
* The filename of the user properties, loaded from the user's current
* working directory
*/
private static final String USER_PROPERTIES_FILENAME = "dwriter.xml";
/**
* The open files
*/
private ArrayList<WorkFile> workfiles = new ArrayList<>();
/**
* The active file (on display)
*/
private WorkFile activeWorkFile;
/**
* The factory of workfiles
*/
private WorkFileFactory workFileFactory;
/**
* The application's properties
*/
private Properties props;
/**
* The main window of the application.
*/
private Frame frame;
/**
* Creates the Dwriter application.
*/
public Dwriter() {
workFileFactory = new WorkFileFactory();
addNewWorkFile();
/*System.out.println(I18N.getInstance().getString("test"));
I18N.getInstance().setLanguage(Lang.EN);
System.out.println(I18N.getInstance().getString("test"));*/
// Loads extensions
//ExtensionManager.getInstance();
// Loads default properties
loadProperties();
//System.out.println(props.getProperty("i18n.language"));
// Creates user interface
frame = new dwriter.ui.Frame.Creator(this).createAndWait();
}
/**
* Adds a new workfile to the arraylist of workfiles in display on the
* frame. And sets this new WorkFile as the active one.
*/
public void addNewWorkFile() {
// For now its only one tab...
// otherwise remove this if
if(workfiles.size() == 1) {
workfiles.remove(0);
}
WorkFile obj = workFileFactory.getWorkFileV1("Sem titulo", "", null);
workfiles.add(obj);
activeWorkFile = workfiles.get(workfiles.size() - 1);
}
/**
* Adds a new workfile to the arraylist of workfiles in display on the
* frame. And sets this new WorkFile as the active one.
*
* @param workFile
*/
public void addNewWorkFile(WorkFile workFile) {
// For now its only one tab...
workfiles.remove(0);
workfiles.add(workFile);
activeWorkFile = workfiles.get(workfiles.size() - 1);
}
/**
*
* @return
*/
public ArrayList<WorkFile> getWorkFiles() {
return workfiles;
}
/**
* Returns the workFile in use.
*
* @return the active workFile
*/
public WorkFile getActiveWorkFile() {
return activeWorkFile;
}
/**
*
* @return
*/
public boolean saveActiveWorkFile() {
int op = -1;
// Checks if its a new file or not ()
if (activeWorkFile.getFile() != null) {
String content = loadContent(activeWorkFile.getFile());
// Checks if the content has been altered
if (!activeWorkFile.getContent().equals(content)) {
op = yesNoCancelMessage("Do you want to save the changes?", "Save");
switch (op) {
case 0:
// hit the Yes option (will save)
saveFile(activeWorkFile);
return true;
case 1:
// hit the No option (wont save)
return true;
default:
break;
}
} else {
// No need to save (No changes was made to the active work file)
return true;
}
} else if (!activeWorkFile.getContent().equals("")) {
op = yesNoCancelMessage("Do you want to save the changes?", "Save");
switch (op) {
case 0:
// hit the Yes option (will save)
saveAsFile(activeWorkFile);
return true;
case 1:
// hit the No option (wont save)
return true;
default:
break;
}
} else {
return true;
}
return false;
}
/**
*
* @param workFile
*/
public void saveFile(WorkFile workFile) {
Formatter formatter;
try {
formatter = new Formatter(workFile.getFile());
formatter.format(workFile.getContent());
formatter.close();
} catch (FileNotFoundException ex) {
System.out.println(ex.getMessage());
}
}
/**
*
* @param workFile
*/
public void saveAsFile(WorkFile workFile) {
FileChooser chooser = new FileChooser();
Formatter formatter;
File saveFile;
int r = chooser.showSaveDialog(frame);
if (r == JFileChooser.APPROVE_OPTION) {
saveFile = chooser.getSelectedFile();
try {
formatter = new Formatter(saveFile);
formatter.format(workFile.getContent());
formatter.close();
} catch (FileNotFoundException ex) {
System.out.println(ex.getMessage());
}
}
}
/**
*
* @param message
* @param top
* @return
*/
public int yesNoCancelMessage(String message, String top) {
int op = -1;
Object[] options = {"Yes", "No", "Cancel"};
op = JOptionPane.showOptionDialog(frame,
message,
top,
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
2);
return op;
}
/**
* This method loads the data of the selected file. If an error occurred it
* will return null.
*
* @param file
* @return file content
*/
public String loadContent(File file) {
Scanner in = null;
String data;
StringBuilder stringB = new StringBuilder((int) file.length());
String lineSeparator = System.getProperty("line.separator");
try {
in = new Scanner(file);
while (in.hasNextLine()) {
stringB.append(in.nextLine()).append(lineSeparator);
}
data = stringB.toString();
} catch (FileNotFoundException ex) {
System.out.println(ex.getMessage());
return null;
} finally {
in.close();
}
return data;
}
/**
* Loads default properties.
*/
private void loadDefaultProperties() {
Properties defaultProps = new Properties();
InputStream defaultStream = Dwriter.class.
getResourceAsStream(DEFAULT_PROPERTIES_FILENAME);
if (defaultStream != null) {
try {
defaultProps.loadFromXML(defaultStream);
} catch (IOException e) {
e.getLocalizedMessage();
System.err.println("Could not load default application "
+ "properties.");
} finally {
try {
if (defaultStream != null) {
defaultStream.close();
}
} catch (IOException e) {
}
}
}
props = defaultProps;
}
/**
* Loads user properties.
*/
private void loadProperties() {
try {
FileInputStream uProps = new FileInputStream(USER_PROPERTIES_FILENAME);
props = new Properties();
//InputStream uProps = Dwriter.class.
// getResourceAsStream(USER_PROPERTIES_FILENAME);
props.loadFromXML(uProps);
uProps.close();
} catch (NullPointerException | IOException ex) {
ex.getMessage();
System.err.println("no user properties.");
loadDefaultProperties();
createUserProperties();
}
}
private void createUserProperties() {
try {
Properties uProps = new Properties();
uProps.setProperty("mainwindow.width",
props.getProperty("mainwindow.width"));
uProps.setProperty("mainwindow.height",
props.getProperty("mainwindow.height"));
uProps.setProperty("i18n.language",
props.getProperty("i18n.language"));
FileOutputStream out = new FileOutputStream(USER_PROPERTIES_FILENAME);
//File f = new File(USER_PROPERTIES_FILENAME);
//OutputStream out = new FileOutputStream(f);
uProps.storeToXML(out, null);
out.close();
props = uProps;
} catch (NullPointerException | IOException e) {
e.getMessage();
System.err.println("Error creating user properties!");
}
}
//public void saveUserProperties() {}
/**
* Returns the current user properties.
*
* @return the current user properties
*/
public Properties getUserProperties() {
return props;
}
/**
* Exits the application.
*/
public void exit() {
// Stores properties
/*if (props.size() > 0) {
try {
props.storeToXML("CleanSheets User Properties ("
+ DateFormat.getDateTimeInstance().format(new Date()) + ")");
} catch (IOException e) {
System.err.println("An error occurred while saving properties.");
}
}*/
// Terminates the virtual machine
System.exit(0);
}
/**
* Starts Driter from the command-line.
*
* @param args the command-line arguments (not used)
*/
public static void main(String[] args) {
Dwriter app = new Dwriter();
// Configures look and feel
/*javax.swing.JFrame.setDefaultLookAndFeelDecorated(true);
javax.swing.JDialog.setDefaultLookAndFeelDecorated(false);
try {
javax.swing.UIManager.setLookAndFeel(
javax.swing.UIManager.getCrossPlatformLookAndFeelClassName());
} catch (Exception e) {
}*/
}
}
|
package net.bull.javamelody;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.util.Locale;
import java.util.StringTokenizer;
/**
* PID du process java.
*/
final class PID {
private PID() {
super();
}
/**
* @return PID du process java
*/
static String getPID() {
String pid = System.getProperty("pid");
if (pid == null) {
final RuntimeMXBean rtb = ManagementFactory.getRuntimeMXBean();
final String processName = rtb.getName();
/* tested on: */
/* - windows xp sp 2, java 1.5.0_13 */
/* - mac os x 10.4.10, java 1.5.0 */
/* - debian linux, java 1.5.0_13 */
/* all return pid@host, e.g 2204@antonius */
if (processName.indexOf('@') != -1) {
pid = processName.substring(0, processName.indexOf('@'));
} else {
// following is not always reliable as is (for example, see issue 3 on solaris 10
final String[] cmd;
File tempFile = null;
Process process = null;
try {
try {
if (!System.getProperty("os.name").toLowerCase(Locale.getDefault())
.contains("windows")) {
cmd = new String[] { "/bin/sh", "-c", "echo $$ $PPID" };
} else {
tempFile = File.createTempFile("getpids", ".exe");
// extract the embedded getpids.exe file from the jar and save it to above file
pump(PID.class.getResourceAsStream("resource/getpids.exe"),
new FileOutputStream(tempFile), true, true);
cmd = new String[] { tempFile.getAbsolutePath() };
}
process = Runtime.getRuntime().exec(cmd);
final ByteArrayOutputStream bout = new ByteArrayOutputStream();
pump(process.getInputStream(), bout, false, true);
final StringTokenizer stok = new StringTokenizer(bout.toString());
stok.nextToken(); // this is pid of the process we spanned
pid = stok.nextToken();
process.waitFor();
} finally {
if (process != null) {
process.getInputStream().close();
process.getOutputStream().close();
process.getErrorStream().close();
process.destroy();
}
if (tempFile != null && !tempFile.delete()) {
tempFile.deleteOnExit();
}
}
} catch (final InterruptedException e) {
pid = e.toString();
} catch (final IOException e) {
pid = e.toString();
}
}
System.setProperty("pid", pid);
}
return pid;
}
private static void pump(InputStream is, OutputStream os, boolean closeIn, boolean closeOut)
throws IOException {
try {
TransportFormat.pump(is, os);
} finally {
try {
if (closeIn) {
is.close();
}
} finally {
if (closeOut) {
os.close();
}
}
}
}
}
|
package com.mfk.web.maker.client;
import java.util.Vector;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.search.client.DrawMode;
import com.google.gwt.search.client.ExpandMode;
import com.google.gwt.search.client.ImageResult;
import com.google.gwt.search.client.ImageSearch;
import com.google.gwt.search.client.KeepHandler;
import com.google.gwt.search.client.LinkTarget;
import com.google.gwt.search.client.Result;
import com.google.gwt.search.client.ResultSetSize;
import com.google.gwt.search.client.SafeSearchValue;
import com.google.gwt.search.client.SearchControl;
import com.google.gwt.search.client.SearchControlOptions;
import com.google.gwt.search.client.SearchResultsHandler;
import com.google.gwt.search.client.SearchStartingHandler;
import com.google.gwt.search.client.WebSearch;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.UIObject;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
// TODO(mjkelly): See this example:
// https://code.google.com/apis/ajax/playground/#raw_search
/**
* Entry point classes define <code>onModuleLoad()</code>.
*/
public class MfkMaker implements EntryPoint {
/**
* This is the entry point method.
*/
public static Image selected;
// arrays holding the attributes of the 3 items in the new triple
public static TextBox names[] = {new TextBox(),
new TextBox(),
new TextBox()};
public static Image images[] = {null, null, null};
public static Button setButtons[] = {new Button("Set Item 1"),
new Button("Set Item 2"),
new Button("Set Item 3")};
public static MfkItem items[] = {null, null, null};
// the actual image results
public static Vector<Image> results = new Vector<Image>();
// the UI panel that displays the search results
static RootPanel resultPanel = RootPanel.get("search-results");
// a pane shown only when loading results
static RootPanel resultsLoadingPanel = RootPanel.get("results-loading");
static ImageSearch imageSearch = new ImageSearch();
static Button searchButton = new Button("Search");
static TextBox searchBox = new TextBox();
static final DialogBox box = new DialogBox(true);
static final String DEFAULT_SEARCH = "treehouse";
static final HTML LOADING =
new HTML("<img src=\"/gwt/loading.gif\" alt=\"\"> Loading...");
public void onModuleLoad() {
MfkMaker.searchButton = new Button("Search");
MfkMaker.searchBox = new TextBox();
MfkMaker.resultPanel = RootPanel.get("search-results");
MfkMaker.imageSearch = new ImageSearch();
MfkMaker.names[0].setText("item one name");
MfkMaker.names[1].setText("item two name");
MfkMaker.names[2].setText("item three name");
final SearchControlOptions options = new SearchControlOptions();
imageSearch.setSafeSearch(SafeSearchValue.STRICT);
imageSearch.setResultSetSize(ResultSetSize.LARGE);
options.add(imageSearch, ExpandMode.OPEN);
options.setKeepLabel("<b>Keep It!</b>");
options.setLinkTarget(LinkTarget.BLANK);
//final ResultClickHandler resultClick = new ResultClickHandler();
MfkMaker.box.setAnimationEnabled(true);
final ShowImageDialogHandler resultClick = new ShowImageDialogHandler();
imageSearch.addSearchResultsHandler(new SearchResultsHandler() {
public void onSearchResults(SearchResultsEvent event) {
MfkMaker.resultsLoadingPanel.setVisible(false);
JsArray<? extends Result> results = event.getResults();
System.out.println("Handler! #results = " + results.length());
for (int i = 0; i < results.length(); i++) {
ImageResult r = (ImageResult)results.get(i);
Image thumb = new Image(r.getThumbnailUrl());
thumb.setHeight(String.valueOf(r.getThumbnailHeight()));
thumb.setWidth(String.valueOf(r.getThumbnailWidth()));
thumb.addStyleName("search-result");
thumb.addClickHandler(resultClick);
resultPanel.add(thumb);
MfkMaker.results.add(thumb);
}
}
});
searchButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
MfkMaker.DoSearch();
}
});
searchBox.addKeyPressHandler(new KeyPressHandler() {
public void onKeyPress(KeyPressEvent event) {
if (event.getCharCode() == '\n' || event.getCharCode() == '\r') {
MfkMaker.DoSearch();
}
}
});
RootPanel.get("search-control").add(searchBox);
RootPanel.get("search-control").add(searchButton);
searchBox.setText(MfkMaker.DEFAULT_SEARCH);
MfkMaker.DoSearch();
}
private static void DoSearch() {
MfkMaker.resultsLoadingPanel.setVisible(true);
MfkMaker.resultPanel.clear();
MfkMaker.results.clear();
MfkMaker.imageSearch.execute(MfkMaker.searchBox.getText());
}
public static void addItem(MfkItem item) {
RootPanel.get("created-items").add(item.getWidget());
}
}
class ShowImageDialogHandler implements ClickHandler {
public void onClick(ClickEvent event){
Image source = (Image)event.getSource();
System.out.println("Showing dialog for :" + source.getUrl());
final Image img = new Image(source.getUrl());
final TextBox t = new TextBox();
VerticalPanel p = new VerticalPanel();
p.setSpacing(5);
Button create = new Button("<b>Create</b>");
create.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent e) {
System.out.println("Should create item here");
MfkMaker.box.hide();
MfkMaker.addItem(new MfkItem(t.getText(), img));
}
});
Button cancel = new Button("Cancel");
cancel.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent e) {
MfkMaker.box.hide();
}
});
t.setText("my thing");
p.add(new HTML("<b>Image:</b>"));
p.add(img);
p.add(new HTML("<b>Name:</b>"));
p.add(t);
HorizontalPanel buttonPanel = new HorizontalPanel();
buttonPanel.setSpacing(5);
buttonPanel.add(create);
buttonPanel.add(cancel);
p.add(buttonPanel);
MfkMaker.box.setWidget(p);
MfkMaker.box.show();
MfkMaker.box.center();
}
}
class SetImageHandler implements ClickHandler {
private int itemIndex;
private String id;
public SetImageHandler(int itemIndex) {
this.itemIndex = itemIndex;
this.id = "saved-" + Integer.toString(this.itemIndex+1) + "-inner";
}
public void onClick(ClickEvent event) {
System.out.println("Click #" + this.itemIndex + " -> " + this.id);
RootPanel p = RootPanel.get(this.id);
p.clear();
Image img = new Image(MfkMaker.selected.getUrl());
p.add(img);
MfkMaker.images[this.itemIndex] = img;
}
}
class MfkItem {
public String title;
public Image image;
public MfkItem(String title, Image image) {
this.title = title;
this.image = image;
}
public Widget getWidget() {
VerticalPanel panel = new VerticalPanel();
panel.add(new HTML("<i>" + this.title + "</i>"));
panel.add(this.image);
return panel;
}
}
// TODO(mjkelly): Do client-side validation here.
class SubmitHandler implements ClickHandler {
public void onClick(ClickEvent event) {
System.out.println("Want to create:\n"
+ "{n:" + MfkMaker.names[0].getText()
+ ", u:" + MfkMaker.images[0].getUrl() + "}\n"
+ "{n:" + MfkMaker.names[1].getText()
+ ", u:" + MfkMaker.images[1].getUrl() + "}\n"
+ "{n:" + MfkMaker.names[2].getText()
+ ", u:" + MfkMaker.images[2].getUrl() + "}");
String url = "/rpc/create/";
RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, url);
builder.setHeader("Content-Type", "application/x-www-form-urlencoded");
StringBuffer reqData = new StringBuffer();
reqData.append("n1=").append(MfkMaker.names[0].getText());
reqData.append("&n2=").append(MfkMaker.names[1].getText());
reqData.append("&n3=").append(MfkMaker.names[2].getText());
reqData.append("&u1=").append(MfkMaker.images[0].getUrl());
reqData.append("&u2=").append(MfkMaker.images[1].getUrl());
reqData.append("&u3=").append(MfkMaker.images[2].getUrl());
try {
builder.sendRequest(reqData.toString(), new RequestCallback() {
public void onError(Request request, Throwable exception) {
System.out.println("Error creating new Triple");
}
public void onResponseReceived(Request request,
Response response) {
if (response.getStatusCode() == 200) {
System.out.println("Successful creation request: "
+ response.getText());
}
else {
System.out.println("Server didn't like our new triple. "
+ "Response code: " + response.getStatusCode()
+ ". Response text: " + response.getText());
}
}
});
} catch (RequestException e) {
System.out.println("Error sending vote: " + e);
}
}
}
|
package cn.jzvd;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.provider.Settings;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import java.lang.reflect.Constructor;
import java.util.LinkedHashMap;
import java.util.Timer;
import java.util.TimerTask;
public abstract class JZVideoPlayer extends FrameLayout implements View.OnClickListener, SeekBar.OnSeekBarChangeListener, View.OnTouchListener {
public static final String TAG = "JiaoZiVideoPlayer";
public static final int THRESHOLD = 80;
public static final int FULL_SCREEN_NORMAL_DELAY = 300;
public static final int SCREEN_WINDOW_NORMAL = 0;
public static final int SCREEN_WINDOW_LIST = 1;
public static final int SCREEN_WINDOW_FULLSCREEN = 2;
public static final int SCREEN_WINDOW_TINY = 3;
public static final int CURRENT_STATE_NORMAL = 0;
public static final int CURRENT_STATE_PREPARING = 1;
public static final int CURRENT_STATE_PREPARING_CHANGING_URL = 2;
public static final int CURRENT_STATE_PLAYING = 3;
public static final int CURRENT_STATE_PAUSE = 5;
public static final int CURRENT_STATE_AUTO_COMPLETE = 6;
public static final int CURRENT_STATE_ERROR = 7;
public static final String URL_KEY_DEFAULT = "URL_KEY_DEFAULT";//key
public static final int VIDEO_IMAGE_DISPLAY_TYPE_ADAPTER = 0;//default
public static final int VIDEO_IMAGE_DISPLAY_TYPE_FILL_PARENT = 1;
public static final int VIDEO_IMAGE_DISPLAY_TYPE_FILL_SCROP = 2;
public static final int VIDEO_IMAGE_DISPLAY_TYPE_ORIGINAL = 3;
public static boolean ACTION_BAR_EXIST = true;
public static boolean TOOL_BAR_EXIST = true;
public static int FULLSCREEN_ORIENTATION = ActivityInfo.SCREEN_ORIENTATION_SENSOR;
public static int NORMAL_ORIENTATION = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
public static boolean SAVE_PROGRESS = true;
public static boolean WIFI_TIP_DIALOG_SHOWED = false;
public static int VIDEO_IMAGE_DISPLAY_TYPE = 0;
public static long CLICK_QUIT_FULLSCREEN_TIME = 0;
public static long lastAutoFullscreenTime = 0;
public static AudioManager.OnAudioFocusChangeListener onAudioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() {//class
@Override
public void onAudioFocusChange(int focusChange) {
switch (focusChange) {
case AudioManager.AUDIOFOCUS_GAIN:
break;
case AudioManager.AUDIOFOCUS_LOSS:
releaseAllVideos();
Log.d(TAG, "AUDIOFOCUS_LOSS [" + this.hashCode() + "]");
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
try {
JZVideoPlayer player = JZVideoPlayerManager.getCurrentJzvd();
if (player != null && player.currentState == JZVideoPlayer.CURRENT_STATE_PLAYING) {
player.startButton.performClick();
}
} catch (IllegalStateException e) {
e.printStackTrace();
}
Log.d(TAG, "AUDIOFOCUS_LOSS_TRANSIENT [" + this.hashCode() + "]");
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
break;
}
}
};
protected static JZUserAction JZ_USER_EVENT;
protected static Timer UPDATE_PROGRESS_TIMER;
public int currentState = -1;
public int currentScreen = -1;
public Object[] objects = null;
public long seekToInAdvance = 0;
public ImageView startButton;
public SeekBar progressBar;
public ImageView fullscreenButton;
public TextView currentTimeTextView, totalTimeTextView;
public ViewGroup textureViewContainer;
public ViewGroup topContainer, bottomContainer;
public int widthRatio = 0;
public int heightRatio = 0;
public Object[] dataSourceObjects;//JZMeidaManagerJZMediaInterface
public int currentUrlMapIndex = 0;
public int positionInList = -1;
public int videoRotation = 0;
protected int mScreenWidth;
protected int mScreenHeight;
protected AudioManager mAudioManager;
protected ProgressTimerTask mProgressTimerTask;
protected boolean mTouchingProgressBar;
protected float mDownX;
protected float mDownY;
protected boolean mChangeVolume;
protected boolean mChangePosition;
protected boolean mChangeBrightness;
protected long mGestureDownPosition;
protected int mGestureDownVolume;
protected float mGestureDownBrightness;
protected long mSeekTimePosition;
boolean tmp_test_back = false;
public JZVideoPlayer(Context context) {
super(context);
init(context);
}
public JZVideoPlayer(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public static void releaseAllVideos() {
if ((System.currentTimeMillis() - CLICK_QUIT_FULLSCREEN_TIME) > FULL_SCREEN_NORMAL_DELAY) {
Log.d(TAG, "releaseAllVideos");
JZVideoPlayerManager.completeAll();
JZMediaManager.instance().positionInList = -1;
JZMediaManager.instance().releaseMediaPlayer();
}
}
public static void startFullscreen(Context context, Class _class, String url, Object... objects) {
LinkedHashMap map = new LinkedHashMap();
map.put(URL_KEY_DEFAULT, url);
Object[] dataSourceObjects = new Object[1];
dataSourceObjects[0] = map;
startFullscreen(context, _class, dataSourceObjects, 0, objects);
}
public static void startFullscreen(Context context, Class _class, Object[] dataSourceObjects, int defaultUrlMapIndex, Object... objects) {
hideSupportActionBar(context);
JZUtils.setRequestedOrientation(context, FULLSCREEN_ORIENTATION);
ViewGroup vp = (JZUtils.scanForActivity(context))//.getWindow().getDecorView();
.findViewById(Window.ID_ANDROID_CONTENT);
View old = vp.findViewById(R.id.jz_fullscreen_id);
if (old != null) {
vp.removeView(old);
}
try {
Constructor<JZVideoPlayer> constructor = _class.getConstructor(Context.class);
final JZVideoPlayer jzVideoPlayer = constructor.newInstance(context);
jzVideoPlayer.setId(R.id.jz_fullscreen_id);
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
vp.addView(jzVideoPlayer, lp);
// final Animation ra = AnimationUtils.loadAnimation(context, R.anim.start_fullscreen);
// jzVideoPlayer.setAnimation(ra);
jzVideoPlayer.setUp(dataSourceObjects, defaultUrlMapIndex, JZVideoPlayerStandard.SCREEN_WINDOW_FULLSCREEN, objects);
CLICK_QUIT_FULLSCREEN_TIME = System.currentTimeMillis();
jzVideoPlayer.startButton.performClick();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static boolean backPress() {
Log.i(TAG, "backPress");
if ((System.currentTimeMillis() - CLICK_QUIT_FULLSCREEN_TIME) < FULL_SCREEN_NORMAL_DELAY)
return false;
if (JZVideoPlayerManager.getSecondFloor() != null) {
CLICK_QUIT_FULLSCREEN_TIME = System.currentTimeMillis();
if (JZUtils.dataSourceObjectsContainsUri(JZVideoPlayerManager.getFirstFloor().dataSourceObjects, JZMediaManager.getCurrentDataSource())) {
JZVideoPlayer jzVideoPlayer = JZVideoPlayerManager.getSecondFloor();
jzVideoPlayer.onEvent(jzVideoPlayer.currentScreen == JZVideoPlayerStandard.SCREEN_WINDOW_FULLSCREEN ?
JZUserAction.ON_QUIT_FULLSCREEN :
JZUserAction.ON_QUIT_TINYSCREEN);
JZVideoPlayerManager.getFirstFloor().playOnThisJzvd();
} else {
quitFullscreenOrTinyWindow();
}
return true;
} else if (JZVideoPlayerManager.getFirstFloor() != null &&
(JZVideoPlayerManager.getFirstFloor().currentScreen == SCREEN_WINDOW_FULLSCREEN ||
JZVideoPlayerManager.getFirstFloor().currentScreen == SCREEN_WINDOW_TINY)) {
CLICK_QUIT_FULLSCREEN_TIME = System.currentTimeMillis();
quitFullscreenOrTinyWindow();
return true;
}
return false;
}
public static void quitFullscreenOrTinyWindow() {
JZVideoPlayerManager.getFirstFloor().clearFloatScreen();
JZMediaManager.instance().releaseMediaPlayer();
JZVideoPlayerManager.completeAll();
}
@SuppressLint("RestrictedApi")
public static void showSupportActionBar(Context context) {
if (ACTION_BAR_EXIST && JZUtils.getAppCompActivity(context) != null) {
ActionBar ab = JZUtils.getAppCompActivity(context).getSupportActionBar();
if (ab != null) {
ab.setShowHideAnimationEnabled(false);
ab.show();
}
}
if (TOOL_BAR_EXIST) {
JZUtils.getWindow(context).clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
}
@SuppressLint("RestrictedApi")
public static void hideSupportActionBar(Context context) {
if (ACTION_BAR_EXIST && JZUtils.getAppCompActivity(context) != null) {
ActionBar ab = JZUtils.getAppCompActivity(context).getSupportActionBar();
if (ab != null) {
ab.setShowHideAnimationEnabled(false);
ab.hide();
}
}
if (TOOL_BAR_EXIST) {
JZUtils.getWindow(context).setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
}
public static void clearSavedProgress(Context context, String url) {
JZUtils.clearSavedProgress(context, url);
}
public static void setJzUserAction(JZUserAction jzUserEvent) {
JZ_USER_EVENT = jzUserEvent;
}
public static void goOnPlayOnResume() {
if (JZVideoPlayerManager.getCurrentJzvd() != null) {
JZVideoPlayer jzvd = JZVideoPlayerManager.getCurrentJzvd();
if (jzvd.currentState == JZVideoPlayer.CURRENT_STATE_PAUSE) {
jzvd.onStatePlaying();
JZMediaManager.start();
}
}
}
public static void goOnPlayOnPause() {
if (JZVideoPlayerManager.getCurrentJzvd() != null) {
JZVideoPlayer jzvd = JZVideoPlayerManager.getCurrentJzvd();
if (jzvd.currentState == JZVideoPlayer.CURRENT_STATE_AUTO_COMPLETE ||
jzvd.currentState == JZVideoPlayer.CURRENT_STATE_NORMAL ||
jzvd.currentState == JZVideoPlayer.CURRENT_STATE_ERROR) {
// JZVideoPlayer.releaseAllVideos();
} else {
jzvd.onStatePause();
JZMediaManager.pause();
}
}
}
public static void onScrollAutoTiny(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
int lastVisibleItem = firstVisibleItem + visibleItemCount;
int currentPlayPosition = JZMediaManager.instance().positionInList;
if (currentPlayPosition >= 0) {
if ((currentPlayPosition < firstVisibleItem || currentPlayPosition > (lastVisibleItem - 1))) {
if (JZVideoPlayerManager.getCurrentJzvd() != null &&
JZVideoPlayerManager.getCurrentJzvd().currentScreen != JZVideoPlayer.SCREEN_WINDOW_TINY &&
JZVideoPlayerManager.getCurrentJzvd().currentScreen != JZVideoPlayer.SCREEN_WINDOW_FULLSCREEN) {
if (JZVideoPlayerManager.getCurrentJzvd().currentState == JZVideoPlayer.CURRENT_STATE_PAUSE) {
JZVideoPlayer.releaseAllVideos();
} else {
Log.e(TAG, "onScroll: out screen");
JZVideoPlayerManager.getCurrentJzvd().startWindowTiny();
}
}
} else {
if (JZVideoPlayerManager.getCurrentJzvd() != null &&
JZVideoPlayerManager.getCurrentJzvd().currentScreen == JZVideoPlayer.SCREEN_WINDOW_TINY) {
Log.e(TAG, "onScroll: into screen");
JZVideoPlayer.backPress();
}
}
}
}
public static void onScrollReleaseAllVideos(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
int lastVisibleItem = firstVisibleItem + visibleItemCount;
int currentPlayPosition = JZMediaManager.instance().positionInList;
Log.e(TAG, "onScrollReleaseAllVideos: " +
currentPlayPosition + " " + firstVisibleItem + " " + currentPlayPosition + " " + lastVisibleItem);
if (currentPlayPosition >= 0) {
if ((currentPlayPosition < firstVisibleItem || currentPlayPosition > (lastVisibleItem - 1))) {
if (JZVideoPlayerManager.getCurrentJzvd().currentScreen != JZVideoPlayer.SCREEN_WINDOW_FULLSCREEN) {
JZVideoPlayer.releaseAllVideos();
}
}
}
}
public static void onChildViewAttachedToWindow(View view, int jzvdId) {
if (JZVideoPlayerManager.getCurrentJzvd() != null && JZVideoPlayerManager.getCurrentJzvd().currentScreen == JZVideoPlayer.SCREEN_WINDOW_TINY) {
JZVideoPlayer videoPlayer = view.findViewById(jzvdId);
if (videoPlayer != null && JZUtils.getCurrentFromDataSource(videoPlayer.dataSourceObjects, videoPlayer.currentUrlMapIndex).equals(JZMediaManager.getCurrentDataSource())) {
JZVideoPlayer.backPress();
}
}
}
public static void onChildViewDetachedFromWindow(View view) {
if (JZVideoPlayerManager.getCurrentJzvd() != null && JZVideoPlayerManager.getCurrentJzvd().currentScreen != JZVideoPlayer.SCREEN_WINDOW_TINY) {
JZVideoPlayer videoPlayer = JZVideoPlayerManager.getCurrentJzvd();
if (((ViewGroup) view).indexOfChild(videoPlayer) != -1) {
if (videoPlayer.currentState == JZVideoPlayer.CURRENT_STATE_PAUSE) {
JZVideoPlayer.releaseAllVideos();
} else {
videoPlayer.startWindowTiny();
}
}
}
}
public static void setTextureViewRotation(int rotation) {
if (JZMediaManager.textureView != null) {
JZMediaManager.textureView.setRotation(rotation);
}
}
public static void setVideoImageDisplayType(int type) {
JZVideoPlayer.VIDEO_IMAGE_DISPLAY_TYPE = type;
if (JZMediaManager.textureView != null) {
JZMediaManager.textureView.requestLayout();
}
}
public Object getCurrentUrl() {
return JZUtils.getCurrentFromDataSource(dataSourceObjects, currentUrlMapIndex);
}
public abstract int getLayoutId();
public void init(Context context) {
View.inflate(context, getLayoutId(), this);
startButton = findViewById(R.id.start);
fullscreenButton = findViewById(R.id.fullscreen);
progressBar = findViewById(R.id.bottom_seek_progress);
currentTimeTextView = findViewById(R.id.current);
totalTimeTextView = findViewById(R.id.total);
bottomContainer = findViewById(R.id.layout_bottom);
textureViewContainer = findViewById(R.id.surface_container);
topContainer = findViewById(R.id.layout_top);
startButton.setOnClickListener(this);
fullscreenButton.setOnClickListener(this);
progressBar.setOnSeekBarChangeListener(this);
bottomContainer.setOnClickListener(this);
textureViewContainer.setOnClickListener(this);
textureViewContainer.setOnTouchListener(this);
mScreenWidth = getContext().getResources().getDisplayMetrics().widthPixels;
mScreenHeight = getContext().getResources().getDisplayMetrics().heightPixels;
mAudioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
try {
if (isCurrentPlay()) {
NORMAL_ORIENTATION = ((AppCompatActivity) context).getRequestedOrientation();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void setUp(String url, int screen, Object... objects) {
LinkedHashMap map = new LinkedHashMap();
map.put(URL_KEY_DEFAULT, url);
Object[] dataSourceObjects = new Object[1];
dataSourceObjects[0] = map;
setUp(dataSourceObjects, 0, screen, objects);
}
public void setUp(Object[] dataSourceObjects, int defaultUrlMapIndex, int screen, Object... objects) {
if (this.dataSourceObjects != null && JZUtils.getCurrentFromDataSource(dataSourceObjects, currentUrlMapIndex) != null &&
JZUtils.getCurrentFromDataSource(this.dataSourceObjects, currentUrlMapIndex).equals(JZUtils.getCurrentFromDataSource(dataSourceObjects, currentUrlMapIndex))) {
return;
}
if (isCurrentJZVD() && JZUtils.dataSourceObjectsContainsUri(dataSourceObjects, JZMediaManager.getCurrentDataSource())) {
long position = 0;
try {
position = JZMediaManager.getCurrentPosition();
} catch (IllegalStateException e) {
e.printStackTrace();
}
if (position != 0) {
JZUtils.saveProgress(getContext(), JZMediaManager.getCurrentDataSource(), position);
}
JZMediaManager.instance().releaseMediaPlayer();
} else if (isCurrentJZVD() && !JZUtils.dataSourceObjectsContainsUri(dataSourceObjects, JZMediaManager.getCurrentDataSource())) {
startWindowTiny();
} else if (!isCurrentJZVD() && JZUtils.dataSourceObjectsContainsUri(dataSourceObjects, JZMediaManager.getCurrentDataSource())) {
if (JZVideoPlayerManager.getCurrentJzvd() != null &&
JZVideoPlayerManager.getCurrentJzvd().currentScreen == JZVideoPlayer.SCREEN_WINDOW_TINY) {
tmp_test_back = true;
}
} else if (!isCurrentJZVD() && !JZUtils.dataSourceObjectsContainsUri(dataSourceObjects, JZMediaManager.getCurrentDataSource())) {
}
this.dataSourceObjects = dataSourceObjects;
this.currentUrlMapIndex = defaultUrlMapIndex;
this.currentScreen = screen;
this.objects = objects;
onStateNormal();
}
@Override
public void onClick(View v) {
int i = v.getId();
if (i == R.id.start) {
Log.i(TAG, "onClick start [" + this.hashCode() + "] ");
if (dataSourceObjects == null || JZUtils.getCurrentFromDataSource(dataSourceObjects, currentUrlMapIndex) == null) {
Toast.makeText(getContext(), getResources().getString(R.string.no_url), Toast.LENGTH_SHORT).show();
return;
}
if (currentState == CURRENT_STATE_NORMAL) {
if (!JZUtils.getCurrentFromDataSource(dataSourceObjects, currentUrlMapIndex).toString().startsWith("file") && !
JZUtils.getCurrentFromDataSource(dataSourceObjects, currentUrlMapIndex).toString().startsWith("/") &&
!JZUtils.isWifiConnected(getContext()) && !WIFI_TIP_DIALOG_SHOWED) {
showWifiDialog();
return;
}
startVideo();
onEvent(JZUserAction.ON_CLICK_START_ICON);
} else if (currentState == CURRENT_STATE_PLAYING) {
onEvent(JZUserAction.ON_CLICK_PAUSE);
Log.d(TAG, "pauseVideo [" + this.hashCode() + "] ");
JZMediaManager.pause();
onStatePause();
} else if (currentState == CURRENT_STATE_PAUSE) {
onEvent(JZUserAction.ON_CLICK_RESUME);
JZMediaManager.start();
onStatePlaying();
} else if (currentState == CURRENT_STATE_AUTO_COMPLETE) {
onEvent(JZUserAction.ON_CLICK_START_AUTO_COMPLETE);
startVideo();
}
} else if (i == R.id.fullscreen) {
Log.i(TAG, "onClick fullscreen [" + this.hashCode() + "] ");
if (currentState == CURRENT_STATE_AUTO_COMPLETE) return;
if (currentScreen == SCREEN_WINDOW_FULLSCREEN) {
//quit fullscreen
backPress();
} else {
Log.d(TAG, "toFullscreenActivity [" + this.hashCode() + "] ");
onEvent(JZUserAction.ON_ENTER_FULLSCREEN);
startWindowFullscreen();
}
}
}
@Override
public boolean onTouch(View v, MotionEvent event) {
float x = event.getX();
float y = event.getY();
int id = v.getId();
if (id == R.id.surface_container) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
Log.i(TAG, "onTouch surfaceContainer actionDown [" + this.hashCode() + "] ");
mTouchingProgressBar = true;
mDownX = x;
mDownY = y;
mChangeVolume = false;
mChangePosition = false;
mChangeBrightness = false;
break;
case MotionEvent.ACTION_MOVE:
Log.i(TAG, "onTouch surfaceContainer actionMove [" + this.hashCode() + "] ");
float deltaX = x - mDownX;
float deltaY = y - mDownY;
float absDeltaX = Math.abs(deltaX);
float absDeltaY = Math.abs(deltaY);
if (currentScreen == SCREEN_WINDOW_FULLSCREEN) {
if (!mChangePosition && !mChangeVolume && !mChangeBrightness) {
if (absDeltaX > THRESHOLD || absDeltaY > THRESHOLD) {
cancelProgressTimer();
if (absDeltaX >= THRESHOLD) {
// CURRENT_STATE_ERROR,.
// mediaplayerApp Crash
if (currentState != CURRENT_STATE_ERROR) {
mChangePosition = true;
mGestureDownPosition = getCurrentPositionWhenPlaying();
}
} else {
if (mDownX < mScreenWidth * 0.5f) {
mChangeBrightness = true;
WindowManager.LayoutParams lp = JZUtils.getWindow(getContext()).getAttributes();
if (lp.screenBrightness < 0) {
try {
mGestureDownBrightness = Settings.System.getInt(getContext().getContentResolver(), Settings.System.SCREEN_BRIGHTNESS);
Log.i(TAG, "current system brightness: " + mGestureDownBrightness);
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
}
} else {
mGestureDownBrightness = lp.screenBrightness * 255;
Log.i(TAG, "current activity brightness: " + mGestureDownBrightness);
}
} else {
mChangeVolume = true;
mGestureDownVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
}
}
}
}
}
if (mChangePosition) {
long totalTimeDuration = getDuration();
mSeekTimePosition = (int) (mGestureDownPosition + deltaX * totalTimeDuration / mScreenWidth);
if (mSeekTimePosition > totalTimeDuration)
mSeekTimePosition = totalTimeDuration;
String seekTime = JZUtils.stringForTime(mSeekTimePosition);
String totalTime = JZUtils.stringForTime(totalTimeDuration);
showProgressDialog(deltaX, seekTime, mSeekTimePosition, totalTime, totalTimeDuration);
}
if (mChangeVolume) {
deltaY = -deltaY;
int max = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
int deltaV = (int) (max * deltaY * 3 / mScreenHeight);
mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, mGestureDownVolume + deltaV, 0);
//dialog
int volumePercent = (int) (mGestureDownVolume * 100 / max + deltaY * 3 * 100 / mScreenHeight);
showVolumeDialog(-deltaY, volumePercent);
}
if (mChangeBrightness) {
deltaY = -deltaY;
int deltaV = (int) (255 * deltaY * 3 / mScreenHeight);
WindowManager.LayoutParams params = JZUtils.getWindow(getContext()).getAttributes();
if (((mGestureDownBrightness + deltaV) / 255) >= 1) {
params.screenBrightness = 1;
} else if (((mGestureDownBrightness + deltaV) / 255) <= 0) {
params.screenBrightness = 0.01f;
} else {
params.screenBrightness = (mGestureDownBrightness + deltaV) / 255;
}
JZUtils.getWindow(getContext()).setAttributes(params);
//dialog
int brightnessPercent = (int) (mGestureDownBrightness * 100 / 255 + deltaY * 3 * 100 / mScreenHeight);
showBrightnessDialog(brightnessPercent);
// mDownY = y;
}
break;
case MotionEvent.ACTION_UP:
Log.i(TAG, "onTouch surfaceContainer actionUp [" + this.hashCode() + "] ");
mTouchingProgressBar = false;
dismissProgressDialog();
dismissVolumeDialog();
dismissBrightnessDialog();
if (mChangePosition) {
onEvent(JZUserAction.ON_TOUCH_SCREEN_SEEK_POSITION);
JZMediaManager.seekTo(mSeekTimePosition);
long duration = getDuration();
int progress = (int) (mSeekTimePosition * 100 / (duration == 0 ? 1 : duration));
progressBar.setProgress(progress);
}
if (mChangeVolume) {
onEvent(JZUserAction.ON_TOUCH_SCREEN_SEEK_VOLUME);
}
startProgressTimer();
break;
}
}
return false;
}
public void startVideo() {
JZVideoPlayerManager.completeAll();
Log.d(TAG, "startVideo [" + this.hashCode() + "] ");
initTextureView();
addTextureView();
AudioManager mAudioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
mAudioManager.requestAudioFocus(onAudioFocusChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
JZUtils.scanForActivity(getContext()).getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
JZMediaManager.setDataSource(dataSourceObjects);
JZMediaManager.setCurrentDataSource(JZUtils.getCurrentFromDataSource(dataSourceObjects, currentUrlMapIndex));
JZMediaManager.instance().positionInList = positionInList;
onStatePreparing();
JZVideoPlayerManager.setFirstFloor(this);
}
public void onPrepared() {
Log.i(TAG, "onPrepared " + " [" + this.hashCode() + "] ");
onStatePrepared();
onStatePlaying();
}
public void setState(int state) {
setState(state, 0, 0);
}
public void setState(int state, int urlMapIndex, int seekToInAdvance) {
switch (state) {
case CURRENT_STATE_NORMAL:
onStateNormal();
break;
case CURRENT_STATE_PREPARING:
onStatePreparing();
break;
case CURRENT_STATE_PREPARING_CHANGING_URL:
onStatePreparingChangingUrl(urlMapIndex, seekToInAdvance);
break;
case CURRENT_STATE_PLAYING:
onStatePlaying();
break;
case CURRENT_STATE_PAUSE:
onStatePause();
break;
case CURRENT_STATE_ERROR:
onStateError();
break;
case CURRENT_STATE_AUTO_COMPLETE:
onStateAutoComplete();
break;
}
}
public void onStateNormal() {
Log.i(TAG, "onStateNormal " + " [" + this.hashCode() + "] ");
currentState = CURRENT_STATE_NORMAL;
cancelProgressTimer();
}
public void onStatePreparing() {
Log.i(TAG, "onStatePreparing " + " [" + this.hashCode() + "] ");
currentState = CURRENT_STATE_PREPARING;
resetProgressAndTime();
}
public void onStatePreparingChangingUrl(int urlMapIndex, long seekToInAdvance) {
currentState = CURRENT_STATE_PREPARING_CHANGING_URL;
this.currentUrlMapIndex = urlMapIndex;
this.seekToInAdvance = seekToInAdvance;
JZMediaManager.setDataSource(dataSourceObjects);
JZMediaManager.setCurrentDataSource(JZUtils.getCurrentFromDataSource(dataSourceObjects, currentUrlMapIndex));
JZMediaManager.instance().prepare();
}
public void onStatePrepared() {//state
if (seekToInAdvance != 0) {
JZMediaManager.seekTo(seekToInAdvance);
seekToInAdvance = 0;
} else {
long position = JZUtils.getSavedProgress(getContext(), JZUtils.getCurrentFromDataSource(dataSourceObjects, currentUrlMapIndex));
if (position != 0) {
JZMediaManager.seekTo(position);
}
}
}
public void onStatePlaying() {
Log.i(TAG, "onStatePlaying " + " [" + this.hashCode() + "] ");
currentState = CURRENT_STATE_PLAYING;
startProgressTimer();
}
public void onStatePause() {
Log.i(TAG, "onStatePause " + " [" + this.hashCode() + "] ");
currentState = CURRENT_STATE_PAUSE;
startProgressTimer();
}
public void onStateError() {
Log.i(TAG, "onStateError " + " [" + this.hashCode() + "] ");
currentState = CURRENT_STATE_ERROR;
cancelProgressTimer();
}
public void onStateAutoComplete() {
Log.i(TAG, "onStateAutoComplete " + " [" + this.hashCode() + "] ");
currentState = CURRENT_STATE_AUTO_COMPLETE;
cancelProgressTimer();
progressBar.setProgress(100);
currentTimeTextView.setText(totalTimeTextView.getText());
}
public void onInfo(int what, int extra) {
Log.d(TAG, "onInfo what - " + what + " extra - " + extra);
}
public void onError(int what, int extra) {
Log.e(TAG, "onError " + what + " - " + extra + " [" + this.hashCode() + "] ");
if (what != 38 && extra != -38 && what != -38 && extra != 38 && extra != -19) {
onStateError();
if (isCurrentPlay()) {
JZMediaManager.instance().releaseMediaPlayer();
}
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (currentScreen == SCREEN_WINDOW_FULLSCREEN || currentScreen == SCREEN_WINDOW_TINY) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
return;
}
if (widthRatio != 0 && heightRatio != 0) {
int specWidth = MeasureSpec.getSize(widthMeasureSpec);
int specHeight = (int) ((specWidth * (float) heightRatio) / widthRatio);
setMeasuredDimension(specWidth, specHeight);
int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(specWidth, MeasureSpec.EXACTLY);
int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(specHeight, MeasureSpec.EXACTLY);
getChildAt(0).measure(childWidthMeasureSpec, childHeightMeasureSpec);
} else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
public void onAutoCompletion() {
Runtime.getRuntime().gc();
Log.i(TAG, "onAutoCompletion " + " [" + this.hashCode() + "] ");
onEvent(JZUserAction.ON_AUTO_COMPLETE);
dismissVolumeDialog();
dismissProgressDialog();
dismissBrightnessDialog();
onStateAutoComplete();
if (currentScreen == SCREEN_WINDOW_FULLSCREEN || currentScreen == SCREEN_WINDOW_TINY) {
backPress();
}
JZMediaManager.instance().releaseMediaPlayer();
JZUtils.saveProgress(getContext(), JZUtils.getCurrentFromDataSource(dataSourceObjects, currentUrlMapIndex), 0);
}
public void onCompletion() {
Log.i(TAG, "onCompletion " + " [" + this.hashCode() + "] ");
if (currentState == CURRENT_STATE_PLAYING || currentState == CURRENT_STATE_PAUSE) {
long position = getCurrentPositionWhenPlaying();
JZUtils.saveProgress(getContext(), JZUtils.getCurrentFromDataSource(dataSourceObjects, currentUrlMapIndex), position);
}
cancelProgressTimer();
dismissBrightnessDialog();
dismissProgressDialog();
dismissVolumeDialog();
onStateNormal();
textureViewContainer.removeView(JZMediaManager.textureView);
JZMediaManager.instance().currentVideoWidth = 0;
JZMediaManager.instance().currentVideoHeight = 0;
AudioManager mAudioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
mAudioManager.abandonAudioFocus(onAudioFocusChangeListener);
JZUtils.scanForActivity(getContext()).getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
clearFullscreenLayout();
JZUtils.setRequestedOrientation(getContext(), NORMAL_ORIENTATION);
if (JZMediaManager.surface != null) JZMediaManager.surface.release();
if (JZMediaManager.savedSurfaceTexture != null)
JZMediaManager.savedSurfaceTexture.release();
JZMediaManager.textureView = null;
JZMediaManager.savedSurfaceTexture = null;
}
public void release() {
if (JZUtils.getCurrentFromDataSource(dataSourceObjects, currentUrlMapIndex).equals(JZMediaManager.getCurrentDataSource()) &&
(System.currentTimeMillis() - CLICK_QUIT_FULLSCREEN_TIME) > FULL_SCREEN_NORMAL_DELAY) {
//backPress()
if (JZVideoPlayerManager.getSecondFloor() != null &&
JZVideoPlayerManager.getSecondFloor().currentScreen == SCREEN_WINDOW_FULLSCREEN) {
} else if (JZVideoPlayerManager.getSecondFloor() == null && JZVideoPlayerManager.getFirstFloor() != null &&
JZVideoPlayerManager.getFirstFloor().currentScreen == SCREEN_WINDOW_FULLSCREEN) {
} else {
Log.d(TAG, "releaseMediaPlayer [" + this.hashCode() + "]");
releaseAllVideos();
}
}
}
public void initTextureView() {
removeTextureView();
JZMediaManager.textureView = new JZResizeTextureView(getContext());
JZMediaManager.textureView.setSurfaceTextureListener(JZMediaManager.instance());
}
public void addTextureView() {
Log.d(TAG, "addTextureView [" + this.hashCode() + "] ");
FrameLayout.LayoutParams layoutParams =
new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT,
Gravity.CENTER);
textureViewContainer.addView(JZMediaManager.textureView, layoutParams);
}
public void removeTextureView() {
JZMediaManager.savedSurfaceTexture = null;
if (JZMediaManager.textureView != null && JZMediaManager.textureView.getParent() != null) {
((ViewGroup) JZMediaManager.textureView.getParent()).removeView(JZMediaManager.textureView);
}
}
public void clearFullscreenLayout() {
ViewGroup vp = (JZUtils.scanForActivity(getContext()))//.getWindow().getDecorView();
.findViewById(Window.ID_ANDROID_CONTENT);
View oldF = vp.findViewById(R.id.jz_fullscreen_id);
View oldT = vp.findViewById(R.id.jz_tiny_id);
if (oldF != null) {
vp.removeView(oldF);
}
if (oldT != null) {
vp.removeView(oldT);
}
showSupportActionBar(getContext());
}
public void clearFloatScreen() {
JZUtils.setRequestedOrientation(getContext(), NORMAL_ORIENTATION);
showSupportActionBar(getContext());
ViewGroup vp = (JZUtils.scanForActivity(getContext()))//.getWindow().getDecorView();
.findViewById(Window.ID_ANDROID_CONTENT);
JZVideoPlayer fullJzvd = vp.findViewById(R.id.jz_fullscreen_id);
JZVideoPlayer tinyJzvd = vp.findViewById(R.id.jz_tiny_id);
if (fullJzvd != null) {
vp.removeView(fullJzvd);
if (fullJzvd.textureViewContainer != null)
fullJzvd.textureViewContainer.removeView(JZMediaManager.textureView);
}
if (tinyJzvd != null) {
vp.removeView(tinyJzvd);
if (tinyJzvd.textureViewContainer != null)
tinyJzvd.textureViewContainer.removeView(JZMediaManager.textureView);
}
JZVideoPlayerManager.setSecondFloor(null);
}
public void onVideoSizeChanged() {
Log.i(TAG, "onVideoSizeChanged " + " [" + this.hashCode() + "] ");
if (JZMediaManager.textureView != null) {
if (videoRotation != 0) {
JZMediaManager.textureView.setRotation(videoRotation);
}
JZMediaManager.textureView.setVideoSize(JZMediaManager.instance().currentVideoWidth, JZMediaManager.instance().currentVideoHeight);
}
}
public void startProgressTimer() {
Log.i(TAG, "startProgressTimer: " + " [" + this.hashCode() + "] ");
cancelProgressTimer();
UPDATE_PROGRESS_TIMER = new Timer();
mProgressTimerTask = new ProgressTimerTask();
UPDATE_PROGRESS_TIMER.schedule(mProgressTimerTask, 0, 300);
}
public void cancelProgressTimer() {
if (UPDATE_PROGRESS_TIMER != null) {
UPDATE_PROGRESS_TIMER.cancel();
}
if (mProgressTimerTask != null) {
mProgressTimerTask.cancel();
}
}
public void setProgressAndText(int progress, long position, long duration) {
// Log.d(TAG, "setProgressAndText: progress=" + progress + " position=" + position + " duration=" + duration);
if (!mTouchingProgressBar) {
if (progress != 0) progressBar.setProgress(progress);
}
if (position != 0) currentTimeTextView.setText(JZUtils.stringForTime(position));
totalTimeTextView.setText(JZUtils.stringForTime(duration));
}
public void setBufferProgress(int bufferProgress) {
if (bufferProgress != 0) progressBar.setSecondaryProgress(bufferProgress);
}
public void resetProgressAndTime() {
progressBar.setProgress(0);
progressBar.setSecondaryProgress(0);
currentTimeTextView.setText(JZUtils.stringForTime(0));
totalTimeTextView.setText(JZUtils.stringForTime(0));
}
public long getCurrentPositionWhenPlaying() {
long position = 0;
//TODO MediaPlayer
if (currentState == CURRENT_STATE_PLAYING ||
currentState == CURRENT_STATE_PAUSE) {
try {
position = JZMediaManager.getCurrentPosition();
} catch (IllegalStateException e) {
e.printStackTrace();
return position;
}
}
return position;
}
public long getDuration() {
long duration = 0;
//TODO MediaPlayer
// if (JZMediaManager.instance().mediaPlayer == null) return duration;
try {
duration = JZMediaManager.getDuration();
} catch (IllegalStateException e) {
e.printStackTrace();
return duration;
}
return duration;
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
Log.i(TAG, "bottomProgress onStartTrackingTouch [" + this.hashCode() + "] ");
cancelProgressTimer();
ViewParent vpdown = getParent();
while (vpdown != null) {
vpdown.requestDisallowInterceptTouchEvent(true);
vpdown = vpdown.getParent();
}
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
Log.i(TAG, "bottomProgress onStopTrackingTouch [" + this.hashCode() + "] ");
onEvent(JZUserAction.ON_SEEK_POSITION);
startProgressTimer();
ViewParent vpup = getParent();
while (vpup != null) {
vpup.requestDisallowInterceptTouchEvent(false);
vpup = vpup.getParent();
}
if (currentState != CURRENT_STATE_PLAYING &&
currentState != CURRENT_STATE_PAUSE) return;
long time = seekBar.getProgress() * getDuration() / 100;
JZMediaManager.seekTo(time);
Log.i(TAG, "seekTo " + time + " [" + this.hashCode() + "] ");
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser) {
//progrestextview
long duration = getDuration();
currentTimeTextView.setText(JZUtils.stringForTime(progress * duration / 100));
}
}
public void startWindowFullscreen() {
Log.i(TAG, "startWindowFullscreen " + " [" + this.hashCode() + "] ");
hideSupportActionBar(getContext());
ViewGroup vp = (JZUtils.scanForActivity(getContext()))//.getWindow().getDecorView();
.findViewById(Window.ID_ANDROID_CONTENT);
View old = vp.findViewById(R.id.jz_fullscreen_id);
if (old != null) {
vp.removeView(old);
}
textureViewContainer.removeView(JZMediaManager.textureView);
try {
Constructor<JZVideoPlayer> constructor = (Constructor<JZVideoPlayer>) JZVideoPlayer.this.getClass().getConstructor(Context.class);
JZVideoPlayer jzVideoPlayer = constructor.newInstance(getContext());
jzVideoPlayer.setId(R.id.jz_fullscreen_id);
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
vp.addView(jzVideoPlayer, lp);
jzVideoPlayer.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN);
jzVideoPlayer.setUp(dataSourceObjects, currentUrlMapIndex, JZVideoPlayerStandard.SCREEN_WINDOW_FULLSCREEN, objects);
jzVideoPlayer.setState(currentState);
jzVideoPlayer.addTextureView();
JZVideoPlayerManager.setSecondFloor(jzVideoPlayer);
// final Animation ra = AnimationUtils.loadAnimation(getContext(), R.anim.start_fullscreen);
// jzVideoPlayer.setAnimation(ra);
JZUtils.setRequestedOrientation(getContext(), FULLSCREEN_ORIENTATION);
onStateNormal();
jzVideoPlayer.progressBar.setSecondaryProgress(progressBar.getSecondaryProgress());
jzVideoPlayer.startProgressTimer();
CLICK_QUIT_FULLSCREEN_TIME = System.currentTimeMillis();
} catch (Exception e) {
e.printStackTrace();
}
}
public void startWindowTiny() {
Log.i(TAG, "startWindowTiny " + " [" + this.hashCode() + "] ");
onEvent(JZUserAction.ON_ENTER_TINYSCREEN);
if (currentState == CURRENT_STATE_NORMAL || currentState == CURRENT_STATE_ERROR || currentState == CURRENT_STATE_AUTO_COMPLETE)
return;
ViewGroup vp = (JZUtils.scanForActivity(getContext()))//.getWindow().getDecorView();
.findViewById(Window.ID_ANDROID_CONTENT);
View old = vp.findViewById(R.id.jz_tiny_id);
if (old != null) {
vp.removeView(old);
}
textureViewContainer.removeView(JZMediaManager.textureView);
try {
Constructor<JZVideoPlayer> constructor = (Constructor<JZVideoPlayer>) JZVideoPlayer.this.getClass().getConstructor(Context.class);
JZVideoPlayer jzVideoPlayer = constructor.newInstance(getContext());
jzVideoPlayer.setId(R.id.jz_tiny_id);
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(400, 400);
lp.gravity = Gravity.RIGHT | Gravity.BOTTOM;
vp.addView(jzVideoPlayer, lp);
jzVideoPlayer.setUp(dataSourceObjects, currentUrlMapIndex, JZVideoPlayerStandard.SCREEN_WINDOW_TINY, objects);
jzVideoPlayer.setState(currentState);
jzVideoPlayer.addTextureView();
JZVideoPlayerManager.setSecondFloor(jzVideoPlayer);
onStateNormal();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public boolean isCurrentPlay() {
return isCurrentJZVD()
&& JZUtils.dataSourceObjectsContainsUri(dataSourceObjects, JZMediaManager.getCurrentDataSource());//url
}
public boolean isCurrentJZVD() {
return JZVideoPlayerManager.getCurrentJzvd() != null
&& JZVideoPlayerManager.getCurrentJzvd() == this;
}
public void playOnThisJzvd() {
Log.i(TAG, "playOnThisJzvd " + " [" + this.hashCode() + "] ");
//1.jzvd
currentState = JZVideoPlayerManager.getSecondFloor().currentState;
currentUrlMapIndex = JZVideoPlayerManager.getSecondFloor().currentUrlMapIndex;
clearFloatScreen();
//2.jzvd
setState(currentState);
// removeTextureView();
addTextureView();
}
public void autoFullscreen(float x) {
if (isCurrentPlay()
&& (currentState == CURRENT_STATE_PLAYING || currentState == CURRENT_STATE_PAUSE)
&& currentScreen != SCREEN_WINDOW_FULLSCREEN
&& currentScreen != SCREEN_WINDOW_TINY) {
if (x > 0) {
JZUtils.setRequestedOrientation(getContext(), ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
} else {
JZUtils.setRequestedOrientation(getContext(), ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
}
onEvent(JZUserAction.ON_ENTER_FULLSCREEN);
startWindowFullscreen();
}
}
public void autoQuitFullscreen() {
if ((System.currentTimeMillis() - lastAutoFullscreenTime) > 2000
&& isCurrentPlay()
&& currentState == CURRENT_STATE_PLAYING
&& currentScreen == SCREEN_WINDOW_FULLSCREEN) {
lastAutoFullscreenTime = System.currentTimeMillis();
backPress();
}
}
public void onEvent(int type) {
if (JZ_USER_EVENT != null && isCurrentPlay() && dataSourceObjects != null) {
JZ_USER_EVENT.onEvent(type, JZUtils.getCurrentFromDataSource(dataSourceObjects, currentUrlMapIndex), currentScreen, objects);
}
}
public static void setMediaInterface(JZMediaInterface mediaInterface) {
JZMediaManager.instance().jzMediaInterface = mediaInterface;
}
//TODO
public void onSeekComplete() {
}
public void showWifiDialog() {
}
public void showProgressDialog(float deltaX,
String seekTime, long seekTimePosition,
String totalTime, long totalTimeDuration) {
}
public void dismissProgressDialog() {
}
public void showVolumeDialog(float deltaY, int volumePercent) {
}
public void dismissVolumeDialog() {
}
public void showBrightnessDialog(int brightnessPercent) {
}
public void dismissBrightnessDialog() {
}
public static class JZAutoFullscreenListener implements SensorEventListener {
@Override
public void onSensorChanged(SensorEvent event) {
final float x = event.values[SensorManager.DATA_X];
float y = event.values[SensorManager.DATA_Y];
float z = event.values[SensorManager.DATA_Z];
if (x < -12 || x > 12) {
if ((System.currentTimeMillis() - lastAutoFullscreenTime) > 2000) {
if (JZVideoPlayerManager.getCurrentJzvd() != null) {
JZVideoPlayerManager.getCurrentJzvd().autoFullscreen(x);
}
lastAutoFullscreenTime = System.currentTimeMillis();
}
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
public class ProgressTimerTask extends TimerTask {
@Override
public void run() {
if (currentState == CURRENT_STATE_PLAYING || currentState == CURRENT_STATE_PAUSE) {
// Log.v(TAG, "onProgressUpdate " + "[" + this.hashCode() + "] ");
post(new Runnable() {
@Override
public void run() {
long position = getCurrentPositionWhenPlaying();
long duration = getDuration();
int progress = (int) (position * 100 / (duration == 0 ? 1 : duration));
setProgressAndText(progress, position, duration);
}
});
}
}
}
}
|
package com.podio.sdk.parser;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.podio.sdk.Parser;
public class ItemToJsonParser implements Parser<Object> {
@Override
public List<?> parse(Object source, Class<?> classOfTarget) {
List<String> result = new ArrayList<String>(1);
if (source != null) {
GsonBuilder builder = new GsonBuilder();
builder.disableHtmlEscaping();
Gson gson = builder.create();
String json = gson.toJson(source);
result.add(json);
}
return result;
}
}
|
package io.spine.testdata;
import com.google.common.base.Charsets;
import com.google.protobuf.Any;
import com.google.protobuf.ByteString;
import com.google.protobuf.Descriptors;
import com.google.protobuf.Descriptors.Descriptor;
import com.google.protobuf.Descriptors.FieldDescriptor;
import com.google.protobuf.Descriptors.FieldDescriptor.JavaType;
import com.google.protobuf.Descriptors.FieldDescriptor.Type;
import com.google.protobuf.GeneratedMessageV3;
import com.google.protobuf.Message;
import io.spine.core.Command;
import io.spine.core.Event;
import io.spine.protobuf.AnyPacker;
import io.spine.type.TypeUrl;
import java.security.SecureRandom;
import java.util.Collection;
import java.util.List;
import java.util.Random;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static io.spine.protobuf.Messages.builderFor;
import static java.lang.String.format;
/**
* Utility for creating simple stubs for generated messages, DTOs (like {@link Event} and
* {@link Command}), storage objects and else.
*
* @author Dmytro Dashenkov
*/
public class Sample {
private Sample() {
}
/**
* Generates a new stub {@link Message.Builder} with all the fields set to
* {@link Random random} values.
*
* <p> All the fields are guaranteed to be not {@code null} and not default.
* Number and {@code boolean} fields may or may not have their default values ({@code 0} and
* {@code false}).
*
* @param clazz Java class of the stub message
* @param <M> type of the required message
* @param <B> type of the {@link Message.Builder} for the message
* @return new instance of the {@link Message.Builder} for given type
* @see #valueFor(FieldDescriptor)
*/
public static <M extends Message, B extends Message.Builder> B builderForType(Class<M> clazz) {
checkClass(clazz);
final B builder = builderFor(clazz);
final Descriptor builderDescriptor = builder.getDescriptorForType();
final Collection<FieldDescriptor> fields = builderDescriptor.getFields();
for (FieldDescriptor field : fields) {
final Object value = valueFor(field);
if (field.isRepeated()) {
builder.addRepeatedField(field, value);
} else {
builder.setField(field, value);
}
}
return builder;
}
/**
* Generates a new stub {@link Message} with all the fields set to {@link Random random} values.
*
* <p> All the fields are guaranteed to be not {@code null} and not default.
* Number and {@code boolean} fields
* may or may not have their default values ({@code 0} and {@code false}).
*
* <p>If the required type is {@link Any}, an instance of an empty {@link Any} wrapped into
* another {@link Any} is returned. See {@link AnyPacker}.
*
* @param clazz Java class of the required stub message
* @param <M> type of the required message
* @return new instance of the given {@link Message} type with random fields
* @see #builderForType(Class)
*/
public static <M extends Message> M messageOfType(Class<M> clazz) {
checkClass(clazz);
if (Any.class.equals(clazz)) {
final Any any = Any.getDefaultInstance();
@SuppressWarnings("unchecked")
final M result = (M) AnyPacker.pack(any);
return result;
}
final Message.Builder builder = builderForType(clazz);
@SuppressWarnings("unchecked") // Checked cast
final M result = (M) builder.build();
return result;
}
private static void checkClass(Class<? extends Message> clazz) {
checkNotNull(clazz);
// Support only generated protobuf messages
checkArgument(GeneratedMessageV3.class.isAssignableFrom(clazz),
"Only generated protobuf messages are allowed.");
}
/**
* Generates a non-default value for the given message field.
*
* <p>All the protobuf types are supported including nested {@link Message}s and
* the {@code enum}s.
*
* @param field {@link FieldDescriptor} to take the type info from
* @return a non-default generated value of type of the given field
*/
@SuppressWarnings("OverlyComplexMethod")
private static Object valueFor(FieldDescriptor field) {
final Type type = field.getType();
final JavaType javaType = type.getJavaType();
final Random random = new SecureRandom();
switch (javaType) {
case INT:
return random.nextInt();
case LONG:
return random.nextLong();
case FLOAT:
return random.nextFloat();
case DOUBLE:
return random.nextDouble();
case BOOLEAN:
return random.nextBoolean();
case STRING:
final byte[] bytes = new byte[8];
random.nextBytes(bytes);
return new String(bytes, Charsets.UTF_8);
case BYTE_STRING:
final byte[] bytesPrimitive = new byte[8];
random.nextBytes(bytesPrimitive);
return ByteString.copyFrom(bytesPrimitive);
case ENUM:
return enumValueFor(field, random);
case MESSAGE:
return messageValueFor(field);
default:
throw new IllegalArgumentException(format("Field type %s is not supported.", type));
}
}
private static Object enumValueFor(FieldDescriptor field, Random random) {
final Descriptors.EnumDescriptor descriptor = field.getEnumType();
final List<Descriptors.EnumValueDescriptor> enumValues = descriptor.getValues();
if (enumValues.isEmpty()) {
return null;
}
// Value under index 0 is usually used to store `undefined` option
// Use values with indexes from 1 to n
final int index = random.nextInt(enumValues.size() - 1) + 1;
final Descriptors.EnumValueDescriptor enumValue = descriptor.findValueByNumber(index);
return enumValue;
}
private static Message messageValueFor(FieldDescriptor field) {
final TypeUrl messageType = TypeUrl.from(field.getMessageType());
final Class<? extends Message> javaClass = classFor(messageType);
final Message fieldValue = messageOfType(javaClass);
return fieldValue;
}
@SuppressWarnings("unchecked") // Reflective class definition retrieving
private static <M extends Message> Class<M> classFor(TypeUrl url) {
final Class<M> javaClass = url.getJavaClass();
return javaClass;
}
}
|
package com.asafge.newsblurplus;
import android.content.Context;
import com.noinnion.android.reader.api.ExtensionPrefs;
public class Prefs extends ExtensionPrefs {
public static final String KEY_LOGGED_IN = "logged_in";
public static final String KEY_SESSION_ID_NAME = "session_id_name";
public static final String KEY_SESSION_ID_VALUE = "session_id_value";
public static final String KEY_HASHES_LIST = "hashes_list";
public static final String USER_AGENT = System.getProperty("http.agent");
public static boolean isLoggedIn(Context c) {
return getBoolean(c, KEY_LOGGED_IN, false);
}
public static void setLoggedIn(Context c, boolean value) {
putBoolean(c, KEY_LOGGED_IN, value);
}
public static String[] getSessionID(Context c) {
String[] sessionID = { getString(c, KEY_SESSION_ID_NAME), getString(c, KEY_SESSION_ID_VALUE)};
return sessionID;
}
public static void setSessionID(Context c, String name, String value) {
putString(c, KEY_SESSION_ID_NAME, name);
putString(c, KEY_SESSION_ID_VALUE, value);
}
public static String getHashesList(Context c, String hashes) {
return getString(c, KEY_HASHES_LIST);
}
public static void setHashesList(Context c, String hashes) {
putString(c, KEY_HASHES_LIST, hashes);
}
}
|
package st.alr.mqttitude.services;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttPersistenceException;
import org.eclipse.paho.client.mqttv3.MqttTopic;
import org.json.JSONObject;
import st.alr.mqttitude.R;
import st.alr.mqttitude.preferences.ActivityPreferences;
import st.alr.mqttitude.support.Defaults;
import st.alr.mqttitude.support.Defaults.State;
import st.alr.mqttitude.support.Events;
import st.alr.mqttitude.support.GeocodableLocation;
import st.alr.mqttitude.support.MqttPublish;
import android.annotation.SuppressLint;
import android.app.AlarmManager;
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.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.preference.PreferenceManager;
import android.util.Log;
import de.greenrobot.event.EventBus;
public class ServiceMqtt extends ServiceBindable implements MqttCallback
{
private static State.ServiceMqtt state = State.ServiceMqtt.INITIAL;
private short keepAliveSeconds;
private MqttClient mqttClient;
private SharedPreferences sharedPreferences;
private static ServiceMqtt instance;
private SharedPreferences.OnSharedPreferenceChangeListener preferencesChangedListener;
private Thread workerThread;
private LinkedList<DeferredPublishable> deferredPublishables;
private Exception error;
private HandlerThread pubThread;
private Handler pubHandler;
private BroadcastReceiver netConnReceiver;
private BroadcastReceiver pingSender;
@Override
public void onCreate()
{
super.onCreate();
instance = this;
workerThread = null;
error = null;
changeState(Defaults.State.ServiceMqtt.INITIAL);
keepAliveSeconds = 15 * 60;
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
deferredPublishables = new LinkedList<DeferredPublishable>();
EventBus.getDefault().register(this);
pubThread = new HandlerThread("MQTTPUBTHREAD");
pubThread.start();
pubHandler = new Handler(pubThread.getLooper());
}
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
doStart(intent, startId);
return super.onStartCommand(intent, flags, startId);
}
private void doStart(final Intent intent, final int startId) {
// init();
Thread thread1 = new Thread() {
@Override
public void run() {
handleStart(intent, startId);
if (this == workerThread) // Clean up worker thread
workerThread = null;
}
@Override
public void interrupt() {
if (this == workerThread) // Clean up worker thread
workerThread = null;
super.interrupt();
}
};
thread1.start();
}
void handleStart(Intent intent, int startId) {
Log.v(this.toString(), "handleStart");
// Respect user's wish to stay disconnected. Overwrite with startId == -1 to reconnect manually afterwards
if ((state == Defaults.State.ServiceMqtt.DISCONNECTED_USERDISCONNECT) && startId != -1) {
Log.d(this.toString(), "handleStart: respecting user disconnect ");
return;
}
if (isConnecting()) {
Log.d(this.toString(), "handleStart: already connecting");
return;
}
// Respect user's wish to not use data
if (!isBackgroundDataEnabled()) {
Log.e(this.toString(), "handleStart: !isBackgroundDataEnabled");
changeState(Defaults.State.ServiceMqtt.DISCONNECTED_DATADISABLED);
return;
}
// Don't do anything unless we're disconnected
if (isDisconnected())
{
Log.v(this.toString(), "handleStart: !isConnected");
// Check if there is a data connection
if (isOnline(true))
{
if (connect())
{
Log.v(this.toString(), "handleStart: connect sucessfull");
onConnect();
}
}
else
{
Log.e(this.toString(), "handleStart: !isOnline");
changeState(Defaults.State.ServiceMqtt.DISCONNECTED_WAITINGFORINTERNET);
}
} else {
Log.d(this.toString(), "handleStart: already connected");
}
}
private boolean isDisconnected(){
Log.v(this.toString(), "disconnect check: " + state);
return state == Defaults.State.ServiceMqtt.INITIAL
|| state == Defaults.State.ServiceMqtt.DISCONNECTED
|| state == Defaults.State.ServiceMqtt.DISCONNECTED_USERDISCONNECT
|| state == Defaults.State.ServiceMqtt.DISCONNECTED_WAITINGFORINTERNET
|| state == Defaults.State.ServiceMqtt.DISCONNECTED_ERROR;
}
/**
* @category CONNECTION HANDLING
*/
private void init()
{
Log.v(this.toString(), "initMqttClient");
if (mqttClient != null) {
return;
}
try
{
String brokerAddress = sharedPreferences.getString(Defaults.SETTINGS_KEY_BROKER_HOST,
Defaults.VALUE_BROKER_HOST);
String brokerPort = sharedPreferences.getString(Defaults.SETTINGS_KEY_BROKER_PORT,
Defaults.VALUE_BROKER_PORT);
String prefix = getBrokerSecurityMode() == Defaults.VALUE_BROKER_SECURITY_NONE ? "tcp"
: "ssl";
String cid = ActivityPreferences.getDeviceName(true);
mqttClient = new MqttClient(prefix + "://" + brokerAddress + ":" + (brokerPort.equals("") ? Defaults.VALUE_BROKER_PORT : brokerPort),
cid , null);
mqttClient.setCallback(this);
} catch (MqttException e)
{
// something went wrong!
mqttClient = null;
changeState(Defaults.State.ServiceMqtt.DISCONNECTED);
}
}
private int getBrokerSecurityMode() {
return sharedPreferences.getInt(Defaults.SETTINGS_KEY_BROKER_SECURITY,
Defaults.VALUE_BROKER_SECURITY_NONE);
}
private javax.net.ssl.SSLSocketFactory getSSLSocketFactory() throws CertificateException,
KeyStoreException, NoSuchAlgorithmException, IOException, KeyManagementException {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
InputStream caInput = new BufferedInputStream(new FileInputStream(
sharedPreferences.getString(Defaults.SETTINGS_KEY_BROKER_SECURITY_SSL_CA_PATH, "")));
java.security.cert.Certificate ca;
try {
ca = cf.generateCertificate(caInput);
} finally {
caInput.close();
}
// Create a KeyStore containing our trusted CAs
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);
// Create a TrustManager that trusts the CAs in our KeyStore
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
// Create an SSLContext that uses our TrustManager
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, tmf.getTrustManagers(), null);
return context.getSocketFactory();
}
private boolean connect()
{
workerThread = Thread.currentThread(); // We connect, so we're the
// worker thread
Log.v(this.toString(), "connect");
error = null; // clear previous error on connect
init();
try
{
changeState(Defaults.State.ServiceMqtt.CONNECTING);
MqttConnectOptions options = new MqttConnectOptions();
switch (ActivityPreferences.getBrokerAuthType()) {
case Defaults.VALUE_BROKER_AUTH_ANONYMOUS:
break;
default:
options.setPassword(sharedPreferences.getString(
Defaults.SETTINGS_KEY_BROKER_PASSWORD, "").toCharArray());
options.setUserName(ActivityPreferences.getUsername());
break;
}
if (getBrokerSecurityMode() == Defaults.VALUE_BROKER_SECURITY_SSL_CUSTOMCACRT)
options.setSocketFactory(this.getSSLSocketFactory());
//setWill(options);
options.setKeepAliveInterval(keepAliveSeconds);
options.setConnectionTimeout(10);
options.setCleanSession(false);
mqttClient.connect(options);
Log.d(this.toString(), "No error during connect");
changeState(Defaults.State.ServiceMqtt.CONNECTED);
return true;
} catch (Exception e) { // Catch paho and socket factory exceptions
Log.e(this.toString(), e.toString());
changeState(e);
return false;
}
}
private void setWill(MqttConnectOptions m) {
StringBuffer payload = new StringBuffer();
payload.append("{");
payload.append("\"type\": ").append("\"").append("_lwt").append("\"");
payload.append(", \"tst\": ").append("\"").append((int) (new Date().getTime() / 1000))
.append("\"");
payload.append("}");
m.setWill(mqttClient.getTopic(ActivityPreferences.getPubTopic(true)), payload.toString().getBytes(), 0, false);
}
private void onConnect() {
if (!isConnected())
Log.e(this.toString(), "onConnect: !isConnected");
// Establish observer to monitor wifi and radio connectivity
if (netConnReceiver == null) {
netConnReceiver = new NetworkConnectionIntentReceiver();
registerReceiver(netConnReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
// Establish ping sender
if (pingSender == null) {
pingSender = new PingSender();
registerReceiver(pingSender, new IntentFilter(Defaults.INTENT_ACTION_PUBLICH_PING));
}
scheduleNextPing();
try {
if(ActivityPreferences.areContactsEnabled())
mqttClient.subscribe(ActivityPreferences.getSubTopic(true));
} catch (MqttException e) {
e.printStackTrace();
}
}
public void disconnect(boolean fromUser)
{
Log.v(this.toString(), "disconnect");
if(isConnecting()) // throws MqttException.REASON_CODE_CONNECT_IN_PROGRESS when disconnecting while connect is in progress.
return;
if (fromUser)
changeState(Defaults.State.ServiceMqtt.DISCONNECTED_USERDISCONNECT);
try
{
if (netConnReceiver != null)
{
unregisterReceiver(netConnReceiver);
netConnReceiver = null;
}
if (pingSender != null)
{
unregisterReceiver(pingSender);
pingSender = null;
}
} catch (Exception eee)
{
Log.e(this.toString(), "Unregister failed", eee);
}
try
{
if (isConnected())
mqttClient.disconnect();
} catch (Exception e) {
e.printStackTrace();
} finally {
mqttClient = null;
if (workerThread != null) {
workerThread.interrupt();
}
}
}
@SuppressLint("Wakelock")
// Lint check derps with the wl.release() call.
@Override
public void connectionLost(Throwable t)
{
Log.e(this.toString(), "error: " + t.toString());
// we protect against the phone switching off while we're doing this
// by requesting a wake lock - we request the minimum possible wake
// lock - just enough to keep the CPU running until we've finished
PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MQTT");
wl.acquire();
if (!isOnline(true))
{
changeState(Defaults.State.ServiceMqtt.DISCONNECTED_WAITINGFORINTERNET);
}
else
{
changeState(Defaults.State.ServiceMqtt.DISCONNECTED);
scheduleNextPing();
}
wl.release();
}
public void reconnect() {
disconnect(true);
doStart(null, -1);
}
public void onEvent(Events.StateChanged.ServiceMqtt event) {
if (event.getState() == Defaults.State.ServiceMqtt.CONNECTED)
publishDeferrables();
}
private void changeState(Exception e) {
error = e;
changeState(Defaults.State.ServiceMqtt.DISCONNECTED_ERROR, e);
}
private void changeState(Defaults.State.ServiceMqtt newState) {
changeState(newState, null);
}
private void changeState(Defaults.State.ServiceMqtt newState, Exception e) {
Log.d(this.toString(), "ServiceMqtt state changed to: " + newState);
state = newState;
EventBus.getDefault().postSticky(new Events.StateChanged.ServiceMqtt(newState, e));
}
private boolean isOnline(boolean shouldCheckIfOnWifi)
{
ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null
&& netInfo.isAvailable()
&& netInfo.isConnected();
}
public boolean isConnected()
{
return ((mqttClient != null) && (mqttClient.isConnected() == true));
}
public static boolean isErrorState(Defaults.State.ServiceMqtt state) {
return state == Defaults.State.ServiceMqtt.DISCONNECTED_ERROR;
}
public boolean hasError(){
return error != null;
}
public boolean isConnecting() {
return (mqttClient != null) && state == Defaults.State.ServiceMqtt.CONNECTING;
}
private boolean isBackgroundDataEnabled() {
return isOnline(false);
}
/**
* @category MISC
*/
public static ServiceMqtt getInstance() {
return instance;
}
@Override
public void onDestroy()
{
// disconnect immediately
disconnect(false);
changeState(Defaults.State.ServiceMqtt.DISCONNECTED);
sharedPreferences.unregisterOnSharedPreferenceChangeListener(preferencesChangedListener);
super.onDestroy();
}
public static Defaults.State.ServiceMqtt getState() {
return state;
}
public static String getErrorMessage() {
Exception e = getInstance().error;
if(getInstance() != null && getInstance().hasError() && e.getCause() != null)
return "Error: " + e.getCause().getLocalizedMessage();
else
return "Error: " + getInstance().getString(R.string.na);
}
public static String getStateAsString(Context c){
return Defaults.State.toString(state, c);
}
public static String stateAsString(Defaults.State.ServiceLocator state, Context c) {
return Defaults.State.toString(state, c);
}
private void deferPublish(final DeferredPublishable p) {
p.wait(deferredPublishables, new Runnable() {
@Override
public void run() {
if(deferredPublishables != null && deferredPublishables.contains(p))
deferredPublishables.remove(p);
if(!p.isPublishing())//might happen that the publish is in progress while the timeout occurs.
p.publishFailed();
}
});
}
public void publish(String topic, String payload) {
publish(topic, payload, false, 0, 0, null, null);
}
public void publish(String topic, String payload, boolean retained) {
publish(topic, payload, retained, 0, 0, null, null);
}
public void publish(final String topic, final String payload, final boolean retained, final int qos, final int timeout,
final MqttPublish callback, final Object extra) {
publish(new DeferredPublishable(topic, payload, retained, qos, timeout, callback, extra));
}
private void publish(final DeferredPublishable p) {
pubHandler.post(new Runnable() {
@Override
public void run() {
if(Looper.getMainLooper().getThread() == Thread.currentThread()){
Log.e(this.toString(), "PUB ON MAIN THREAD");
}
if (!isOnline(false) || !isConnected()) {
Log.d(this.toString(), "pub deferred");
deferPublish(p);
doStart(null, 1);
return;
}
try
{
p.publishing();
mqttClient.getTopic(p.getTopic()).publish(p);
p.publishSuccessfull();
} catch (MqttException e)
{
Log.e(this.toString(), e.getMessage());
e.printStackTrace();
p.cancelWait();
p.publishFailed();
}
}
});
}
private void publishDeferrables() {
for (Iterator<DeferredPublishable> iter = deferredPublishables.iterator(); iter.hasNext(); ) {
DeferredPublishable p = iter.next();
iter.remove();
publish(p);
}
}
private class DeferredPublishable extends MqttMessage {
private Handler timeoutHandler;
private MqttPublish callback;
private String topic;
private int timeout = 0;
private boolean isPublishing;
private Object extra;
public DeferredPublishable(String topic, String payload, boolean retained, int qos,
int timeout, MqttPublish callback, Object extra) {
super(payload.getBytes());
this.setQos(qos);
this.setRetained(retained);
this.extra = extra;
this.callback = callback;
this.topic = topic;
this.timeout = timeout;
}
public void publishFailed() {
if (callback != null)
callback.publishFailed(extra);
}
public void publishSuccessfull() {
if (callback != null)
callback.publishSuccessfull(extra);
cancelWait();
}
public void publishing() {
isPublishing = true;
if (callback != null)
callback.publishing(extra);
}
public boolean isPublishing(){
return isPublishing;
}
public String getTopic() {
return topic;
}
public void cancelWait(){
if(timeoutHandler != null)
this.timeoutHandler.removeCallbacksAndMessages(this);
}
public void wait(LinkedList<DeferredPublishable> queue, Runnable onRemove) {
if (timeoutHandler != null) {
Log.d(this.toString(), "This DeferredPublishable already has a timeout set");
return;
}
// No need signal waiting for timeouts of 0. The command will be
// failed right away
if (callback != null && timeout > 0)
callback.publishWaiting(extra);
queue.addLast(this);
this.timeoutHandler = new Handler();
this.timeoutHandler.postDelayed(onRemove, timeout * 1000);
}
}
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
scheduleNextPing();
Log.v(this.toString(), "Received message: " + topic + " : " + message.getPayload().toString());
String msg = new String(message.getPayload());
String type;
JSONObject json = new JSONObject(msg);
try {
type = json.getString("_type");
} catch (Exception e) {
Log.e(this.toString(), "Received invalid message: " + msg);
return;
}
if(!type.equals("location")) {
Log.d(this.toString(), "Ignoring message of type " + type);
return;
}
GeocodableLocation l = GeocodableLocation.fromJsonObject(json);
EventBus.getDefault().postSticky(new Events.ContactLocationUpdated(l, topic));
}
@Override
public void deliveryComplete(IMqttDeliveryToken token) {}
@Override
protected void onStartOnce() {}
private class NetworkConnectionIntentReceiver extends BroadcastReceiver
{
@Override
@SuppressLint("Wakelock")
public void onReceive(Context ctx, Intent intent)
{
Log.v(this.toString(), "NetworkConnectionIntentReceiver: onReceive");
PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MQTTitude");
wl.acquire();
if (isOnline(true) && !isConnected() && !isConnecting()) {
Log.v(this.toString(), "NetworkConnectionIntentReceiver: triggering doStart(null, -1)");
doStart(null, 1);
}
wl.release();
}
}
public class PingSender extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
if (isOnline(true) && !isConnected() && !isConnecting()) {
Log.v(this.toString(), "ping: isOnline()=" + isOnline(true) + ", isConnected()=" + isConnected());
doStart(null, -1);
} else if (!isOnline(true)) {
Log.d(this.toString(), "ping: Waiting for network to come online again");
} else {
try
{
ping();
} catch (MqttException e)
{
// if something goes wrong, it should result in
// connectionLost
// being called, so we will handle it there
Log.e(this.toString(), "ping failed - MQTT exception", e);
// assume the client connection is broken - trash it
try {
mqttClient.disconnect();
} catch (MqttPersistenceException e1) {
Log.e(this.toString(), "disconnect failed - persistence exception", e1);
} catch (MqttException e2)
{
Log.e(this.toString(), "disconnect failed - mqtt exception", e2);
}
// reconnect
Log.w(this.toString(), "onReceive: MqttException=" + e);
doStart(null, -1);
}
}
scheduleNextPing();
}
}
private void scheduleNextPing()
{
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(
Defaults.INTENT_ACTION_PUBLICH_PING), PendingIntent.FLAG_UPDATE_CURRENT);
Calendar wakeUpTime = Calendar.getInstance();
wakeUpTime.add(Calendar.SECOND, keepAliveSeconds);
AlarmManager aMgr = (AlarmManager) getSystemService(ALARM_SERVICE);
aMgr.set(AlarmManager.RTC_WAKEUP, wakeUpTime.getTimeInMillis(), pendingIntent);
}
private void ping() throws MqttException {
MqttTopic topic = mqttClient.getTopic("$SYS/keepalive");
MqttMessage message = new MqttMessage();
message.setRetained(false);
message.setQos(1);
message.setPayload(new byte[] {
0
});
try
{
topic.publish(message);
} catch (org.eclipse.paho.client.mqttv3.MqttPersistenceException e)
{
e.printStackTrace();
} catch (org.eclipse.paho.client.mqttv3.MqttException e)
{
throw new MqttException(e);
}
}
}
|
/**
* @Company Riot Games
*
* Given a list of kill events where a kill event is defined as [ timestamp, killerId, victimId ].
* Return a list of the users who have the largest killstreak. A killstreak is defined as a sequence
* of kills where each kill is no more than 15 units of time from the next kill.
*
* If there is a tie of users with the largest killstreak, then return an array of them.
* The return format should be a list of all the users with the largest killstreak in the format of a list of their ids.
*
* Problem Ex.
* Input: [
* [ 1, 1, 2 ],
* [ 5, 1, 3 ],
* [ 3, 1, 4 ],
* [ 9, 2, 1 ],
* ]
* Output: [ 1, 3 ]
*
* Note: the list of kills are not in any specific order.
*/
public List<Integer> largestKillstreak(int[][] kills) {
Arrays.sort(kills, (a, b) -> a[0] - b[0]);
// Mapping of userId -> [ killCount, killTime ].
HashMap<Integer, int[]> map = new HashMap<Integer, int[]>();
int max = Integer.MIN_VALUE;
for (int i = 0; i < kills.length; i ++) {
int timestamp = kills[i][0];
int killer = kills[i][1];
int pair = map.getOrDefault(killer, new int[] { 0, 0 });
if (pair[1] + 15 < timestmap) {
pair[0] = 0;
}
pair[0] ++;
pair[1] = timestamp;
max = Math.max(max, pair[0]);
map.put(killer, pair);
}
List<Integer> list = new ArrayList<Integer>();
for (int i : map.keySet()) {
int[] pair = map.get(i);
if (pair[0] == max) list.add(i);
}
return list;
}
/**
* Part 2 expands on the definition of killstreak.
* Killstreak is now defined as a sequence of kills where each kill is no more than 15 units of time from the next
* as well as not dying from the beginning of the sequence to the end of the sequence.
*
* This is more commonly the actual definition of a multi killstreak found in games.
*/
public List<Integer> largestKillstreak(int[][] kills) {
Arrays.sort(kills, (a, b) -> a[0] - b[0]);
// Mapping of userId -> [ killCount, killTime ].
HashMap<Integer, int[]> map = new HashMap<Integer, int[]>();
int max = Integer.MIN_VALUE;
for (int i = 0; i < kills.length; i ++) {
int timestamp = kills[i][0];
int killer = kills[i][1];
int victim = kils[i][2];
// Reset the victim's kill count.
if (map.containsKey(victim)) {
int[] victimPair = map.get(victim);
victimPair[0] = 0;
map.put(victim, victimPair);
}
int pair = map.getOrDefault(killer, new int[] { 0, 0 });
if (pair[1] + 15 < timestmap) {
pair[0] = 0;
}
pair[0] ++;
pair[1] = timestamp;
max = Math.max(max, pair[0]);
map.put(killer, pair);
}
List<Integer> list = new ArrayList<Integer>();
for (int i : map.keySet()) {
int[] pair = map.get(i);
if (pair[0] == max) list.add(i);
}
return list;
}
|
package limelight.ui;
import java.awt.*;
public class InputLayout implements LayoutManager
{
public void addLayoutComponent(String string, Component component)
{
}
public void removeLayoutComponent(Component component)
{
}
public Dimension preferredLayoutSize(Container container)
{
return container.getPreferredSize();
}
public Dimension minimumLayoutSize(Container container)
{
return container.getMinimumSize();
}
public void layoutContainer(Container parent)
{
parent.setSize(parent.getMaximumSize());
for(Component component : parent.getComponents())
{
Dimension size = parent.getSize();
component.setSize(size);
}
}
}
|
package jj.http.server;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http.websocketx.WebSocketServerHandshakerFactory;
import java.io.IOException;
import java.util.List;
import java.util.regex.Pattern;
import javax.inject.Inject;
import com.google.inject.AbstractModule;
import com.google.inject.Injector;
import com.google.inject.Provides;
import jj.event.Publisher;
import jj.execution.TaskRunner;
import jj.http.server.servable.RequestProcessor;
import jj.http.server.servable.Servable;
import jj.http.server.servable.Servables;
import jj.logging.Emergency;
import jj.resource.ResourceTask;
import jj.resource.Resource;
/**
* Reads incoming http messages and looks for ways to respond
* @author jason
*
*
*/
public class EngineHttpHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
private static final Pattern HTTP_REPLACER = Pattern.compile("http");
private final TaskRunner taskRunner;
private final Servables servables;
private final Injector parentInjector;
private final WebSocketRequestChecker webSocketRequestChecker;
private final Publisher publisher;
@Inject
EngineHttpHandler(
final TaskRunner taskRunner,
final Servables servables,
final Injector parentInjector,
final WebSocketRequestChecker webSocketRequestChecker,
final Publisher publisher
) {
this.taskRunner = taskRunner;
this.servables = servables;
this.parentInjector = parentInjector;
this.webSocketRequestChecker = webSocketRequestChecker;
this.publisher = publisher;
}
private Injector makeInjector(final ChannelHandlerContext ctx, final FullHttpRequest request) {
return parentInjector.createChildInjector(new AbstractModule() {
@Override
protected void configure() {
bind(ChannelHandlerContext.class).toInstance(ctx);
bind(FullHttpRequest.class).toInstance(request);
bind(HttpServerRequest.class).to(HttpServerRequestImpl.class);
bind(HttpServerResponse.class).to(HttpServerResponseImpl.class);
bind(WebSocketConnectionMaker.class);
bind(WebSocketFrameHandlerCreator.class);
}
@Provides
protected WebSocketServerHandshakerFactory provideHandshaker() {
String uri = HTTP_REPLACER.matcher(
request.headers().get(HttpHeaders.Names.ORIGIN) +
request.getUri()
).replaceFirst("ws");
return new WebSocketServerHandshakerFactory(uri, null, false);
}
});
}
@Override
protected void channelRead0(final ChannelHandlerContext ctx, final FullHttpRequest request) throws Exception {
//long time = System.nanoTime();
Injector injector = makeInjector(ctx, request);
//System.out.println("takes " + MILLISECONDS.convert(System.nanoTime() - time, NANOSECONDS));
if (!request.getDecoderResult().isSuccess()) {
injector.getInstance(HttpServerResponse.class).sendError(HttpResponseStatus.BAD_REQUEST);
} else if (webSocketRequestChecker.isWebSocketRequest(request)) {
injector.getInstance(WebSocketConnectionMaker.class).handshakeWebsocket();
} else {
handleHttpRequest(injector.getInstance(HttpServerRequest.class), injector.getInstance(HttpServerResponse.class));
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
if (!(cause instanceof IOException)) {
publisher.publish(new Emergency("engine caught an exception", cause));
try {
ctx.writeAndFlush(
new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR)
).addListener(ChannelFutureListener.CLOSE);
} catch (Exception e) {
publisher.publish(new Emergency("additionally, an exception occurred while responding with an error", e));
}
}
}
void handleHttpRequest(
final HttpServerRequest request,
final HttpServerResponse response
) throws Exception {
// look up the candidate ways to service the request
// try them out to see if the request can be handled?
// - TODO always in the IO thread? not sure there, maybe document servable can launch the script execution immediately
// - but it may not matter since all threads will generally be warm under load and it's no big deal otherwise
// see if the request can get handled
// return 404 if not
final List<Servable<? extends Resource>> list = servables.findMatchingServables(request.uriMatch());
assert (!list.isEmpty()) : "no servables found - something is misconfigured";
taskRunner.execute(new ResourceTask("JJEngine core processing") {
@Override
public void run() {
try {
boolean found = false;
for (Servable<? extends Resource> servable : list) {
RequestProcessor requestProcessor = servable.makeRequestProcessor(request, response);
if (requestProcessor != null) {
requestProcessor.process();
found = true;
break;
}
}
if (!found) {
response.sendNotFound();
}
} catch (Throwable e) {
response.error(e);
}
}
});
}
}
|
package pl.edu.icm.cermine.structure;
import com.google.common.collect.Lists;
import java.util.*;
import pl.edu.icm.cermine.exception.AnalysisException;
import pl.edu.icm.cermine.structure.model.*;
import pl.edu.icm.cermine.structure.tools.BxBoundsBuilder;
import pl.edu.icm.cermine.structure.tools.BxModelUtils;
import pl.edu.icm.cermine.tools.DisjointSets;
import pl.edu.icm.cermine.tools.Histogram;
import pl.edu.icm.cermine.tools.timeout.TimeoutRegister;
/**
* Page segmenter using Docstrum algorithm.
*
* @author Krzysztof Rusek
*/
public class DocstrumSegmenter implements DocumentSegmenter {
public static final int MAX_ZONES_PER_PAGE = 300;
public static final int PAGE_MARGIN = 2;
public static final double ORIENTATION_MARGIN = 0.2;
public static final int LINES_PER_PAGE_MARGIN = 100;
private double docOrientation = Double.NaN;
private Map<BxPage, List<Component>> componentMap = new HashMap<BxPage, List<Component>>();
@Override
public BxDocument segmentDocument(BxDocument document) throws AnalysisException {
computeDocumentOrientation(document);
BxDocument output = new BxDocument();
for (BxPage page: document) {
BxPage segmentedPage = segmentPage(page);
if (segmentedPage.getBounds() != null) {
output.addPage(segmentedPage);
}
}
return output;
}
protected void computeDocumentOrientation(BxDocument document) throws AnalysisException {
List<Component> components = new ArrayList<Component>();
for (BxPage page : document.asPages()) {
List<Component> pageComponents = createComponents(page);
componentMap.put(page, pageComponents);
components.addAll(pageComponents);
}
docOrientation = computeInitialOrientation(components);
}
protected void computeDocumentOrientation(Map<BxPage, List<Component>> componentMap) throws AnalysisException {
this.componentMap = componentMap;
List<Component> components = new ArrayList<Component>();
for (Map.Entry<BxPage, List<Component>> entry : componentMap.entrySet()) {
components.addAll(entry.getValue());
}
docOrientation = computeInitialOrientation(components);
}
protected BxPage segmentPage(BxPage page) throws AnalysisException {
List<Component> components = componentMap.get(page);
double orientation = docOrientation;
if (Double.isNaN(orientation)) {
orientation = computeInitialOrientation(components);
}
double characterSpacing = computeCharacterSpacing(components, orientation);
double lineSpacing = computeLineSpacing(components, orientation);
List<ComponentLine> lines = determineLines(components, orientation,
characterSpacing * componentDistanceCharacterMultiplier,
lineSpacing * maxVerticalComponentDistanceMultiplier);
if (Math.abs(orientation) > ORIENTATION_MARGIN) {
List<ComponentLine> linesZero = determineLines(components, 0,
characterSpacing * componentDistanceCharacterMultiplier,
lineSpacing * maxVerticalComponentDistanceMultiplier);
if (Math.abs(lines.size() - LINES_PER_PAGE_MARGIN) > Math.abs(linesZero.size() - LINES_PER_PAGE_MARGIN)) {
orientation = 0;
lines = linesZero;
}
}
double lineOrientation = computeOrientation(lines);
if (!Double.isNaN(lineOrientation)) {
orientation = lineOrientation;
}
List<List<ComponentLine>> zones = determineZones(lines, orientation,
characterSpacing * minHorizontalDistanceMultiplier, Double.POSITIVE_INFINITY,
lineSpacing * minVerticalDistanceMultiplier, lineSpacing * maxVerticalDistanceMultiplier,
characterSpacing * minHorizontalMergeDistanceMultiplier, 0.0,
0.0, lineSpacing * maxVerticalMergeDistanceMultiplier);
zones = mergeZones(zones, characterSpacing * 0.5);
zones = mergeLines(zones, orientation,
Double.NEGATIVE_INFINITY, 0.0,
0.0, lineSpacing * maxVerticalMergeDistanceMultiplier);
return convertToBxModel(page, zones, wordDistanceMultiplier * characterSpacing);
}
/**
* Constructs sorted by x coordinate array of components from page's chunks.
*
* @param page page containing chunks
* @return array of components
* @throws AnalysisException AnalysisException
*/
protected List<Component> createComponents(BxPage page) throws AnalysisException {
List<BxChunk> chunks = Lists.newArrayList(page.getChunks());
Component[] components = new Component[chunks.size()];
for (int i = 0; i < components.length; i++) {
try {
components[i] = new Component(chunks.get(i));
} catch(IllegalArgumentException ex) {
throw new AnalysisException(ex);
}
}
TimeoutRegister.get().check();
Arrays.sort(components, ComponentXComparator.getInstance());
TimeoutRegister.get().check();
findNeighbors(components);
return Arrays.asList(components);
}
/**
* Performs for each component search for nearest-neighbors and stores the
* result in component's neighbors attribute.
*
* @param components array of components
* @throws AnalysisException if the number of components is less than or
* equal to the number of nearest-neighbors per component.
*/
private void findNeighbors(Component[] components) throws AnalysisException {
if (components.length == 0) {
return;
}
if (components.length == 1) {
components[0].setNeighbors(new ArrayList<Neighbor>());
return;
}
int pageNeighborCount = neighborCount;
if (components.length <= neighborCount) {
pageNeighborCount = components.length - 1;
}
List<Neighbor> candidates = new ArrayList<Neighbor>();
for (int i = 0; i < components.length; i++) {
int start = i, end = i + 1;
// Contains components from components array
// from ranges [start, i) and [i+1, end)
double dist = Double.POSITIVE_INFINITY;
for (double searchDist = 0; searchDist < dist; ) {
searchDist += DISTANCE_STEP;
boolean newCandidatesFound = false;
while (start > 0 && components[i].getX() - components[start - 1].getX() < searchDist) {
start
candidates.add(new Neighbor(components[start], components[i]));
if (candidates.size() > pageNeighborCount) {
Collections.sort(candidates, NeighborDistanceComparator.getInstance());
candidates.subList(pageNeighborCount, candidates.size()).clear();
}
newCandidatesFound = true;
}
TimeoutRegister.get().check();
while (end < components.length && components[end].getX() - components[i].getX() < searchDist) {
candidates.add(new Neighbor(components[end], components[i]));
if (candidates.size() > pageNeighborCount) {
Collections.sort(candidates, NeighborDistanceComparator.getInstance());
candidates.subList(pageNeighborCount, candidates.size()).clear();
}
end++;
newCandidatesFound = true;
}
if (newCandidatesFound && candidates.size() >= pageNeighborCount) {
Collections.sort(candidates, NeighborDistanceComparator.getInstance());
dist = candidates.get(pageNeighborCount - 1).getDistance();
}
TimeoutRegister.get().check();
}
candidates.subList(pageNeighborCount, candidates.size()).clear();
components[i].setNeighbors(new ArrayList<Neighbor>(candidates));
candidates.clear();
}
}
/**
* Computes initial orientation estimation based on nearest-neighbors' angles.
*
* @param components
* @return initial orientation estimation
*/
private double computeInitialOrientation(List<Component> components) {
Histogram histogram = new Histogram(-Math.PI/2, Math.PI/2, angleHistogramResolution);
for (Component component : components) {
for (Neighbor neighbor : component.getNeighbors()) {
histogram.add(neighbor.getAngle());
}
}
// Rectangular smoothing window has been replaced with gaussian smoothing window
histogram.circularGaussianSmooth(angleHistogramSmoothingWindowLength,
angleHistogramSmoothingWindowStdDeviation);
return histogram.getPeakValue();
}
/**
* Computes within-line spacing based on nearest-neighbors distances.
*
* @param components
* @param orientation estimated text orientation
* @return estimated within-line spacing
*/
private double computeCharacterSpacing(List<Component> components, double orientation) {
return computeSpacing(components, orientation);
}
/**
* Computes between-line spacing based on nearest-neighbors distances.
*
* @param components
* @param orientation estimated text orientation
* @return estimated between-line spacing
*/
private double computeLineSpacing(List<Component> components, double orientation) {
if (orientation >= 0) {
return computeSpacing(components, orientation - Math.PI / 2);
} else {
return computeSpacing(components, orientation + Math.PI / 2);
}
}
private double computeSpacing(List<Component> components, double angle) {
double maxDistance = Double.NEGATIVE_INFINITY;
for (Component component : components) {
for (Neighbor neighbor : component.getNeighbors()) {
maxDistance = Math.max(maxDistance, neighbor.getDistance());
}
}
Histogram histogram = new Histogram(0, maxDistance, spacingHistogramResolution);
AngleFilter filter = AngleFilter.newInstance(angle - angleTolerance, angle + angleTolerance);
for (Component component : components) {
for (Neighbor neighbor : component.getNeighbors()) {
if (filter.matches(neighbor)) {
histogram.add(neighbor.getDistance());
}
}
}
// Rectangular smoothing window has been replaced with gaussian smoothing window
histogram.gaussianSmooth(spacingHistogramSmoothingWindowLength,
spacingHistogramSmoothingWindowStdDeviation);
return histogram.getPeakValue();
}
/**
* Groups components into text lines.
*
* @param components component list
* @param orientation - estimated text orientation
* @param maxHorizontalDistance - maximum horizontal distance between components
* @param maxVerticalDistance - maximum vertical distance between components
* @return lines of components
*/
private List<ComponentLine> determineLines(List<Component> components, double orientation,
double maxHorizontalDistance, double maxVerticalDistance) {
DisjointSets<Component> sets = new DisjointSets<Component>(components);
AngleFilter filter = AngleFilter.newInstance(orientation - angleTolerance, orientation + angleTolerance);
for (Component component : components) {
for (Neighbor neighbor : component.getNeighbors()) {
double x = neighbor.getHorizontalDistance(orientation) / maxHorizontalDistance;
double y = neighbor.getVerticalDistance(orientation) / maxVerticalDistance;
if (filter.matches(neighbor) && x * x + y * y <= 1) {
sets.union(component, neighbor.getComponent());
}
}
}
List<ComponentLine> lines = new ArrayList<ComponentLine>();
for (Set<Component> group : sets) {
List<Component> lineComponents = new ArrayList<Component>(group);
Collections.sort(lineComponents, ComponentXComparator.getInstance());
lines.add(new ComponentLine(lineComponents, orientation));
}
return lines;
}
private double computeOrientation(List<ComponentLine> lines) {
// Compute weighted mean of line angles
double valueSum = 0.0;
double weightSum = 0.0;
for (ComponentLine line : lines) {
valueSum += line.getAngle() * line.getLength();
weightSum += line.getLength();
}
return valueSum / weightSum;
}
private List<List<ComponentLine>> determineZones(List<ComponentLine> lines, double orientation,
double minHorizontalDistance, double maxHorizontalDistance,
double minVerticalDistance, double maxVerticalDistance,
double minHorizontalMergeDistance, double maxHorizontalMergeDistance,
double minVerticalMergeDistance, double maxVerticalMergeDistance) {
DisjointSets<ComponentLine> sets = new DisjointSets<ComponentLine>(lines);
// Mean height is computed so that all distances can be scaled
// relative to the line height
double meanHeight = 0.0, weights = 0.0;
for (ComponentLine line : lines) {
double weight = line.getLength();
meanHeight += line.getHeight() * weight;
weights += weight;
}
meanHeight /= weights;
for (int i = 0; i < lines.size(); i++) {
ComponentLine li = lines.get(i);
for (int j = i + 1; j < lines.size(); j++) {
ComponentLine lj = lines.get(j);
double scale = Math.min(li.getHeight(), lj.getHeight()) / meanHeight;
scale = Math.max(minLineSizeScale, Math.min(scale, maxLineSizeScale));
// "<=" is used instead of "<" for consistency and to allow setting minVertical(Merge)Distance
// to 0.0 with meaning "no minimal distance required"
if (!sets.areTogether(li, lj) && li.angularDifference(lj) <= angleTolerance) {
double hDist = li.horizontalDistance(lj, orientation) / scale;
double vDist = li.verticalDistance(lj, orientation) / scale;
// Line over or above
if (minHorizontalDistance <= hDist && hDist <= maxHorizontalDistance
&& minVerticalDistance <= vDist && vDist <= maxVerticalDistance) {
sets.union(li, lj);
}
// Split line that needs later merging
else if (minHorizontalMergeDistance <= hDist && hDist <= maxHorizontalMergeDistance
&& minVerticalMergeDistance <= vDist && vDist <= maxVerticalMergeDistance) {
sets.union(li, lj);
}
}
TimeoutRegister.get().check();
}
}
List<List<ComponentLine>> zones = new ArrayList<List<ComponentLine>>();
for (Set<ComponentLine> group : sets) {
zones.add(new ArrayList<ComponentLine>(group));
}
return zones;
}
private List<List<ComponentLine>> mergeZones(List<List<ComponentLine>> zones, double tolerance) {
List<BxBounds> bounds = new ArrayList<BxBounds>(zones.size());
for (List<ComponentLine> zone : zones) {
BxBoundsBuilder builder = new BxBoundsBuilder();
for (ComponentLine line : zone) {
for (Component component : line.getComponents()) {
builder.expand(component.getChunk().getBounds());
}
}
bounds.add(builder.getBounds());
}
List<List<ComponentLine>> outputZones = new ArrayList<List<ComponentLine>>();
mainFor: for (int i = 0; i < zones.size(); i++) {
for (int j = 0; j < zones.size(); j++) {
if (i == j || bounds.get(j) == null || bounds.get(i) == null) {
continue;
}
if (BxModelUtils.contains(bounds.get(j), bounds.get(i), tolerance)) {
zones.get(j).addAll(zones.get(i));
bounds.set(i, null);
continue mainFor;
}
TimeoutRegister.get().check();
}
outputZones.add(zones.get(i));
}
return outputZones;
}
private List<List<ComponentLine>> mergeLines(List<List<ComponentLine>> zones, double orientation,
double minHorizontalDistance, double maxHorizontalDistance,
double minVerticalDistance, double maxVerticalDistance) {
List<List<ComponentLine>> outputZones = new ArrayList<List<ComponentLine>>(zones.size());
for (List<ComponentLine> zone : zones) {
outputZones.add(mergeLinesInZone(zone, orientation,
minHorizontalDistance, maxHorizontalDistance,
minVerticalDistance, maxVerticalDistance));
}
return outputZones;
}
private List<ComponentLine> mergeLinesInZone(List<ComponentLine> lines, double orientation,
double minHorizontalDistance, double maxHorizontalDistance,
double minVerticalDistance, double maxVerticalDistance) {
DisjointSets<ComponentLine> sets = new DisjointSets<ComponentLine>(lines);
for (int i = 0; i < lines.size(); i++) {
ComponentLine li = lines.get(i);
for (int j = i + 1; j < lines.size(); j++) {
ComponentLine lj = lines.get(j);
double hDist = li.horizontalDistance(lj, orientation);
double vDist = li.verticalDistance(lj, orientation);
if (minHorizontalDistance <= hDist && hDist <= maxHorizontalDistance
&& minVerticalDistance <= vDist && vDist <= maxVerticalDistance) {
sets.union(li, lj);
} else if (minVerticalDistance <= vDist && vDist <= maxVerticalDistance
&& Math.abs(hDist-Math.min(li.getLength(), lj.getLength())) < 0.1) {
boolean componentOverlap = false;
int overlappingCount = 0;
for (Component ci : li.getComponents()) {
for (Component cj : lj.getComponents()) {
double dist = ci.overlappingDistance(cj, orientation);
if (dist > 2) {
componentOverlap = true;
}
if (dist > 0) {
overlappingCount++;
}
}
}
if (!componentOverlap && overlappingCount <= 2) {
sets.union(li, lj);
}
}
}
}
List<ComponentLine> outputZone = new ArrayList<ComponentLine>();
for (Set<ComponentLine> group : sets) {
List<Component> components = new ArrayList<Component>();
for (ComponentLine line : group) {
components.addAll(line.getComponents());
}
Collections.sort(components, ComponentXComparator.getInstance());
outputZone.add(new ComponentLine(components, orientation));
}
return outputZone;
}
/**
* Converts list of zones from internal format (using components and
* component lines) to BxModel.
*
* @param zones zones in internal format
* @param wordSpacing - maximum allowed distance between components that
* belong to one word
* @return BxModel page
*/
private BxPage convertToBxModel(BxPage origPage, List<List<ComponentLine>> zones, double wordSpacing) {
BxPage page = new BxPage();
page.addImages(origPage.getImages());
List<BxPage> pages = Lists.newArrayList(origPage.getParent());
int pageIndex = pages.indexOf(origPage);
boolean groupped = false;
if (zones.size() > MAX_ZONES_PER_PAGE && pageIndex >= PAGE_MARGIN
&& pageIndex < pages.size() - PAGE_MARGIN) {
List<ComponentLine> oneZone = new ArrayList<ComponentLine>();
for (List<ComponentLine> zone : zones) {
oneZone.addAll(zone);
}
zones = new ArrayList<List<ComponentLine>>();
zones.add(oneZone);
groupped = true;
}
for (List<ComponentLine> lines : zones) {
BxZone zone = new BxZone();
if (groupped) {
zone.setLabel(BxZoneLabel.GEN_OTHER);
}
for (ComponentLine line : lines) {
zone.addLine(line.convertToBxLine(wordSpacing));
}
List<BxLine> zLines = Lists.newArrayList(zone);
Collections.sort(zLines, new Comparator<BxLine>() {
@Override
public int compare(BxLine o1, BxLine o2) {
return Double.compare(o1.getBounds().getY(), o2.getBounds().getY());
}
});
zone.setLines(zLines);
BxBoundsBuilder.setBounds(zone);
page.addZone(zone);
}
BxModelUtils.sortZonesYX(page);
BxBoundsBuilder.setBounds(page);
return page;
}
/**
* Internal representation of character.
*/
protected static class Component {
private final double x;
private final double y;
private final BxChunk chunk;
private List<Neighbor> neighbors;
public Component(BxChunk chunk) {
BxBounds bounds = chunk.getBounds();
if (bounds == null) {
throw new IllegalArgumentException("Bounds must not be null");
}
if (Double.isNaN(bounds.getX()) || Double.isInfinite(bounds.getX())) {
throw new IllegalArgumentException("Bounds x coordinate must be finite");
}
if (Double.isNaN(bounds.getY()) || Double.isInfinite(bounds.getY())) {
throw new IllegalArgumentException("Bounds y coordinate must be finite");
}
if (Double.isNaN(bounds.getWidth()) || Double.isInfinite(bounds.getWidth())) {
throw new IllegalArgumentException("Bounds width must be finite");
}
if (Double.isNaN(bounds.getHeight()) || Double.isInfinite(bounds.getHeight())) {
throw new IllegalArgumentException("Bounds height must be finite");
}
this.x = chunk.getBounds().getX() + chunk.getBounds().getWidth() / 2;
this.y = chunk.getBounds().getY() + chunk.getBounds().getHeight() / 2;
this.chunk = chunk;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
public double getHeight() {
return chunk.getBounds().getHeight();
}
public double distance(Component c) {
double dx = getX() - c.getX(), dy = getY() - c.getY();
return Math.sqrt(dx * dx + dy * dy);
}
/**
* Computes horizontal distance between components.
*
* @param c component
* @param orientation orientation angle
* @return distance
*/
public double horizontalDistance(Component c, double orientation) {
// TODO: take orientation into account
return Math.abs(getX() - c.getX());
}
public double verticalDistance(Component c, double orientation) {
return Math.abs(getY() - c.getY());
}
public double horizontalBoundsDistance(Component c, double orientation) {
// TODO: take orientation into account
return horizontalDistance(c, orientation) - getChunk().getBounds().getWidth() / 2 -
c.getChunk().getBounds().getWidth() / 2;
}
public BxChunk getChunk() {
return chunk;
}
public List<Neighbor> getNeighbors() {
return neighbors;
}
public void setNeighbors(List<Neighbor> neighbors) {
this.neighbors = neighbors;
}
private double angle(Component c) {
if (getX() > c.getX()) {
return Math.atan2(getY() - c.getY(), getX() - c.getX());
} else {
return Math.atan2(c.getY() - getY(), c.getX() - getX());
}
}
public double overlappingDistance(Component other, double orientation) {
double[] xs = new double[4];
double s = Math.sin(-orientation), c = Math.cos(-orientation);
xs[0] = c * x - s * y;
xs[1] = c * (x+chunk.getWidth()) - s * (y+chunk.getHeight());
xs[2] = c * other.x - s * other.y;
xs[3] = c * (other.x+other.chunk.getWidth()) - s * (other.y+other.chunk.getHeight());
boolean overlapping = xs[1] >= xs[2] && xs[3] >= xs[0];
Arrays.sort(xs);
return Math.abs(xs[2] - xs[1]) * (overlapping ? 1 : -1);
}
}
/**
* Class representing nearest-neighbor pair.
*/
protected static class Neighbor {
private final double distance;
private final double angle;
private final Component component;
private final Component origin;
public Neighbor(Component neighbor, Component origin) {
this.distance = neighbor.distance(origin);
this.angle = neighbor.angle(origin);
this.component = neighbor;
this.origin = origin;
}
public double getDistance() {
return distance;
}
public double getHorizontalDistance(double orientation) {
return component.horizontalDistance(origin, orientation);
}
public double getVerticalDistance(double orientation) {
return component.verticalDistance(origin, orientation);
}
public double getAngle() {
return angle;
}
public Component getComponent() {
return component;
}
}
/**
* Component comparator based on x coordinate of the centroid of component.
*
* The ordering is not consistent with equals.
*/
protected static final class ComponentXComparator implements Comparator<Component> {
private ComponentXComparator() {
}
@Override
public int compare(Component o1, Component o2) {
return Double.compare(o1.getX(), o2.getX());
}
private static ComponentXComparator instance = new ComponentXComparator();
public static ComponentXComparator getInstance() {
return instance;
}
}
/**
* Neighbor distance comparator based on the distance.
*
* The ordering is not consistent with equals.
*/
protected static final class NeighborDistanceComparator implements Comparator<Neighbor> {
private NeighborDistanceComparator() {
}
@Override
public int compare(Neighbor o1, Neighbor o2) {
return Double.compare(o1.getDistance(), o2.getDistance());
}
private static NeighborDistanceComparator instance = new NeighborDistanceComparator();
public static NeighborDistanceComparator getInstance() {
return instance;
}
}
/**
* Internal representation of the text line.
*/
protected static class ComponentLine {
private final double x0;
private final double y0;
private final double x1;
private final double y1;
private final double height;
private List<Component> components;
public ComponentLine(List<Component> components, double orientation) {
this.components = components;
if (components.size() >= 2) {
// Simple linear regression
double sx = 0.0, sxx = 0.0, sxy = 0.0, sy = 0.0;
for (Component component : components) {
sx += component.getX();
sxx += component.getX() * component.getX();
sxy += component.getX() * component.getY();
sy += component.getY();
}
double b = (components.size() * sxy - sx * sy) / (components.size() * sxx - sx * sx);
double a = (sy - b * sx) / components.size();
this.x0 = components.get(0).getX();
this.y0 = a + b * this.x0;
this.x1 = components.get(components.size() - 1).getX();
this.y1 = a + b * this.x1;
}
else if (! components.isEmpty()) {
Component component = components.get(0);
double dx = component.getChunk().getBounds().getWidth() / 3;
double dy = dx * Math.tan(orientation);
this.x0 = component.getX() - dx;
this.x1 = component.getX() + dx;
this.y0 = component.getY() - dy;
this.y1 = component.getY() + dy;
}
else {
throw new IllegalArgumentException("Component list must not be empty");
}
height = computeHeight();
}
public double getAngle() {
return Math.atan2(y1 - y0, x1 - x0);
}
public double getSlope() {
return (y1 - y0) / (x1 - x0);
}
public double getLength() {
return Math.sqrt((x0 - x1) * (x0 - x1) + (y0 - y1) * (y0 - y1));
}
private double computeHeight() {
double sum = 0.0;
for (Component component : components) {
sum += component.getHeight();
}
return sum / components.size();
}
public double getHeight() {
return height;
}
public List<Component> getComponents() {
return components;
}
public double angularDifference(ComponentLine j) {
double diff = Math.abs(getAngle() - j.getAngle());
if (diff <= Math.PI/2) {
return diff;
} else {
return Math.PI - diff;
}
}
public double horizontalDistance(ComponentLine other, double orientation) {
double[] xs = new double[4];
double s = Math.sin(-orientation), c = Math.cos(-orientation);
xs[0] = c * x0 - s * y0;
xs[1] = c * x1 - s * y1;
xs[2] = c * other.x0 - s * other.y0;
xs[3] = c * other.x1 - s * other.y1;
boolean overlapping = xs[1] >= xs[2] && xs[3] >= xs[0];
Arrays.sort(xs);
return Math.abs(xs[2] - xs[1]) * (overlapping ? 1 : -1);
}
public double verticalDistance(ComponentLine other, double orientation) {
double xm = (x0 + x1) / 2, ym = (y0 + y1) / 2;
double xn = (other.x0 + other.x1) / 2, yn = (other.y0 + other.y1) / 2;
double a = Math.tan(orientation);
return Math.abs(a * (xn - xm) + ym - yn) / Math.sqrt(a * a + 1);
}
public BxLine convertToBxLine(double wordSpacing) {
BxLine line = new BxLine();
BxWord word = new BxWord();
Component previousComponent = null;
for (Component component : components) {
if (previousComponent != null) {
double dist = component.getChunk().getBounds().getX() -
previousComponent.getChunk().getBounds().getX() -
previousComponent.getChunk().getBounds().getWidth();
if(dist > wordSpacing) {
BxBoundsBuilder.setBounds(word);
line.addWord(word);
word = new BxWord();
}
}
word.addChunk(component.getChunk());
previousComponent = component;
}
BxBoundsBuilder.setBounds(word);
line.addWord(word);
BxBoundsBuilder.setBounds(line);
return line;
}
}
/**
* Filter class for neighbor objects that checks if the angle of the
* neighbor is within specified range.
*/
protected abstract static class AngleFilter {
private final double lowerAngle;
private final double upperAngle;
private AngleFilter(double lowerAngle, double upperAngle) {
this.lowerAngle = lowerAngle;
this.upperAngle = upperAngle;
}
/**
* Constructs new angle filter.
*
* @param lowerAngle minimum angle in range [-3*pi/2, pi/2)
* @param upperAngle maximum angle in range [-pi/2, 3*pi/2)
* @return newly constructed angle filter
*/
public static AngleFilter newInstance(double lowerAngle, double upperAngle) {
if (lowerAngle < -Math.PI/2) {
lowerAngle += Math.PI;
}
if (upperAngle >= Math.PI/2) {
upperAngle -= Math.PI;
}
if (lowerAngle <= upperAngle) {
return new AndFilter(lowerAngle, upperAngle);
} else {
return new OrFilter(lowerAngle, upperAngle);
}
}
public double getLowerAngle() {
return lowerAngle;
}
public double getUpperAngle() {
return upperAngle;
}
public abstract boolean matches(Neighbor neighbor);
public static final class AndFilter extends AngleFilter {
private AndFilter(double lowerAngle, double upperAngle) {
super(lowerAngle, upperAngle);
}
@Override
public boolean matches(Neighbor neighbor) {
return getLowerAngle() <= neighbor.getAngle() && neighbor.getAngle() < getUpperAngle();
}
}
public static final class OrFilter extends AngleFilter {
private OrFilter(double lowerAngle, double upperAngle) {
super(lowerAngle, upperAngle);
}
@Override
public boolean matches(Neighbor neighbor) {
return getLowerAngle() <= neighbor.getAngle() || neighbor.getAngle() < getUpperAngle();
}
}
}
private static final double DISTANCE_STEP = 16.0;
public static final double DEFAULT_ANGLE_HIST_RES = Math.toRadians(0.5);
public static final double DEFAULT_ANGLE_HIST_SMOOTH_LEN = 0.25 * Math.PI;
public static final double DEFAULT_ANGLE_HIST_SMOOTH_STDDEV = 0.0625 * Math.PI;
public static final double DEFAULT_SPACE_HIST_RES = 0.5;
public static final double DEFAULT_SPACE_HIST_SMOOTH_LEN = 2.5;
public static final double DEFAULT_SPACE_HIST_SMOOTH_STDDEV = 0.5;
public static final double DEFAULT_MAX_VERT_COMP_DIST = 0.67;
public static final double DEFAULT_MIN_LINE_SIZE_SCALE = 0.9;
public static final double DEFAULT_MAX_LINE_SIZE_SCALE = 2.5;
public static final double DEFAULT_MIN_HORIZONTAL_DIST = -0.5;
public static final double DEFAULT_MIN_VERTICAL_DIST = 0.0;
public static final double DEFAULT_MAX_VERTICAL_DIST = 1.2;
public static final double DEFAULT_COMP_DIST_CHAR = 3.5;
public static final double DEFAULT_WORD_DIST = 0.2;
public static final double DEFAULT_MIN_HORIZONTAL_MERGE_DIST = -3.0;
public static final double DEFAULT_MAX_VERTICAL_MERGE_DIST = 0.5;
public static final double DEFAULT_ANGLE_TOLERANCE = Math.PI / 6;
public static final int DEFAULT_NEIGHBOR_COUNT = 5;
/**
* Angle histogram resolution in radians per bin.
*/
private double angleHistogramResolution = DEFAULT_ANGLE_HIST_RES;
/**
* Angle histogram smoothing window length in radians.
* Length of angle histogram is equal to pi.
*/
private double angleHistogramSmoothingWindowLength = DEFAULT_ANGLE_HIST_SMOOTH_LEN;
/**
* Angle histogram gaussian smoothing window standard deviation in radians.
*/
private double angleHistogramSmoothingWindowStdDeviation = DEFAULT_ANGLE_HIST_SMOOTH_STDDEV;
/**
* Spacing histogram resolution per bin.
*/
private double spacingHistogramResolution = DEFAULT_SPACE_HIST_RES;
/**
* Spacing histogram smoothing window length.
*/
private double spacingHistogramSmoothingWindowLength = DEFAULT_SPACE_HIST_SMOOTH_LEN;
/**
* Spacing histogram gaussian smoothing window standard deviation.
*/
private double spacingHistogramSmoothingWindowStdDeviation = DEFAULT_SPACE_HIST_SMOOTH_STDDEV;
/**
* Maximum vertical component distance multiplier used during line
* determination.
*
* Maximum vertical distance between components (characters) that belong
* to the same line is equal to the product of this value and estimated
* between-line spacing.
*/
private double maxVerticalComponentDistanceMultiplier = DEFAULT_MAX_VERT_COMP_DIST;
/**
* Minimum line size scale value.
*
* During zone determination (merging lines into zones) line height is
* taken into account. To achieve this, line size scale is estimated and
* limited to range [minLineSizeScale, maxLineSizeScale].
*/
private double minLineSizeScale = DEFAULT_MIN_LINE_SIZE_SCALE;
/**
* Maximum line size scale value.
*
* See minLineSizeScale for more information.
*/
private double maxLineSizeScale = DEFAULT_MAX_LINE_SIZE_SCALE;
/**
* Minimum horizontal line distance multiplier.
*
* Minimum horizontal distance between lines that belong to the same zone
* is equal to the product of this value and estimated within-line spacing.
*/
private double minHorizontalDistanceMultiplier = DEFAULT_MIN_HORIZONTAL_DIST;
/**
* Minimum vertical line distance multiplier.
*
* Minimum vertical distance between lines that belong to the same zone
* is equal to the product of this value and estimated between-line spacing.
*/
private double minVerticalDistanceMultiplier = DEFAULT_MIN_VERTICAL_DIST;
/**
* Maximum vertical line distance multiplier.
*
* Maximum vertical distance between lines that belong to the same zone
* is equal to the product of this value and estimated between-line spacing.
*/
private double maxVerticalDistanceMultiplier = DEFAULT_MAX_VERTICAL_DIST;
/**
* Component distance character spacing multiplier.
*
* Maximum distance between components that belong to the same line is
* equal to (lineSpacing * componentDistanceLineMultiplier +
* characterSpacing * componentDistanceCharacterMultiplier), where
* lineSpacing and characterSpacing are estimated between-line and
* within-line spacing, respectively.
*/
private double componentDistanceCharacterMultiplier = DEFAULT_COMP_DIST_CHAR;
/**
* Word distance multiplier.
*
* Maximum distance between components that belong to the same word is
* equal to the product of this value and estimated within-line spacing.
*/
private double wordDistanceMultiplier = DEFAULT_WORD_DIST;
/**
* Minimum horizontal line merge distance multiplier.
*
* Minimum horizontal distance between lines that should be merged is equal
* to the product of this value and estimated within-line spacing.
*
* Because split lines do not overlap this value should be negative.
*/
private double minHorizontalMergeDistanceMultiplier = DEFAULT_MIN_HORIZONTAL_MERGE_DIST;
/**
* Maximum vertical line merge distance multiplier.
*
* Maximum vertical distance between lines that should be merged is equal
* to the product of this value and estimated between-line spacing.
*/
private double maxVerticalMergeDistanceMultiplier = DEFAULT_MAX_VERTICAL_MERGE_DIST;
/**
* Angle tolerance for comparisons of angles between components and angles
* between lines.
*/
private double angleTolerance = DEFAULT_ANGLE_TOLERANCE;
/**
* Number of nearest-neighbors found per component.
*/
private int neighborCount = DEFAULT_NEIGHBOR_COUNT;
public void setSpacingHistogramResolution(double value) {
spacingHistogramResolution = value;
}
public void setSpacingHistogramSmoothingWindowLength(double value) {
spacingHistogramSmoothingWindowLength = value;
}
public void setSpacingHistogramSmoothingWindowStdDeviation(double value) {
spacingHistogramSmoothingWindowStdDeviation = value;
}
public void setMaxLineSizeScale(double value) {
maxLineSizeScale = value;
}
public void setMaxVerticalDistanceMultiplier(double value) {
maxVerticalDistanceMultiplier = value;
}
public void setMinHorizontalDistanceMultiplier(double value) {
minHorizontalDistanceMultiplier = value;
}
public void setComponentDistanceCharacterMultiplier(double value) {
componentDistanceCharacterMultiplier = value;
}
public void setWordDistanceMultiplier(double value) {
wordDistanceMultiplier = value;
}
public void setMaxVerticalMergeDistanceMultiplier(double value) {
maxVerticalMergeDistanceMultiplier = value;
}
public void setAngleTolerance(double value) {
angleTolerance = value;
}
}
|
package edu.kit.iks.Cryptographics.Caesar;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import edu.kit.iks.Cryptographics.Caesar.Experiment.CryptoModel;
/**
* JUnit testcase class for testing the functionality of the model in the visualization of Caesar.
*
* @author Wasilij Beskorovajnov.
*
*/
public class CryptoModelTest {
// Model to test.
private CryptoModel modelTT;
private final String MESSAGE_HEADER = "[JUnit] Testing the functionality of ";
@Before
public void setUp() throws Exception {
this.modelTT = CryptoModel.getInstance();
}
@Test
public void testEnc() {
String alphabet = "!!!ABcdEFghIJKlmNOPqrSTUvwXYZ!!!";
String expected = "!!!FGhiJKlmNOPqrSTUvwXYZabCDE!!!";
String actual = this.modelTT.enc(5, alphabet);
assertEquals(MESSAGE_HEADER + "enc(String)\n", expected, actual);
}
@Test
public void testDec() {
String cipher = "!!!KLmnOPqrSTUvwXYZabCDEfgHIJ!!!";
String expected = "!!!ABcdEFghIJKlmNOPqrSTUvwXYZ!!!";
String actual = this.modelTT.dec(10, cipher);
assertEquals(MESSAGE_HEADER + "dec(String)\n", expected, actual);
}
@Test
public void testIsKeyValid() {
int[] validKeys = { 1, 13, 26 };
int[] invalidKeys = { -25, 0, 27 };
for (int validKey : validKeys) {
assertTrue(MESSAGE_HEADER + "isKeyValid()\n",
this.modelTT.isKeyValid(validKey));
}
for (int invalidKey : invalidKeys) {
assertFalse(MESSAGE_HEADER + "isKeyValid()\n",
this.modelTT.isKeyValid(invalidKey));
}
}
@Test
public void testIsInputValid() {
String[] validInputArr = { "A", "ABCD", "ABCDFHGRT" };
String[] invalidInputArr = { "", "ABCDHFGRTZ", "ABDGFHRTEZSHD" };
for (String validInput : validInputArr) {
assertTrue(MESSAGE_HEADER + "isInputValid()\n",
this.modelTT.isInputValid(validInput));
}
for (String invalidInput : invalidInputArr) {
assertFalse(MESSAGE_HEADER + "isInputValid()\n",
this.modelTT.isInputValid(invalidInput));
}
}
@Test
public void testGenRandomGrats() {
for (int i = 0; i < 50; i++) {
assertNotNull(this.modelTT.genRandomGrats());
}
}
@Test
public void testGenRandomBlamings() {
for (int i = 0; i < 50; i++) {
assertNotNull(this.modelTT.genRandomBlamings());
}
}
@Test
public void testGenRandomPlainSequence() {
for (int i = 0; i < 50; i++) {
assertNotNull(this.modelTT.genRandomPlainSequence());
}
}
@Test
public void testGenRandomCipher() {
for (int i = 0; i < 50; i++) {
assertNotNull(this.modelTT.genRandomCipher(i));
}
}
@Test
public void testGenRandomText() {
assertNotNull(this.modelTT.genRandomText());
}
@Test
public void testGenerateKey() {
int key = 0;
for (int i = 0; i < 99; i++) {
key = this.modelTT.generateKey();
if (key > 0 && key < 27) {
assertTrue(true);
} else {
assertTrue(false);
}
}
}
}
|
package ru.job4j.carstorage.servlets;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import ru.job4j.carstorage.Image;
import ru.job4j.controller.DBService;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class AddingImageServlet extends HttpServlet {
private static DBService service = DBService.newInstance();
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletFileUpload fileUpload = new ServletFileUpload(new DiskFileItemFactory());
// List<Image> images = new ArrayList<>();
try {
List<FileItem> fileItemList = fileUpload.parseRequest(req);
int count = 0;
for (FileItem fileItem: fileItemList) {
InputStream in = fileItem.getInputStream();
byte[] buffer = new byte[in.available()];
in.read(buffer);
File target = new File("C:/image.jpg" + count++);
OutputStream out = new FileOutputStream(target);
out.write(buffer);
in.close();
out.close();
}
// images.add(new Image(fileItem.get()));
// service.addImagesToCar(1, images);
} catch (FileUploadException e) {
e.printStackTrace();
}
resp.sendRedirect(String.format("%s/carstorage/addCar.html", req.getContextPath()));
}
}
|
package com.sapienter.jbilling.server.payment.tasks;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.net.URL;
import java.net.URLConnection;
import java.util.Calendar;
import org.apache.log4j.Logger;
import com.sapienter.jbilling.server.entity.PaymentAuthorizationDTO;
import com.sapienter.jbilling.server.payment.PaymentAuthorizationBL;
import com.sapienter.jbilling.server.payment.PaymentDTOEx;
import com.sapienter.jbilling.server.pluggableTask.PaymentTask;
import com.sapienter.jbilling.server.pluggableTask.PaymentTaskWithTimeout;
import com.sapienter.jbilling.server.pluggableTask.TaskException;
import com.sapienter.jbilling.server.pluggableTask.admin.PluggableTaskException;
import com.sapienter.jbilling.server.user.ContactBL;
import com.sapienter.jbilling.server.util.Constants;
public class PaymentBeanstreamTask extends PaymentTaskWithTimeout implements
PaymentTask {
// Required parameters
private static final String PARAMATER_MERCHANT_ID = "merchant_id";
private static final String PARAMATER_USERNAME = "username";
private static final String PARAMATER_PASSWORD = "password";
private static final String PARAMATER_TIMEOUT = "timeout";
// Optional parameters
private static final String PARAMATER_CAV_ENABLED = "cav_enabled";
private static final String PARAMATER_CAV_PASSCODE = "cav_passcode";
private static final String PARAMATER_CAV_VERSION = "cav_version";
private static final String PARAMATER_VBV_ENABLED = "vbv_enabled";
private static final String PARAMATER_SC_ENABLED = "sc_enabled";
private static final String BeanstreamURL = "https:
private static final Logger LOG = Logger
.getLogger(PaymentBeanstreamTask.class);
public boolean process(PaymentDTOEx paymentInfo)
throws PluggableTaskException {
try {
if (paymentInfo.getCreditCard() == null) {
String error = "Credit card not present in payment";
LOG.error(error);
throw new TaskException(error);
}
if (paymentInfo.getAch() != null) {
String error = "ACH not supported by Beanstream processing API";
LOG.error(error);
throw new TaskException(error);
}
String POSTString = this.getPOSTString(paymentInfo, "P", null);
String HTTPResponse = doPost(POSTString, paymentInfo);
PaymentAuthorizationDTO paymentDTO = new BeanstreamResponseDTO()
.parseResponse(HTTPResponse);
if (paymentDTO.getCode1().equals("1")) {
paymentInfo.setResultId(Constants.RESULT_OK);
paymentInfo.setAuthorization(paymentDTO);
PaymentAuthorizationBL bl = new PaymentAuthorizationBL();
bl.create(paymentDTO, paymentInfo.getId());
return false;
} else {
paymentInfo.setResultId(Constants.RESULT_FAIL);
paymentInfo.setAuthorization(paymentDTO);
PaymentAuthorizationBL bl = new PaymentAuthorizationBL();
bl.create(paymentDTO, paymentInfo.getId());
return false;
}
} catch (Exception e) {
LOG.error(e);
paymentInfo.setResultId(Constants.RESULT_UNAVAILABLE);
return true;
}
}
public boolean preAuth(PaymentDTOEx paymentInfo)
throws PluggableTaskException {
try {
String POSTString = this.getPOSTString(paymentInfo, "PA", null);
String HTTPResponse = doPost(POSTString, paymentInfo);
PaymentAuthorizationDTO paymentDTO = new BeanstreamResponseDTO()
.parseResponse(HTTPResponse);
if (paymentDTO.getCode1().equals("1")) {
paymentInfo.setResultId(Constants.RESULT_OK);
paymentInfo.setAuthorization(paymentDTO);
PaymentAuthorizationBL bl = new PaymentAuthorizationBL();
bl.create(paymentDTO, paymentInfo.getId());
return false;
} else {
paymentInfo.setResultId(Constants.RESULT_FAIL);
paymentInfo.setAuthorization(paymentDTO);
PaymentAuthorizationBL bl = new PaymentAuthorizationBL();
bl.create(paymentDTO, paymentInfo.getId());
return false;
}
} catch (Exception e) {
paymentInfo.setResultId(Constants.RESULT_UNAVAILABLE);
return true;
}
}
public boolean confirmPreAuth(PaymentAuthorizationDTO paymentDTO,
PaymentDTOEx paymentInfo) throws PluggableTaskException {
try {
String POSTString = this.getPOSTString(paymentInfo, "PAC",
paymentDTO.getTransactionId());
String HTTPResponse = doPost(POSTString, paymentInfo);
PaymentAuthorizationDTO newPaymentDTO = new BeanstreamResponseDTO()
.parseResponse(HTTPResponse);
if (newPaymentDTO.getCode1().equals("1")) {
paymentInfo.setResultId(Constants.RESULT_OK);
paymentInfo.setAuthorization(newPaymentDTO);
PaymentAuthorizationBL bl = new PaymentAuthorizationBL();
bl.create(newPaymentDTO, paymentInfo.getId());
return false;
} else {
paymentInfo.setResultId(Constants.RESULT_FAIL);
paymentInfo.setAuthorization(newPaymentDTO);
PaymentAuthorizationBL bl = new PaymentAuthorizationBL();
bl.create(newPaymentDTO, paymentInfo.getId());
return false;
}
} catch (Exception e) {
paymentInfo.setResultId(Constants.RESULT_UNAVAILABLE);
return true;
}
}
public void failure(Integer userId, Integer retry) {
}
/**
* Returns a string suitable for passing to Beanstream processing API
* (taking into account optional configuration parameters)
*
* @param paymentInfo
* @return String
* @throws PluggableTaskException
*/
private String getPOSTString(PaymentDTOEx paymentInfo, String paymentType,
String transactionId) throws PluggableTaskException {
String merchantId = ensureGetParameter(PARAMATER_MERCHANT_ID);
String username = ensureGetParameter(PARAMATER_USERNAME);
String password = ensureGetParameter(PARAMATER_PASSWORD);
String cav_enabled = getOptionalParameter(PARAMATER_CAV_ENABLED, "0");
String cav_passcode = getOptionalParameter(PARAMATER_CAV_PASSCODE, null);
String cav_version = getOptionalParameter(PARAMATER_CAV_VERSION, null);
String vbv_enabled = getOptionalParameter(PARAMATER_VBV_ENABLED, null);
String sc_enabled = getOptionalParameter(PARAMATER_SC_ENABLED, null);
if (merchantId.length() != 9) {
String error = "Invalid merchant_id for Beanstream payment processor";
LOG.error(error);
throw new PluggableTaskException(error);
}
try {
ContactBL contact = new ContactBL();
contact.set(paymentInfo.getUserId());
Calendar cal = Calendar.getInstance();
cal.setTime(paymentInfo.getCreditCard().getExpiry());
StringBuffer postVars = new StringBuffer("requestType=BACKEND&");
postVars.append("merchant_id=" + merchantId + "&");
postVars.append("username=" + username + "&");
postVars.append("password=" + password + "&");
postVars.append("trnCardOwner="
+ paymentInfo.getCreditCard().getName() + "&");
postVars.append("trnCardNumber="
+ paymentInfo.getCreditCard().getNumber() + "&");
postVars.append("trnExpMonth="
+ ((cal.get(Calendar.MONTH) < 10) ? ("0" + cal
.get(Calendar.MONTH)) : cal.get(Calendar.MONTH))
+ "&");
postVars.append("trnExpYear="
+ (Integer.toString(cal.get(Calendar.YEAR)))
.substring(2, 4) + "&");
postVars.append("trnOrderNumber=" + paymentInfo.getId() + "&");
postVars.append("trnAmount=" + paymentInfo.getAmount() + "&");
postVars.append("trnType=" + paymentType + "&");
postVars.append("trnId=" + getString(transactionId));
postVars.append("ordName="
+ (contact.getEntity().getFirstName() + " " + contact
.getEntity().getLastName()) + "&");
postVars.append("ordEmailAddress="
+ getString(contact.getEntity().getEmail()) + "&");
postVars.append("ordPhoneNumber="
+ getString(contact.getEntity().getPhoneNumber()) + "&");
postVars.append("ordAddress1="
+ getString(contact.getEntity().getAddress1()) + "&");
postVars.append("ordAddress2="
+ getString(contact.getEntity().getAddress2()) + "&");
postVars.append("ordCity="
+ getString(contact.getEntity().getCity()) + "&");
postVars.append("ordProvince="
+ getString(contact.getEntity().getStateProvince()) + "&");
postVars.append("ordPostalCode="
+ getString(contact.getEntity().getPostalCode()) + "&");
postVars.append("ordCountry="
+ getString(contact.getEntity().getCountryCode()) + "&");
postVars.append("cavEnabled=" + cav_enabled + "&");
postVars.append((cav_passcode != null) ? ("cavPassCode="
+ cav_passcode + "&") : "");
postVars.append("cavServiceVersion="
+ ((cav_version != null) ? cav_version : 0) + "&");
postVars.append("vbvEnabled="
+ ((vbv_enabled != null && vbv_enabled.equals("true")) ? 1
: 0) + "&");
postVars.append("scEnabled="
+ ((sc_enabled != null && sc_enabled.equals("true")) ? 1
: 0));
LOG.debug("HTTP POST vars going to beanstream: " + postVars);
return postVars.toString();
} catch (Exception e) {
throw new PluggableTaskException(e);
}
}
/**
* Performs an HTTPS POST request to the Beanstream payment processor
*
* @param postVars
* String The HTTP POST formatted as a GET string
* @return String
* @throws PluggableTaskException
*/
private String doPost(String postVars, PaymentDTOEx paymentInfo)
throws PluggableTaskException {
int ch;
StringBuffer responseText = new StringBuffer();
try {
// Set the location of the Beanstream payment gateway
URL url = new URL(BeanstreamURL);
// Open the connection
URLConnection conn = url.openConnection();
// Set the connection timeout
conn.setConnectTimeout(getTimeoutSeconds() * 1000);
// Set the DoOutput flag to true because we intend
// to use the URL connection for output
conn.setDoOutput(true);
// Send the transaction via HTTPS POST
OutputStream ostream = conn.getOutputStream();
ostream.write(postVars.getBytes());
ostream.close();
// Get the response from Beanstream
InputStream istream = conn.getInputStream();
while ((ch = istream.read()) != -1)
responseText.append((char) ch);
istream.close();
LOG.debug("Beanstream responseText: " + responseText);
return responseText.toString();
} catch (Exception e) {
LOG.error(e);
throw new PluggableTaskException(e);
}
}
class BeanstreamResponseDTO {
private String trnApproved;
private String trnId;
private String messageId;
private String messageText;
private String trnOrderNumber;
private String authCode;
private String hCode;
private String errorType;
private String errorFields;
private String responseType;
private String trnAmount;
private String trnDate;
private String avsProcessed;
private String avsId;
private String avsResult;
private String avsAddrMatch;
private String avsPostalMatch;
private String avsMessage;
private String rspCodeCav;
private String rspCodeAdd2;
private String rspCodeCredit1;
private String rspCodeCredit2;
private String rspCodeCredit3;
private String rspCodeCredit4;
private String rspCodeAddr1;
private String rspCodeAddr2;
private String rspCodeAddr3;
private String rspCodeAddr4;
private String rspCodeDob;
private String rspCustomerDec;
private String trnType;
private String paymentMethod;
private String ref1;
private String ref2;
private String ref3;
private String ref4;
private String ref5;
public BeanstreamResponseDTO() {
}
public PaymentAuthorizationDTO parseResponse(String responseText)
throws PluggableTaskException {
try {
BeanstreamResponseDTO responseDTO = new BeanstreamResponseDTO();
String[] reply = responseText.split("&");
for (int i = 0; i < reply.length; i++) {
String[] pair = reply[i].split("=");
Field field = responseDTO.getClass().getDeclaredField(
pair[0]);
field.set(responseDTO, (pair.length == 1) ? null : pair[1]);
}
PaymentAuthorizationDTO paymentDTO = new PaymentAuthorizationDTO();
paymentDTO.setTransactionId(responseDTO.trnId);
paymentDTO.setProcessor("Beanstream");
paymentDTO.setApprovalCode(responseDTO.authCode);
paymentDTO.setAVS(responseDTO.avsResult);
paymentDTO.setMD5(responseDTO.hCode);
// paymentDTO.setCardCode( ??? );
paymentDTO.setCreateDate(Calendar.getInstance().getTime());
paymentDTO.setResponseMessage(java.net.URLDecoder.decode(
responseDTO.messageText, "UTF-8"));
paymentDTO.setCode1(responseDTO.trnApproved);
return paymentDTO;
} catch (Exception e) {
throw new PluggableTaskException(e);
}
}
}
}
|
package com.intellij.codeInsight.template.impl;
import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.IconLoader;
import com.intellij.ui.BooleanTableCellRenderer;
import com.intellij.ui.ColoredTreeCellRenderer;
import com.intellij.ui.ScrollPaneFactory;
import com.intellij.ui.SimpleTextAttributes;
import com.intellij.ui.dualView.TreeTableView;
import com.intellij.util.Alarm;
import com.intellij.util.ui.ColumnInfo;
import com.intellij.util.ui.treetable.ListTreeTableModelOnColumns;
import com.intellij.util.ui.treetable.TreeTable;
import com.intellij.util.ui.treetable.TreeTableModel;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.table.AbstractTableModel;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.List;
class TemplateListPanel extends JPanel {
private TreeTable myTreeTable;
private JButton myCopyButton;
private JButton myEditButton;
private JButton myRemoveButton;
private Editor myEditor;
private SortedMap<TemplateKey,TemplateImpl> myTemplates = new TreeMap<TemplateKey, TemplateImpl>();
private JComboBox myExpandByCombo;
private boolean isModified = false;
private static final String SPACE = CodeInsightBundle.message("template.shortcut.space");
private static final String TAB = CodeInsightBundle.message("template.shortcut.tab");
private static final String ENTER = CodeInsightBundle.message("template.shortcut.enter");
private static final String[] myColumnNames = {
CodeInsightBundle.message("templates.dialog.table.column.abbreviation"),
CodeInsightBundle.message("templates.dialog.table.column.description"),
CodeInsightBundle.message("templates.dialog.table.column.active")};
private DefaultMutableTreeNode myTreeRoot = new DefaultMutableTreeNode();
private DefaultTreeModel myTreeTableModel;
private Alarm myAlarm = new Alarm();
private boolean myUpdateNeeded = false;
private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.template.impl.TemplateListPanel");
private static final Icon TEMPLATE_ICON = IconLoader.getIcon("/general/template.png");
private static final Icon TEMPLATE_GROUP_ICON = IconLoader.getIcon("/general/templateGroup.png");
public TemplateListPanel() {
setLayout(new BorderLayout());
fillPanel(this);
}
public void dispose() {
EditorFactory.getInstance().releaseEditor(myEditor);
}
public void reset() {
TemplateSettings templateSettings = TemplateSettings.getInstance();
initTemplates(templateSettings.getTemplates(), templateSettings.getLastSelectedTemplateKey());
if (templateSettings.getDefaultShortcutChar() == TemplateSettings.TAB_CHAR) {
myExpandByCombo.setSelectedItem(TAB);
}
else if (templateSettings.getDefaultShortcutChar() == TemplateSettings.ENTER_CHAR) {
myExpandByCombo.setSelectedItem(ENTER);
}
else {
myExpandByCombo.setSelectedItem(SPACE);
}
isModified = false;
myUpdateNeeded = true;
}
public void apply() {
TemplateSettings templateSettings = TemplateSettings.getInstance();
templateSettings.setTemplates(getTemplates());
templateSettings.setDefaultShortcutChar(getDefaultShortcutChar());
}
public boolean isModified() {
TemplateSettings templateSettings = TemplateSettings.getInstance();
if (templateSettings.getDefaultShortcutChar() != getDefaultShortcutChar()) {
return true;
}
return isModified;
}
private char getDefaultShortcutChar() {
Object selectedItem = myExpandByCombo.getSelectedItem();
if (TAB.equals(selectedItem)) {
return TemplateSettings.TAB_CHAR;
}
else if (ENTER.equals(selectedItem)) {
return TemplateSettings.ENTER_CHAR;
}
else {
return TemplateSettings.SPACE_CHAR;
}
}
private TemplateImpl[] getTemplates() {
TemplateImpl[] newTemplates = new TemplateImpl[myTemplates.size()];
Iterator<TemplateKey> iterator = myTemplates.keySet().iterator();
int i = 0;
while (iterator.hasNext()) {
newTemplates[i] = myTemplates.get(iterator.next());
i++;
}
return newTemplates;
}
private void fillPanel(JPanel optionsPanel) {
JPanel tablePanel = new JPanel();
tablePanel.setBorder(BorderFactory.createLineBorder(Color.gray));
tablePanel.setLayout(new BorderLayout());
tablePanel.add(createTable(), BorderLayout.CENTER);
JPanel tableButtonsPanel = new JPanel();
tableButtonsPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
tableButtonsPanel.setLayout(new GridBagLayout());
GridBagConstraints gbConstraints = new GridBagConstraints();
gbConstraints.gridwidth = GridBagConstraints.REMAINDER;
gbConstraints.fill = GridBagConstraints.HORIZONTAL;
gbConstraints.insets = new Insets(0, 0, 4, 0);
final JButton addButton = new JButton(CodeInsightBundle.message("templates.dialog.table.action.add"));
addButton.setMargin(new Insets(2, 4, 2, 4));
tableButtonsPanel.add(addButton, gbConstraints);
myCopyButton = new JButton(CodeInsightBundle.message("templates.dialog.table.action.copy"));
myCopyButton.setEnabled(false);
myCopyButton.setMargin(new Insets(2, 4, 2, 4));
tableButtonsPanel.add(myCopyButton, gbConstraints);
myEditButton = new JButton(CodeInsightBundle.message("templates.dialog.table.action.edit"));
myEditButton.setEnabled(false);
myEditButton.setMargin(new Insets(2, 4, 2, 4));
tableButtonsPanel.add(myEditButton, gbConstraints);
myRemoveButton = new JButton(CodeInsightBundle.message("templates.dialog.table.action.remove"));
myRemoveButton.setEnabled(false);
myRemoveButton.setMargin(new Insets(2, 4, 2, 4));
tableButtonsPanel.add(myRemoveButton, gbConstraints);
gbConstraints.weighty = 1;
tableButtonsPanel.add(new JPanel(), gbConstraints);
tablePanel.add(tableButtonsPanel, BorderLayout.EAST);
optionsPanel.add(tablePanel, BorderLayout.CENTER);
JPanel textPanel = new JPanel(new BorderLayout());
textPanel.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));
myEditor = TemplateEditorUtil.createEditor(true, "");
textPanel.add(myEditor.getComponent(), BorderLayout.CENTER);
textPanel.add(createExpandByPanel(), BorderLayout.SOUTH);
textPanel.setPreferredSize(new Dimension(100, myEditor.getLineHeight() * 12));
optionsPanel.add(textPanel, BorderLayout.SOUTH);
addButton.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent event) {
addRow();
}
}
);
myCopyButton.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent event) {
copyRow();
}
}
);
myEditButton.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent event) {
edit();
}
}
);
myRemoveButton.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent event) {
removeRow();
}
}
);
}
private JPanel createExpandByPanel() {
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbConstraints = new GridBagConstraints();
gbConstraints.weighty = 0;
gbConstraints.insets = new Insets(4, 0, 0, 0);
gbConstraints.weightx = 0;
gbConstraints.gridy = 0;
// panel.add(createLabel("By default expand with "), gbConstraints);
panel.add(new JLabel(CodeInsightBundle.message("templates.dialog.shortcut.chooser.label")), gbConstraints);
gbConstraints.gridx = 1;
myExpandByCombo = new JComboBox();
myExpandByCombo.addItem(SPACE);
myExpandByCombo.addItem(TAB);
myExpandByCombo.addItem(ENTER);
panel.add(myExpandByCombo, gbConstraints);
gbConstraints.gridx = 2;
gbConstraints.weightx = 1;
panel.add(new JPanel(), gbConstraints);
return panel;
}
private TemplateKey getTemplateKey(int row) {
JTree tree = myTreeTable.getTree();
TreePath path = tree.getPathForRow(row);
if (path != null) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent();
if (node.getUserObject() instanceof TemplateImpl) {
return new TemplateKey((TemplateImpl)node.getUserObject());
}
}
return null;
}
private void edit() {
int selected = myTreeTable.getSelectedRow();
if (selected < 0) return;
TemplateKey templateKey = getTemplateKey(selected);
if (templateKey == null) return;
TemplateImpl template = myTemplates.get(templateKey);
EditTemplateDialog dialog = new EditTemplateDialog(this, CodeInsightBundle.message("dialog.edit.live.template.title"), template, getTemplates(),
(String)myExpandByCombo.getSelectedItem());
dialog.show();
if (!dialog.isOK()) return;
myTemplates.remove(new TemplateKey(template));
dialog.apply();
myTemplates.put(new TemplateKey(template), template);
AbstractTableModel model = (AbstractTableModel)myTreeTable.getModel();
model.fireTableRowsUpdated(selected, selected);
myTreeTable.setRowSelectionInterval(selected, selected);
updateTemplateTextArea();
isModified = true;
}
private void addRow() {
TemplateImpl template = new TemplateImpl("", "", TemplateSettings.USER_GROUP_NAME);
EditTemplateDialog dialog = new EditTemplateDialog(this, CodeInsightBundle.message("dialog.edit.live.template.title"), template, getTemplates(),
(String)myExpandByCombo.getSelectedItem());
dialog.show();
if (!dialog.isOK()) return;
dialog.apply();
addTemplate(template);
isModified = true;
}
private void copyRow() {
int selected = myTreeTable.getSelectedRow();
if (selected < 0) return;
TemplateKey templateKey = getTemplateKey(selected);
LOG.assertTrue(templateKey != null);
TemplateImpl template = (myTemplates.get(templateKey)).copy();
EditTemplateDialog dialog = new EditTemplateDialog(this, CodeInsightBundle.message("dialog.copy.live.template.title"), template, getTemplates(),
(String)myExpandByCombo.getSelectedItem());
dialog.show();
if (!dialog.isOK()) return;
dialog.apply();
addTemplate(template);
isModified = true;
}
private void removeRow() {
int selected = myTreeTable.getSelectedRow();
if (selected < 0) return;
TemplateKey templateKey = getTemplateKey(selected);
if (templateKey == null) return;
int result = Messages.showOkCancelDialog(this, CodeInsightBundle.message("template.delete.confirmation.text"),
CodeInsightBundle.message("template.delete.confirmation.title"),
Messages.getQuestionIcon());
if (result != DialogWrapper.OK_EXIT_CODE) return;
removeTemplateAt(selected);
isModified = true;
}
private JScrollPane createTable() {
ColumnInfo[] columnInfos = {new MyColumnInfo(myColumnNames[0]) {
public Class getColumnClass() {
return TreeTableModel.class;
}
public boolean isCellEditable(Object o) {
return true;
}
}, new MyColumnInfo(myColumnNames[1]), new ActivationStateColumnInfo(myColumnNames[2])};
myTreeRoot = new DefaultMutableTreeNode();
myTreeTableModel = new ListTreeTableModelOnColumns(myTreeRoot, columnInfos);
myTreeTable = new MyTable((ListTreeTableModelOnColumns)myTreeTableModel);
myTreeTable.setRootVisible(false);
myTreeTable.setDefaultRenderer(Boolean.class, new BooleanTableCellRenderer());
myTreeTable.getTree().setShowsRootHandles(true);
myTreeTable.getTableHeader().setReorderingAllowed(false);
myTreeTable.setTreeCellRenderer(new ColoredTreeCellRenderer () {
public void customizeCellRenderer(JTree tree,
Object value,
boolean selected,
boolean expanded,
boolean leaf,
int row,
boolean hasFocus) {
value = ((DefaultMutableTreeNode)value).getUserObject();
setPaintFocusBorder(false);
if (value instanceof TemplateImpl) {
setIcon(TEMPLATE_ICON);
append (((TemplateImpl)value).getKey(), SimpleTextAttributes.REGULAR_ATTRIBUTES);
}
else if (value instanceof String) {
setIcon(TEMPLATE_GROUP_ICON);
append ((String)value, SimpleTextAttributes.REGULAR_ATTRIBUTES);
}
}
});
myTreeTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
myTreeTable.setPreferredScrollableViewportSize(new Dimension(300, myTreeTable.getRowHeight() * 10));
myTreeTable.getColumn(myColumnNames[0]).setPreferredWidth(80);
myTreeTable.getColumn(myColumnNames[1]).setPreferredWidth(260);
myTreeTable.getColumn(myColumnNames[2]).setPreferredWidth(12);
myTreeTable.registerKeyboardAction(
new ActionListener() {
public void actionPerformed(ActionEvent event) {
addRow();
}
},
KeyStroke.getKeyStroke(KeyEvent.VK_INSERT, 0),
JComponent.WHEN_FOCUSED
);
myTreeTable.registerKeyboardAction(
new ActionListener() {
public void actionPerformed(ActionEvent event) {
removeRow();
}
},
KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0),
JComponent.WHEN_FOCUSED
);
myTreeTable.addMouseListener(
new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2 && myTreeTable.columnAtPoint(e.getPoint()) != 2) {
edit();
}
}
}
);
JScrollPane scrollpane = ScrollPaneFactory.createScrollPane(myTreeTable);
if (myTemplates.size() > 0) {
myTreeTable.setRowSelectionInterval(0, 0);
}
scrollpane.setPreferredSize(new Dimension(600, 400));
return scrollpane;
}
private void updateTemplateTextArea() {
if (!myUpdateNeeded) return;
myAlarm.cancelAllRequests();
myAlarm.addRequest(new Runnable() {
public void run() {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
int selected = myTreeTable.getSelectedRow();
if (selected < 0 || selected >= myTemplates.size()) {
myEditor.getDocument().replaceString(0, myEditor.getDocument().getTextLength(), "");
}
else {
TemplateKey templateKey = getTemplateKey(selected);
if (templateKey != null) {
TemplateImpl template = myTemplates.get(templateKey);
String text = template.getString();
myEditor.getDocument().replaceString(0, myEditor.getDocument().getTextLength(), text);
TemplateEditorUtil.setHighlighter(myEditor, template.getTemplateContext());
} else {
myEditor.getDocument().replaceString(0, myEditor.getDocument().getTextLength(), "");
}
}
}
});
}
}, 100);
}
private void addTemplate(TemplateImpl template) {
myTemplates.put(new TemplateKey(template), template);
DefaultMutableTreeNode node = new DefaultMutableTreeNode(template);
if (myTreeRoot.getChildCount() > 0) {
for (DefaultMutableTreeNode child = (DefaultMutableTreeNode)myTreeRoot.getFirstChild();
child != null;
child = (DefaultMutableTreeNode)myTreeRoot.getChildAfter(child)) {
String group = (String)child.getUserObject();
if (group.equals(template.getGroupName())) {
int index = getIndexToInsert (child, template.getKey());
child.insert(node, index);
myTreeTableModel.nodesWereInserted(child, new int[]{index});
setSelectedNode(node);
return;
}
}
}
int index = getIndexToInsert(myTreeRoot, template.getGroupName());
DefaultMutableTreeNode groupNode = new DefaultMutableTreeNode(template.getGroupName());
myTreeRoot.insert(groupNode, index);
myTreeTableModel.nodesWereInserted(myTreeRoot, new int[]{index});
groupNode.add(node);
myTreeTableModel.nodesWereInserted(groupNode, new int[]{0});
setSelectedNode(node);
}
private int getIndexToInsert(DefaultMutableTreeNode parent, String key) {
if (parent.getChildCount() == 0) return 0;
int res = 0;
for (DefaultMutableTreeNode child = (DefaultMutableTreeNode)parent.getFirstChild();
child != null;
child = (DefaultMutableTreeNode)parent.getChildAfter(child)) {
Object o = child.getUserObject();
String key1 = o instanceof TemplateImpl ? ((TemplateImpl)o).getKey() : (String)o;
if (key1.compareTo(key) > 0) return res;
res++;
}
return res;
}
private void setSelectedNode(DefaultMutableTreeNode node) {
JTree tree = myTreeTable.getTree();
TreePath path = new TreePath(node.getPath());
tree.expandPath(path.getParentPath());
int row = tree.getRowForPath(path);
myTreeTable.getSelectionModel().setSelectionInterval(row, row);
myTreeTable.scrollRectToVisible(myTreeTable.getCellRect(row, 0, true));
}
private void removeTemplateAt(int row) {
JTree tree = myTreeTable.getTree();
TreePath path = tree.getPathForRow(row);
DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent();
LOG.assertTrue(node.getUserObject() instanceof TemplateImpl);
TemplateImpl template = (TemplateImpl)node.getUserObject();
myTemplates.remove(new TemplateKey(template));
DefaultMutableTreeNode parent = (DefaultMutableTreeNode)node.getParent();
TreePath treePathToSelect = (parent.getChildAfter(node) != null || parent.getChildCount() == 1 ?
tree.getPathForRow(row + 1) :
tree.getPathForRow(row - 1));
DefaultMutableTreeNode toSelect = treePathToSelect != null ? (DefaultMutableTreeNode)treePathToSelect.getLastPathComponent() : null;
removeNodeFromParent(node);
if (parent.getChildCount() == 0) removeNodeFromParent(parent);
if (toSelect != null) {
setSelectedNode(toSelect);
}
}
private void removeNodeFromParent(DefaultMutableTreeNode node) {
TreeNode parent = node.getParent();
int idx = myTreeTableModel.getIndexOfChild(parent, node);
node.removeFromParent();
myTreeTableModel.nodesWereRemoved(parent, new int[]{idx}, new TreeNode[]{node});
}
private void initTemplates(TemplateImpl[] templates, String lastSelectedKey) {
myTreeRoot.removeAllChildren();
SortedMap<String, List<TemplateImpl>> groups = new TreeMap<String, List<TemplateImpl>>();
for (TemplateImpl template1 : templates) {
TemplateImpl template = template1.copy();
myTemplates.put(new TemplateKey(template), template);
String group = template.getGroupName();
List<TemplateImpl> ts = groups.get(group);
if (ts == null) {
ts = new ArrayList<TemplateImpl>();
groups.put(group, ts);
}
ts.add(template);
}
DefaultMutableTreeNode nodeToSelect = null;
for (Map.Entry<String, List<TemplateImpl>> entry : groups.entrySet()) {
String group = entry.getKey();
List<TemplateImpl> groupTemplates = entry.getValue();
DefaultMutableTreeNode groupNode = new DefaultMutableTreeNode(group);
for (final Object groupTemplate : groupTemplates) {
TemplateImpl template = (TemplateImpl)groupTemplate;
DefaultMutableTreeNode node = new DefaultMutableTreeNode(template);
groupNode.add(node);
if (lastSelectedKey != null && lastSelectedKey.equals(template.getKey())) {
nodeToSelect = node;
}
}
myTreeRoot.add(groupNode);
}
myTreeTableModel.nodeStructureChanged(myTreeRoot);
if (nodeToSelect != null) {
JTree tree = myTreeTable.getTree();
TreePath path = new TreePath(nodeToSelect.getPath());
tree.expandPath(path.getParentPath());
int rowToSelect = tree.getRowForPath(path);
myTreeTable.getSelectionModel().setSelectionInterval(rowToSelect, rowToSelect);
final Rectangle rect = myTreeTable.getCellRect(rowToSelect, 0, true);
ApplicationManager.getApplication().invokeLater(new Runnable() {
public void run() {
myTreeTable.scrollRectToVisible(rect);
}
});
}
}
private class MyTable extends TreeTableView {
public MyTable(ListTreeTableModelOnColumns model) {
super(model);
}
public void valueChanged(ListSelectionEvent event) {
super.valueChanged(event);
boolean enableButtons = false;
int selected = getSelectedRow();
if (selected >= 0 && selected < myTreeTable.getRowCount()) {
TemplateSettings templateSettings = TemplateSettings.getInstance();
TemplateKey templateKey = getTemplateKey(selected);
if (templateKey != null) {
TemplateImpl template = myTemplates.get(templateKey);
if (template != null) {
templateSettings.setLastSelectedTemplateKey(template.getKey());
}
} else {
templateSettings.setLastSelectedTemplateKey(null);
}
DefaultMutableTreeNode node = (DefaultMutableTreeNode)myTreeTable.getTree().getPathForRow(selected).getLastPathComponent();
enableButtons = !(node.getUserObject() instanceof String);
}
updateTemplateTextArea();
if (myCopyButton != null) {
myCopyButton.setEnabled(enableButtons);
myEditButton.setEnabled(enableButtons);
myRemoveButton.setEnabled(enableButtons);
}
}
}
private static class TemplateKey implements Comparable {
private String myKey;
private String myGroupName;
public TemplateKey(TemplateImpl template) {
myKey = template.getKey();
if (myKey == null) {
myKey = "";
}
myGroupName = template.getGroupName();
if (myGroupName == null) {
myGroupName = "";
}
}
public boolean equals(Object obj) {
if (!(obj instanceof TemplateKey)) {
return false;
}
TemplateKey templateKey = (TemplateKey)obj;
return (myGroupName.compareTo(templateKey.myGroupName) == 0) &&
(myKey.compareTo(templateKey.myKey) == 0);
}
public int compareTo(Object obj) {
if (!(obj instanceof TemplateKey)) {
return 1;
}
TemplateKey templateKey = (TemplateKey)obj;
int result = myGroupName.compareTo(templateKey.myGroupName);
return result != 0 ? result : myKey.compareTo(templateKey.myKey);
}
}
class ActivationStateColumnInfo extends ColumnInfo {
public ActivationStateColumnInfo(String name) {
super(name);
}
public boolean isCellEditable(Object o) {
return o != null;
}
public void setValue(Object obj, Object aValue) {
obj = ((DefaultMutableTreeNode)obj).getUserObject();
if (obj instanceof TemplateImpl) {
TemplateImpl template = (TemplateImpl)obj;
boolean state = !((Boolean)aValue).booleanValue();
if (state != template.isDeactivated()) {
template.setDeactivated(!((Boolean)aValue).booleanValue());
isModified = true;
}
}
}
public Class getColumnClass() {
return Boolean.class;
}
public Object valueOf(Object object) {
object = ((DefaultMutableTreeNode)object).getUserObject();
if (object instanceof TemplateImpl) {
return ((TemplateImpl)object).isDeactivated() ? Boolean.FALSE : Boolean.TRUE;
}
else {
return null;
}
}
}
class MyColumnInfo extends ColumnInfo {
public MyColumnInfo(String name) {super(name);}
public Object valueOf(Object object) {
object = ((DefaultMutableTreeNode)object).getUserObject();
if (object instanceof TemplateImpl) {
TemplateImpl template = (TemplateImpl)object;
if (getName().equals(myColumnNames[0])) {
return template.getKey();
}
else if (getName().equals(myColumnNames[1])) {
return template.getDescription();
}
}
else if (object instanceof String) {
if (getName().equals(myColumnNames[0])) {
return object;
}
else {
return null;
}
}
LOG.assertTrue(false);
return null;
}
public Comparator getComparator() {
if (myColumnNames[0].equals(getName())) {
return new Comparator() {
public int compare(Object o, Object o1) {
o = ((DefaultMutableTreeNode)o).getUserObject();
o1 = ((DefaultMutableTreeNode)o1).getUserObject();
if (o instanceof TemplateImpl && o1 instanceof TemplateImpl) {
return ((TemplateImpl)o).getKey().compareTo(((TemplateImpl)o1).getKey());
}
else if (o instanceof String && o1 instanceof String) {
return ((String)o).compareTo(((String)o1));
}
return 0;
}
};
}
return null;
}
}
}
|
package edu.duke.cabig.c3pr.dao;
import java.util.Date;
import java.util.List;
import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.Order;
import edu.duke.cabig.c3pr.domain.HealthcareSite;
import edu.duke.cabig.c3pr.domain.Summary3Report;
import edu.duke.cabig.c3pr.domain.Summary3ReportDiseaseSite;
import gov.nih.nci.cabig.ctms.dao.MutableDomainObjectDao;
// TODO: Auto-generated Javadoc
/**
* The Class Summary3ReportDao.
*/
public class Summary3ReportDao extends GridIdentifiableDao<Summary3Report> implements MutableDomainObjectDao<Summary3Report> {
/** The log. */
Logger log = Logger.getLogger(Summary3Report.class);
/* (non-Javadoc)
* @see edu.duke.cabig.c3pr.dao.C3PRBaseDao#domainClass()
*/
@Override
public Class<Summary3Report> domainClass() {
return Summary3Report.class;
}
/**
* Gets the newly enrolled therapeutic study patients for given icd9 disease site.
*
* @param summary3ReportDiseaseSite the disease site
* @param hcs the hcs
* @param startDate the start date
* @param endDate the end date
*
* @return the newly enrolled therapeutic study patients for given anatomic site
*/
public int getNewlyEnrolledTherapeuticStudySubjectCountForGivenSummary3ReportDiseaseSite(
Summary3ReportDiseaseSite summary3ReportDiseaseSite, HealthcareSite hcs, Date startDate,
Date endDate) {
return getHibernateTemplate().find("from StudySubject ss,StudySubjectStudyVersion ssv where ssv=any elements(ss.studySubjectStudyVersions) and " +
"ss.startDate >= ? and ss.startDate <= ? and " +
"ss.diseaseHistoryInternal.icd9DiseaseSite.summary3ReportDiseaseSite.name = ? and ssv.studySiteStudyVersion.studySite.studyInternal.summary3Reportable = '1' " +
"and ssv.studySiteStudyVersion.studySite.healthcareSite.id in " +
"(select h.id from HealthcareSite h where " +
"h.identifiersAssignedToOrganization.value=? and h.identifiersAssignedToOrganization.primaryIndicator = '1')",
new Object[] {startDate, endDate, summary3ReportDiseaseSite.getName(), hcs.getCtepCode()}).size();
}
/**
* Gets the newly registered patients for given anatomic site.
*
* @param summary3ReportDiseaseSite the disease site
* @param hcs the hcs
* @param startDate the start date
* @param endDate the end date
*
* @return the newly registered patients for given anatomic site
*/
public int getNewlyRegisteredSubjectCountForGivenSummary3ReportDiseaseSite(Summary3ReportDiseaseSite summary3ReportDiseaseSite,
HealthcareSite hcs, Date startDate, Date endDate) {
//commented out because C3PR is not the source of truth for newly registered patients.
/*return getHibernateTemplate().find("from StudySubject ss,StudySubjectStudyVersion ssv where ssv=any elements(ss.studySubjectStudyVersions) and" +
" ss.startDate >= ? and ss.startDate <= ? and " +
"ss.diseaseHistoryInternal.icd9DiseaseSite.name = ? and ssv.studySiteStudyVersion.studySite.healthcareSite.id in " +
"(select h.id from HealthcareSite h where " +
"h.identifiersAssignedToOrganization.value=? and h.identifiersAssignedToOrganization.primaryIndicator = '1'))",
new Object[] {startDate, endDate, summary3ReportDiseaseSite.getName(), hcs.getCtepCode()}).size();*/
return 0;
}
/**
* Gets the newly enrolled therapeutic study patients.
*
* @param hcs the hcs
* @param startDate the start date
* @param endDate the end date
*
* @return the newly enrolled therapeutic study patients
*/
public int getNewlyEnrolledTherapeuticStudySubjectCount(HealthcareSite hcs, Date startDate,
Date endDate) {
return getHibernateTemplate().find("from StudySubject ss, StudySubjectStudyVersion ssv where ssv=any elements(ss.studySubjectStudyVersions)and " +
"ss.startDate >= ? and ss.startDate <= ? and " +
"ssv.studySiteStudyVersion.studySite.studyInternal.summary3Reportable = '1' and ssv.studySiteStudyVersion.studySite.healthcareSite.id in " +
"(select h.id from HealthcareSite h where " +
"h.identifiersAssignedToOrganization.value=? and h.identifiersAssignedToOrganization.primaryIndicator = '1'))",
new Object[] {startDate, endDate, hcs.getCtepCode()}).size();
}
/**
* Gets the newly registered patients.
*
* @param hcs the hcs
* @param startDate the start date
* @param endDate the end date
*
* @return the newly registered patients
*/
public int getNewlyRegisteredSubjectCount(HealthcareSite hcs, Date startDate, Date endDate) {
return getHibernateTemplate().find("from StudySubject ss, StudySubjectStudyVersion ssv where ssv=any elements(ss.studySubjectStudyVersions)and" +
" ss.startDate >= ? and ss.startDate <= ? and " +
"ssv.studySiteStudyVersion.studySite.healthcareSite.id in " +
"(select h.id from HealthcareSite h, Identifier I where " +
"h.identifiersAssignedToOrganization.value=? and h.identifiersAssignedToOrganization.primaryIndicator = '1'))",
new Object[] {startDate, endDate, hcs.getCtepCode()}).size();
}
/* (non-Javadoc)
* @see gov.nih.nci.cabig.ctms.dao.MutableDomainObjectDao#save(gov.nih.nci.cabig.ctms.domain.MutableDomainObject)
*/
public void save(Summary3Report arg0) {
// not required
}
public List<Summary3ReportDiseaseSite> getAllOrderedByName(){
Criteria summary3ReportDiseaseSiteCriteria =getSession().createCriteria(Summary3ReportDiseaseSite.class);
summary3ReportDiseaseSiteCriteria.addOrder(Order.asc("name"));
summary3ReportDiseaseSiteCriteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
return summary3ReportDiseaseSiteCriteria.list();
}
}
|
package io.github.kafka101.newsfeed.consumer;
import kafka.consumer.ConsumerConfig;
import kafka.consumer.KafkaStream;
import kafka.javaapi.consumer.ConsumerConnector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import static kafka.consumer.Consumer.createJavaConsumerConnector;
public class KafkaConsumer {
private static final Logger logger = LoggerFactory.getLogger(KafkaConsumer.class);
private final ConsumerConnector consumerConnector;
private final String topic;
private ExecutorService pool;
private final NewsConsumer consumer;
public KafkaConsumer(String zookeeper, String groupId, NewsConsumer consumer) {
this.consumerConnector = createJavaConsumerConnector(createConsumerConfig(zookeeper, groupId));
this.consumer = consumer;
this.topic = consumer.getTopic();
}
private ConsumerConfig createConsumerConfig(String zookeeper, String groupId) {
Properties props = new Properties();
props.put("zookeeper.connect", zookeeper);
props.put("group.id", groupId);
props.put("offsets.storage", "kafka");
props.put("dual.commit.enabled", "false");
props.put("zookeeper.session.timeout.ms", "400");
props.put("zookeeper.sync.time.ms", "200");
props.put("auto.commit.interval.ms", "1000");
return new ConsumerConfig(props);
}
public void shutdown() {
if (consumerConnector != null) {
consumerConnector.shutdown();
}
try {
shutdownExecutor();
} catch (InterruptedException e) {
logger.error("Interrupted during shutdown, exiting uncleanly {}", e);
}
}
private void shutdownExecutor() throws InterruptedException {
if (pool == null) {
return;
}
pool.shutdown();
if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
List<Runnable> rejected = pool.shutdownNow();
logger.debug("Rejected tasks: {}", rejected.size());
if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
logger.error("Timed out waiting for consumer threads to shut down, exiting uncleanly");
}
}
}
public void run(int numThreads) {
Map<String, Integer> topicCountMap = new HashMap();
topicCountMap.put(topic, new Integer(numThreads));
Map<String, List<KafkaStream<byte[], byte[]>>> consumerMap = consumerConnector.createMessageStreams(
topicCountMap);
List<KafkaStream<byte[], byte[]>> streams = consumerMap.get(topic);
// create fixed size thread pool to launch all the threads
pool = Executors.newFixedThreadPool(numThreads);
// create consumer threads to handle the messages
int threadNumber = 0;
for (final KafkaStream stream : streams) {
pool.submit(new KafkaConsumerThread(stream, threadNumber, consumer));
threadNumber++;
}
}
}
|
// OverlayProperties.java
package imagej.core.plugins.roi;
import imagej.ImageJ;
import imagej.data.DataObject;
import imagej.data.roi.Overlay;
import imagej.display.Display;
import imagej.display.DisplayManager;
import imagej.display.DisplayView;
import imagej.plugin.ImageJPlugin;
import imagej.plugin.Menu;
import imagej.plugin.Parameter;
import imagej.plugin.Plugin;
import imagej.plugin.PreviewPlugin;
import imagej.plugin.ui.WidgetStyle;
import imagej.util.ColorRGB;
import java.util.ArrayList;
import java.util.List;
/**
* A plugin to change the properties (e.g., line color, line width) of the
* selected overlays.
*
* @author Curtis Rueden
* @author Lee Kamentsky
*/
@Plugin(menu = { @Menu(label = "Image", mnemonic = 'i'),
@Menu(label = "Overlay", mnemonic = 'o'),
@Menu(label = "Properties...", mnemonic = 'p') })
public class OverlayProperties implements ImageJPlugin, PreviewPlugin {
@Parameter(label = "Line color", persist = false)
private ColorRGB lineColor;
@Parameter(label = "Line width", persist = false, min = "0.1")
private double lineWidth;
@Parameter(label = "Fill color", persist = false)
private ColorRGB fillColor;
@Parameter(label = "Alpha", description = "The opacity or alpha of the "
+ "interior of the overlay (0=transparent, 255=opaque)", persist = false,
style = WidgetStyle.NUMBER_SCROLL_BAR, min = "0", max = "255")
private int alpha;
public OverlayProperties() {
// set default values to match the first selected overlay
final List<Overlay> selected = getSelectedOverlays();
if (selected.size() > 0) {
final Overlay overlay = selected.get(0);
lineColor = overlay.getLineColor();
lineWidth = overlay.getLineWidth();
fillColor = overlay.getFillColor();
alpha = overlay.getAlpha();
}
}
@Override
public void run() {
// change properties of all selected overlays
final List<Overlay> selected = getSelectedOverlays();
for (final Overlay overlay : selected) {
overlay.setLineColor(lineColor);
overlay.setLineWidth(lineWidth);
overlay.setFillColor(fillColor);
overlay.setAlpha(alpha);
overlay.update();
}
}
@Override
public void preview() {
run();
}
public ColorRGB getLineColor() {
return lineColor;
}
public double getLineWidth() {
return lineWidth;
}
public ColorRGB getFillColor() {
return fillColor;
}
public int getAlpha() {
return alpha;
}
private List<Overlay> getSelectedOverlays() {
final ArrayList<Overlay> result = new ArrayList<Overlay>();
final DisplayManager displayManager = ImageJ.get(DisplayManager.class);
final Display display = displayManager.getActiveDisplay();
for (final DisplayView view : display.getViews()) {
if (!view.isSelected()) continue;
final DataObject dataObject = view.getDataObject();
if (!(dataObject instanceof Overlay)) continue;
final Overlay overlay = (Overlay) dataObject;
result.add(overlay);
}
return result;
}
}
|
package org.eclipse.birt.core.script;
import java.util.Collection;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.core.exception.CoreException;
import org.eclipse.birt.core.i18n.ResourceConstants;
import com.ibm.icu.util.TimeZone;
public class ScriptContext implements IScriptContext
{
private Locale locale = Locale.getDefault( );
private TimeZone timeZone = TimeZone.getDefault( );
private ClassLoader applicationClassLoader;
private ScriptContext parent;
private Object scope;
private Map<String, Object> attributes;
private Map<String, IScriptEngine> engines;
private Map<String, IScriptContext> scriptContexts;
public ScriptContext( )
{
this( null, null, null );
}
private ScriptContext( ScriptContext scriptContext, Object scope,
Map<String, Object> attributes )
{
if ( scriptContext == null )
{
engines = new HashMap<String, IScriptEngine>( );
}
else
{
engines = scriptContext.engines;
}
this.attributes = new HashMap<String, Object>( );
if ( attributes != null )
{
this.attributes.putAll( attributes );
}
parent = scriptContext;
scriptContexts = new HashMap<String, IScriptContext>( );
this.scope = scope;
if ( parent != null )
{
this.locale = parent.locale;
this.timeZone = parent.timeZone;
}
}
public ClassLoader getApplicationClassLoader( )
{
if ( parent != null )
{
return parent.getApplicationClassLoader( );
}
return applicationClassLoader;
}
/**
* the user can only set the application class loader to the top most
* context.
*/
public void setApplicationClassLoader( ClassLoader loader )
{
if ( parent != null )
{
parent.setApplicationClassLoader( loader );
}
else
{
this.applicationClassLoader = loader;
Collection<IScriptEngine> engineSet = engines.values( );
for ( IScriptEngine engine : engineSet )
{
engine.setApplicationClassLoader( loader );
}
}
}
public ScriptContext newContext( Object scope )
{
return newContext( scope, null );
}
public ScriptContext newContext( Object scope,
Map<String, Object> attributes )
{
ScriptContext scriptContext = new ScriptContext( this, scope,
attributes );
return scriptContext;
}
public Map<String, Object> getAttributes( )
{
return attributes;
}
public void setAttributes( Map<String, Object> attributes )
{
if ( attributes != null )
{
for ( Entry<String, Object> attribute : attributes.entrySet( ) )
{
setAttribute( attribute.getKey( ), attribute.getValue( ) );
}
}
}
public void setAttribute( String name, Object value )
{
attributes.put( name, value );
for ( IScriptContext context : scriptContexts.values( ) )
{
context.setAttribute( name, value );
}
}
public void removeAttribute( String name )
{
attributes.remove( name );
for ( IScriptContext context : scriptContexts.values( ) )
{
context.removeAttribute( name );
}
}
public ICompiledScript compile( String language, String fileName,
int lineNo, String script ) throws BirtException
{
assert ( language != null );
IScriptEngine engine = getScriptEngine( language );
return engine.compile( this, fileName, lineNo, script );
}
public Object evaluate( ICompiledScript script ) throws BirtException
{
IScriptEngine engine = getScriptEngine( script.getLanguage( ) );
return engine.evaluate( this, script );
}
public void setLocale( Locale locale )
{
this.locale = locale;
Collection<IScriptEngine> engineSet = engines.values( );
for ( IScriptEngine engine : engineSet )
{
engine.setLocale( locale );
}
}
public Locale getLocale( )
{
return locale;
}
public void setTimeZone( TimeZone timeZone )
{
this.timeZone = timeZone;
Collection<IScriptEngine> engineSet = engines.values( );
for ( IScriptEngine engine : engineSet )
{
engine.setTimeZone( timeZone );
}
}
public TimeZone getTimeZone( )
{
return timeZone;
}
public void close( )
{
// remove all the attribute from the existing context
Collection<IScriptContext> contexts = scriptContexts.values( );
for ( IScriptContext context : contexts )
{
for ( String attrName : attributes.keySet( ) )
{
context.removeAttribute( attrName );
}
}
scriptContexts.clear( );
attributes.clear( );
if ( parent == null )
{
Collection<IScriptEngine> engineSet = engines.values( );
for ( IScriptEngine engine : engineSet )
{
engine.close( );
}
engines.clear( );
}
}
public IScriptEngine getScriptEngine( String scriptName )
throws BirtException
{
if ( scriptName == null )
{
throw new NullPointerException( );
}
if ( engines.containsKey( scriptName ) )
{
return engines.get( scriptName );
}
IScriptEngineFactory factory = ScriptEngineFactoryManager.getInstance( )
.getScriptEngineFactory( scriptName );
if ( factory == null )
{
throw new CoreException(
ResourceConstants.NO_SUCH_SCRIPT_EXTENSION, scriptName );
}
return createEngine( factory );
}
public ScriptContext getParent( )
{
return parent;
}
private IScriptEngine createEngine( IScriptEngineFactory factory )
throws BirtException
{
IScriptEngine scriptEngine = factory.createScriptEngine( );
scriptEngine.setLocale( locale );
scriptEngine.setTimeZone( timeZone );
scriptEngine.setApplicationClassLoader( getApplicationClassLoader( ) );
engines.put( factory.getScriptLanguage( ), scriptEngine );
return scriptEngine;
}
public Object getScopeObject( )
{
return scope;
}
public IScriptContext getScriptContext( String language )
{
return scriptContexts.get( language );
}
public void setScriptContext( String language, IScriptContext scriptContext )
{
scriptContexts.put( language, scriptContext );
}
}
|
package com.github.mizool.core.validation;
import java.util.function.Predicate;
import lombok.experimental.UtilityClass;
import com.github.mizool.core.Streams;
@UtilityClass
public class ConstraintValidators
{
public static <T> boolean isValid(T validationObject, boolean mandatory, Predicate<T> isValidValue)
{
boolean result;
if (validationObject instanceof Iterable)
{
Iterable<T> validationObjects = (Iterable<T>) validationObject;
result = isNotNullAndValid(validationObjects, isValidValue);
}
else
{
result = isNullButOptional(validationObject, mandatory) ||
isNotNullAndValid(validationObject, isValidValue);
}
return result;
}
private static <T> boolean isNullButOptional(T validationObject, boolean mandatory)
{
return validationObject == null && !mandatory;
}
private static <T> boolean isNotNullAndValid(T validationObject, Predicate<T> isValidValue)
{
return validationObject != null && isValidValue.test(validationObject);
}
private static <T> boolean isNotNullAndValid(Iterable<T> validationObjects, Predicate<T> isValidValue)
{
return Streams.sequential(validationObjects)
.allMatch(isValidValue);
}
}
|
package net.mabako.steamgifts.fragments;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.util.Log;
import net.mabako.steamgifts.adapters.GiveawayAdapter;
import net.mabako.steamgifts.adapters.IEndlessAdaptable;
import net.mabako.steamgifts.core.R;
import net.mabako.steamgifts.data.Giveaway;
import net.mabako.steamgifts.fragments.interfaces.IActivityTitle;
import net.mabako.steamgifts.fragments.interfaces.IHasEnterableGiveaways;
import net.mabako.steamgifts.fragments.profile.LoadEnteredGameListTask;
import net.mabako.steamgifts.fragments.profile.ProfileGiveaway;
import net.mabako.steamgifts.fragments.util.GiveawayListFragmentStack;
import net.mabako.steamgifts.persistentdata.SavedGiveaways;
import net.mabako.steamgifts.tasks.EnterLeaveGiveawayTask;
import java.io.Serializable;
import java.util.List;
/**
* Show a list of saved giveaways.
*/
// TODO implements IHasEnterableGiveaways?
public class SavedGiveawaysFragment extends ListFragment<GiveawayAdapter> implements IActivityTitle, IHasEnterableGiveaways {
private static final String TAG = SavedGiveawaysFragment.class.getSimpleName();
private SavedGiveaways savedGiveaways;
private LoadEnteredGameListTask enteredGameListTask;
private EnterLeaveGiveawayTask enterLeaveTask;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
adapter.setFragmentValues(getActivity(), this, savedGiveaways);
GiveawayListFragmentStack.addFragment(this);
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
savedGiveaways = new SavedGiveaways(getContext());
}
@Override
public void onDetach() {
super.onDetach();
if (savedGiveaways != null) {
savedGiveaways.close();
savedGiveaways = null;
}
}
@Override
public void onDestroyView() {
super.onDestroyView();
GiveawayListFragmentStack.removeFragment(this);
}
@Override
public void onDestroy() {
super.onDestroy();
if (enteredGameListTask != null) {
enteredGameListTask.cancel(true);
enteredGameListTask = null;
}
if (enterLeaveTask != null) {
enterLeaveTask.cancel(true);
enterLeaveTask = null;
}
}
@NonNull
@Override
protected GiveawayAdapter createAdapter() {
return new GiveawayAdapter(-1, false, PreferenceManager.getDefaultSharedPreferences(getContext()));
}
@Override
protected AsyncTask<Void, Void, ?> getFetchItemsTask(int page) {
return null;
}
@Override
protected Serializable getType() {
return null;
}
@Override
protected void fetchItems(int page) {
if (page != 1)
return;
super.addItems(savedGiveaways.all(), true);
adapter.reachedTheEnd();
// Load all entered giveaways
if (enteredGameListTask != null)
enteredGameListTask.cancel(true);
enteredGameListTask = new LoadEnteredGameListTask(this, 1);
enteredGameListTask.execute();
}
@Override
public int getTitleResource() {
return R.string.saved_giveaways_title;
}
@Override
public String getExtraTitle() {
return null;
}
public void onRemoveSavedGiveaway(String giveawayId) {
adapter.removeGiveaway(giveawayId);
}
/**
* Callback for {@link #enteredGameListTask}
* <p>Note: do NOT call this from within this class.</p>
*/
@Override
public void addItems(List<? extends IEndlessAdaptable> items, boolean clearExistingItems) {
if (items != null) {
// closed or not deleted
boolean foundAnyClosedGiveaways = false;
// do nothing much except update the status of existing giveaways.
for (IEndlessAdaptable endlessAdaptable : items) {
ProfileGiveaway giveaway = (ProfileGiveaway) endlessAdaptable;
Log.d(TAG, giveaway.getGiveawayId() + " ~> " + giveaway.isOpen() + ", " + giveaway.isDeleted());
if (!giveaway.isOpen() && !giveaway.isDeleted()) {
foundAnyClosedGiveaways = true;
break;
}
Giveaway existingGiveaway = adapter.findItem(giveaway.getGiveawayId());
if (existingGiveaway != null) {
existingGiveaway.setEntries(giveaway.getEntries());
existingGiveaway.setEntered(true);
adapter.notifyItemChanged(existingGiveaway);
}
}
// have we found any non-closed giveaways?
if (foundAnyClosedGiveaways) {
enteredGameListTask = null;
} else {
enteredGameListTask = new LoadEnteredGameListTask(this, enteredGameListTask.getPage() + 1);
enteredGameListTask.execute();
}
} else {
showSnack("Failed to update entered giveaways", Snackbar.LENGTH_LONG);
}
}
@Override
public void requestEnterLeave(String giveawayId, String enterOrDelete, String xsrfToken) {
if (enterLeaveTask != null)
enterLeaveTask.cancel(true);
enterLeaveTask = new EnterLeaveGiveawayTask(this, getContext(), giveawayId, xsrfToken, enterOrDelete);
enterLeaveTask.execute();
}
@Override
public void onEnterLeaveResult(String giveawayId, String what, Boolean success, boolean propagate) {
if (success == Boolean.TRUE) {
Giveaway giveaway = adapter.findItem(giveawayId);
if (giveaway != null) {
giveaway.setEntered(GiveawayDetailFragment.ENTRY_INSERT.equals(what));
adapter.notifyItemChanged(giveaway);
}
} else {
Log.e(TAG, "Probably an error catching the result...");
}
if (propagate)
GiveawayListFragmentStack.onEnterLeaveResult(giveawayId, what, success);
}
}
|
package org.semagrow.evaluation.reactor;
import org.semagrow.evaluation.BindingSetOps;
import org.semagrow.evaluation.IterationPublisher;
import org.semagrow.evaluation.util.BindingSetUtil;
import org.semagrow.evaluation.util.QueryEvaluationUtil;
import org.semagrow.evaluation.util.SimpleBindingSetOps;
import org.semagrow.evaluation.EvaluationStrategy;
import org.eclipse.rdf4j.common.iteration.Iteration;
import org.eclipse.rdf4j.model.Literal;
import org.eclipse.rdf4j.model.Value;
import org.eclipse.rdf4j.model.ValueFactory;
import org.eclipse.rdf4j.model.datatypes.XMLDatatypeUtil;
import org.eclipse.rdf4j.model.vocabulary.XMLSchema;
import org.eclipse.rdf4j.query.BindingSet;
import org.eclipse.rdf4j.query.Dataset;
import org.eclipse.rdf4j.query.QueryEvaluationException;
import org.eclipse.rdf4j.query.algebra.*;
import org.eclipse.rdf4j.query.algebra.evaluation.QueryBindingSet;
import org.eclipse.rdf4j.query.algebra.evaluation.TripleSource;
import org.eclipse.rdf4j.query.algebra.evaluation.ValueExprEvaluationException;
import org.eclipse.rdf4j.query.algebra.evaluation.federation.FederatedServiceResolverImpl;
import org.eclipse.rdf4j.query.algebra.evaluation.impl.ExternalSet;
import org.eclipse.rdf4j.query.algebra.evaluation.util.MathUtil;
import org.eclipse.rdf4j.query.algebra.evaluation.util.OrderComparator;
import org.eclipse.rdf4j.query.algebra.evaluation.util.ValueComparator;
import org.reactivestreams.Publisher;
import org.semagrow.plan.operators.CrossProduct;
import reactor.core.publisher.Flux;
import reactor.core.publisher.GroupedFlux;
import reactor.core.publisher.Mono;
import java.util.*;
public class EvaluationStrategyImpl implements EvaluationStrategy {
private ValueFactory vf;
private org.eclipse.rdf4j.query.algebra.evaluation.EvaluationStrategy evalStrategy;
protected BindingSetOps bindingSetOps = SimpleBindingSetOps.getInstance();
public EvaluationStrategyImpl(TripleSource tripleSource) {
vf = tripleSource.getValueFactory();
evalStrategy = new org.eclipse.rdf4j.query.algebra.evaluation.impl.SimpleEvaluationStrategy(tripleSource, new FederatedServiceResolverImpl());
//Environment.initializeIfEmpty();
//dispatcher = new MDCAwareDispatcher(Environment.dispatcher(Environment.THREAD_POOL));
}
public EvaluationStrategyImpl(TripleSource tripleSource, Dataset dataset) {
vf = tripleSource.getValueFactory();
evalStrategy = new org.eclipse.rdf4j.query.algebra.evaluation.impl.SimpleEvaluationStrategy(tripleSource,dataset,new FederatedServiceResolverImpl());
//Environment.initializeIfEmpty();
//dispatcher = new MDCAwareDispatcher(Environment.dispatcher(Environment.THREAD_POOL));
}
public Publisher<BindingSet> evaluate(TupleExpr expr, BindingSet bindings)
throws QueryEvaluationException
{
//return RxReactiveStreams.toPublisher(evaluateReactorInternal(expr, bindings));;
return evaluateReactorInternal(expr, bindings);
//.subscribeOn(new MDCAwareDispatcher(Environment.dispatcher(Environment.THREAD_POOL)));
}
public boolean isTrue(ValueExpr expr, BindingSet bindings)
throws ValueExprEvaluationException, QueryEvaluationException
{
return evalStrategy.isTrue(expr, bindings);
}
public Value evaluate(ValueExpr expr, BindingSet bindings)
throws ValueExprEvaluationException, QueryEvaluationException
{
return evalStrategy.evaluate(expr, bindings);
}
public Value evaluateValue(ValueExpr expr, BindingSet bindings)
throws ValueExprEvaluationException, QueryEvaluationException
{
return evaluate(expr, bindings);
}
public Flux<BindingSet> evaluateReactorInternal(TupleExpr expr, BindingSet bindings)
throws QueryEvaluationException
{
if (expr instanceof StatementPattern) {
return evaluateReactorInternal((StatementPattern) expr, bindings);
}
else if (expr instanceof UnaryTupleOperator) {
return evaluateReactorInternal((UnaryTupleOperator) expr, bindings);
}
else if (expr instanceof BinaryTupleOperator) {
return evaluateReactorInternal((BinaryTupleOperator) expr, bindings);
}
else if (expr instanceof SingletonSet) {
return evaluateReactorInternal((SingletonSet) expr, bindings);
}
else if (expr instanceof EmptySet) {
return evaluateReactorInternal((EmptySet) expr, bindings);
}
else if (expr instanceof ExternalSet) {
return evaluateReactorInternal((ExternalSet) expr, bindings);
}
else if (expr instanceof ZeroLengthPath) {
return evaluateReactorInternal((ZeroLengthPath) expr, bindings);
}
else if (expr instanceof ArbitraryLengthPath) {
return evaluateReactorInternal((ArbitraryLengthPath) expr, bindings);
}
else if (expr instanceof BindingSetAssignment) {
return evaluateReactorInternal((BindingSetAssignment) expr, bindings);
}
else if (expr == null) {
throw new IllegalArgumentException("expr must not be null");
}
else {
throw new QueryEvaluationException("Unsupported tuple expr type: " + expr.getClass());
}
}
public Flux<BindingSet> evaluateReactorInternal(UnaryTupleOperator expr, BindingSet bindings)
throws QueryEvaluationException
{
if (expr instanceof Projection) {
return evaluateReactorInternal((Projection) expr, bindings);
}
else if (expr instanceof MultiProjection) {
return evaluateReactorInternal((MultiProjection) expr, bindings);
}
else if (expr instanceof Filter) {
return evaluateReactorInternal((Filter) expr, bindings);
}
else if (expr instanceof Extension) {
return evaluateReactorInternal((Extension) expr, bindings);
}
else if (expr instanceof Group) {
return evaluateReactorInternal((Group) expr, bindings);
}
else if (expr instanceof Order) {
return evaluateReactorInternal((Order) expr, bindings);
}
else if (expr instanceof Slice) {
return evaluateReactorInternal((Slice) expr, bindings);
}
else if (expr instanceof Distinct) {
return evaluateReactorInternal((Distinct) expr, bindings);
}
else if (expr instanceof Reduced) {
return evaluateReactorInternal((Reduced) expr, bindings);
}
else if (expr instanceof Service) {
return evaluateReactorInternal((Service) expr, bindings);
}
else if (expr instanceof QueryRoot) {
return evaluateReactorInternal(expr.getArg(), bindings);
}
else if (expr instanceof DescribeOperator) {
return evaluateReactorInternal((DescribeOperator) expr, bindings);
}
else if (expr == null) {
throw new IllegalArgumentException("expr must not be null");
}
else {
throw new QueryEvaluationException("Unsupported tuple expr type: " + expr.getClass());
}
}
public Flux<BindingSet> evaluateReactorInternal(BinaryTupleOperator expr, BindingSet bindings)
throws QueryEvaluationException
{
if (expr instanceof Union) {
return evaluateReactorInternal((Union) expr, bindings);
}
else if (expr instanceof CrossProduct) {
return evaluateReactorInternal((CrossProduct) expr, bindings);
}
else if (expr instanceof Join) {
return evaluateReactorInternal((Join) expr, bindings);
}
else if (expr instanceof LeftJoin) {
return evaluateReactorInternal((LeftJoin) expr, bindings);
}
else if (expr instanceof Intersection) {
return evaluateReactorInternal((Intersection) expr, bindings);
}
else if (expr instanceof Difference) {
return evaluateReactorInternal((Difference) expr, bindings);
}
else if (expr == null) {
throw new IllegalArgumentException("expr must not be null");
}
else {
throw new QueryEvaluationException("Unsupported tuple expr type: " + expr.getClass());
}
}
public Flux<BindingSet> evaluateReactorInternal(SingletonSet expr, BindingSet bindings)
throws QueryEvaluationException
{
return Flux.just(bindings);
}
public Flux<BindingSet> evaluateReactorInternal(EmptySet expr, BindingSet bindings)
throws QueryEvaluationException
{
return Flux.empty();
}
public Flux<BindingSet> evaluateReactorInternal(StatementPattern expr, BindingSet bindings)
throws QueryEvaluationException
{
return fromIteration(evalStrategy.evaluate(expr, bindings));
}
public Flux<BindingSet> evaluateReactorInternal(BindingSetAssignment expr, BindingSet bindings)
throws QueryEvaluationException
{
return Flux.fromIterable(expr.getBindingSets())
.filter((b) -> BindingSetUtil.agreesOn(bindings, b))
.map((b) -> bindingSetOps.merge(bindings, b));
}
public Flux<BindingSet> evaluateReactorInternal(ExternalSet expr, BindingSet bindings)
throws QueryEvaluationException
{
return fromIteration(evalStrategy.evaluate(expr, bindings));
}
public Flux<BindingSet> evaluateReactorInternal(ZeroLengthPath expr, BindingSet bindings)
throws QueryEvaluationException
{
return fromIteration(evalStrategy.evaluate(expr, bindings));
}
public Flux<BindingSet> evaluateReactorInternal(ArbitraryLengthPath expr, BindingSet bindings)
throws QueryEvaluationException
{
return fromIteration(evalStrategy.evaluate(expr, bindings));
}
public Flux<BindingSet> evaluateReactorInternal(Filter expr, BindingSet bindings)
throws QueryEvaluationException
{
QueryBindingSet scopeBindings = new QueryBindingSet(bindings);
return evaluateReactorInternal(expr.getArg(), bindings)
.filter((b) -> {
try {
return this.isTrue(expr.getCondition(), b);
} catch (QueryEvaluationException /*| ValueExprEvaluationException */ e) {
return false;
}
});
}
public Flux<BindingSet> evaluateReactorInternal(Projection expr, BindingSet bindings)
throws QueryEvaluationException
{
return evaluateReactorInternal(expr.getArg(), bindings)
.map((b) -> QueryEvaluationUtil.project(expr.getProjectionElemList(), b, bindings));
}
public Flux<BindingSet> evaluateReactorInternal(Extension expr, BindingSet bindings)
throws QueryEvaluationException
{
return evaluateReactorInternal(expr.getArg(), bindings)
.flatMap((b) -> {
try {
return Flux.just(QueryEvaluationUtil.extend(this, expr.getElements(), b));
} catch (Exception e) {
return Flux.error(e);
}
});
}
public Flux<BindingSet> evaluateReactorInternal(Union expr, BindingSet bindings)
throws QueryEvaluationException
{
return Flux.concat(
this.evaluateReactorInternal(expr.getLeftArg(), bindings),
this.evaluateReactorInternal(expr.getRightArg(), bindings));
}
public Flux<BindingSet> evaluateReactorInternal(Join expr, BindingSet bindings)
throws QueryEvaluationException
{
return evaluateReactorInternal(expr.getLeftArg(), bindings)
.concatMap((b) -> {
try {
return this.evaluateReactorInternal(expr.getRightArg(), b);
} catch (Exception e) {
return Flux.error(e);
}
});
}
public Flux<BindingSet> evaluateReactorInternal(CrossProduct expr, BindingSet bindings)
throws QueryEvaluationException
{
//expr.getLeftArg();
//expr.getRightArg();
Mono<List<BindingSet>> left = evaluateReactorInternal(expr.getLeftArg(), bindings).collectList();
return evaluateReactorInternal(expr.getRightArg(), bindings)
.flatMap(b -> left.flatMap( bb -> Flux.fromIterable(bb).map( bbb -> bindingSetOps.merge(b,bbb)) ) );
}
public Flux<BindingSet> evaluateReactorInternal(LeftJoin expr, BindingSet bindings)
throws QueryEvaluationException
{
//Stream<BindingSet> r = evaluateReactorInternal(expr.getRightArg(), bindings);
Set<String> joinAttributes = expr.getLeftArg().getBindingNames();
joinAttributes.retainAll(expr.getRightArg().getBindingNames());
return evaluateReactorInternal(expr.getLeftArg(), bindings)
.flatMap((b) -> {
try {
return this.evaluateReactorInternal(expr.getRightArg(), b).defaultIfEmpty(b);
} catch (Exception e) {
return Flux.error(e);
}
});
}
public Flux<BindingSet> evaluateReactorInternal(Group expr, BindingSet bindings)
throws QueryEvaluationException
{
Set<String> groupByBindings = expr.getGroupBindingNames();
Flux<BindingSet> s = evaluateReactorInternal(expr.getArg(), bindings);
Flux<GroupedFlux<BindingSet, BindingSet>> g = s.groupBy((b) -> bindingSetOps.project(groupByBindings, b, bindings));
//return g.flatMap((gs) -> Streams.just(gs.key()));
return g.flatMap((gs) -> aggregate(gs, expr, bindings));
}
public Flux<BindingSet> aggregate(GroupedFlux<BindingSet, BindingSet> g, Group expr, BindingSet parentBindings) {
BindingSet k = g.key();
try {
Entry e = new Entry(k, parentBindings, expr);
Mono<Entry> s = g.reduce( e, (e1, b) -> {
try { e1.addSolution(b);
return e1;
}
catch(Exception x) {
return null;
}
});
return s.flatMap( (ee) -> {
QueryBindingSet b = new QueryBindingSet(k);
try {
ee.bindSolution(b);
return Flux.just(b);
} catch(Exception x) {
return Flux.error(x);
}
});
}catch(QueryEvaluationException e)
{
return Flux.error(e);
}
}
public Flux<BindingSet> evaluateReactorInternal(Order expr, BindingSet bindings)
throws QueryEvaluationException
{
ValueComparator vcmp = new ValueComparator();
OrderComparator cmp = new OrderComparator(evalStrategy, expr, vcmp);
/*return evaluateReactorInternal(expr.getArg(), bindings)
.toSortedList(cmp::compare)
.flatMap(Streams::from);*/
return evaluateReactorInternal(expr.getArg(), bindings)
.sort(cmp::compare);
}
public Flux<BindingSet> evaluateReactorInternal(Slice expr, BindingSet bindings)
throws QueryEvaluationException {
Flux<BindingSet> result = evaluateReactorInternal(expr.getArg(), bindings);
if (expr.hasOffset())
result = result.skip((int) expr.getOffset());
if (expr.hasLimit())
result = result.take((int) expr.getLimit());
return result;
}
public Flux<BindingSet> evaluateReactorInternal(Distinct expr, BindingSet bindings)
throws QueryEvaluationException {
return evaluateReactorInternal(expr.getArg(), bindings).distinct();
}
public Flux<BindingSet> evaluateReactorInternal(Reduced expr, BindingSet bindings)
throws QueryEvaluationException {
return evaluateReactorInternal(expr.getArg(), bindings).distinctUntilChanged();
}
public Flux<BindingSet> evaluateReactorInternal(DescribeOperator expr, BindingSet bindings)
throws QueryEvaluationException {
return fromIteration(evalStrategy.evaluate(expr, bindings));
}
public Flux<BindingSet> evaluateReactorInternal(Intersection expr, BindingSet bindings)
throws QueryEvaluationException {
return fromIteration(evalStrategy.evaluate(expr, bindings));
}
public Flux<BindingSet> evaluateReactorInternal(Difference expr, BindingSet bindings)
throws QueryEvaluationException {
return fromIteration(evalStrategy.evaluate(expr, bindings));
}
public Flux<BindingSet> evaluateReactorInternal(Service expr, BindingSet bindings)
throws QueryEvaluationException {
return fromIteration(evalStrategy.evaluate(expr, bindings));
}
protected <T> Flux<T> fromIteration(Iteration<T, ? extends Exception> it) {
return Flux.from(new IterationPublisher(it));
}
private class ConcatAggregate extends Aggregate {
private StringBuilder concatenated = new StringBuilder();
private String separator = " ";
public ConcatAggregate(GroupConcat groupConcatOp, BindingSet parentBindings)
throws ValueExprEvaluationException, QueryEvaluationException {
super(groupConcatOp);
ValueExpr separatorExpr = groupConcatOp.getSeparator();
if(separatorExpr != null) {
Value separatorValue = evaluateValue(separatorExpr, parentBindings);
this.separator = separatorValue.stringValue();
}
}
public void processAggregate(BindingSet s) throws QueryEvaluationException {
Value v = this.evaluate(s);
if(v != null && this.distinctValue(v)) {
this.concatenated.append(v.stringValue());
this.concatenated.append(this.separator);
}
}
public Value getValue() {
if(this.concatenated.length() == 0) {
return vf.createLiteral("");
} else {
int len = this.concatenated.length() - this.separator.length();
return vf.createLiteral(this.concatenated.substring(0, len));
}
}
}
private class SampleAggregate extends Aggregate {
private Value sample = null;
private Random random = new Random(System.currentTimeMillis());
public SampleAggregate(Sample operator) {
super(operator);
}
public void processAggregate(BindingSet s) throws QueryEvaluationException {
if(this.sample == null || this.random.nextFloat() < 0.5F) {
this.sample = this.evaluate(s);
}
}
public Value getValue() {
return this.sample;
}
}
private class AvgAggregate extends Aggregate {
private long count = 0L;
private Literal sum;
private ValueExprEvaluationException typeError;
public AvgAggregate(Avg operator) {
super(operator);
this.sum = vf.createLiteral("0", XMLSchema.INTEGER);
this.typeError = null;
}
public void processAggregate(BindingSet s) throws QueryEvaluationException {
if(this.typeError == null) {
Value v = this.evaluate(s);
if(this.distinctValue(v)) {
if(v instanceof Literal) {
Literal nextLiteral = (Literal)v;
if(nextLiteral.getDatatype() != null && XMLDatatypeUtil.isNumericDatatype(nextLiteral.getDatatype())) {
this.sum = MathUtil.compute(this.sum, nextLiteral, MathExpr.MathOp.PLUS);
} else {
this.typeError = new ValueExprEvaluationException("not a number: " + v);
}
++this.count;
} else if(v != null) {
this.typeError = new ValueExprEvaluationException("not a number: " + v);
}
}
}
}
public Value getValue() throws ValueExprEvaluationException {
if(this.typeError != null) {
throw this.typeError;
} else if(this.count == 0L) {
return vf.createLiteral(0.0D);
} else {
Literal sizeLit = vf.createLiteral(this.count);
return MathUtil.compute(this.sum, sizeLit, MathExpr.MathOp.DIVIDE);
}
}
}
private class SumAggregate extends Aggregate {
private Literal sum;
private ValueExprEvaluationException typeError;
public SumAggregate(Sum operator) {
super(operator);
this.sum = vf.createLiteral("0", XMLSchema.INTEGER);
this.typeError = null;
}
public void processAggregate(BindingSet s) throws QueryEvaluationException {
if(this.typeError == null) {
Value v = this.evaluate(s);
if(this.distinctValue(v)) {
if(v instanceof Literal) {
Literal nextLiteral = (Literal)v;
if(nextLiteral.getDatatype() != null && XMLDatatypeUtil.isNumericDatatype(nextLiteral.getDatatype())) {
this.sum = MathUtil.compute(this.sum, nextLiteral, MathExpr.MathOp.PLUS);
} else {
this.typeError = new ValueExprEvaluationException("not a number: " + v);
}
} else if(v != null) {
this.typeError = new ValueExprEvaluationException("not a number: " + v);
}
}
}
}
public Value getValue() throws ValueExprEvaluationException {
if(this.typeError != null) {
throw this.typeError;
} else {
return this.sum;
}
}
}
private class MaxAggregate extends Aggregate {
private final ValueComparator comparator = new ValueComparator();
private Value max = null;
public MaxAggregate(Max operator) {
super(operator);
}
public void processAggregate(BindingSet s) throws QueryEvaluationException {
Value v = this.evaluate(s);
if(this.distinctValue(v)) {
if(this.max == null) {
this.max = v;
} else if(this.comparator.compare(v, this.max) > 0) {
this.max = v;
}
}
}
public Value getValue() {
return this.max;
}
}
private class MinAggregate extends Aggregate {
private final ValueComparator comparator = new ValueComparator();
private Value min = null;
public MinAggregate(Min operator) {
super(operator);
}
public void processAggregate(BindingSet s) throws QueryEvaluationException {
Value v = this.evaluate(s);
if(this.distinctValue(v)) {
if(this.min == null) {
this.min = v;
} else if(this.comparator.compare(v, this.min) < 0) {
this.min = v;
}
}
}
public Value getValue() {
return this.min;
}
}
private class CountAggregate extends Aggregate {
private long count = 0L;
private final Set<BindingSet> distinctBindingSets;
public CountAggregate(Count operator) {
super(operator);
if(operator.isDistinct() && this.getArg() == null) {
this.distinctBindingSets = new HashSet();
} else {
this.distinctBindingSets = null;
}
}
public void processAggregate(BindingSet s) throws QueryEvaluationException {
if(this.getArg() != null) {
Value value = this.evaluate(s);
if(value != null && this.distinctValue(value)) {
++this.count;
}
} else if(this.distinctBindingSet(s)) {
++this.count;
}
}
protected boolean distinctBindingSet(BindingSet s) {
return this.distinctBindingSets == null || this.distinctBindingSets.add(s);
}
public Value getValue() {
return vf.createLiteral(Long.toString(this.count), XMLSchema.INTEGER);
}
}
private abstract class Aggregate {
private final Set<Value> distinctValues;
private final ValueExpr arg;
public Aggregate(AbstractAggregateOperator operator) {
this.arg = operator.getArg();
if(operator.isDistinct()) {
this.distinctValues = new HashSet();
} else {
this.distinctValues = null;
}
}
public abstract Value getValue() throws ValueExprEvaluationException;
public abstract void processAggregate(BindingSet var1) throws QueryEvaluationException;
protected boolean distinctValue(Value value) {
return this.distinctValues == null || this.distinctValues.add(value);
}
protected ValueExpr getArg() {
return this.arg;
}
protected Value evaluate(BindingSet s) throws QueryEvaluationException {
try {
return evaluateValue(getArg(), s);
} catch (ValueExprEvaluationException var3) {
return null;
}
}
}
private class Entry {
private BindingSet prototype;
private BindingSet parentBindings;
private Map<String, Aggregate> aggregates;
public Entry(BindingSet prototype, BindingSet parentBindings, Group group)
throws ValueExprEvaluationException, QueryEvaluationException
{
this.prototype = prototype;
this.parentBindings = parentBindings;
this.aggregates = new LinkedHashMap();
Iterator i$ = group.getGroupElements().iterator();
while(i$.hasNext()) {
GroupElem ge = (GroupElem)i$.next();
Aggregate create = this.create(ge.getOperator());
if(create != null) {
this.aggregates.put(ge.getName(), create);
}
}
}
public BindingSet getPrototype() {
return this.prototype;
}
public void addSolution(BindingSet bindingSet) throws QueryEvaluationException {
Iterator i$ = this.aggregates.values().iterator();
while(i$.hasNext()) {
Aggregate aggregate = (Aggregate)i$.next();
aggregate.processAggregate(bindingSet);
}
}
public void bindSolution(QueryBindingSet sol) throws QueryEvaluationException {
Iterator i$ = this.aggregates.keySet().iterator();
while(i$.hasNext()) {
String name = (String)i$.next();
try {
Value ex = ((Aggregate)this.aggregates.get(name)).getValue();
if(ex != null) {
sol.setBinding(name, ex);
}
} catch (ValueExprEvaluationException var5) {
;
}
}
}
private Aggregate create(AggregateOperator operator)
throws QueryEvaluationException
{
if (operator instanceof Count)
return new CountAggregate((Count)operator);
else if (operator instanceof Min)
return new MinAggregate((Min)operator);
else if (operator instanceof Max)
return new MaxAggregate((Max)operator);
else if (operator instanceof Sum)
return new SumAggregate((Sum)operator);
else if (operator instanceof Avg)
return new AvgAggregate((Avg)operator);
else if (operator instanceof Sample)
return new SampleAggregate((Sample)operator);
else if (operator instanceof GroupConcat)
return new ConcatAggregate((GroupConcat)operator, parentBindings);
else
return null;
}
}
}
|
package com.graphhopper.routing.ch;
import com.graphhopper.Repeat;
import com.graphhopper.RepeatRule;
import com.graphhopper.routing.util.*;
import com.graphhopper.routing.weighting.ShortestWeighting;
import com.graphhopper.routing.weighting.TurnWeighting;
import com.graphhopper.routing.weighting.Weighting;
import com.graphhopper.storage.*;
import com.graphhopper.util.*;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import java.util.*;
import static org.junit.Assert.*;
/**
* In this test we mainly test if {@link EdgeBasedNodeContractorTest} inserts the correct shortcuts when certain
* nodes are contracted.
*
* @see CHTurnCostTest where node contraction is tested in combination with the routing query
*/
public class EdgeBasedNodeContractorTest {
private final int maxCost = 10;
// todo: u-turn support ? so far tests etc. focus on case without u-turns
private final TraversalMode traversalMode = TraversalMode.EDGE_BASED_2DIR;
private CHGraph chGraph;
private CarFlagEncoder encoder;
private GraphHopperStorage graph;
private TurnCostExtension turnCostExtension;
private TurnWeighting turnWeighting;
private TurnWeighting chTurnWeighting;
@Rule
public RepeatRule repeatRule = new RepeatRule();
@Before
public void setup() {
// its important to use @Before when using Repeat Rule!
initialize();
}
private void initialize() {
encoder = new CarFlagEncoder(5, 5, maxCost);
EncodingManager encodingManager = new EncodingManager(encoder);
Weighting weighting = new ShortestWeighting(encoder);
PreparationWeighting preparationWeighting = new PreparationWeighting(weighting);
graph = new GraphBuilder(encodingManager).setCHGraph(weighting).setEdgeBasedCH(true).create();
turnCostExtension = (TurnCostExtension) graph.getExtension();
turnWeighting = new TurnWeighting(weighting, turnCostExtension);
chTurnWeighting = new TurnWeighting(preparationWeighting, turnCostExtension);
chGraph = graph.getGraph(CHGraph.class);
}
@Test
public void testContractNodes_simpleLoop() {
// 6- 7-8
graph.edge(6, 7, 2, false);
final EdgeIteratorState edge7to8 = graph.edge(7, 8, 2, false);
final EdgeIteratorState edge8to3 = graph.edge(8, 3, 1, false);
final EdgeIteratorState edge3to2 = graph.edge(3, 2, 2, false);
final EdgeIteratorState edge2to7 = graph.edge(2, 7, 1, false);
graph.edge(7, 9, 1, false);
graph.freeze();
setMaxLevelOnAllNodes();
addRestriction(6, 7, 9);
addTurnCost(8, 3, 2, 2);
contractNodes(5, 6, 3, 2, 9, 1, 8, 4, 7, 0);
checkShortcuts(
createShortcut(8, 2, edge8to3, edge3to2, 5),
createShortcut(8, 7, edge8to3.getEdge(), edge2to7.getEdge(), 6, edge2to7.getEdge(), 6),
createShortcut(7, 7, edge7to8.getEdge(), edge2to7.getEdge(), edge7to8.getEdge(), 7, 8)
);
}
@Test
public void testContractNodes_necessaryAlternative() {
// | can't go 1->6->3
// 2 -> 6 -> 3 -> 5 -> 4
final EdgeIteratorState e6to0 = graph.edge(6, 0, 4, false);
final EdgeIteratorState e0to3 = graph.edge(0, 3, 5, false);
graph.edge(1, 6, 1, false);
final EdgeIteratorState e6to3 = graph.edge(6, 3, 1, false);
final EdgeIteratorState e3to5 = graph.edge(3, 5, 2, false);
graph.edge(2, 6, 1, false);
graph.edge(5, 4, 2, false);
graph.freeze();
setMaxLevelOnAllNodes();
addRestriction(1, 6, 3);
contractAllNodesInOrder();
checkShortcuts(
// from contracting node 0: need a shortcut because of turn restriction
createShortcut(6, 3, e6to0, e0to3, 9),
// from contracting node 3: two shortcuts:
// 1) in case we come from 1->6 (cant turn left)
// 2) in case we come from 2->6 (going via node 0 would be more expensive)
createShortcut(6, 5, e6to0.getEdge(), e3to5.getEdge(), 7, e3to5.getEdge(), 11),
createShortcut(6, 5, e6to3, e3to5, 3)
);
}
@Test
public void testContractNodes_alternativeNecessary_noUTurn() {
EdgeIteratorState e0to4 = graph.edge(4, 0, 3, true);
EdgeIteratorState e0to2 = graph.edge(0, 2, 5, false);
EdgeIteratorState e2to3 = graph.edge(2, 3, 2, false);
EdgeIteratorState e1to3 = graph.edge(3, 1, 2, false);
EdgeIteratorState e2to4 = graph.edge(4, 2, 2, true);
graph.freeze();
setMaxLevelOnAllNodes();
contractAllNodesInOrder();
checkShortcuts(
// from contraction of node 0
createShortcut(4, 2, e0to4, e0to2, 8),
// from contraction of node 2
// It might look like it is always better to go directly from 4 to 2, but when we come from edge (2->4)
// we may not do a u-turn at 4.
createShortcut(4, 3, e0to4.getEdge(), e2to3.getEdge(), 5, e2to3.getEdge(), 10),
createShortcut(4, 3, e2to4, e2to3, 4)
);
}
@Test
public void testContractNodes_bidirectionalLoop() {
// 1 3
// 0-4-6
graph.edge(1, 0, 1, false);
graph.edge(0, 4, 2, false);
final EdgeIteratorState e4to6 = graph.edge(4, 6, 2, true);
final EdgeIteratorState e3to6 = graph.edge(6, 3, 1, true);
final EdgeIteratorState e3to4 = graph.edge(3, 4, 1, true);
final EdgeIteratorState e4to5 = graph.edge(4, 5, 1, false);
graph.edge(5, 2, 2, false);
graph.freeze();
// enforce loop (going counter-clockwise)
addRestriction(0, 4, 5);
addTurnCost(6, 3, 4, 2);
addTurnCost(4, 3, 6, 4);
setMaxLevelOnAllNodes();
contractAllNodesInOrder();
checkShortcuts(
// from contraction of node 3
createShortcut(4, 6, e3to4, e3to6, 6),
createShortcut(6, 4, e3to6, e3to4, 4),
// from contraction of node 4
// two 'parallel' shortcuts to preserve shortest paths to 5 when coming from 4->6 and 3->6 !!
createShortcut(6, 5, e3to6.getEdge(), e4to5.getEdge(), 8, e4to5.getEdge(), 5),
createShortcut(6, 5, e4to6, e4to5, 3)
);
}
@Test
public void testContractNode_twoNormalEdges_noSourceEdgeToConnect() {
// 1 --> 0 --> 2 --> 3
graph.edge(1, 0, 3, false);
graph.edge(0, 2, 5, false);
graph.edge(2, 3, 1, false);
graph.freeze();
setMaxLevelOnAllNodes();
contractNodes(0);
// it looks like we need a shortcut from 1 to 2, but shortcuts are only introduced to maintain shortest paths
// between original edges, so there should be no shortcuts here, because there is no original edge incoming
// to node 1.
checkShortcuts();
}
@Test
public void testContractNode_twoNormalEdges_noTargetEdgeToConnect() {
// 3 --> 1 --> 0 --> 2
graph.edge(3, 1, 1, false);
graph.edge(1, 0, 3, false);
graph.edge(0, 2, 5, false);
graph.freeze();
setMaxLevelOnAllNodes();
contractNodes(0);
// it looks like we need a shortcut from 1 to 2, but shortcuts are only introduced to maintain shortest paths
// between original edges, so there should be no shortcuts here, because there is no original edge outgoing
// from node 2.
checkShortcuts();
}
@Test
public void testContractNode_twoNormalEdges_noEdgesToConnectBecauseOfTurnRestrictions() {
// 0 --> 3 --> 2 --> 4 --> 1
graph.edge(0, 3, 1, false);
graph.edge(3, 2, 3, false);
graph.edge(2, 4, 5, false);
graph.edge(4, 1, 1, false);
addRestriction(0, 3, 2);
addRestriction(2, 4, 1);
graph.freeze();
setMaxLevelOnAllNodes();
contractNodes(2);
// It looks like we need a shortcut from 3 to 4, but due to the turn restrictions there should be none.
checkShortcuts();
}
@Test
public void testContractNode_twoNormalEdges_noTurncosts() {
// 0 --> 3 --> 2 --> 4 --> 1
graph.edge(0, 3, 1, false);
final EdgeIteratorState e3to2 = graph.edge(3, 2, 3, false);
final EdgeIteratorState e2to4 = graph.edge(2, 4, 5, false);
graph.edge(4, 1, 1, false);
graph.freeze();
setMaxLevelOnAllNodes();
EdgeBasedNodeContractor nodeContractor = createNodeContractor();
contractNode(nodeContractor, 0, 0);
contractNode(nodeContractor, 1, 1);
// no shortcuts so far
checkShortcuts();
// contracting node 2 should yield a shortcut to preserve the shortest path from (1->2) to (3->4). note that
// it does not matter that nodes 0 and 1 have lower level and are contracted already!
contractNode(nodeContractor, 2, 2);
checkShortcuts(createShortcut(3, 4, e3to2, e2to4, 8));
}
@Test
public void testContractNode_twoNormalEdges_noShortcuts() {
// 0 --> 1 --> 2 --> 3 --> 4
graph.edge(0, 1, 1, false);
graph.edge(1, 2, 3, false);
graph.edge(2, 3, 5, false);
graph.edge(3, 4, 1, false);
graph.freeze();
setMaxLevelOnAllNodes();
contractAllNodesInOrder();
// for each contraction the node levels are such that no shortcuts are introduced
checkShortcuts();
}
@Test
public void testContractNode_twoNormalEdges_noOutgoingEdges() {
// 0 --> 1 --> 2 <-- 3 <-- 4
graph.edge(0, 1, 1, false);
graph.edge(1, 2, 3, false);
graph.edge(3, 2, 5, false);
graph.edge(4, 3, 1, false);
graph.freeze();
setMaxLevelOnAllNodes();
contractNodes(2);
checkShortcuts();
}
@Test
public void testContractNode_twoNormalEdges_noIncomingEdges() {
// 0 <-- 1 <-- 2 --> 3 --> 4
graph.edge(1, 0, 1, false);
graph.edge(2, 1, 3, false);
graph.edge(2, 3, 5, false);
graph.edge(3, 4, 1, false);
graph.freeze();
setMaxLevelOnAllNodes();
contractNodes(2);
checkShortcuts();
}
@Test
public void testContractNode_duplicateOutgoingEdges_differentWeight() {
// duplicate edges with different weight occur frequently, because there might be different ways between
// the tower nodes
// 0 -> 1 -> 2 -> 3 -> 4
graph.edge(0, 1, 1, false);
graph.edge(1, 2, 1, false);
graph.edge(2, 3, 2, false);
graph.edge(2, 3, 1, false);
graph.edge(3, 4, 1, false);
graph.freeze();
setMaxLevelOnAllNodes();
contractNodes(2);
// there should be only one shortcut
checkShortcuts(
createShortcut(1, 3, 1, 3, 1, 3, 2)
);
}
@Test
public void testContractNode_duplicateIncomingEdges_differentWeight() {
// 0 -> 1 -> 2 -> 3 -> 4
graph.edge(0, 1, 1, false);
graph.edge(1, 2, 2, false);
graph.edge(1, 2, 1, false);
graph.edge(2, 3, 1, false);
graph.edge(3, 4, 1, false);
graph.freeze();
setMaxLevelOnAllNodes();
contractNodes(2);
checkShortcuts(
createShortcut(1, 3, 2, 3, 2, 3, 2)
);
}
@Test
public void testContractNode_duplicateOutgoingEdges_sameWeight() {
// there might be duplicates of edges with the same weight, for example here:
// http://www.openstreetmap.org/#map=19/51.93569/10.5781
// this test makes sure that the necessary shortcuts are introduced nonetheless
// 0 -> 1 -> 2 -> 3 -> 4
graph.edge(0, 1, 1, false);
graph.edge(1, 2, 1, false);
graph.edge(2, 3, 1, false);
graph.edge(2, 3, 1, false);
graph.edge(3, 4, 1, false);
graph.freeze();
setMaxLevelOnAllNodes();
contractNodes(2);
// todo: we could prevent one of the two shortcuts, because once the first one is inserted it is a witness
// for the other one, but right now this does not work because we do not re-run the witness search after
// inserting the first shortcut. a better solution would probably be a clean-up after parsing the osm data where
// duplicate edges get removed. However, there should not be too many such duplicates
checkShortcuts(
createShortcut(1, 3, 1, 2, 1, 2, 2),
createShortcut(1, 3, 1, 3, 1, 3, 2)
);
}
@Test
@Repeat(times = 10)
public void testContractNode_duplicateIncomingEdges_sameWeight() {
// 0 -> 1 -> 2 -> 3 -> 4
graph.edge(0, 1, 1, false);
graph.edge(1, 2, 1, false);
graph.edge(1, 2, 1, false);
graph.edge(2, 3, 1, false);
graph.edge(3, 4, 1, false);
graph.freeze();
setMaxLevelOnAllNodes();
contractNodes(2);
checkNumShortcuts(1);
}
@Test
public void testContractNode_twoNormalEdges_withTurnCost() {
// 0 --> 3 --> 2 --> 4 --> 1
graph.edge(0, 3, 1, false);
final EdgeIteratorState e3to2 = graph.edge(3, 2, 3, false);
final EdgeIteratorState e2to4 = graph.edge(2, 4, 5, false);
graph.edge(4, 1, 1, false);
addTurnCost(3, 2, 4, 4);
graph.freeze();
setMaxLevelOnAllNodes();
contractNodes(2);
double weight = calcWeight(e3to2, e2to4);
checkShortcuts(createShortcut(3, 4, e3to2, e2to4, weight));
}
@Test
public void testContractNode_twoNormalEdges_withTurnRestriction() {
// 0 --> 3 --> 2 --> 4 --> 1
graph.edge(0, 3, 1, false);
graph.edge(3, 2, 3, false);
graph.edge(2, 4, 5, false);
graph.edge(4, 1, 1, false);
addRestriction(3, 2, 4);
graph.freeze();
setMaxLevelOnAllNodes();
contractNodes(2);
checkShortcuts();
}
@Test
public void testContractNode_twoNormalEdges_bidirectional() {
// 0 -- 3 -- 2 -- 4 -- 1
graph.edge(0, 3, 1, true);
final EdgeIteratorState e3to2 = graph.edge(3, 2, 3, true);
final EdgeIteratorState e2to4 = graph.edge(2, 4, 5, true);
graph.edge(4, 1, 1, true);
addTurnCost(e3to2, e2to4, 2, 4);
addTurnCost(e2to4, e3to2, 2, 4);
graph.freeze();
setMaxLevelOnAllNodes();
contractNodes(2);
checkShortcuts(
// note that for now we add a shortcut for each direction. using fwd/bwd flags would be more efficient,
// but requires a more sophisticated way to determine the 'first' and 'last' original edges at various
// places
createShortcut(3, 4, e3to2, e2to4, 12),
createShortcut(4, 3, e2to4, e3to2, 12)
);
}
@Test
public void testContractNode_twoNormalEdges_bidirectional_differentCosts() {
// 0 -- 3 -- 2 -- 4 -- 1
graph.edge(0, 3, 1, true);
final EdgeIteratorState e2to3 = graph.edge(3, 2, 3, true);
final EdgeIteratorState e2to4 = graph.edge(2, 4, 5, true);
graph.edge(4, 1, 1, true);
addTurnCost(e2to3, e2to4, 2, 4);
addTurnCost(e2to4, e2to3, 2, 7);
graph.freeze();
setMaxLevelOnAllNodes();
contractNodes(2);
checkShortcuts(
createShortcut(3, 4, e2to3, e2to4, 12),
createShortcut(4, 3, e2to4, e2to3, 15)
);
}
@Test
public void testContractNode_multiple_bidirectional_linear() {
// 3 -- 2 -- 1 -- 4
graph.edge(3, 2, 2, true);
graph.edge(2, 1, 3, true);
graph.edge(1, 4, 6, true);
graph.freeze();
setMaxLevelOnAllNodes();
contractNodes(1, 2);
// no shortcuts needed
checkShortcuts();
}
@Test
public void testContractNode_twoNormalEdges_withTurnCost_andLoop() {
runTestWithTurnCostAndLoop(false);
}
@Test
public void testContractNode_twoNormalEdges_withTurnCost_andLoop_loopHelps() {
runTestWithTurnCostAndLoop(true);
}
private void runTestWithTurnCostAndLoop(boolean loopHelps) {
// 0 --> 3 --> 2 --> 4 --> 1
graph.edge(0, 3, 1, false);
final EdgeIteratorState e3to2 = graph.edge(3, 2, 3, false);
final EdgeIteratorState e2to2 = graph.edge(2, 2, 2, false);
final EdgeIteratorState e2to4 = graph.edge(2, 4, 5, false);
graph.edge(4, 1, 1, false);
addTurnCost(e3to2, e2to2, 2, 2);
addTurnCost(e2to2, e2to4, 2, 1);
addTurnCost(e3to2, e2to4, 2, loopHelps ? 6 : 3);
graph.freeze();
setMaxLevelOnAllNodes();
createNodeContractor().contractNode(2);
if (loopHelps) {
// it is better to take the loop at node 2, so we need to introduce two shortcuts where the second contains
// the first (this is important for path unpacking)
checkShortcuts(
createShortcut(3, 2, e3to2, e2to2, 7),
createShortcut(3, 4, e3to2.getEdge(), e2to4.getEdge(), 5, e2to4.getEdge(), 13));
} else {
// taking the loop would be worse, so the path is just 3-2-4 and we only need a single shortcut
checkShortcuts(
createShortcut(3, 4, e3to2, e2to4, 11));
}
}
@Test
public void testContractNode_shortcutDoesNotSpanUTurn() {
// 2 -> 7 -> 3 -> 5 -> 6
// 1 <-> 4
final EdgeIteratorState e7to3 = graph.edge(7, 3, 1, false);
final EdgeIteratorState e3to5 = graph.edge(3, 5, 1, false);
final EdgeIteratorState e3to4 = graph.edge(3, 4, 2, true);
graph.edge(2, 7, 1, false);
graph.edge(5, 6, 1, false);
graph.edge(1, 4, 1, true);
graph.freeze();
setMaxLevelOnAllNodes();
addRestriction(7, 3, 5);
contractNodes(3, 4);
checkShortcuts(
// from contracting node 3
createShortcut(7, 4, e7to3, e3to4, 3),
createShortcut(4, 5, e3to4, e3to5, 3)
// important! no shortcut from 7 to 5 when contracting node 4, because it includes a u-turn
);
}
@Test
public void testContractNode_multiple_loops_directTurnIsBest() {
// turning on any of the loops is restricted so we take the direct turn -> one extra shortcuts
GraphWithTwoLoops g = new GraphWithTwoLoops(maxCost, maxCost, 1, 2, 3, 4);
g.contractAndCheckShortcuts(
createShortcut(7, 8, g.e7to6, g.e6to8, 11));
}
@Test
public void testContractNode_multiple_loops_leftLoopIsBest() {
// direct turn is restricted, so we take the left loop -> two extra shortcuts
GraphWithTwoLoops g = new GraphWithTwoLoops(2, maxCost, 1, 2, 3, maxCost);
g.contractAndCheckShortcuts(
createShortcut(7, 6, g.e7to6.getEdge(), g.e1to6.getEdge(), g.e7to6.getEdge(), g.getScEdge(1), 12),
createShortcut(7, 8, g.e7to6.getEdge(), g.e6to8.getEdge(), g.getScEdge(4), g.e6to8.getEdge(), 20)
);
}
@Test
public void testContractNode_multiple_loops_rightLoopIsBest() {
// direct turn is restricted, going on left loop is expensive, so we take the right loop -> two extra shortcuts
GraphWithTwoLoops g = new GraphWithTwoLoops(8, 1, 1, 2, 3, maxCost);
g.contractAndCheckShortcuts(
createShortcut(7, 6, g.e7to6.getEdge(), g.e3to6.getEdge(), g.e7to6.getEdge(), g.getScEdge(3), 12),
createShortcut(7, 8, g.e7to6.getEdge(), g.e6to8.getEdge(), g.getScEdge(4), g.e6to8.getEdge(), 21)
);
}
@Test
public void testContractNode_multiple_loops_leftRightLoopIsBest() {
// multiple turns are restricted, it is best to take the left and the right loop -> three extra shortcuts
GraphWithTwoLoops g = new GraphWithTwoLoops(3, maxCost, 1, maxCost, 3, maxCost);
g.contractAndCheckShortcuts(
createShortcut(7, 6, g.e7to6.getEdge(), g.e1to6.getEdge(), g.e7to6.getEdge(), g.getScEdge(1), 13),
createShortcut(7, 6, g.e7to6.getEdge(), g.e3to6.getEdge(), g.getScEdge(4), g.getScEdge(3), 24),
createShortcut(7, 8, g.e7to6.getEdge(), g.e6to8.getEdge(), g.getScEdge(5), g.e6to8.getEdge(), 33)
);
}
@Test
public void testContractNode_multiple_loops_rightLeftLoopIsBest() {
// multiple turns are restricted, it is best to take the right and the left loop -> three extra shortcuts
GraphWithTwoLoops g = new GraphWithTwoLoops(maxCost, 5, 4, 2, maxCost, maxCost);
g.contractAndCheckShortcuts(
createShortcut(7, 6, g.e7to6.getEdge(), g.e3to6.getEdge(), g.e7to6.getEdge(), g.getScEdge(3), 16),
createShortcut(7, 6, g.e7to6.getEdge(), g.e1to6.getEdge(), g.getScEdge(4), g.getScEdge(1), 25),
createShortcut(7, 8, g.e7to6.getEdge(), g.e6to8.getEdge(), g.getScEdge(5), g.e6to8.getEdge(), 33)
);
}
// 1 4 2
// 0-6-3
// 9--7 5 8--10
private class GraphWithTwoLoops {
final int centerNode = 6;
final EdgeIteratorState e0to1 = graph.edge(0, 1, 3, false);
final EdgeIteratorState e1to6 = graph.edge(1, 6, 2, false);
final EdgeIteratorState e6to0 = graph.edge(6, 0, 4, false);
final EdgeIteratorState e2to3 = graph.edge(2, 3, 2, false);
final EdgeIteratorState e3to6 = graph.edge(3, 6, 7, false);
final EdgeIteratorState e6to2 = graph.edge(6, 2, 1, false);
final EdgeIteratorState e7to6 = graph.edge(7, 6, 1, false);
final EdgeIteratorState e6to8 = graph.edge(6, 8, 6, false);
final EdgeIteratorState e9to7 = graph.edge(9, 7, 2, false);
final EdgeIteratorState e8to10 = graph.edge(8, 10, 3, false);
// these two edges help to avoid loop avoidance for the left and right loops
final EdgeIteratorState e4to6 = graph.edge(4, 6, 1, false);
final EdgeIteratorState e5to6 = graph.edge(5, 6, 1, false);
final int numEdges = 12;
GraphWithTwoLoops(int turnCost70, int turnCost72, int turnCost12, int turnCost18, int turnCost38, int turnCost78) {
addCostOrRestriction(e7to6, e6to0, centerNode, turnCost70);
addCostOrRestriction(e7to6, e6to2, centerNode, turnCost72);
addCostOrRestriction(e7to6, e6to8, centerNode, turnCost78);
addCostOrRestriction(e1to6, e6to2, centerNode, turnCost12);
addCostOrRestriction(e1to6, e6to8, centerNode, turnCost18);
addCostOrRestriction(e3to6, e6to8, centerNode, turnCost38);
// restrictions to make sure that no loop avoidance takes place when the left&right loops are contracted
addRestriction(e4to6, e6to8, centerNode);
addRestriction(e5to6, e6to2, centerNode);
addRestriction(e4to6, e6to0, centerNode);
graph.freeze();
setMaxLevelOnAllNodes();
}
private void contractAndCheckShortcuts(Shortcut... shortcuts) {
contractNodes(0, 1, 2, 3, 4, 5, 6);
HashSet<Shortcut> expectedShortcuts = new HashSet<>();
expectedShortcuts.addAll(Arrays.asList(
createShortcut(6, 1, e6to0, e0to1, 7),
createShortcut(6, 6, e6to0.getEdge(), e1to6.getEdge(), getScEdge(0), e1to6.getEdge(), 9),
createShortcut(6, 3, e6to2, e2to3, 3),
createShortcut(6, 6, e6to2.getEdge(), e3to6.getEdge(), getScEdge(2), e3to6.getEdge(), 10)
));
expectedShortcuts.addAll(Arrays.asList(shortcuts));
checkShortcuts(expectedShortcuts);
}
private int getScEdge(int shortcutId) {
return numEdges + shortcutId;
}
}
@Test
public void testContractNode_detour_detourIsBetter() {
// starting the detour by turning left at node 1 seems expensive but is still worth it because going straight
// at node 2 when coming from node 1 is worse -> one shortcut required
GraphWithDetour g = new GraphWithDetour(2, 9, 5, 1);
contractNodes(0);
checkShortcuts(
createShortcut(1, 2, g.e1to0, g.e0to2, 7)
);
}
@Test
public void testContractNode_detour_detourIsWorse() {
// starting the detour is cheap but going left at node 2 is expensive -> no shortcut
GraphWithDetour g = new GraphWithDetour(4, 1, 1, 7);
contractNodes(0);
checkShortcuts();
}
private class GraphWithDetour {
private final EdgeIteratorState e4to1 = graph.edge(4, 1, 2, false);
private final EdgeIteratorState e1to0 = graph.edge(1, 0, 4, false);
private final EdgeIteratorState e1to2 = graph.edge(1, 2, 3, false);
private final EdgeIteratorState e0to2 = graph.edge(0, 2, 3, false);
private final EdgeIteratorState e2to3 = graph.edge(2, 3, 2, false);
GraphWithDetour(int turnCost42, int turnCost13, int turnCost40, int turnCost03) {
addCostOrRestriction(e4to1, e1to2, 1, turnCost42);
addCostOrRestriction(e4to1, e1to0, 1, turnCost40);
addCostOrRestriction(e1to2, e2to3, 2, turnCost13);
addCostOrRestriction(e0to2, e2to3, 2, turnCost03);
graph.freeze();
setMaxLevelOnAllNodes();
}
}
@Test
public void testContractNode_detour_multipleInOut_needsShortcut() {
GraphWithDetourMultipleInOutEdges g = new GraphWithDetourMultipleInOutEdges(0, 0, 0, 1, 3);
contractNodes(0);
checkShortcuts(createShortcut(1, 4, g.e1to0, g.e0to4, 7));
}
@Test
public void testContractNode_detour_multipleInOut_noShortcuts() {
GraphWithDetourMultipleInOutEdges g = new GraphWithDetourMultipleInOutEdges(0, 0, 0, 0, 0);
contractNodes(0);
checkShortcuts();
}
@Test
public void testContractNode_detour_multipleInOut_restrictedIn() {
GraphWithDetourMultipleInOutEdges g = new GraphWithDetourMultipleInOutEdges(0, maxCost, 0, maxCost, 0);
contractNodes(0);
checkShortcuts();
}
// 5 3 7
// 2-1-0-4-6
private class GraphWithDetourMultipleInOutEdges {
final EdgeIteratorState e5to1 = graph.edge(5, 1, 3, false);
final EdgeIteratorState e2to1 = graph.edge(2, 1, 2, false);
final EdgeIteratorState e1to3 = graph.edge(1, 3, 1, false);
final EdgeIteratorState e3to4 = graph.edge(3, 4, 2, false);
final EdgeIteratorState e1to0 = graph.edge(1, 0, 5, false);
final EdgeIteratorState e0to4 = graph.edge(0, 4, 2, false);
final EdgeIteratorState e4to6 = graph.edge(4, 6, 1, false);
final EdgeIteratorState e4to7 = graph.edge(4, 7, 3, false);
public GraphWithDetourMultipleInOutEdges(int turnCost20, int turnCost50, int turnCost23, int turnCost53, int turnCost36) {
addTurnCost(e1to3, e3to4, 3, 2);
addCostOrRestriction(e2to1, e1to0, 1, turnCost20);
addCostOrRestriction(e2to1, e1to3, 1, turnCost23);
addCostOrRestriction(e5to1, e1to0, 1, turnCost50);
addCostOrRestriction(e5to1, e1to3, 1, turnCost53);
addCostOrRestriction(e3to4, e4to6, 4, turnCost36);
graph.freeze();
setMaxLevelOnAllNodes();
}
}
@Test
public void testContractNode_loopAvoidance_loopNecessary() {
// turning from 3 via 2 to 4 is costly, it is better to take the 2-1-0-2 loop so a loop shortcut is required
GraphWithLoop g = new GraphWithLoop(7);
contractNodes(0, 1);
final int numEdges = 6;
checkShortcuts(
createShortcut(2, 1, g.e2to0, g.e0to1, 3),
createShortcut(2, 2, g.e2to0.getEdge(), g.e1to2.getEdge(), numEdges, g.e1to2.getEdge(), 4)
);
}
@Test
public void testContractNode_loopAvoidance_loopAvoidable() {
// turning from 3 via 2 to 4 is cheap, it is better to go straight 3-2-4, no loop shortcut necessary
GraphWithLoop g = new GraphWithLoop(3);
contractNodes(0, 1);
checkShortcuts(
createShortcut(2, 1, g.e2to0, g.e0to1, 3)
);
}
// 0 - 1
// 3 - 2 - 4
private class GraphWithLoop {
final EdgeIteratorState e0to1 = graph.edge(0, 1, 2, false);
final EdgeIteratorState e1to2 = graph.edge(1, 2, 1, false);
final EdgeIteratorState e2to0 = graph.edge(2, 0, 1, false);
final EdgeIteratorState e3to2 = graph.edge(3, 2, 3, false);
final EdgeIteratorState e2to4 = graph.edge(2, 4, 5, false);
final EdgeIteratorState e5to2 = graph.edge(5, 2, 2, false);
GraphWithLoop(int turnCost34) {
addCostOrRestriction(e3to2, e2to4, 2, turnCost34);
graph.freeze();
setMaxLevelOnAllNodes();
}
}
@Test
public void testContractNode_witnessPathsAreFound() {
// 0 - 1 3 - 4 |
graph.edge(0, 1, 1, false);
graph.edge(1, 2, 1, false);
graph.edge(2, 3, 5, false);
graph.edge(3, 4, 1, false);
graph.edge(1, 5, 1, false);
graph.edge(5, 9, 1, false);
graph.edge(9, 3, 1, false);
graph.edge(2, 7, 6, false);
graph.edge(9, 7, 1, false);
graph.edge(7, 10, 1, false);
graph.freeze();
setMaxLevelOnAllNodes();
contractNodes(2);
checkShortcuts();
}
@Test
@Ignore("not sure how to fix this yet")
@Repeat(times = 10)
public void testContractNode_noUnnecessaryShortcut_witnessPathOfEqualWeight() {
// this test runs repeatedly because it might pass/fail by chance (because path lengths are equal)
// 0 -> 1 -> 5
// v v
// 2 -> 3 -> 4 -> 5
graph.edge(0, 1, 1, false);
graph.edge(1, 2, 1, false);
graph.edge(1, 5, 1, false);
EdgeIteratorState e2to3 = graph.edge(2, 3, 1, false);
EdgeIteratorState e3to4 = graph.edge(3, 4, 1, false);
graph.edge(4, 5, 1, false);
EdgeIteratorState e5to3 = graph.edge(5, 3, 1, false);
graph.freeze();
setMaxLevelOnAllNodes();
contractNodes(3, 2);
// when contracting node 2 there is a witness (1-5-3-4) and no shortcut from 1 to 4 should be introduced.
// what might be tricky here is that both the original path and the witness path have equal weight!
checkShortcuts(
createShortcut(2, 4, e2to3, e3to4, 2),
createShortcut(5, 4, e5to3, e3to4, 2)
);
}
@Test
public void testContractNode_noUnnecessaryShortcut_differentWitnessesForDifferentOutEdges() {
graph.edge(0, 1, 1, false);
graph.edge(1, 2, 1, false);
graph.edge(1, 3, 1, false);
graph.edge(1, 4, 1, false);
graph.edge(2, 5, 1, true); // bidirectional
graph.edge(3, 5, 1, false);
graph.edge(4, 5, 1, true); // bidirectional
graph.edge(5, 6, 1, false);
graph.freeze();
setMaxLevelOnAllNodes();
contractNodes(3);
// We do not need a shortcut here! we can only access node 1 from node 0 and at node 5 we can either go to
// node 2,4 or 6. To get to node 6 we can either take the northern witness via 2 or the southern one via 4.
// to get to node 2 we need to take the witness via node 4 and vice versa. the interesting part here is that
// we use a different witness depending on the target edge and even more that the witness paths itself yield
// outgoing edges that need to be witnessed because edges 2->5 and 4->5 are bidirectional like the majority
// of edges in road networks.
checkShortcuts();
}
@Test
public void testContractNode_noUnnecessaryShortcut_differentInitialEntriesForDifferentInEdges() {
// this test shows a (quite realistic) example where the aggressive search finds a witness where the turn
// replacement search does not. this test will fail with turn replacement search enabled
graph.edge(0, 1, 1, false);
graph.edge(1, 2, 1, true); // bidirectional
graph.edge(1, 3, 1, false);
graph.edge(1, 4, 1, true); // bidirectional
graph.edge(2, 5, 1, false);
graph.edge(3, 5, 1, false);
graph.edge(4, 5, 1, false);
graph.edge(5, 6, 1, false);
graph.freeze();
setMaxLevelOnAllNodes();
contractNodes(3);
// We do not need a shortcut here! node 1 can be reached from nodes 0, 2 and 4 and from the target node 5 we can
// only reach node 6. so coming into node 1 from node 0 we can either go north or south via nodes 2/4 to reach
// the edge 5->6. If we come from node 2 we can take the southern witness via 4 and vice versa.
// This is an example of an unnecessary shortcut introduced by the turn replacement algorithm, because the
// out turn replacement difference for the potential witnesses would be infinite at node 1.
// Note that this happens basically whenever there is a bidirectional edge (and u-turns are forbidden) !
checkShortcuts();
}
@Test
public void testContractNode_bidirectional_edge_at_fromNode() {
int nodeToContract = 2;
// we might come from (5->1) so we still need a way back to (3->4) -> we need a shortcut
Shortcut expectedShortcuts = createShortcut(1, 3, 1, 2, 1, 2, 2);
runTestWithBidirectionalEdgeAtFromNode(nodeToContract, false, expectedShortcuts);
}
@Test
public void testContractNode_bidirectional_edge_at_fromNode_is() {
int nodeToContract = 2;
// we might come from (5->1) so we still need a way back to (3->4) -> we need a shortcut
Shortcut expectedShortcuts = createShortcut(1, 3, 1, 2, 1, 2, 2);
runTestWithBidirectionalEdgeAtFromNode(nodeToContract, true, expectedShortcuts);
}
@Test
public void testContractNode_bidirectional_edge_at_fromNode_going_to_node() {
int nodeToContract = 5;
// wherever we come from we can always go via node 2 -> no shortcut needed
Shortcut[] expectedShortcuts = new Shortcut[0];
runTestWithBidirectionalEdgeAtFromNode(nodeToContract, false, expectedShortcuts);
}
private void runTestWithBidirectionalEdgeAtFromNode(int nodeToContract, boolean edge1to2bidirectional, Shortcut... expectedShortcuts) {
// 0 -> 1 <-> 5
// v v
// 2 --> 3 -> 4
graph.edge(0, 1, 1, false);
graph.edge(1, 2, 1, edge1to2bidirectional);
graph.edge(2, 3, 1, false);
graph.edge(3, 4, 1, false);
graph.edge(1, 5, 1, true);
graph.edge(5, 3, 1, false);
graph.freeze();
setMaxLevelOnAllNodes();
contractNodes(nodeToContract);
checkShortcuts(expectedShortcuts);
}
@Test
public void testNodeContraction_directWitness() {
// 0 -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8
graph.edge(0, 1, 1, false);
graph.edge(1, 2, 1, false);
graph.edge(2, 3, 1, false);
graph.edge(3, 4, 1, false);
graph.edge(4, 5, 1, false);
graph.edge(5, 6, 1, false);
graph.edge(6, 7, 1, false);
graph.edge(7, 8, 1, false);
graph.edge(2, 9, 1, false);
graph.edge(9, 6, 1, false);
graph.edge(10, 1, 1, false);
graph.edge(7, 11, 1, false);
graph.freeze();
setMaxLevelOnAllNodes();
contractNodes(2, 6, 3, 5, 4);
// note that the shortcut edge ids depend on the insertion order which might change when changing the implementation
checkShortcuts(
createShortcut(1, 3, 1, 2, 1, 2, 2),
createShortcut(1, 9, 1, 8, 1, 8, 2),
createShortcut(5, 7, 5, 6, 5, 6, 2),
createShortcut(9, 7, 9, 6, 9, 6, 2),
createShortcut(1, 4, 1, 3, 13, 3, 3),
createShortcut(4, 7, 4, 6, 4, 15, 3)
);
}
@Test
@Ignore("does not work for aggressive search")
public void testNodeContraction_witnessBetterBecauseOfTurnCostAtTargetNode() {
// when we contract node 2 we should not stop searching for witnesses when edge 2->3 is settled, because then we miss
// the witness path via 5 that is found later, but still has less weight because of the turn costs at node 3
// 0 -> 1 -> 2 -> 3 -> 4
graph.edge(0, 1, 1, false);
graph.edge(1, 2, 1, false);
graph.edge(2, 3, 1, false);
graph.edge(3, 4, 1, false);
graph.edge(1, 5, 3, false);
graph.edge(5, 3, 1, false);
addTurnCost(2, 3, 4, 5);
addTurnCost(5, 3, 4, 2);
graph.freeze();
setMaxLevelOnAllNodes();
contractNodes(2);
checkShortcuts();
}
@Test
public void testNodeContraction_letShortcutsWitnessEachOther_twoIn() {
// coming from (0->1) it is best to go via node 2 to reach (5->6)
// when contracting node 3 adding the shortcut 2->3->4 is therefore enough and we do not need an
// additional shortcut 1->3->4. while this seems obvious it requires that the 1->3->4 witness search is
// somehow 'aware' of the fact that the shortcut 2->3->4 will be introduced anyway.
// 0 -> 1 -> 2 -> 3 -> 4 -> 5
graph.edge(0, 1, 1, false);
graph.edge(1, 2, 1, false);
graph.edge(2, 3, 1, false);
graph.edge(3, 4, 1, false);
graph.edge(1, 3, 4, false);
graph.edge(4, 5, 1, false);
graph.freeze();
setMaxLevelOnAllNodes();
contractNodes(3);
checkShortcuts(
createShortcut(2, 4, 2, 3, 2, 3, 2)
);
}
@Test
public void testNodeContraction_letShortcutsWitnessEachOther_twoOut() {
// coming from (0->1) it is best to go via node 3 to reach (4->5)
// when contracting node 2 adding the shortcut 1->2->3 is therefore enough and we do not need an
// additional shortcut 1->2->4.
// 0 -> 1 -> 2 -> 3 -> 4 -> 5
graph.edge(0, 1, 1, false);
graph.edge(1, 2, 1, false);
graph.edge(2, 3, 1, false);
graph.edge(3, 4, 1, false);
graph.edge(4, 5, 1, false);
graph.edge(2, 4, 4, false);
graph.freeze();
setMaxLevelOnAllNodes();
contractNodes(2);
checkShortcuts(
createShortcut(1, 3, 1, 2, 1, 2, 2)
);
}
@Test
@Ignore("does not work for aggressive search")
public void testNodeContraction_parallelEdges_onlyOneLoopShortcutNeeded() {
// 0 -- 1 -- 2
EdgeIteratorState edge0 = graph.edge(0, 1, 2, true);
EdgeIteratorState edge1 = graph.edge(1, 0, 4, true);
graph.edge(1, 2, 5, true);
addTurnCost(edge0, edge1, 0, 1);
addTurnCost(edge1, edge0, 0, 2);
graph.freeze();
setMaxLevelOnAllNodes();
contractNodes(0);
// it is sufficient to be able to travel the 1-0-1 loop in one (the cheaper) direction
checkShortcuts(
createShortcut(1, 1, 0, 1, 0, 1, 7)
);
}
@Test
@Ignore("does not work for aggressive search")
public void testNodeContraction_duplicateEdge_severalLoops() {
// 5 -- 4 -- 3 -- 1
graph.edge(1, 3, 47, true);
graph.edge(2, 4, 19, true);
EdgeIteratorState e2 = graph.edge(2, 5, 38, true);
EdgeIteratorState e3 = graph.edge(2, 5, 57, true); // note there is a duplicate edge here (with different weight)
graph.edge(3, 4, 10, true);
EdgeIteratorState e5 = graph.edge(4, 5, 56, true);
addTurnCost(e3, e2, 5, 4);
addTurnCost(e2, e3, 5, 5);
addTurnCost(e5, e3, 5, 3);
addTurnCost(e3, e5, 5, 2);
addTurnCost(e2, e5, 5, 2);
addTurnCost(e5, e2, 5, 1);
graph.freeze();
setMaxLevelOnAllNodes();
contractNodes(4, 5);
// note that the shortcut edge ids depend on the insertion order which might change when changing the implementation
checkNumShortcuts(11);
checkShortcuts(
// from node 4 contraction
createShortcut(5, 3, 5, 4, 5, 4, 66),
createShortcut(3, 5, 4, 5, 4, 5, 66),
createShortcut(2, 3, 1, 4, 1, 4, 29),
createShortcut(3, 2, 4, 1, 4, 1, 29),
createShortcut(2, 5, 1, 5, 1, 5, 75),
createShortcut(5, 2, 5, 1, 5, 1, 75),
// from node 5 contraction
createShortcut(2, 2, 3, 2, 3, 2, 99),
createShortcut(2, 2, 3, 1, 3, 7, 134),
createShortcut(2, 2, 1, 2, 10, 2, 114),
createShortcut(2, 3, 2, 4, 2, 6, 106),
createShortcut(3, 2, 4, 2, 8, 2, 105)
);
}
@Test
@Ignore("does not work for aggressive search")
public void testNodeContraction_tripleConnection() {
graph.edge(0, 1, 1.0, true);
graph.edge(0, 1, 2.0, true);
graph.edge(0, 1, 3.5, true);
graph.freeze();
setMaxLevelOnAllNodes();
contractNodes(1);
checkShortcuts(
createShortcut(0, 0, 1, 2, 1, 2, 5.5),
createShortcut(0, 0, 0, 2, 0, 2, 4.5),
createShortcut(0, 0, 0, 1, 0, 1, 3.0)
);
}
@Test
@Ignore("does not work for aggressive search")
public void testNodeContraction_fromAndToNodesEqual() {
// 0 -> 1 -> 3
graph.edge(0, 1, 1, false);
graph.edge(1, 2, 1, false);
graph.edge(2, 1, 1, false);
graph.edge(1, 3, 1, true);
graph.freeze();
setMaxLevelOnAllNodes();
contractNodes(2);
checkShortcuts();
}
@Test
public void testNodeContraction_node_in_loop() {
// 0-4-3
graph.edge(0, 4, 2, false);
graph.edge(4, 3, 2, true);
graph.edge(3, 2, 1, true);
graph.edge(2, 4, 1, true);
graph.edge(4, 1, 1, false);
graph.freeze();
setMaxLevelOnAllNodes();
// enforce loop (going counter-clockwise)
addRestriction(0, 4, 1);
addTurnCost(4, 2, 3, 4);
addTurnCost(3, 2, 4, 2);
contractNodes(2);
checkShortcuts(
createShortcut(4, 3, 3, 2, 3, 2, 6),
createShortcut(3, 4, 2, 3, 2, 3, 4)
);
}
@Test
@Ignore("does not work for aggressive search")
public void testNodeContraction_turnRestrictionAndLoop() {
// 0 1--2
graph.edge(0, 1, 5, true);
graph.edge(0, 1, 6, true);
graph.edge(1, 2, 2, true);
graph.edge(3, 2, 3, false);
graph.edge(2, 4, 3, false);
addRestriction(3, 2, 4);
graph.freeze();
setMaxLevelOnAllNodes();
contractNodes(0);
checkNumShortcuts(1);
}
@Test
public void testNodeContraction_numPolledEdges() {
graph.edge(3, 2, 71, false);
graph.edge(0, 3, 79, false);
graph.edge(2, 0, 21, false);
graph.edge(2, 4, 16, false);
graph.edge(4, 2, 16, false);
graph.edge(2, 1, 33, false);
graph.edge(4, 5, 29, false);
graph.freeze();
setMaxLevelOnAllNodes();
EdgeBasedNodeContractor nodeContractor = createNodeContractor();
nodeContractor.contractNode(2);
// todo: make sure that 8 or less edges got polled
}
private void contractNode(NodeContractor nodeContractor, int node, int level) {
nodeContractor.contractNode(node);
chGraph.setLevel(node, level);
}
private void contractAllNodesInOrder() {
EdgeBasedNodeContractor nodeContractor = createNodeContractor();
for (int node = 0; node < graph.getNodes(); ++node) {
nodeContractor.contractNode(node);
chGraph.setLevel(node, node);
}
}
/**
* contracts the given nodes and sets the node levels in order.
* this method may only be called once per test !
*/
private void contractNodes(int... nodes) {
EdgeBasedNodeContractor nodeContractor = createNodeContractor();
for (int i = 0; i < nodes.length; ++i) {
nodeContractor.contractNode(nodes[i]);
chGraph.setLevel(nodes[i], i);
}
}
private EdgeBasedNodeContractor createNodeContractor() {
Directory dir = new GHDirectory("", DAType.RAM_INT);
EdgeBasedNodeContractor nodeContractor = new EdgeBasedNodeContractor(dir, graph, chGraph, chTurnWeighting, traversalMode);
nodeContractor.initFromGraph();
return nodeContractor;
}
private double calcWeight(EdgeIteratorState edge1, EdgeIteratorState edge2) {
return turnWeighting.calcWeight(edge1, false, EdgeIterator.NO_EDGE) +
turnWeighting.calcWeight(edge2, false, edge1.getEdge());
}
private void addRestriction(EdgeIteratorState inEdge, EdgeIteratorState outEdge, int viaNode) {
turnCostExtension.addTurnInfo(inEdge.getEdge(), viaNode, outEdge.getEdge(), encoder.getTurnFlags(true, 0));
}
private void addRestriction(int from, int via, int to) {
addRestriction(getEdge(from, via), getEdge(via, to), via);
}
private void addTurnCost(EdgeIteratorState inEdge, EdgeIteratorState outEdge, int viaNode, double cost) {
turnCostExtension.addTurnInfo(inEdge.getEdge(), viaNode, outEdge.getEdge(), encoder.getTurnFlags(false, cost));
}
private void addTurnCost(int from, int via, int to, int cost) {
addTurnCost(getEdge(from, via), getEdge(via, to), via, cost);
}
private void addCostOrRestriction(EdgeIteratorState inEdge, EdgeIteratorState outEdge, int viaNode, int cost) {
if (cost >= maxCost) {
addRestriction(inEdge, outEdge, viaNode);
} else {
addTurnCost(inEdge, outEdge, viaNode, cost);
}
}
private EdgeIteratorState getEdge(int from, int to) {
return GHUtility.getEdge(graph, from, to);
}
private Shortcut createShortcut(int from, int to, EdgeIteratorState edge1, EdgeIteratorState edge2, double weight) {
return createShortcut(from, to, edge1.getEdge(), edge2.getEdge(), edge1.getEdge(), edge2.getEdge(), weight);
}
private Shortcut createShortcut(int from, int to, int firstOrigEdge, int lastOrigEdge, int skipEdge1, int skipEdge2, double weight) {
// when the shortcuts are compared with the existing ones the all edge iterator in checkShortcuts()
// will always use the smaller node id as base
boolean fwd = from <= to;
boolean bwd = !fwd;
int baseNode = from <= to ? from : to;
int adjNode = from <= to ? to : from;
return new Shortcut(baseNode, adjNode, firstOrigEdge, lastOrigEdge, skipEdge1, skipEdge2, weight, fwd, bwd);
}
/**
* Queries the ch graph and checks if the graph's shortcuts match the given expected shortcuts.
*/
private void checkShortcuts(Shortcut... expectedShortcuts) {
Set<Shortcut> expected = setOf(expectedShortcuts);
if (expected.size() != expectedShortcuts.length) {
fail("was given duplicate shortcuts");
}
checkShortcuts(expected);
}
private void checkShortcuts(Set<Shortcut> expected) {
assertEquals(expected, getCurrentShortcuts());
}
private void checkNumShortcuts(int expected) {
assertEquals(expected, getCurrentShortcuts().size());
}
private Set<Shortcut> getCurrentShortcuts() {
Set<Shortcut> shortcuts = new HashSet<>();
AllCHEdgesIterator iter = chGraph.getAllEdges();
while (iter.next()) {
if (iter.isShortcut()) {
shortcuts.add(new Shortcut(
iter.getBaseNode(), iter.getAdjNode(),
iter.getFirstOrigEdge(), iter.getLastOrigEdge(), iter.getSkippedEdge1(), iter.getSkippedEdge2(), iter.getWeight(),
iter.isForward(encoder), iter.isBackward(encoder)
));
}
}
return shortcuts;
}
private Set<Shortcut> setOf(Shortcut... shortcuts) {
return new HashSet<>(Arrays.asList(shortcuts));
}
private void setMaxLevelOnAllNodes() {
int nodes = chGraph.getNodes();
for (int node = 0; node < nodes; node++) {
chGraph.setLevel(node, nodes);
}
}
private static class Shortcut {
int baseNode;
int adjNode;
int firstOrigEdge;
int lastOrigEdge;
double weight;
boolean fwd;
boolean bwd;
int skipEdge1;
int skipEdge2;
public Shortcut(int baseNode, int adjNode, int firstOrigEdge, int lastOrigEdge, int skipEdge1, int skipEdge2, double weight,
boolean fwd, boolean bwd) {
this.baseNode = baseNode;
this.adjNode = adjNode;
this.firstOrigEdge = firstOrigEdge;
this.lastOrigEdge = lastOrigEdge;
this.weight = weight;
this.fwd = fwd;
this.bwd = bwd;
this.skipEdge1 = skipEdge1;
this.skipEdge2 = skipEdge2;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Shortcut shortcut = (Shortcut) o;
return baseNode == shortcut.baseNode &&
adjNode == shortcut.adjNode &&
firstOrigEdge == shortcut.firstOrigEdge &&
lastOrigEdge == shortcut.lastOrigEdge &&
Double.compare(shortcut.weight, weight) == 0 &&
fwd == shortcut.fwd &&
bwd == shortcut.bwd &&
skipEdge1 == shortcut.skipEdge1 &&
skipEdge2 == shortcut.skipEdge2;
}
@Override
public int hashCode() {
return Objects.hash(baseNode, adjNode, firstOrigEdge, lastOrigEdge, weight, fwd, bwd,
skipEdge1, skipEdge2);
}
@Override
public String toString() {
return "Shortcut{" +
"baseNode=" + baseNode +
", adjNode=" + adjNode +
", firstOrigEdge=" + firstOrigEdge +
", lastOrigEdge=" + lastOrigEdge +
", weight=" + weight +
", fwd=" + fwd +
", bwd=" + bwd +
", skipEdge1=" + skipEdge1 +
", skipEdge2=" + skipEdge2 +
'}';
}
}
}
|
package com.jme3.input;
import com.jme3.collision.MotionAllowedListener;
import com.jme3.input.controls.*;
import com.jme3.math.FastMath;
import com.jme3.math.Matrix3f;
import com.jme3.math.Quaternion;
import com.jme3.math.Vector3f;
import com.jme3.renderer.Camera;
/**
* A first person view camera controller.
* After creation, you must register the camera controller with the
* dispatcher using #registerWithDispatcher().
*
* Controls:
* - Move the mouse to rotate the camera
* - Mouse wheel for zooming in or out
* - WASD keys for moving forward/backward and strafing
* - QZ keys raise or lower the camera
*/
public class FlyByCamera implements AnalogListener, ActionListener {
private static String[] mappings = new String[]{
"FLYCAM_Left",
"FLYCAM_Right",
"FLYCAM_Up",
"FLYCAM_Down",
"FLYCAM_StrafeLeft",
"FLYCAM_StrafeRight",
"FLYCAM_Forward",
"FLYCAM_Backward",
"FLYCAM_ZoomIn",
"FLYCAM_ZoomOut",
"FLYCAM_RotateDrag",
"FLYCAM_Rise",
"FLYCAM_Lower"
};
protected Camera cam;
protected Vector3f initialUpVec;
protected float rotationSpeed = 1f;
protected float moveSpeed = 3f;
protected MotionAllowedListener motionAllowed = null;
protected boolean enabled = true;
protected boolean dragToRotate = false;
protected boolean canRotate = false;
protected InputManager inputManager;
/**
* Creates a new FlyByCamera to control the given Camera object.
* @param cam
*/
public FlyByCamera(Camera cam){
this.cam = cam;
initialUpVec = cam.getUp().clone();
}
/**
* Sets the up vector that should be used for the camera.
* @param upVec
*/
public void setUpVector(Vector3f upVec) {
initialUpVec.set(upVec);
}
public void setMotionAllowedListener(MotionAllowedListener listener){
this.motionAllowed = listener;
}
/**
* Sets the move speed. The speed is given in world units per second.
* @param moveSpeed
*/
public void setMoveSpeed(float moveSpeed){
this.moveSpeed = moveSpeed;
}
/**
* Gets the move speed. The speed is given in world units per second.
* @return moveSpeed
*/
public float getMoveSpeed(){
return moveSpeed;
}
/**
* Sets the rotation speed.
* @param rotationSpeed
*/
public void setRotationSpeed(float rotationSpeed){
this.rotationSpeed = rotationSpeed;
}
/**
* Gets the move speed. The speed is given in world units per second.
* @return rotationSpeed
*/
public float getRotationSpeed(){
return rotationSpeed;
}
/**
* @param enable If false, the camera will ignore input.
*/
public void setEnabled(boolean enable){
if (enabled && !enable){
if (inputManager!= null && (!dragToRotate || (dragToRotate && canRotate))){
inputManager.setCursorVisible(true);
}
}
enabled = enable;
}
/**
* @return If enabled
* @see FlyByCamera#setEnabled(boolean)
*/
public boolean isEnabled(){
return enabled;
}
/**
* @return If drag to rotate feature is enabled.
*
* @see FlyByCamera#setDragToRotate(boolean)
*/
public boolean isDragToRotate() {
return dragToRotate;
}
/**
* Set if drag to rotate mode is enabled.
*
* When true, the user must hold the mouse button
* and drag over the screen to rotate the camera, and the cursor is
* visible until dragged. Otherwise, the cursor is invisible at all times
* and holding the mouse button is not needed to rotate the camera.
* This feature is disabled by default.
*
* @param dragToRotate True if drag to rotate mode is enabled.
*/
public void setDragToRotate(boolean dragToRotate) {
this.dragToRotate = dragToRotate;
if (inputManager != null) {
inputManager.setCursorVisible(dragToRotate);
}
}
/**
* Registers the FlyByCamera to receive input events from the provided
* Dispatcher.
* @param inputManager
*/
public void registerWithInput(InputManager inputManager){
this.inputManager = inputManager;
// both mouse and button - rotation of cam
inputManager.addMapping("FLYCAM_Left", new MouseAxisTrigger(MouseInput.AXIS_X, true),
new KeyTrigger(KeyInput.KEY_LEFT));
inputManager.addMapping("FLYCAM_Right", new MouseAxisTrigger(MouseInput.AXIS_X, false),
new KeyTrigger(KeyInput.KEY_RIGHT));
inputManager.addMapping("FLYCAM_Up", new MouseAxisTrigger(MouseInput.AXIS_Y, false),
new KeyTrigger(KeyInput.KEY_UP));
inputManager.addMapping("FLYCAM_Down", new MouseAxisTrigger(MouseInput.AXIS_Y, true),
new KeyTrigger(KeyInput.KEY_DOWN));
// mouse only - zoom in/out with wheel, and rotate drag
inputManager.addMapping("FLYCAM_ZoomIn", new MouseAxisTrigger(MouseInput.AXIS_WHEEL, false));
inputManager.addMapping("FLYCAM_ZoomOut", new MouseAxisTrigger(MouseInput.AXIS_WHEEL, true));
inputManager.addMapping("FLYCAM_RotateDrag", new MouseButtonTrigger(MouseInput.BUTTON_LEFT));
// keyboard only WASD for movement and WZ for rise/lower height
inputManager.addMapping("FLYCAM_StrafeLeft", new KeyTrigger(KeyInput.KEY_A));
inputManager.addMapping("FLYCAM_StrafeRight", new KeyTrigger(KeyInput.KEY_D));
inputManager.addMapping("FLYCAM_Forward", new KeyTrigger(KeyInput.KEY_W));
inputManager.addMapping("FLYCAM_Backward", new KeyTrigger(KeyInput.KEY_S));
inputManager.addMapping("FLYCAM_Rise", new KeyTrigger(KeyInput.KEY_Q));
inputManager.addMapping("FLYCAM_Lower", new KeyTrigger(KeyInput.KEY_Z));
inputManager.addListener(this, mappings);
inputManager.setCursorVisible(dragToRotate || !isEnabled());
Joystick[] joysticks = inputManager.getJoysticks();
if (joysticks != null && joysticks.length > 0){
Joystick joystick = joysticks[0];
joystick.assignAxis("FLYCAM_StrafeRight", "FLYCAM_StrafeLeft", JoyInput.AXIS_POV_X);
joystick.assignAxis("FLYCAM_Forward", "FLYCAM_Backward", JoyInput.AXIS_POV_Y);
joystick.assignAxis("FLYCAM_Right", "FLYCAM_Left", joystick.getXAxisIndex());
joystick.assignAxis("FLYCAM_Down", "FLYCAM_Up", joystick.getYAxisIndex());
}
}
/**
* Registers the FlyByCamera to receive input events from the provided
* Dispatcher.
* @param inputManager
*/
public void unregisterInput(){
if (inputManager == null) {
return;
}
for (String s : mappings) {
if (inputManager.hasMapping(s)) {
inputManager.deleteMapping( s );
}
}
inputManager.removeListener(this);
inputManager.setCursorVisible(!dragToRotate);
Joystick[] joysticks = inputManager.getJoysticks();
if (joysticks != null && joysticks.length > 0){
Joystick joystick = joysticks[0];
// No way to unassing axis
}
}
protected void rotateCamera(float value, Vector3f axis){
if (dragToRotate){
if (canRotate){
// value = -value;
}else{
return;
}
}
Matrix3f mat = new Matrix3f();
mat.fromAngleNormalAxis(rotationSpeed * value, axis);
Vector3f up = cam.getUp();
Vector3f left = cam.getLeft();
Vector3f dir = cam.getDirection();
mat.mult(up, up);
mat.mult(left, left);
mat.mult(dir, dir);
Quaternion q = new Quaternion();
q.fromAxes(left, up, dir);
q.normalize();
cam.setAxes(q);
}
protected void zoomCamera(float value){
// derive fovY value
float h = cam.getFrustumTop();
float w = cam.getFrustumRight();
float aspect = w / h;
float near = cam.getFrustumNear();
float fovY = FastMath.atan(h / near)
/ (FastMath.DEG_TO_RAD * .5f);
fovY += value * 0.1f;
h = FastMath.tan( fovY * FastMath.DEG_TO_RAD * .5f) * near;
w = h * aspect;
cam.setFrustumTop(h);
cam.setFrustumBottom(-h);
cam.setFrustumLeft(-w);
cam.setFrustumRight(w);
}
protected void riseCamera(float value){
Vector3f vel = new Vector3f(0, value * moveSpeed, 0);
Vector3f pos = cam.getLocation().clone();
if (motionAllowed != null)
motionAllowed.checkMotionAllowed(pos, vel);
else
pos.addLocal(vel);
cam.setLocation(pos);
}
protected void moveCamera(float value, boolean sideways){
Vector3f vel = new Vector3f();
Vector3f pos = cam.getLocation().clone();
if (sideways){
cam.getLeft(vel);
}else{
cam.getDirection(vel);
}
vel.multLocal(value * moveSpeed);
if (motionAllowed != null)
motionAllowed.checkMotionAllowed(pos, vel);
else
pos.addLocal(vel);
cam.setLocation(pos);
}
public void onAnalog(String name, float value, float tpf) {
if (!enabled)
return;
if (name.equals("FLYCAM_Left")){
rotateCamera(value, initialUpVec);
}else if (name.equals("FLYCAM_Right")){
rotateCamera(-value, initialUpVec);
}else if (name.equals("FLYCAM_Up")){
rotateCamera(-value, cam.getLeft());
}else if (name.equals("FLYCAM_Down")){
rotateCamera(value, cam.getLeft());
}else if (name.equals("FLYCAM_Forward")){
moveCamera(value, false);
}else if (name.equals("FLYCAM_Backward")){
moveCamera(-value, false);
}else if (name.equals("FLYCAM_StrafeLeft")){
moveCamera(value, true);
}else if (name.equals("FLYCAM_StrafeRight")){
moveCamera(-value, true);
}else if (name.equals("FLYCAM_Rise")){
riseCamera(value);
}else if (name.equals("FLYCAM_Lower")){
riseCamera(-value);
}else if (name.equals("FLYCAM_ZoomIn")){
zoomCamera(value);
}else if (name.equals("FLYCAM_ZoomOut")){
zoomCamera(-value);
}
}
public void onAction(String name, boolean value, float tpf) {
if (!enabled)
return;
if (name.equals("FLYCAM_RotateDrag") && dragToRotate){
canRotate = value;
inputManager.setCursorVisible(!value);
}
}
}
|
package com.continuuity.data;
import com.continuuity.common.conf.CConfiguration;
import com.continuuity.data2.dataset.api.DataSetManager;
import com.google.common.collect.Maps;
import javax.annotation.Nullable;
import java.util.Collections;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
/**
* Holds namespacing logic.
* NOTE: This logic should be moved into DataSetService when we have it.
*/
public abstract class NamespacingDataSetAccessor implements DataSetAccessor {
protected abstract <T> T getDataSetClient(String name, Class<? extends T> type, @Nullable Properties props)
throws Exception;
protected abstract <T> DataSetManager getDataSetManager(Class<? extends T> type) throws Exception;
// todo: for now simplest support for managing datasets, should be improved with DataSetService
protected abstract Map<String, Class<?>> list(String prefix) throws Exception;
private final String reactorNameSpace;
protected NamespacingDataSetAccessor(CConfiguration conf) {
// todo: use single namespace for everything in reactor
this.reactorNameSpace = conf.get(CFG_TABLE_PREFIX, DEFAULT_TABLE_PREFIX);
}
@Override
public <T> T getDataSetClient(String name, Class<? extends T> type, Namespace namespace) throws Exception {
return getDataSetClient(name, type, null, namespace);
}
@Override
public <T> T getDataSetClient(String name, Class<? extends T> type, @Nullable Properties props, Namespace namespace)
throws Exception {
return getDataSetClient(namespace(name, namespace), type, props);
}
@Override
public <T> DataSetManager getDataSetManager(Class<? extends T> type, Namespace namespace) throws Exception {
return new NamespacedDataSetManager(namespace, getDataSetManager(type));
}
@Override
public String namespace(String name, Namespace namespace) {
return reactorNameSpace + "." + namespace.namespace(name);
}
@Override
public Map<String, Class<?>> list(Namespace namespace) throws Exception {
Map<String, Class<?>> namespaced = list(namespace("", namespace));
Map<String, Class<?>> unnamespaced = Maps.newHashMap();
for (Map.Entry<String, Class<?>> ds : namespaced.entrySet()) {
unnamespaced.put(unnamespace(ds.getKey(), namespace), ds.getValue());
}
return unnamespaced;
}
@Override
public void dropAll(Namespace namespace) throws Exception {
for (Map.Entry<String, Class<?>> dataset : list(namespace).entrySet()) {
getDataSetManager(dataset.getValue(), namespace).drop(dataset.getKey());
}
}
@Override
public void truncateAll(Namespace namespace) throws Exception {
truncateAllExceptBlacklist(namespace, Collections.<String>emptySet());
}
@Override
public void truncateAllExceptBlacklist(Namespace namespace, Set<String> blacklist) throws Exception {
for (Map.Entry<String, Class<?>> dataset : list(namespace).entrySet()) {
if (!blacklist.contains(dataset.getKey())) {
getDataSetManager(dataset.getValue(), namespace).truncate(dataset.getKey());
}
}
}
private String unnamespace(String name, Namespace namespace) {
return name.substring(namespace("", namespace).length());
}
private class NamespacedDataSetManager implements DataSetManager {
private final Namespace namespace;
private final DataSetManager delegate;
private NamespacedDataSetManager(Namespace namespace, DataSetManager delegate) {
this.namespace = namespace;
this.delegate = delegate;
}
@Override
public boolean exists(String name) throws Exception {
return delegate.exists(namespace(name, namespace));
}
@Override
public void create(String name) throws Exception {
delegate.create(namespace(name, namespace));
}
@Override
public void create(String name, @Nullable Properties props) throws Exception {
delegate.create(namespace(name, namespace), props);
}
@Override
public void truncate(String name) throws Exception {
delegate.truncate(namespace(name, namespace));
}
@Override
public void drop(String name) throws Exception {
delegate.drop(namespace(name, namespace));
}
}
}
|
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.LineBorder;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.xy.XYSeriesCollection;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import java.awt.event.*;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.awt.*;
import java.io.*;
import java.text.NumberFormat;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Locale;
import java.util.ArrayList;
import java.util.LinkedList;
import org.jfree.ui.ExtensionFileFilter;
public class Genoplot extends JFrame implements ActionListener {
private DataDirectory db;
/** Mode, determining the way, the Diagram responses to mouse gestures.
* <code>true</code> means lasso select, <code>false</code> means zooming in.*/
boolean MOUSE_MODE = false;
String plottedSNP = null;
private JTextField snpField;
private JButton goButton;
private JPanel plotArea;
private PrintStream output;
private LinkedList<String> snpList;
private String currentSNPinList;
private String currentSNP = null;
private int currentSNPindex;
private int displaySNPindex;
private boolean backSNP = false;
private boolean historySNP = false;
private boolean markerList = false;
private boolean endOfList;
private HashMap<String, Integer> listScores = new HashMap<String, Integer>();
private Hashtable<String, String> pdfScores;
JFileChooser jfc;
DataConnectionDialog dcd;
PDFDialog pdfd;
ProgressMonitor pm;
SettingsDialog sd;
private JPanel scorePanel;
private JPanel messagePanel;
private JLabel message;
private JButton yesButton;
private JButton maybeButton;
private JButton noButton;
private JButton backButton;
private JMenu fileMenu;
private JMenu saveMenu;
private JMenuItem openDirectory;
private JMenuItem openRemote;
private JMenuItem loadList;
private JMenuItem loadExclude;
private JMenu toolsMenu;
private JCheckBoxMenuItem filterData;
private JMenuItem saveAll;
private JMenuItem exportPDF;
private JMenu viewMenu;
private JMenuItem viewPolar;
private JMenuItem viewCart;
private JMenu historyMenu;
private ButtonGroup snpGroup;
private JMenuItem returnToListPosition;
private JMenuItem showLogItem;
private JMenu settingsMenu;
private JMenuItem plotSize;
public static LoggingDialog ld;
private JButton randomSNPButton;
private EvokerPDF allPDF = null;
private EvokerPDF yesPDF = null;
private EvokerPDF maybePDF = null;
private EvokerPDF noPDF = null;
private int yesPlotNum;
private int maybePlotNum;
private int noPlotNum;
// default values
private String coordSystem = "CART";
private int plotHeight = 300;
private int plotWidth = 300;
public static void main(String[] args) {
new Genoplot();
}
Genoplot() {
super("Evoke...");
jfc = new JFileChooser("user.dir");
dcd = new DataConnectionDialog(this);
pdfd = new PDFDialog(this);
sd = new SettingsDialog(this);
JMenuBar mb = new JMenuBar();
int menumask = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
fileMenu = new JMenu("File");
openDirectory = new JMenuItem("Open directory");
openDirectory.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,
menumask));
openDirectory.addActionListener(this);
fileMenu.add(openDirectory);
openRemote = new JMenuItem("Connect to remote server");
openRemote.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,
menumask));
openRemote.addActionListener(this);
fileMenu.add(openRemote);
saveMenu = new JMenu("Save BED...");
saveMenu.setEnabled(false);
fileMenu.add(saveMenu);
loadList = new JMenuItem("Load marker list");
loadList.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, menumask));
loadList.addActionListener(this);
loadList.setEnabled(false);
fileMenu.add(loadList);
loadExclude = new JMenuItem("Load sample exclude list");
loadExclude.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E,
menumask));
loadExclude.addActionListener(this);
loadExclude.setEnabled(false);
fileMenu.add(loadExclude);
mb.add(fileMenu);
toolsMenu = new JMenu("Tools");
filterData = new JCheckBoxMenuItem("Filter samples");
filterData.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F,
menumask));
filterData.addActionListener(this);
filterData.setEnabled(false);
toolsMenu.add(filterData);
saveAll = new JMenuItem("Save SNP Plots");
saveAll.addActionListener(this);
saveAll.setEnabled(false);
toolsMenu.add(saveAll);
exportPDF = new JMenuItem("Generate PDF from scores");
exportPDF.addActionListener(this);
exportPDF.setEnabled(false);
toolsMenu.add(exportPDF);
if (!(System.getProperty("os.name").toLowerCase().contains("mac"))) {
JMenuItem quitItem = new JMenuItem("Quit");
quitItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q,
menumask));
quitItem.addActionListener(this);
fileMenu.add(quitItem);
}
mb.add(toolsMenu);
viewMenu = new JMenu("View");
ButtonGroup viewGroup = new ButtonGroup();
viewCart = new JCheckBoxMenuItem("Cartesian coordinates");
viewCart.addActionListener(this);
viewCart.setEnabled(false);
viewGroup.add(viewCart);
viewMenu.add(viewCart);
viewPolar = new JCheckBoxMenuItem("Polar coordinates");
viewPolar.addActionListener(this);
viewPolar.setEnabled(false);
viewGroup.add(viewPolar);
viewMenu.add(viewPolar);
mb.add(viewMenu);
historyMenu = new JMenu("History");
returnToListPosition = new JMenuItem("Return to current list position");
snpGroup = new ButtonGroup();
returnToListPosition.setEnabled(false);
returnToListPosition.addActionListener(this);
historyMenu.add(returnToListPosition);
historyMenu.addSeparator();
mb.add(historyMenu);
JMenu logMenu = new JMenu("Log");
showLogItem = new JMenuItem("Show Evoker log");
showLogItem.addActionListener(this);
logMenu.add(showLogItem);
mb.add(logMenu);
setJMenuBar(mb);
settingsMenu = new JMenu("Settings");
plotSize = new JMenuItem("Plot settings");
plotSize.addActionListener(this);
plotSize.setEnabled(true);
settingsMenu.add(plotSize);
mb.add(settingsMenu);
JPanel controlsPanel = new JPanel();
snpField = new JTextField(10);
snpField.setEnabled(false);
JPanel snpPanel = new JPanel();
snpPanel.add(new JLabel("SNP:"));
snpPanel.add(snpField);
goButton = new JButton("Go");
goButton.addActionListener(this);
goButton.setEnabled(false);
snpPanel.add(goButton);
randomSNPButton = new JButton("Random");
randomSNPButton.addActionListener(this);
randomSNPButton.setEnabled(false);
snpPanel.add(randomSNPButton);
controlsPanel.add(snpPanel);
controlsPanel.add(Box.createRigidArea(new Dimension(50, 1)));
scorePanel = new JPanel();
scorePanel.add(new JLabel("Approve?"));
yesButton = new JButton("Yes");
scorePanel.registerKeyboardAction(this, "Yes", KeyStroke.getKeyStroke(
KeyEvent.VK_Y, 0),
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
yesButton.addActionListener(this);
yesButton.setEnabled(false);
scorePanel.add(yesButton);
maybeButton = new JButton("Maybe");
scorePanel.registerKeyboardAction(this, "Maybe", KeyStroke.getKeyStroke(KeyEvent.VK_M, 0),
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
maybeButton.addActionListener(this);
maybeButton.setEnabled(false);
scorePanel.add(maybeButton);
noButton = new JButton("No");
scorePanel.registerKeyboardAction(this, "No", KeyStroke.getKeyStroke(
KeyEvent.VK_N, 0),
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
noButton.addActionListener(this);
noButton.setEnabled(false);
scorePanel.add(noButton);
backButton = new JButton("Back");
scorePanel.registerKeyboardAction(this, "Back", KeyStroke.getKeyStroke(
KeyEvent.VK_B, 0),
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
backButton.addActionListener(this);
backButton.setEnabled(false);
scorePanel.add(backButton);
messagePanel = new JPanel();
message = new JLabel("");
message.setEnabled(false);
messagePanel.add(message);
message.setVisible(false);
JPanel rightPanel = new JPanel();
rightPanel.add(scorePanel);
rightPanel.add(messagePanel);
rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.Y_AXIS));
controlsPanel.add(rightPanel);
controlsPanel.setMaximumSize(new Dimension(2000, (int) controlsPanel.getPreferredSize().getHeight()));
controlsPanel.setMinimumSize(new Dimension(10, (int) controlsPanel.getPreferredSize().getHeight()));
plotArea = new JPanel();
plotArea.setPreferredSize(new Dimension(700, 350));
plotArea.setBorder(new LineBorder(Color.BLACK));
plotArea.setBackground(Color.WHITE);
JPanel contentPanel = new JPanel();
contentPanel.setLayout(new BoxLayout(contentPanel, BoxLayout.Y_AXIS));
contentPanel.add(plotArea);
contentPanel.add(controlsPanel);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
this.setContentPane(contentPanel);
this.pack();
this.setVisible(true);
ld = new LoggingDialog(this);
ld.pack();
}
public void actionPerformed(ActionEvent actionEvent) {
try {
String command = actionEvent.getActionCommand();
if (command.equals("Go")) {
if (markerListLoaded()) {
if (snpList.contains(snpField.getText().trim())) {
setHistorySNP(true);
displaySNPindex = snpList.indexOf(snpField.getText().trim());
}
}
plotIntensitas(snpField.getText().trim());
} else if (command.equals("No")) {
noButton.requestFocusInWindow();
recordVerdict(-1);
} else if (command.equals("Maybe")) {
maybeButton.requestFocusInWindow();
recordVerdict(0);
} else if (command.equals("Yes")) {
yesButton.requestFocusInWindow();
recordVerdict(1);
} else if (command.equals("Back")) {
setBackSNP(true);
displaySNPindex
if (displaySNPindex == 0) {
backButton.setEnabled(false);
}
int lastCall = listScores.get(snpList.get(displaySNPindex));
if (lastCall == 1) {
yesButton.requestFocusInWindow();
} else if (lastCall == 0) {
maybeButton.requestFocusInWindow();
} else {
noButton.requestFocusInWindow();
}
plotIntensitas(snpList.get(displaySNPindex));
} else if (command.equals("Return to current list position")) {
plotIntensitas(snpList.get(currentSNPindex));
} else if (command.equals("Random")) {
plotIntensitas(db.getRandomSNP());
} else if (command.startsWith("PLOTSNP")) {
String[] bits = command.split("\\s");
if (markerListLoaded()) {
if (snpList.contains(bits[1])) {
setHistorySNP(true);
displaySNPindex = snpList.indexOf(bits[1]);
}
}
plotIntensitas(bits[1]);
} else if (command.equals("Open directory")) {
jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if (jfc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
try {
this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
if (!new File(jfc.getSelectedFile().getAbsolutePath()).exists()) {
throw new IOException("Directory does not exist!");
}
db = new DataDirectory(jfc.getSelectedFile().getAbsolutePath());
plottedSNP = null;
finishLoadingDataSource();
refreshSaveMenu();
} finally {
this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
}
} else if (command.equals("Connect to remote server")) {
final Genoplot gp = this;
// put loading data into a swing worker so that evoker does not hang when loading lots of data
new SwingWorker() {
Exception pendingException = null;
public Object doInBackground() throws Exception {
try {
dcd.pack();
dcd.setVisible(true);
DataClient dc = new DataClient(dcd, gp);
if (dc.getConnectionStatus()) {
// when loading only allow the user to view the log
disableAllActions();
showLogItem.setEnabled(true);
db = new DataDirectory(dc);
finishLoadingDataSource();
refreshSaveMenu();
}
} catch (Exception e) {
pendingException = e;
}
return null;
}
protected void done() {
if (pendingException != null) {
JOptionPane.showMessageDialog(gp, pendingException.getMessage());
}
}
}.execute();
} else if (command.equals("Load marker list")) {
currentSNPindex = 0;
displaySNPindex = currentSNPindex;
jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
if (jfc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
String markerList = jfc.getSelectedFile().getAbsolutePath();
File outfile = checkOverwriteFile(new File(jfc.getSelectedFile().getAbsolutePath()
+ ".scores"));
try {
if (outfile != null) {
loadList(markerList);
FileOutputStream fos = new FileOutputStream(outfile);
output = new PrintStream(fos);
} else {
throw new IOException();
}
} catch (IOException ioe) {
throw new IOException("No score file selected");
}
}
} else if (command.equals("Load sample exclude list")) {
jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
if (jfc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
// TODO: before setting as the new list check it is a valid
// not empty exclude file
db.setExcludeList(new QCFilterData(jfc.getSelectedFile().getAbsolutePath()));
db.setFilterState(true);
filterData.setEnabled(true);
filterData.setSelected(true);
Genoplot.ld.log("Loaded exclude file: "
+ jfc.getSelectedFile().getName());
if (currentSNP != null) {
plotIntensitas(currentSNP);
}
}
} else if (command.equals("Filter samples")) {
// turn filtering on/off
if (filterData.isSelected()) {
db.setFilterState(true);
} else {
db.setFilterState(false);
}
if (currentSNP != null) {
plotIntensitas(currentSNP);
}
} else if (command.equals("Save SNP Plots")) {
File defaultFileName = new File(plottedSNP + ".png");
jfc.setSelectedFile(defaultFileName);
if (jfc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
File png;
if (!jfc.getSelectedFile().toString().endsWith(".png")) {
png = new File(jfc.getSelectedFile().toString()
+ ".png");
} else {
png = jfc.getSelectedFile();
}
BufferedImage image = new BufferedImage(
plotArea.getWidth(), plotArea.getHeight(),
BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = image.createGraphics();
plotArea.paint(g2);
g2.dispose();
try {
ImageIO.write(image, "png", png);
} catch (IOException ioe) {
System.out.println(ioe.getMessage());
}
}
} else if (command.equals("Generate PDF from scores")) {
pdfd.pack();
pdfd.setVisible(true);
if (pdfd.success()) {
generatePDFs();
}
} else if (command.equals("Cartesian coordinates")) {
setCoordSystem("CART");
refreshPlot();
} else if (command.equals("Polar coordinates")) {
setCoordSystem("POLAR");
refreshPlot();
} else if (command.equals("Plot settings")) {
sd.pack();
sd.setVisible(true);
} else if (command.equals("Show Evoker log")) {
ld.setVisible(true);
} else if (command.equals("Quit")) {
System.exit(0);
} else {
ArrayList<String> collections = db.getCollections();
for (String s : collections) {
if (command.equals(s)) {
dumpChanges();
if (!db.changesByCollection.containsKey(s)) {
throw new IOException("Not made any changes to that collection!");
}
save(s);
}
}
}
} catch (IOException ioe) {
JOptionPane.showMessageDialog(this, ioe.getMessage(), "File error",
JOptionPane.ERROR_MESSAGE);
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void disableAllActions() {
// disable all actions while loading data
goButton.setEnabled(false);
randomSNPButton.setEnabled(false);
snpField.setEnabled(false);
yesButton.setEnabled(false);
noButton.setEnabled(false);
maybeButton.setEnabled(false);
backButton.setEnabled(false);
scorePanel.setEnabled(false);
openDirectory.setEnabled(false);
openRemote.setEnabled(false);
loadList.setEnabled(false);
loadExclude.setEnabled(false);
filterData.setEnabled(false);
saveAll.setEnabled(false);
exportPDF.setEnabled(false);
viewCart.setEnabled(false);
viewPolar.setEnabled(false);
returnToListPosition.setEnabled(false);
// clear history items
snpGroup.clearSelection();
}
private void generatePDFs() throws DocumentException, IOException {
loadScores(pdfd.getscoresFile());
pm = new ProgressMonitor(this.getContentPane(), "Exporting plots to PDF", null, 0, pdfScores.size());
SwingWorker pdfWorker = new SwingWorker() {
public Object doInBackground() throws IOException {
Enumeration<String> keys = pdfScores.keys();
try {
openPDFs();
} catch (DocumentException/*|IOException ex*/ ex) {
ex.printStackTrace();
throw new IOException("Could not write PDF");
} catch (IOException ex){
ex.printStackTrace();
throw new IOException("Could not write PDF");
}
File tempFile = null;
try {
tempFile = File.createTempFile("temp", "png");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
tempFile.deleteOnExit();
int progressCounter = 0;
try {
while (keys.hasMoreElements() && !pm.isCanceled()) {
String snp = (String) keys.nextElement();
String score = (String) pdfScores.get(snp);
ArrayList<Image> images = new ArrayList<Image>();
ArrayList<String> stats = new ArrayList<String>();
for (String collection : db.getCollections()) {
PlotPanel pp = new PlotPanel(collection, db.getRecord(snp, collection, getCoordSystem()), plotWidth, plotHeight, MOUSE_MODE);
pp.refresh();
if (pp.hasData()) {
pp.setDimensions(pp.getMinDim(), pp.getMaxDim());
ChartUtilities.saveChartAsPNG(tempFile, pp.getChart(), 400, 400);
images.add(Image.getInstance(tempFile.getAbsolutePath()));
stats.add(pp.generateInfoStr());
} else {
// print the jpanel displaying the no data
// message
BufferedImage noSNP = new BufferedImage(400, 400, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = noSNP.createGraphics();
pp.paint(g2);
g2.dispose();
ImageIO.write(noSNP, "png", tempFile);
images.add(Image.getInstance(tempFile.getAbsolutePath()));
stats.add("");
}
}
PdfPTable table = new PdfPTable(images.size());
PdfPCell snpCell = new PdfPCell(new Paragraph(snp));
snpCell.setColspan(images.size());
snpCell.setBorder(0);
snpCell.setHorizontalAlignment(Element.ALIGN_CENTER);
snpCell.setVerticalAlignment(Element.ALIGN_TOP);
table.addCell(snpCell);
Iterator<Image> ii = images.iterator();
while (ii.hasNext()) {
PdfPCell imageCell = new PdfPCell((Image) ii.next());
imageCell.setBorder(0);
table.addCell(imageCell);
}
Iterator<String> si = stats.iterator();
while (si.hasNext()) {
PdfPCell statsCell = new PdfPCell(new Paragraph(
(String) si.next()));
statsCell.setBorder(0);
statsCell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(statsCell);
}
if (pdfd.allPlots()) {
allPDF.getDocument().add(table);
allPDF.getDocument().newPage();
}
if (score.matches("1") && pdfd.yesPlots()) {
yesPDF.getDocument().add(table);
yesPDF.getDocument().newPage();
yesPlotNum++;
}
if (score.matches("0") && pdfd.maybePlots()) {
maybePDF.getDocument().add(table);
maybePDF.getDocument().newPage();
maybePlotNum++;
}
if (score.matches("-1") && pdfd.noPlots()) {
noPDF.getDocument().add(table);
noPDF.getDocument().newPage();
noPlotNum++;
}
progressCounter++;
pm.setProgress(progressCounter);
}
closePDFs();
} catch (Exception e) {
//TODO: catch this
}
return null;
}
};
pdfWorker.execute();
}
private void printScores() {
ListIterator<String> snpi = snpList.listIterator();
while (snpi.hasNext()) {
String snp = (String) snpi.next();
output.println(snp + "\t" + listScores.get(snp));
}
output.close();
}
private void setMarkerList(boolean marker) {
markerList = marker;
}
private boolean markerListLoaded() {
return markerList;
}
private void activeScorePanel(boolean score) {
if (score) {
yesButton.setEnabled(true);
noButton.setEnabled(true);
maybeButton.setEnabled(true);
scorePanel.setEnabled(true);
if (currentSNPindex == 0 || displaySNPindex == 0) {
backButton.setEnabled(false);
} else {
backButton.setEnabled(true);
}
} else {
yesButton.setEnabled(false);
noButton.setEnabled(false);
maybeButton.setEnabled(false);
backButton.setEnabled(false);
scorePanel.setEnabled(false);
}
}
private void setBackSNP(boolean back) {
backSNP = back;
}
private boolean isBackSNP() {
return backSNP;
}
private void setHistorySNP(boolean history) {
historySNP = history;
}
private boolean isHistorySNP() {
return historySNP;
}
private void setCoordSystem(String s) {
coordSystem = s;
}
private String getCoordSystem() {
return coordSystem;
}
private File checkOverwriteFile(File file) {
if (file.exists()) {
int n = JOptionPane.showConfirmDialog(
this.getContentPane(),
"The file " + file.getName() + " already exists\n would you like to overwrite this file?",
"Overwrite file?", JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE);
// n 0 = yes 1 = no
if (n == 1) {
if (jfc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
file = new File(jfc.getSelectedFile().getAbsolutePath());
} else {
file = null;
}
}
}
return file;
}
private void recordVerdict(int v) throws DocumentException {
if (isBackSNP()) {
listScores.put(snpList.get(displaySNPindex), v);
setBackSNP(false);
if (displaySNPindex == 0) {
backButton.setEnabled(true);
}
displaySNPindex = currentSNPindex;
plotIntensitas(snpList.get(currentSNPindex));
} else if (isHistorySNP()) {
listScores.put(snpList.get(displaySNPindex), v);
setHistorySNP(false);
if (displaySNPindex == 0) {
backButton.setEnabled(true);
}
displaySNPindex = currentSNPindex;
plotIntensitas(snpList.get(currentSNPindex));
} else {
listScores.put(snpList.get(currentSNPindex), v);
if (currentSNPindex < (snpList.size() - 1)) {
currentSNPindex++;
displaySNPindex = currentSNPindex;
backButton.setEnabled(true);
plotIntensitas(snpList.get(currentSNPindex));
} else {
plotIntensitas("ENDLIST");
activeScorePanel(false);
returnToListPosition.setEnabled(false);
int n = JOptionPane.showConfirmDialog(
this.getContentPane(),
"Would you like to save the scores you have generated?",
"Finish scoring list?",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE);
// n 0 = yes 1 = no
if (n == 0) {
printScores();
setMarkerList(false);
randomSNPButton.setEnabled(true);
snpList.clear();
} else {
activeScorePanel(true);
plotIntensitas(snpList.get(currentSNPindex));
}
}
}
}
private void printMessage(String string) {
message.setText(string);
message.setVisible(true);
}
private void openPDFs() throws DocumentException, IOException {
if (pdfd.allPlots()) {
allPDF = new EvokerPDF(checkOverwriteFile(new File(pdfd.getPdfDir()
+ "/all.pdf")), db.getNumCollections());
}
if (pdfd.yesPlots()) {
yesPDF = new EvokerPDF(checkOverwriteFile(new File(pdfd.getPdfDir()
+ "/yes.pdf")), db.getNumCollections());
yesPlotNum = 0;
}
if (pdfd.maybePlots()) {
maybePDF = new EvokerPDF(checkOverwriteFile(new File(pdfd.getPdfDir()
+ "/maybe.pdf")), db.getNumCollections());
maybePlotNum = 0;
}
if (pdfd.noPlots()) {
noPDF = new EvokerPDF(checkOverwriteFile(new File(pdfd.getPdfDir()
+ "/no.pdf")), db.getNumCollections());
noPlotNum = 0;
}
}
private void closePDFs() throws DocumentException {
if (pdfd.allPlots() && allPDF.isFileOpen()) {
allPDF.getDocument().close();
}
if (pdfd.yesPlots() && yesPDF.isFileOpen()) {
if (yesPlotNum == 0) {
yesPDF.getDocument().add(new Paragraph("No Yes plots recorded"));
}
yesPDF.getDocument().close();
}
if (pdfd.maybePlots() && maybePDF.isFileOpen()) {
if (maybePlotNum == 0) {
maybePDF.getDocument().add(
new Paragraph("No Maybe plots recorded"));
}
maybePDF.getDocument().close();
}
if (pdfd.noPlots() && noPDF.isFileOpen()) {
if (noPlotNum == 0) {
noPDF.getDocument().add(new Paragraph("No No plots recorded"));
}
noPDF.getDocument().close();
}
}
private void viewedSNP(String name) {
boolean inHistory = false;
for (Component i : historyMenu.getMenuComponents()) {
if (i instanceof JMenuItem) {
if (((JMenuItem) i).getText().equals(name)) {
((JRadioButtonMenuItem) i).setSelected(true);
inHistory = true;
break;
}
}
}
if (!inHistory) {
// new guy
JRadioButtonMenuItem snpItem = new JRadioButtonMenuItem(name);
snpItem.setActionCommand("PLOTSNP " + name);
snpItem.addActionListener(this);
snpGroup.add(snpItem);
snpItem.setSelected(true);
historyMenu.add(snpItem, 2);
// only track last ten
if (historyMenu.getMenuComponentCount() > 12) {
historyMenu.remove(12);
}
}
}
/**
* Sets all menu entries enabled
*/
private void finishLoadingDataSource() {
if (db != null) {
setPlotAreaSize();
goButton.setEnabled(true);
randomSNPButton.setEnabled(true);
snpField.setEnabled(true);
openDirectory.setEnabled(true);
openRemote.setEnabled(true);
loadList.setEnabled(true);
loadExclude.setEnabled(true);
saveAll.setEnabled(true);
viewCart.setEnabled(true);
viewPolar.setEnabled(true);
exportPDF.setEnabled(true);
saveMenu.setEnabled(true);
while (historyMenu.getMenuComponentCount() > 2) {
historyMenu.remove(2);
}
if (db.qcList() != null) {
// if a exclude file is loaded from the directory enable
// filtering
filterData.setEnabled(true);
filterData.setSelected(true);
}
this.setTitle("Evoke...[" + db.getDisplayName() + "]");
plotArea.removeAll();
plotArea.repaint();
}
}
private void plotIntensitas(String name) {
dumpChanges();
plottedSNP = name;
plotArea.removeAll();
plotArea.setLayout(new BoxLayout(plotArea, BoxLayout.Y_AXIS));
if (name != null) {
if (!name.equals("ENDLIST")) {
currentSNP = name;
plotArea.add(new JLabel(name));
fetchRecord(name);
viewedSNP(name);
if (markerListLoaded()) {
if (snpList.contains((String) name)) {
activeScorePanel(true);
plotArea.add(new JLabel((currentSNPindex + 1) + "/"
+ snpList.size()));
}
} else {
activeScorePanel(false);
}
endOfList = false;
} else {
// I tried very hard to get the label right in the middle and
// failed because java layouts blow
plotArea.add(Box.createVerticalGlue());
JPanel p = new JPanel();
p.add(new JLabel("End of list."));
p.setBackground(Color.WHITE);
plotArea.add(p);
plotArea.add(Box.createVerticalGlue());
activeScorePanel(false);
endOfList = true;
}
}
// seems to need both of these to avoid floating old crud left behind
plotArea.revalidate();
plotArea.repaint();
}
private void loadList(String filename) throws IOException {
snpList = new LinkedList<String>();
BufferedReader listReader = new BufferedReader(new FileReader(filename));
String currentLine;
while ((currentLine = listReader.readLine()) != null) {
String[] bits = currentLine.split("\n");
snpList.add(bits[0]);
}
listReader.close();
setMarkerList(true);
listScores.clear();
try {
this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
db.listNotify((LinkedList) snpList.clone());
displaySNPindex = currentSNPindex;
randomSNPButton.setEnabled(false);
plotIntensitas(snpList.get(currentSNPindex));
returnToListPosition.setEnabled(true);
yesButton.requestFocusInWindow();
} finally {
this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
}
private void loadScores(String filename) throws IOException {
BufferedReader listReader = new BufferedReader(new FileReader(filename));
pdfScores = new Hashtable<String, String>();
String currentLine;
while ((currentLine = listReader.readLine()) != null) {
String[] bits = currentLine.split("\t");
pdfScores.put(bits[0], bits[1]);
}
}
private void dumpChanges() {
if (plottedSNP != null) {
JPanel jp = (JPanel) plotArea.getComponent(1);
//check if this is the end of a marker list
// if it is there will be no changes to commit
if (!endOfList) {
ArrayList<String> collections = db.getCollections();
for (int i = 0; i < collections.size(); i++) {
PlotPanel plotPanel = (PlotPanel) jp.getComponent(i);
MOUSE_MODE = plotPanel.getMouseMode();
PlotData plotData = plotPanel.getPlotData();
if (plotData.changed) {
db.commitGenotypeChange(collections.get(i), plottedSNP, plotData.getGenotypeChanges());
}
}
}
}
}
private void fetchRecord(String name) {
try {
if (db.isRemote()) {
this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
}
JPanel plotHolder = new JPanel();
plotHolder.setBackground(Color.WHITE);
plotArea.add(plotHolder);
ArrayList<String> v = db.getCollections();
ArrayList<PlotPanel> plots = new ArrayList<PlotPanel>();
double maxdim = -100000;
double mindim = 100000;
for (String c : v) {
PlotPanel pp = new PlotPanel(c, db.getRecord(name, c, getCoordSystem()), plotWidth, plotHeight, MOUSE_MODE);
pp.refresh();
if (pp.getMaxDim() > maxdim) {
maxdim = pp.getMaxDim();
}
if (pp.getMinDim() < mindim) {
mindim = pp.getMinDim();
}
plots.add(pp);
}
for (PlotPanel pp : plots) {
pp.setDimensions(mindim, maxdim);
plotHolder.add(pp);
}
} catch (IOException ioe) {
JOptionPane.showMessageDialog(this, ioe.getMessage(), "File error",
JOptionPane.ERROR_MESSAGE);
} finally {
this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
}
private void refreshSaveMenu() {
saveMenu.removeAll();
ArrayList<String> v = db.getCollections();
for (String c : v) {
JMenuItem collectionEntry = new JMenuItem(c);
collectionEntry.addActionListener(this);
saveMenu.add(collectionEntry);
}
}
public void setPlotHeight(int ph) {
plotHeight = ph;
}
public void setPlotWidth(int pw) {
plotWidth = pw;
}
public void setPlotAreaSize() {
int windowWidth = 0;
int windowHeight = 0;
if (db != null) {
if (db.getCollections().size() == 3) {
windowWidth = (plotWidth * 3) + 2500;
windowHeight = plotHeight + 150;
} else if (db.getCollections().size() == 4) {
windowWidth = (plotWidth * 2) + 250;
windowHeight = (plotHeight * 2) + 150;
} else {
windowWidth = (plotWidth * 2) + 250;
windowHeight = plotHeight + 150;
}
} else {
windowWidth = (plotWidth * 2) + 250;
windowHeight = plotHeight + 150;
}
this.setSize(new Dimension(windowWidth, windowHeight));
}
public void refreshPlot() {
if (currentSNP != null) {
plotIntensitas(currentSNP);
}
}
private void save(String collection) throws FileNotFoundException, IOException {
JFileChooser fileChooser = new JFileChooser();
ExtensionFileFilter filter = new ExtensionFileFilter("BED Binary Files", ".bed");
fileChooser.addChoosableFileFilter(filter);
int option = fileChooser.showSaveDialog(this);
if (option == JFileChooser.APPROVE_OPTION) {
String filename = fileChooser.getSelectedFile().getAbsolutePath();
BEDFileChanger bfc = new BEDFileChanger(db.getMarkerData().collectionIndices.get(collection),
collection, db.getDisplayName(), db.samplesByCollection.get(collection).inds,
db.getMarkerData().snpsPerCollection.get(collection), db.getMarkerData().getMarkerTable(),
db.changesByCollection.get(collection), filename);
}
}
}
|
package replicant;
import java.util.Objects;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import static org.realityforge.braincheck.Guards.*;
/**
* A record of a request sent to the server that we need to keep track of.
*/
public final class RequestEntry
{
//TODO: Make this package access after all classes migrated to replicant package
@Nonnull
private final String _requestId;
@Nullable
private final String _name;
@Nullable
private final String _cacheKey;
private Boolean _normalCompletion;
private boolean _expectingResults;
private boolean _resultsArrived;
private SafeProcedure _completionAction;
public RequestEntry( @Nonnull final String requestId,
@Nullable final String name,
@Nullable final String cacheKey )
{
if ( Replicant.shouldCheckInvariants() )
{
invariant( () -> Replicant.areNamesEnabled() || null == name,
() -> "Replicant-0041: RequestEntry passed a name '" + name +
"' but Replicant.areNamesEnabled() is false" );
}
_requestId = Objects.requireNonNull( requestId );
_name = Replicant.areNamesEnabled() ? Objects.requireNonNull( name ) : null;
_cacheKey = cacheKey;
}
@Nonnull
public String getRequestId()
{
return _requestId;
}
@Nonnull
public String getName()
{
if ( Replicant.shouldCheckApiInvariants() )
{
apiInvariant( Replicant::areNamesEnabled,
() -> "Replicant-0043: RequestEntry.getName() invoked when Replicant.areNamesEnabled() is false" );
}
assert null != _name;
return _name;
}
@Nullable
public String getCacheKey()
{
return _cacheKey;
}
@Nullable
public SafeProcedure getCompletionAction()
{
return _completionAction;
}
public void setNormalCompletion( final boolean normalCompletion )
{
_normalCompletion = normalCompletion;
}
void setCompletionAction( @Nonnull final SafeProcedure completionAction )
{
_completionAction = completionAction;
}
public boolean isCompletionDataPresent()
{
return null != _normalCompletion;
}
public boolean isNormalCompletion()
{
if ( Replicant.shouldCheckInvariants() )
{
invariant( this::isCompletionDataPresent,
() -> "Replicant-0008: isNormalCompletion invoked before completion data specified." );
}
return _normalCompletion;
}
public boolean isExpectingResults()
{
return _expectingResults;
}
public void setExpectingResults( final boolean expectingResults )
{
_expectingResults = expectingResults;
}
boolean haveResultsArrived()
{
return _resultsArrived;
}
public void markResultsAsArrived()
{
_resultsArrived = true;
}
@Override
public String toString()
{
if ( Replicant.areNamesEnabled() )
{
return "Request(" + getName() + ")[ID=" + _requestId +
( ( null != _cacheKey ? ",Cache=" + _cacheKey : "" ) ) + "]";
}
else
{
return super.toString();
}
}
}
|
package fi.laverca;
import java.io.UnsupportedEncodingException;
import org.apache.axis.encoding.Base64;
import org.etsi.uri.TS102204.v1_1_2.DataToBeSigned;
/**
* Dual-mode mapper class for "DataToBeSigned"
* This thing would benefit from a near-total rewrite.
*
* @author Asko Saura (asko@methics.fi)
* @author Mikael Lindelf (mikaelj
*
*/
public class DTBS {
String encoding = null;
String text = null;
byte[] data = null;
String mimeType = null;
final static public String ENCODING_UTF8 = "UTF-8";
final static public String ENCODING_BASE64 = "base64";
final static public String MIME_STREAM = "application/octet-stream";
final static public String MIME_SHA1 = "application/x-sha1";
final static public String MIME_SHA256 = "application/x-sha256";
final static public String MIME_UCS2 = "text/plain;ucs2";
final static public String MIME_GSM = "text/plain;gsm";
final static public String MIME_UTF8 = "text/plain;UTF-8";
final static public String MIME_TEXTPLAIN = "text/plain";
/**
* Initialize a DTBS with text.
*
* @param text
* @param encoding
* @param mimeType
*/
public DTBS(final String text, final String encoding, final String mimeType) {
this.text = text;
this.encoding = encoding;
this.mimeType = mimeType;
}
/**
* Initialize a DTBS with data.
*
* @param data
* @param encoding
* @param mimeType
*/
public DTBS(final byte[] data, final String encoding, final String mimeType) {
this.data = data;
this.encoding = encoding;
this.mimeType = mimeType;
}
/**
* Initialize a DTBS without a mime type for <code>toBytes()</code>
*
* @param text
* @param encoding
*/
public DTBS(final String text, final String encoding) {
this(text, encoding, null);
}
/**
* Initialize a DTBS without a mime type for <code>toBytes()</code>
*
* @param text
* @param encoding
*/
public DTBS(final String text) {
this(text, ENCODING_UTF8);
}
public String getText() { return this.text; }
public byte[] getData() { return this.data; }
/**
* Converter of incoming DTBS to byte-array, if the incoming
* form happened to be a String, otherwise returning it as is.
*
* @return byte-array
*/
public byte[] toBytes() {
if (this.data != null) {
return data;
}
if (this.text != null) {
try {
return this.text.getBytes(this.encoding);
}
catch (UnsupportedEncodingException uee) {
throw new RuntimeException(uee);
}
}
throw new RuntimeException("Illegal DTBS");
}
/**
* Retrieve DTBS as a string - if it was a String at creation time.
*
* @return String
*/
public String toString() {
if (this.text != null) {
return this.text;
}
else if (this.data != null) {
return "-binary DTBS-";
}
else {
return "-illegal DTBS-";
}
}
public DataToBeSigned toDataToBeSigned() {
DataToBeSigned rv = new DataToBeSigned();
rv.setEncoding(this.encoding);
rv.setMimeType(this.mimeType);
if(this.text == null) {
rv.setContent(Base64.encode(this.data));
} else {
rv.setContent(this.text);
}
return rv;
}
/**
* Length of DTBS data, either the string, or the byte-array
*
* @return int - length of data
*/
public int length() {
if (this.text != null) {
return this.text.length();
}
else if (this.data != null) {
return this.data.length;
}
else {
throw new RuntimeException("illegal dtbs");
}
}
}
|
package com.bugsnag;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.junit.Before;
import org.junit.Test;
import java.lang.Exception;
import java.util.List;
public class ThreadStateTest {
private List<ThreadState> threadStates;
/**
* Generates a list of current thread states
*
* @throws Exception if the thread state could not be constructed
*/
@Before
public void setUp() throws Exception {
threadStates = ThreadState.getLiveThreads(new Configuration("apikey"));
}
@Test
public void testThreadStateDoesNotContainCurrentThread() {
for (ThreadState thread : threadStates) {
if (thread.getId() == Thread.currentThread().getId()) {
fail();
}
}
// Just test that there is at least one thread
assertTrue(threadStates.size() > 1);
}
@Test
public void testThreadName() {
for (ThreadState threadState : threadStates) {
assertNotNull(threadState.getName());
}
}
@Test
public void testThreadStacktrace() {
for (ThreadState threadState : threadStates) {
List<Stackframe> stacktrace = threadState.getStacktrace();
assertNotNull(stacktrace);
}
}
}
|
package com.jcabi.aether;
import com.jcabi.log.VerboseRunnable;
import com.jcabi.log.VerboseThreads;
import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.apache.maven.project.MavenProject;
import org.hamcrest.CustomMatcher;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.mockito.Mockito;
import org.sonatype.aether.artifact.Artifact;
import org.sonatype.aether.repository.RemoteRepository;
import org.sonatype.aether.util.artifact.DefaultArtifact;
import org.sonatype.aether.util.artifact.JavaScopes;
/**
* Test case for {@link Aether}.
* @author Yegor Bugayenko (yegor@jcabi.com)
* @version $Id$
* @checkstyle ClassDataAbstractionCoupling (500 lines)
*/
@SuppressWarnings("PMD.DoNotUseThreads")
public final class AetherTest {
/**
* Temp dir.
* @checkstyle VisibilityModifier (3 lines)
*/
@Rule
public final transient TemporaryFolder temp = new TemporaryFolder();
/**
* Aether can find and load artifacts.
* @throws Exception If there is some problem inside
*/
@Test
@SuppressWarnings("unchecked")
public void findsAndLoadsArtifacts() throws Exception {
final MavenProject project = this.project();
final File local = this.temp.newFolder("local-repository");
final Aether aether = new Aether(project, local.getPath());
final Artifact[] artifacts = new Artifact[] {
new DefaultArtifact("com.jcabi:jcabi-log:jar:0.1.5"),
new DefaultArtifact("com.rexsl:rexsl-core:jar:mock:0.3.8"),
};
for (Artifact artifact : artifacts) {
MatcherAssert.assertThat(
aether.resolve(artifact, JavaScopes.RUNTIME),
Matchers.<Artifact>hasItems(
Matchers.<Artifact>hasProperty(
"file",
new CustomMatcher<String>("file exists") {
@Override
public boolean matches(final Object file) {
return File.class.cast(file).exists();
}
}
)
)
);
}
}
/**
* Aether can resolve in parallel threads.
* @throws Exception If there is some problem inside
*/
@Test
@SuppressWarnings("unchecked")
public void resolvesArtifactsInParallelThreads() throws Exception {
final MavenProject project = this.project();
final File local = this.temp.newFolder("local-repo-2");
final Aether aether = new Aether(project, local.getPath());
final int threads = Runtime.getRuntime().availableProcessors() * 5;
final Artifact artifact = new DefaultArtifact(
"com.jcabi",
"jcabi-aether",
"",
"jar",
"0.1.10"
);
final CountDownLatch start = new CountDownLatch(1);
final CountDownLatch latch = new CountDownLatch(threads);
final Runnable task = new VerboseRunnable(
new Callable<Void>() {
@Override
public Void call() throws Exception {
start.await();
MatcherAssert.assertThat(
aether.resolve(artifact, JavaScopes.RUNTIME),
Matchers.not(Matchers.<Artifact>empty())
);
latch.countDown();
return null;
}
},
true
);
final ExecutorService svc =
Executors.newFixedThreadPool(threads, new VerboseThreads());
for (int thread = 0; thread < threads; ++thread) {
svc.submit(task);
}
start.countDown();
MatcherAssert.assertThat(
latch.await(1, TimeUnit.MINUTES),
Matchers.is(true)
);
svc.shutdown();
}
/**
* Make mock maven project.
* @return The project
* @throws Exception If there is some problem inside
*/
private MavenProject project() throws Exception {
final MavenProject project = Mockito.mock(MavenProject.class);
Mockito.doReturn(
Arrays.asList(
new RemoteRepository(
"id",
"default",
"http://repo1.maven.org/maven2/"
)
)
).when(project).getRemoteProjectRepositories();
return project;
}
}
|
package guitests;
import javafx.application.Platform;
import org.junit.Test;
import util.DialogMessage;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import static org.junit.Assert.assertEquals;
import static org.loadui.testfx.Assertions.assertNodeExists;
import static org.loadui.testfx.controls.Commons.hasText;
public class DialogMessageTests extends UITest {
@Test
public void showErrorDialogTest() {
Platform.runLater(() -> DialogMessage.showErrorDialog("Error", "Test Error Dialog"));
waitUntilNodeAppears(hasText("Test Error Dialog"));
assertNodeExists(hasText("Test Error Dialog"));
clickOn("OK");
}
@Test
public void showYesNoWarningDialogTest() throws ExecutionException, InterruptedException {
FutureTask<Boolean> yesTask = new FutureTask<>(() ->
DialogMessage.showYesNoWarningDialog("Warning", "Warning Header", "Warning Message", "yEs", "nO"));
Platform.runLater(yesTask);
waitUntilNodeAppears(hasText("Warning Header"));
assertNodeExists(hasText("Warning Header"));
clickOn("yEs");
assertEquals(true, yesTask.get());
FutureTask<Boolean> noTask = new FutureTask<>(() ->
DialogMessage.showYesNoWarningDialog("Warning", "Warning Header", "Warning Message", "yEs", "nO"));
Platform.runLater(noTask);
waitUntilNodeAppears(hasText("Warning Message"));
assertNodeExists(hasText("Warning Message"));
clickOn("nO");
assertEquals(false, noTask.get());
}
@Test
public void showYesNoConfirmationDialogTest() throws ExecutionException, InterruptedException {
FutureTask<Boolean> yesTask = new FutureTask<>(() ->
DialogMessage.showYesNoConfirmationDialog("Confirm", "Confirm Header", "Confirm Message", "yEs", "nO"));
Platform.runLater(yesTask);
waitUntilNodeAppears(hasText("Confirm Header"));
assertNodeExists(hasText("Confirm Header"));
clickOn("yEs");
assertEquals(true, yesTask.get());
FutureTask<Boolean> noTask = new FutureTask<>(() ->
DialogMessage.showYesNoWarningDialog("Confirm", "Confirm Header", "Confirm Message", "yEs", "nO"));
Platform.runLater(noTask);
waitUntilNodeAppears(hasText("Confirm Message"));
assertNodeExists(hasText("Confirm Message"));
clickOn("nO");
assertEquals(false, noTask.get());
}
@Test
public void showInformationDialogTest() {
Platform.runLater(() -> DialogMessage.showInformationDialog("Information", "Test Information Dialog"));
waitUntilNodeAppears(hasText("Test Information Dialog"));
assertNodeExists(hasText("Test Information Dialog"));
clickOn("OK");
}
}
|
package innovimax.mixthem;
import innovimax.mixthem.arguments.Arguments;
import innovimax.mixthem.exceptions.ArgumentException;
import org.junit.Assert;
import org.junit.Test;
public class BasicTest {
@Test
public final void failedPrintUsage() {
boolean check = false;
try {
final String args[] = {};
Arguments mixArgs = Arguments.checkArguments(args);
check = true;
} catch (ArgumentException e) {
System.out.println(e.getMessage());
}
Assert.assertFalse(check);
check = false;
try {
final String args[] = { "ghost1", "ghost2" };
Arguments mixArgs = Arguments.checkArguments(args);
check = true;
} catch (ArgumentException e) {
System.out.println(e.getMessage());
}
Assert.assertFalse(check);
Arguments.printUsage();
}
}
|
package innovimax.mixthem;
import innovimax.mixthem.MixThem;
import org.junit.Assert;
import org.junit.Test;
public class BasicTest {
@Test
public final void failedPrintUsage() {
final String args1[] = {};
Assert.assertNull(MixThem.checkArguments(args1));
final String args2[] = { "ghost1", "ghost2" };
Assert.assertNull(MixThem.checkArguments(args2));
MixThem.printUsage();
}
}
|
/*
Author : Michael Aldridge
Class : CS2336
Section: 001
Assignment: 5
Instructions: Compile with javac inToPost.java; run as java inToPost; This implementation will make an attempt to calculate all expressions that are calculable.
Expressions containing variable components will not be calculated.
Multi-digit integer input is accepted.
*/
import java.util.Scanner;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
public class inToPost {
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
String infixInput = "";
System.out.print("Please input a valid infix expression: ");
infixInput = kbd.nextLine();
eqMan expressionManager = new eqMan();
//tokenize the input
Queue<QType> infix = expressionManager.tokenize(infixInput);
//shunt through the yard to create postfix
Queue<QType> postfix = expressionManager.shunt(infix);
System.out.println("Infix expression: " + infixInput);
System.out.println("Postfix expression: " + expressionManager.getPostFix(postfix));
if(expressionManager.hasVar(postfix)) {
System.out.println("This expression has variable terms, evaluation not possible.");
} else {
System.out.println("This expression is solvable, answer is: " + expressionManager.calculate(postfix));
}
}
}
class eqMan {
public boolean hasVar(Queue<QType> exp) {
Queue<QType> temp = new LinkedList<QType>(exp);
QType current;
while(!temp.isEmpty()) {
current = temp.poll();
if(current.type == QType.Type.VARIABLE) {
return true;
}
}
return false; //no variables, safe to evaluate
}
public String getPostFix(Queue<QType> exp) {
Queue<QType> rpn = new LinkedList<QType>(exp);
StringBuilder out = new StringBuilder();
while(!rpn.isEmpty()) {
QType token = rpn.poll();
switch(token.type) {
case OPERAND:
out.append(token.value);
break;
case VARIABLE:
out.append(token.var);
break;
case OPERATOR:
char c = '|';
switch(token.op) {
case ADD:
c='+';
break;
case SUB:
c='-';
break;
case MUL:
c='*';
break;
case DIV:
c='/';
break;
case EXP:
c='^';
break;
}
out.append(c);
}
out.append(" ");
}
return out.toString();
}
public double calculate(Queue<QType> postfix) {
Stack<Double> evalStack = new Stack<Double>();
QType token;
while(!postfix.isEmpty()) {
token = postfix.poll();
switch(token.type) {
case OPERAND:
evalStack.push((double)(token.value));
break;
case OPERATOR:
double a,b;
a = evalStack.pop();
b = evalStack.pop();
switch(token.op) {
case ADD:
evalStack.push(a+b);
break;
case SUB:
evalStack.push(b-a);
break;
case MUL:
evalStack.push(a*b);
break;
case DIV:
evalStack.push(b/a);
break;
case EXP:
evalStack.push(Math.pow(b,a));
break;
}
}
}
//if everything has gone right, the answer is on evalStack
return evalStack.pop();
}
public int getOpPriority(QType.OP op) {
switch(op) {
case ADD:
case SUB:
return 1;
case MUL:
case DIV:
return 2;
case EXP:
return 3;
case LPR:
case RPR:
return 0;
}
return -1; //never should make it to here
}
public Queue<QType> shunt(Queue<QType> expression) {
Queue<QType> rpnExpression = new LinkedList<QType>();
Stack<QType> opStack = new Stack<QType>();
while(!expression.isEmpty()) {
QType currentToken = expression.poll();
switch(currentToken.type) {
case OPERAND:
//if it is an operand, add it to the stack
rpnExpression.add(currentToken);
break;
case VARIABLE:
//if it is a variable, it is just an operand
rpnExpression.add(currentToken);
break;
case OPERATOR:
//if it is an operator, we need to know if it is an lparen
if(currentToken.op == QType.OP.LPR) {
//push the paren on to the opstack and descend
opStack.push(currentToken);
} else if(currentToken.op == QType.OP.RPR) {
//if right paren, pop all ops from the stack
while(opStack.peek().op != QType.OP.LPR) {
rpnExpression.add(opStack.pop());
}
opStack.pop(); //get rid of the lparen sitting on the stack
} else {
while(!opStack.empty() && getOpPriority(currentToken.op) <= getOpPriority(opStack.peek().op)) {
//if precidence is correct, pop to stack
rpnExpression.add(opStack.pop());
}
opStack.push(currentToken);
}
break;
default:
System.out.println("EXPRESSION NOT MATHEMATICALLY VALID");
break;
}
}
//return any remaining operators
while(!opStack.isEmpty()) {
rpnExpression.add(opStack.pop());
}
return rpnExpression;
}
public Queue<QType> tokenize(String eq) {
Queue<QType> tokens = new LinkedList<QType>();
String operators = "+-*/^()";
//remove all whitespace
eq = eq.replaceAll("\\s","");
for(int i=0; i<eq.length(); i++) {
if(operators.contains(Character.toString(eq.charAt(i)))) {
//catch operators
switch(Character.toString(eq.charAt(i))) {
case "+":
tokens.add(toQ(QType.OP.ADD));
break;
case "-":
tokens.add(toQ(QType.OP.SUB));
break;
case "*":
tokens.add(toQ(QType.OP.MUL));
break;
case "/":
tokens.add(toQ(QType.OP.DIV));
break;
case "^":
tokens.add(toQ(QType.OP.EXP));
break;
case "(":
tokens.add(toQ(QType.OP.LPR));
break;
case ")":
tokens.add(toQ(QType.OP.RPR));
break;
}
} else if(Character.isDigit(eq.charAt(i))) {
int j = i;
int num = 0;
while(Character.isDigit(eq.charAt(i))) {
//get char, mul by 10
num=num*10+Character.getNumericValue(eq.charAt(i));
if(i+1<eq.length()) {
if(Character.isDigit(eq.charAt(i+1))) {
i++;
} else {
break;
}
} else {
break;
}
}
tokens.add(toQ(num));
} else {
tokens.add(toQ(eq.charAt(i)));
}
}
return tokens;
}
//convenience functions to build Tokens
public QType toQ(QType.OP o) {
QType temp = new QType();
temp.type = QType.Type.OPERATOR;
temp.op = o;
return temp;
}
public QType toQ(char v) {
QType temp = new QType();
temp.type = QType.Type.VARIABLE;
temp.var = v;
return temp;
}
public QType toQ(int i) {
QType temp = new QType();
temp.type = QType.Type.OPERAND;
temp.value = i;
return temp;
}
}
class QType {
public enum Type {OPERATOR, OPERAND, VARIABLE};
public enum OP {ADD, SUB, MUL, DIV, EXP, LPR, RPR};
public Type type;
public int value;
public char var;
public OP op;
public String toString() {
StringBuilder out = new StringBuilder();
out.append("Type: " + type + " Value: ");
switch(type) {
case OPERATOR:
out.append(op);
break;
case OPERAND:
out.append(value);
break;
case VARIABLE:
out.append(var);
break;
}
return out.toString();
}
}
|
package eu.sajato.logw;
import eu.sajato.logw.javaLogging.JavaLoggingWrapper;
import java.util.Iterator;
import java.util.ServiceLoader;
import java.util.function.Supplier;
/**
* This is the main class of the logging wrapper.
* You can use any of the static logging methods to directly log messages
* to the wrapped logging framework without creating a logger.
* <p>
* Which logging framework is used is determined by the binding contained
* in the classpath (for details see the {@link LoggingWrapper} interface).
* When no binding is found the java util logging api from the JDK is used.
* <p>
* You can use the general log methods named {@code log} or the methods named
* with the associated log level. All methods have six variations one with only the
* simple message string ({@link #log(Level, String)}, {@link #log(String, Level, String)}),
* one with a message pattern and the parameters for the placeholders ({@link #log(Level, String, Object...)}, {@link #log(String, Level, String, Object...)})
* and one with a massage pattern and lambda expressions for the placeholders ({@link #log(Level, String, Supplier...)}, {@link #log(String, Level, String, Supplier...)}),
* each of this tree with logger name and without.
* <p>
* When the evaluation of placeholders is expensive pay special attention to
* the methods with lambda expressions. You can use it to evaluate expressions
* only when they are really needed.
*
* @author Sascha Rinne
* @version 1.0.0
*/
public class Logw {
static LoggingWrapper logger;
static {
ServiceLoader<LoggingWrapper> serviceLoader = ServiceLoader.load(LoggingWrapper.class);
Iterator<LoggingWrapper> ite = serviceLoader.iterator();
if(ite.hasNext()) {
setInnerLogger(ite.next());
if(ite.hasNext())
Logw.warn("More then one LoggingWrapper loaded with ServiceLoader. Check if multiple logw bindings are in classpath. Anyway, we use the first one for now.");
} else {
setInnerLogger(new JavaLoggingWrapper());
}
Logw.info("Logw use log wrapper " + logger.getClass().getName());
}
static void setInnerLogger(LoggingWrapper logger) {
Logw.logger = logger;
}
// Constructor not needed.
private Logw(){}
/**
* <p>Logs a simple log message with {@link Level#TRACE}.</p>
* Same as: {@link #log(Level, String) Logw.log(Level.TRACE, message)}
*/
public static void trace(String message) {
Logw.log(Level.TRACE, message);
}
/**
* <p>Logs a message, compiled from message pattern and the parameters, with {@link Level#TRACE}.</p>
* Same as: {@link #log(Level, String, Object...)} Logw.log(Level.TRACE, messagePattern, parameters)}
*/
public static void trace(String messagePattern, Object... parameters) {
Logw.log(Level.TRACE, messagePattern, parameters);
}
/**
* <p>Logs a message, compiled from message pattern and values from the evaluated lambda expressions, with {@link Level#TRACE}.</p>
* Same as: {@link #log(Level, String, Supplier...)} Logw.log(Level.TRACE, messagePattern, arguments)}
*/
public static void trace(String messagePattern, Supplier<Object>... arguments) {
Logw.log(Level.TRACE, messagePattern, arguments);
}
/**
* <p>Logs a simple log message with {@link Level#TRACE} to the logger with the given name.</p>
* Same as: {@link #log(String, Level, String) Logw.log(loggerName, Level.TRACE, message)}
*/
public static void trace(String loggerName, String message) {
Logw.log(loggerName, Level.TRACE, message);
}
/**
* <p>Logs a message, compiled from message pattern and the parameters, with {@link Level#TRACE} to the logger with the given name.</p>
* Same as: {@link #log(String, Level, String, Object...)} Logw.log(loggerName, Level.TRACE, messagePattern, parameters)}
*/
public static void trace(String loggerName, String messagePattern, Object... parameters) {
Logw.log(loggerName, Level.TRACE, messagePattern, parameters);
}
public static void trace(String loggerName, String messagePattern, Supplier<Object>... arguments) {
Logw.log(loggerName, Level.TRACE, messagePattern, arguments);
}
/**
* <p>Logs a simple log message with {@link Level#DEBUG}.</p>
* Same as: {@link #log(Level, String) Logw.log(Level.DEBUG, message)}
*/
public static void debug(String message) {
Logw.log(Level.DEBUG, message);
}
/**
* <p>Logs a message, compiled from message pattern and the parameters, with {@link Level#DEBUG}.</p>
* Same as: {@link #log(Level, String, Object...)} Logw.log(Level.DEBUG, messagePattern, parameters)}
*/
public static void debug(String messagePattern, Object... parameters) {
Logw.log(Level.DEBUG, messagePattern, parameters);
}
public static void debug(String messagePattern, Supplier<Object>... arguments) {
Logw.log(Level.DEBUG, messagePattern, arguments);
}
/**
* <p>Logs a simple log message with {@link Level#DEBUG} to the logger with the given name.</p>
* Same as: {@link #log(String, Level, String) Logw.log(loggerName, Level.DEBUG, message)}
*/
public static void debug(String loggerName, String message) {
Logw.log(loggerName, Level.DEBUG, message);
}
/**
* <p>Logs a message, compiled from message pattern and the parameters, with {@link Level#DEBUG} to the logger with the given name.</p>
* Same as: {@link #log(String, Level, String, Object...)} Logw.log(loggerName, Level.DEBUG, messagePattern, parameters)}
*/
public static void debug(String loggerName, String messagePattern, Object... parameters) {
Logw.log(loggerName, Level.DEBUG, messagePattern, parameters);
}
public static void debug(String loggerName, String messagePattern, Supplier<Object>... arguments) {
Logw.log(loggerName, Level.DEBUG, messagePattern, arguments);
}
/**
* <p>Logs a simple log message with {@link Level#INFO}.</p>
* Same as: {@link #log(Level, String) Logw.log(Level.INFO, message)}
*/
public static void info(String message) {
Logw.log(Level.INFO, message);
}
/**
* <p>Logs a message, compiled from message pattern and the parameters, with {@link Level#INFO}.</p>
* Same as: {@link #log(Level, String, Object...)} Logw.log(Level.INFO, messagePattern, parameters)}
*/
public static void info(String messagePattern, Object... parameters) {
Logw.log(Level.INFO, messagePattern, parameters);
}
public static void info(String messagePattern, Supplier<Object>... arguments) {
Logw.log(Level.INFO, messagePattern, arguments);
}
/**
* <p>Logs a simple log message with {@link Level#INFO} to the logger with the given name.</p>
* Same as: {@link #log(String, Level, String) Logw.log(loggerName, Level.INFO, message)}
*/
public static void info(String loggerName, String message) {
Logw.log(loggerName, Level.INFO, message);
}
/**
* <p>Logs a message, compiled from message pattern and the parameters, with {@link Level#INFO} to the logger with the given name.</p>
* Same as: {@link #log(String, Level, String, Object...)} Logw.log(loggerName, Level.INFO, messagePattern, parameters)}
*/
public static void info(String loggerName, String messagePattern, Object... parameters) {
Logw.log(loggerName, Level.INFO, messagePattern, parameters);
}
public static void info(String loggerName, String messagePattern, Supplier<Object>... arguments) {
Logw.log(loggerName, Level.INFO, messagePattern, arguments);
}
/**
* <p>Logs a simple log message with {@link Level#WARN}.</p>
* Same as: {@link #log(Level, String) Logw.log(Level.WARN, message)}
*/
public static void warn(String message) {
Logw.log(Level.WARN, message);
}
/**
* <p>Logs a message, compiled from message pattern and the parameters, with {@link Level#WARN}.</p>
* Same as: {@link #log(Level, String, Object...)} Logw.log(Level.WARN, messagePattern, parameters)}
*/
public static void warn(String messagePattern, Object... parameters) {
Logw.log(Level.WARN, messagePattern, parameters);
}
public static void warn(String messagePattern, Supplier<Object>... arguments) {
Logw.log(Level.WARN, messagePattern, arguments);
}
/**
* <p>Logs a simple log message with {@link Level#WARN} to the logger with the given name.</p>
* Same as: {@link #log(String, Level, String) Logw.log(loggerName, Level.WARN, message)}
*/
public static void warn(String loggerName, String message) {
Logw.log(loggerName, Level.WARN, message);
}
/**
* <p>Logs a message, compiled from message pattern and the parameters, with {@link Level#WARN} to the logger with the given name.</p>
* Same as: {@link #log(String, Level, String, Object...)} Logw.log(loggerName, Level.WARN, messagePattern, parameters)}
*/
public static void warn(String loggerName, String messagePattern, Object... parameters) {
Logw.log(loggerName, Level.WARN, messagePattern, parameters);
}
public static void warn(String loggerName, String messagePattern, Supplier<Object>... arguments) {
Logw.log(loggerName, Level.WARN, messagePattern, arguments);
}
/**
* <p>Logs a simple log message with {@link Level#ERROR}.</p>
* Same as: {@link #log(Level, String) Logw.log(Level.ERROR, message)}
*/
public static void error(String message) {
Logw.log(Level.ERROR, message);
}
/**
* <p>Logs a message, compiled from message pattern and the parameters, with {@link Level#ERROR}.</p>
* Same as: {@link #log(Level, String, Object...)} Logw.log(Level.ERROR, messagePattern, parameters)}
*/
public static void error(String messagePattern, Object... parameters) {
Logw.log(Level.ERROR, messagePattern, parameters);
}
public static void error(String messagePattern, Supplier<Object>... arguments) {
Logw.log(Level.ERROR, messagePattern, arguments);
}
/**
* <p>Logs a simple log message with {@link Level#ERROR} to the logger with the given name.</p>
* Same as: {@link #log(String, Level, String) Logw.log(loggerName, Level.ERROR, message)}
*/
public static void error(String loggerName, String message) {
Logw.log(loggerName, Level.ERROR, message);
}
/**
* <p>Logs a message, compiled from message pattern and the parameters, with {@link Level#ERROR} to the logger with the given name.</p>
* Same as: {@link #log(String, Level, String, Object...)} Logw.log(loggerName, Level.ERROR, messagePattern, parameters)}
*/
public static void error(String loggerName, String messagePattern, Object... parameters) {
Logw.log(loggerName, Level.ERROR, messagePattern, parameters);
}
public static void error(String loggerName, String messagePattern, Supplier<Object>... arguments) {
Logw.log(loggerName, Level.ERROR, messagePattern, arguments);
}
public static void log(Level level, String message) {
String loggerName = NameDiscoverer.discoverer();
Logw.log(loggerName, level, message);
}
public static void log(Level level, String messagePattern, Object... parameters) {
String loggerName = NameDiscoverer.discoverer();
Logw.log(loggerName, level, messagePattern, parameters);
}
public static void log(Level level, String messagePattern, Supplier<Object>... arguments) {
String loggerName = NameDiscoverer.discoverer();
Logw.log(loggerName, level, messagePattern, arguments);
}
public static void log(String loggerName, Level level, String message) {
if(!logger.isLoggable(loggerName, level))
return;
logger.log(loggerName, level, message);
}
public static void log(String loggerName, Level level, String messagePattern, Object... parameters){
if(!logger.isLoggable(loggerName, level))
return;
logger.log(loggerName, level, MessageFormatter.format(messagePattern, parameters));
}
public static void log(String loggerName, Level level, String messagePattern, Supplier<Object>... arguments){
if(!logger.isLoggable(loggerName, level))
return;
Object[] args = new Object[arguments.length];
for(int i = 0; i < arguments.length; i++){
args[i] = arguments[i].get();
}
logger.log(loggerName, level, MessageFormatter.format(messagePattern, args));
}
}
|
package org.spin.mhive;
import org.fmod.FMODAudioDevice;
import org.spin.mhive.replay.HapticNote;
import org.spin.mhive.replay.HapticNoteRecord;
import org.spin.mhive.replay.HapticNoteRecordADSR;
import org.spin.mhive.replay.HapticNoteRecordEnableADSR;
import org.spin.mhive.replay.HapticNoteRecordPlay;
import org.spin.mhive.replay.HapticNoteRecordStop;
import org.spin.mhive.replay.HapticNoteRecordVisualPoint;
import org.spin.mhive.replay.HapticNoteRecordWaveform;
import android.R;
import android.os.Environment;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.lang.UnsupportedOperationException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Observable;
//Handles audio generation for mHIVE
public class HIVEAudioGenerator extends Observable
{
//log to file?
private final boolean LOGGING = true;
private long LOG_START_TIME = 0;
private PrintWriter outWriter;
private FMODAudioDevice mFMODAudioDevice = new FMODAudioDevice();
//These are integers for tighter integration with JNI
//ENUM would be better, but unfortunately
public static final int OSCILLATOR_SINE = 0;
public static final int OSCILLATOR_SQUARE = 1;
public static final int OSCILLATOR_SAWUP = 2;
public static final int OSCILLATOR_TRIANGLE = 4;
private int currentWaveform = OSCILLATOR_SINE;
private final float[] waveformScaleFactor = {0.8f, 0.1f, 0.1f, 0.0f, 1.0f}; //balancing overall output
private boolean initiated = false;
private boolean playing = false;
public final String TAG = "HIVEAudioGenerator";
ADSREnvelope currentADSREnvelope;
ReplayThread replayThread;
private boolean currentlyRecording = false;
private HapticNote recordingNote;
private long previousRecordTime = 0L;
VisualTraceView visualTraceView;
ADSRView adsrView;
static {
System.loadLibrary("fmodex");
System.loadLibrary("main");
}
public void setWaveform(int waveform)
{
if( waveform == OSCILLATOR_SINE
|| waveform == OSCILLATOR_SQUARE
|| waveform == OSCILLATOR_SAWUP
|| waveform == OSCILLATOR_TRIANGLE)
{
currentWaveform = waveform;
cSetWaveform(currentWaveform);
cSetChannelVolume(0);
if(currentlyRecording)
{
long currentTime = System.currentTimeMillis();
recordingNote.AddRecord(new HapticNoteRecordWaveform(currentTime - previousRecordTime, waveform));
previousRecordTime = currentTime;
}
setChanged();
notifyObservers();
}
Log("SETWAVEFORM", new String[] {getCurrentWaveformName()});
}
public int getCurrentWaveform()
{
return currentWaveform;
}
public String getCurrentWaveformName()
{
//TODO: Access resources for this
switch(currentWaveform)
{
case OSCILLATOR_SINE:
return "Sine";
case OSCILLATOR_SQUARE:
return "Square";
case OSCILLATOR_SAWUP:
return "SawUp";
case OSCILLATOR_TRIANGLE:
return "Triangle";
}
return "Error - unsupported waveform for waveform "+currentWaveform;
}
public HIVEAudioGenerator()
{
if(LOGGING)
{
SetupLogging();
}
initiated = true;
mFMODAudioDevice.start();
cBegin();
cSetWaveform(currentWaveform);
cSetChannelVolume(0);
SetADSR(new ADSREnvelope(100, 100, 0.5f, 300));
EnableADSR();
}
private void SetupLogging()
{
//set up output file (comma separated value text file)
//date formats for directory and file name
//file will have the day, hour, minute, and second as part of the file name
DateFormat dateFormat = new SimpleDateFormat("yyyyMMMdd-hh-mm-ss");
Date date = new Date();
//set up the file name
String fileString = "mHIVE_"+dateFormat.format(date)+".csv";
//create directory
File d = new File(Environment.getExternalStorageDirectory() + "/" + "mHIVE");
if(!d.exists())
{
d.mkdirs();
}
File f = new File(Environment.getExternalStorageDirectory() + "/" + "mHIVE" + "/" + fileString);
try {
outWriter = new PrintWriter(f);
LOG_START_TIME = System.currentTimeMillis();
outWriter.println("START,"+LOG_START_TIME);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void Log(String cmd) {Log(cmd, null);}
private void Log(String cmd, String[] args)
{
if (LOGGING)
{
long t = System.currentTimeMillis() - LOG_START_TIME;
String logString = ""+t+","+cmd;
if (args != null)
{
for (String arg : args)
{
logString = logString + "," + arg;
}
}
outWriter.println(logString);
outWriter.flush();
}
}
public void SetVisualTraceView(VisualTraceView vtv)
{
visualTraceView = vtv;
}
public void SetADSRView(ADSRView adsrView)
{
this.adsrView = adsrView;
}
public VisualTraceView GetVisualTraceView()
{
return visualTraceView;
}
public void ReplayVisualPoint(HapticNoteRecordVisualPoint vp)
{
if (visualTraceView != null)
{
visualTraceView.GetUIHandler().post(vp);
}
if (currentlyRecording)
{
long currentTime = System.currentTimeMillis();
recordingNote.AddRecord(new HapticNoteRecordVisualPoint(currentTime - previousRecordTime, vp.getX(), vp.getY()));
previousRecordTime = currentTime;
}
}
public void Play(int freq, float atten)
{
if(!playing)
{
playing = true;
cNoteOn();
if(adsrView != null)
{
adsrView.NoteOn();
}
}
cSetChannelFrequency(freq);
cSetChannelVolume(atten*waveformScaleFactor[currentWaveform]);
if(currentlyRecording)
{
long currentTime = System.currentTimeMillis();
recordingNote.AddRecord(new HapticNoteRecordPlay(currentTime - previousRecordTime, atten, freq));
previousRecordTime = currentTime;
}
Log("PLAY", new String[] {""+freq, ""+atten});
}
public void Play(int freq, float atten, float x, float y)
{
Play(freq, atten);
if(currentlyRecording)
{
long currentTime = System.currentTimeMillis();
recordingNote.AddRecord(new HapticNoteRecordVisualPoint(currentTime - previousRecordTime, x, y));
previousRecordTime = currentTime;
}
}
public void Stop()
{
if(playing)
{
//cSetChannelVolume(0);
playing = false;
cNoteOff();
if(adsrView != null)
{
adsrView.NoteOff();
}
}
if(currentlyRecording)
{
long currentTime = System.currentTimeMillis();
recordingNote.AddRecord(new HapticNoteRecordStop(currentTime - previousRecordTime));
previousRecordTime = currentTime;
}
Log("STOP");
}
public void Close()
{
Stop();
cEnd();
mFMODAudioDevice.stop();
}
/*
*REPLAYING METHODS AND CLASSES
*/
public void StartRecording()
{
recordingNote = HapticNote.NewIncrementedHapticNote("Recording ", GetADSR(), getCurrentWaveform(), cGetADSREnabled());
previousRecordTime = System.currentTimeMillis();
currentlyRecording = true;
}
public HapticNote StopRecording()
{
currentlyRecording = false;
return recordingNote;
}
public void Replay(HapticNote hapticNote)
{
//if(!currentlyRecording)
StopReplay();
replayThread = new ReplayThread(this, hapticNote);
replayThread.start();
Log("REPLAY");
}
public void StopReplay()
{
if(null != replayThread)
{
replayThread.stopPlaying();
}
Log("STOPREPLAY");
}
class ReplayThread extends Thread
{
HapticNote hapticNote;
HIVEAudioGenerator parent;
boolean running = true;
public ReplayThread(HIVEAudioGenerator parent, HapticNote hapticNote)
{
this.parent = parent;
this.hapticNote = hapticNote;
}
@Override
public void run()
{
Stop();
for (HapticNoteRecord hnr : hapticNote)
{
try {
sleep(hnr.dt);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
hnr.PerformAction(parent);
if(!running)
{
break; //TODO: break should probably be reworked
}
}
Stop();
}
public void stopPlaying()
{
running = false;
}
}
/**
* ADSR STUB METHODS
*/
public void EnableADSR() {EnableADSR(true);}
public void DisableADSR() {EnableADSR(false);}
public void EnableADSR(boolean b)
{
if (b != GetADSREnabled())
{
setChanged();
cSetADSREnabled(b);
}
if(currentlyRecording)
{
long currentTime = System.currentTimeMillis();
recordingNote.AddRecord(new HapticNoteRecordEnableADSR(currentTime - previousRecordTime, b));
previousRecordTime = currentTime;
}
Log("ENABLEADSR", new String[] {""+b});
notifyObservers();
}
public boolean GetADSREnabled()
{
return cGetADSREnabled();
}
public void SetADSR(ADSREnvelope envelope)
{
if (envelope != currentADSREnvelope && envelope != null)
{
currentADSREnvelope = envelope;
cSetADSR(currentADSREnvelope.getAttack(), currentADSREnvelope.getDecay(), currentADSREnvelope.getSustain(), currentADSREnvelope.getRelease());
if(currentlyRecording)
{
long currentTime = System.currentTimeMillis();
recordingNote.AddRecord(new HapticNoteRecordADSR(currentTime - previousRecordTime, currentADSREnvelope));
previousRecordTime = currentTime;
}
setChanged();
notifyObservers();
Log("SETADSR", currentADSREnvelope.GetStringArray());
}
}
public ADSREnvelope GetADSR()
{
return currentADSREnvelope;
}
/**
* Native Methods
*/
//Fundamentals
public native void cBegin();
public native void cUpdate();
public native void cEnd();
//Basic controls
public native void cSetWaveform(int waveform);
public native boolean cGetIsChannelPlaying();
public native float cGetChannelFrequency();
public native float cGetChannelVolume();
public native float cGetChannelPan();
public native void cSetChannelFrequency(float frequency);
public native void cSetChannelVolume(float volume);
public native void cSetChannelPan(float pan);
//ADSR and note handling
public native void cNoteOn();
public native void cNoteOff();
public native void cSetADSR(int attack, int decay, float sustain, int release);
public native void cSetADSREnabled(boolean b);
public native boolean cGetADSREnabled();
public native int cGetADSRAttack();
public native int cGetADSRDecay();
public native float cGetADSRSustain();
public native int cGetADSRRelease();
}
|
/*
Implement the postorder method in BST using a stack instead of recursion.
Write a test program that prompts the user to enter 10 integers, stores them
in a BST, and invokes the postorder method to display the elements.
*/
import java.util.Scanner;
public class E25_05 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter 10 integers: ");
Integer[] list = new Integer[10];
for (int i = 0; i < list.length; i++) {
list[i] = input.nextInt();
}
BST<Integer> tree = new BST<>(list);
tree.postorder();
System.out.println();
}
}
|
package org.freedesktop.dbus.spi;
import java.io.EOFException;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import org.freedesktop.dbus.exceptions.DBusException;
import org.freedesktop.dbus.exceptions.MessageProtocolVersionException;
import org.freedesktop.dbus.messages.Message;
import org.freedesktop.dbus.messages.MessageFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class InputStreamMessageReader implements IMessageReader {
private final Logger logger = LoggerFactory.getLogger(getClass());
private SocketChannel inputChannel;
private byte[] buf;
private byte[] tbuf;
private byte[] header;
private byte[] body;
private int[] len;
public InputStreamMessageReader(SocketChannel _in) {
inputChannel = _in;
len = new int[4];
}
@Override
public Message readMessage() throws IOException, DBusException {
int rv;
if (null == buf) {
buf = new byte[12];
len[0] = 0;
}
/* Read the 12 byte fixed header, retrying as necessary */
if (len[0] < 12) {
try {
ByteBuffer wrapBuf = ByteBuffer.wrap(buf, len[0], 12 - len[0]);
rv = inputChannel.read(wrapBuf);
} catch (SocketTimeoutException exSt) {
return null;
} catch (EOFException _ex) {
return null;
} catch (IOException _ex) {
throw _ex;
}
if (-1 == rv) {
throw new EOFException("Underlying transport returned EOF (1)");
}
len[0] += rv;
}
if (len[0] == 0) {
return null;
}
if (len[0] < 12) {
logger.debug("Only got {} of 12 bytes of header", len[0]);
return null;
}
/* Parse the details from the header */
byte endian = buf[0];
byte type = buf[1];
byte protover = buf[3];
if (protover > Message.PROTOCOL) {
throw new MessageProtocolVersionException(String.format("Protocol version %s is unsupported", protover));
}
/* Read the length of the variable header */
if (null == tbuf) {
tbuf = new byte[4];
len[1] = 0;
}
if (len[1] < 4) {
try {
ByteBuffer wrapTBuf = ByteBuffer.wrap(tbuf, len[1], 4 - len[1]);
rv = inputChannel.read(wrapTBuf);
} catch (SocketTimeoutException exSt) {
return null;
}
if (-1 == rv) {
throw new EOFException("Underlying transport returned EOF (2)");
}
len[1] += rv;
}
if (len[1] < 4) {
logger.debug("Only got {} of 4 bytes of header", len[1]);
return null;
}
/* Parse the variable header length */
int headerlen = 0;
if (null == header) {
headerlen = (int) Message.demarshallint(tbuf, 0, endian, 4);
if (0 != headerlen % 8) {
headerlen += 8 - (headerlen % 8);
}
} else {
headerlen = header.length - 8;
}
/* Read the variable header */
if (null == header) {
header = new byte[headerlen + 8];
System.arraycopy(tbuf, 0, header, 0, 4);
len[2] = 0;
}
if (len[2] < headerlen) {
try {
ByteBuffer wrapHeader = ByteBuffer.wrap(header, 8 + len[2], headerlen - len[2]);
rv = inputChannel.read(wrapHeader);
} catch (SocketTimeoutException exSt) {
return null;
}
if (-1 == rv) {
throw new EOFException("Underlying transport returned EOF (3)");
}
len[2] += rv;
}
if (len[2] < headerlen) {
logger.debug("Only got {} of {} bytes of header", len[2], headerlen);
return null;
}
/* Read the body */
int bodylen = 0;
if (null == body) {
bodylen = (int) Message.demarshallint(buf, 4, endian, 4);
}
if (null == body) {
body = new byte[bodylen];
len[3] = 0;
}
if (len[3] < body.length) {
try {
ByteBuffer wrapBody = ByteBuffer.wrap(body, len[3], body.length - len[3]);
rv = inputChannel.read(wrapBody);
} catch (SocketTimeoutException exSt) {
return null;
}
if (-1 == rv) {
throw new EOFException("Underlying transport returned EOF (4)");
}
len[3] += rv;
}
if (len[3] < body.length) {
logger.debug("Only got {} of {} bytes of body", len[3], body.length);
return null;
}
Message m;
try {
m = MessageFactory.createMessage(type, buf, header, body, null);
} catch (DBusException dbe) {
logger.debug("", dbe);
tbuf = null;
body = null;
header = null;
buf = null;
throw dbe;
} catch (RuntimeException exRe) { // this really smells badly!
logger.debug("", exRe);
tbuf = null;
body = null;
header = null;
buf = null;
throw exRe;
}
logger.debug("=> {}", m);
tbuf = null;
body = null;
header = null;
buf = null;
return m;
}
@Override
public void close() throws IOException {
logger.trace("Closing Message Reader");
if (inputChannel != null) {
inputChannel.close();
}
inputChannel = null;
}
@Override
public boolean isClosed() {
return inputChannel == null;
}
}
|
package com.backtype.cascading.tap;
import java.io.IOException;
import java.io.Serializable;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.FileInputFormat;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.OutputCollector;
import org.apache.hadoop.mapred.RecordReader;
import org.apache.log4j.Logger;
import com.backtype.hadoop.pail.BinaryPailStructure;
import com.backtype.hadoop.pail.DefaultPailStructure;
import com.backtype.hadoop.pail.Pail;
import com.backtype.hadoop.pail.PailFormatFactory;
import com.backtype.hadoop.pail.PailOutputFormat;
import com.backtype.hadoop.pail.PailPathLister;
import com.backtype.hadoop.pail.PailSpec;
import com.backtype.hadoop.pail.PailStructure;
import com.backtype.support.Utils;
import cascading.flow.FlowProcess;
import cascading.scheme.Scheme;
import cascading.scheme.SinkCall;
import cascading.scheme.SourceCall;
import cascading.tap.Tap;
import cascading.tap.TapException;
import cascading.tap.hadoop.Hfs;
import cascading.tuple.Fields;
import cascading.tuple.Tuple;
import cascading.tuple.TupleEntry;
import cascading.tuple.hadoop.TupleSerialization;
public class PailTap extends Hfs {
private static Logger LOG = Logger.getLogger(PailTap.class);
public static PailSpec makeSpec(PailSpec given, PailStructure structure) {
return (given == null) ? PailFormatFactory.getDefaultCopy().setStructure(structure) :
given.setStructure(structure);
}
public static class PailTapOptions implements Serializable {
public PailSpec spec = null;
public String fieldName = "bytes";
public List<String>[] attrs = null;
public PailPathLister lister = null;
public PailTapOptions() {
}
public PailTapOptions(PailSpec spec, String fieldName, List<String>[] attrs,
PailPathLister lister) {
this.spec = spec;
this.fieldName = fieldName;
this.attrs = attrs;
this.lister = lister;
}
}
public class PailScheme
extends Scheme<JobConf, RecordReader, OutputCollector, Object[], Object[]> {
private PailTapOptions _options;
public PailScheme(PailTapOptions options) {
super(new Fields("pail_root", options.fieldName), Fields.ALL);
_options = options;
}
public PailSpec getSpec() {
return _options.spec;
}
private transient BytesWritable bw;
private transient Text keyW;
protected Object deserialize(BytesWritable record) {
PailStructure structure = getStructure();
if (structure instanceof BinaryPailStructure) {
return record;
} else {
return structure.deserialize(Utils.getBytes(record));
}
}
protected void serialize(Object obj, BytesWritable ret) {
if (obj instanceof BytesWritable) {
ret.set((BytesWritable) obj);
} else {
byte[] b = getStructure().serialize(obj);
ret.set(b, 0, b.length);
}
}
private transient PailStructure _structure;
public PailStructure getStructure() {
if (_structure == null) {
if (getSpec() == null) {
_structure = PailFormatFactory.getDefaultCopy().getStructure();
} else {
_structure = getSpec().getStructure();
}
}
return _structure;
}
@Override
public void sourceConfInit(FlowProcess<JobConf> process,
Tap<JobConf, RecordReader, OutputCollector> tap, JobConf conf) {
Pail p;
try {
p = new Pail(_pailRoot); //make sure it exists
} catch (IOException e) {
throw new TapException(e);
}
conf.setInputFormat(p.getFormat().getInputFormatClass());
PailFormatFactory.setPailPathLister(conf, _options.lister);
}
@Override public void sinkConfInit(FlowProcess<JobConf> flowProcess,
Tap<JobConf, RecordReader, OutputCollector> tap, JobConf conf) {
conf.setOutputFormat(PailOutputFormat.class);
Utils.setObject(conf, PailOutputFormat.SPEC_ARG, getSpec());
try {
Pail.create(getFileSystem(conf), _pailRoot, getSpec(), true);
} catch (IOException e) {
throw new TapException(e);
}
}
@Override
public void sourcePrepare(FlowProcess<JobConf> flowProcess,
SourceCall<Object[], RecordReader> sourceCall) {
sourceCall.setContext(new Object[2]);
sourceCall.getContext()[0] = sourceCall.getInput().createKey();
sourceCall.getContext()[1] = sourceCall.getInput().createValue();
}
@Override
public boolean source(FlowProcess<JobConf> process,
SourceCall<Object[], RecordReader> sourceCall) throws IOException {
Object k = sourceCall.getContext()[0];
Object v = sourceCall.getContext()[1];
boolean result = sourceCall.getInput().next(k, v);
if (!result) { return false; }
String relPath = ((Text) k).toString();
Object value = deserialize((BytesWritable) v);
sourceCall.getIncomingEntry().setTuple(new Tuple(relPath, value));
return true;
}
@Override
public void sink(FlowProcess<JobConf> process, SinkCall<Object[], OutputCollector> sinkCall)
throws IOException {
TupleEntry tuple = sinkCall.getOutgoingEntry();
Object obj = tuple.getObject(0);
String key;
//a hack since byte[] isn't natively handled by hadoop
if (getStructure() instanceof DefaultPailStructure) {
key = getCategory(obj);
} else {
key = Utils.join(getStructure().getTarget(obj), "/") + getCategory(obj);
}
if (bw == null) { bw = new BytesWritable(); }
if (keyW == null) { keyW = new Text(); }
serialize(obj, bw);
keyW.set(key);
sinkCall.getOutput().collect(keyW, bw);
}
}
private String _pailRoot;
private PailTapOptions _options;
protected String getCategory(Object obj) {
return "";
}
public PailTap(String root, PailTapOptions options) {
_options = options;
setStringPath(root);
setScheme(new PailScheme(options));
_pailRoot = root;
}
public PailTap(String root) {
this(root, new PailTapOptions());
}
@Override
public String getIdentifier() {
if (_options.attrs != null && _options.attrs.length > 0) {
String rel = "";
for (List<String> attr : _options.attrs) {
rel += Utils.join(attr, Path.SEPARATOR);
}
return getPath().toString() + Path.SEPARATOR + rel;
} else {
return getPath().toString();
}
}
@Override
public long getModifiedTime(JobConf conf) throws IOException {
// TODO: We should either set sinkMode.REPLACE or return something real here when used as a source.
return 0;
}
@Override
public boolean deleteResource(JobConf conf) throws IOException {
throw new UnsupportedOperationException();
}
//no good way to override this, just had to copy/paste and modify
@Override
public void sourceConfInit(FlowProcess<JobConf> process, JobConf conf) {
try {
Path root = getQualifiedPath(conf);
if (_options.attrs != null && _options.attrs.length > 0) {
Pail pail = new Pail(_pailRoot);
for (List<String> attr : _options.attrs) {
String rel = Utils.join(attr, "/");
pail.getSubPail(rel); //ensure the path exists
Path toAdd = new Path(root, rel);
LOG.info("Adding input path " + toAdd.toString());
FileInputFormat.addInputPath(conf, toAdd);
}
} else {
FileInputFormat.addInputPath(conf, root);
}
getScheme().sourceConfInit(process, this, conf);
makeLocal(conf, getQualifiedPath(conf), "forcing job to local mode, via source: ");
TupleSerialization.setSerializations(conf);
} catch (IOException e) {
throw new TapException(e);
}
}
private void makeLocal(JobConf conf, Path qualifiedPath, String infoMessage) {
if (!conf.get("mapred.job.tracker", "").equalsIgnoreCase("local") && qualifiedPath.toUri()
.getScheme().equalsIgnoreCase("file")) {
if (LOG.isInfoEnabled()) { LOG.info(infoMessage + toString()); }
conf.set("mapred.job.tracker", "local"); // force job to run locally
}
}
@Override
public void sinkConfInit(FlowProcess<JobConf> process, JobConf conf) {
if (_options.attrs != null && _options.attrs.length > 0) {
throw new TapException("can't declare attributes in a sink");
}
super.sinkConfInit(process, conf);
}
@Override
public boolean commitResource(JobConf conf) throws IOException {
Pail p = Pail.create(_pailRoot, ((PailScheme) getScheme()).getSpec(), false);
FileSystem fs = p.getFileSystem();
Path tmpPath = new Path(_pailRoot, "_temporary");
if (fs.exists(tmpPath)) {
LOG.info("Deleting _temporary directory left by Hadoop job: " + tmpPath.toString());
fs.delete(tmpPath, true);
}
Path tmp2Path = new Path(_pailRoot, "_temporary2");
if (fs.exists(tmp2Path)) {
LOG.info("Deleting _temporary2 directory: " + tmp2Path.toString());
fs.delete(tmp2Path, true);
}
Path logPath = new Path(_pailRoot, "_logs");
if (fs.exists(logPath)) {
LOG.info("Deleting _logs directory left by Hadoop job: " + logPath.toString());
fs.delete(logPath, true);
}
return true;
}
@Override
public int hashCode() {
return _pailRoot.hashCode();
}
@Override
public boolean equals(Object object) {
if (!getClass().equals(object.getClass())) {
return false;
}
PailTap other = (PailTap) object;
Set<List<String>> myattrs = new HashSet<List<String>>();
if (_options.attrs != null) {
Collections.addAll(myattrs, _options.attrs);
}
Set<List<String>> otherattrs = new HashSet<List<String>>();
if (other._options.attrs != null) {
Collections.addAll(otherattrs, other._options.attrs);
}
return _pailRoot.equals(other._pailRoot) && myattrs.equals(otherattrs);
}
private Path getQualifiedPath(JobConf conf) throws IOException {
return getPath().makeQualified(getFileSystem(conf));
}
}
|
package androidemu.app;
import androidemu.Res;
import androidemu.content.Context;
import androidemu.content.Intent;
import androidemu.os.Bundle;
import androidemu.view.Menu;
import androidemu.view.MenuItem;
import androidemu.view.View;
import androidemu.view.ViewFactory;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.resources.client.TextResource;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Widget;
public class Activity extends Context implements EntryPoint {
public static final String TAG = "Activity";
public static final int RESULT_CANCELED = 0;
public static final int RESULT_FIRST_USER = 1;
public static final int RESULT_OK = -1;
public static final String ACTIVITY_ID = "activity";
int status = 0;
int targetStatus = 0;
String title;
Menu menu;
Widget contentPanel;
private PopupPanel menuPanel;
Integer requestCode;
int resultCode = RESULT_OK;
Intent resultData;
// Data when we return from another activity
Integer returnRequestCode;
int returnResultCode;
Intent returnResultData;
public void onModuleLoad() {
Res.R.style().ensureInjected();
ActivityManager.setup();
startActivity(new Intent(this, this));
}
protected void onCreate(Bundle savedInstanceState) {
}
protected void onResume() {
if (contentPanel != null) {
contentPanel.setVisible(true);
}
}
protected void onPause() {
if (contentPanel != null) {
contentPanel.setVisible(false);
}
}
protected void onDestroy() {
if (contentPanel != null) {
RootPanel.get(ACTIVITY_ID).remove(contentPanel);
}
}
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
return true;
}
void createMenu() {
if (menu == null) {
menu = new Menu();
onCreateOptionsMenu(menu);
if (menu.menuItems.size() > 0) {
menuPanel = new PopupPanel();
menuPanel.setStyleName(Res.R.style().dialog());
FlowPanel fp = new FlowPanel();
for (final MenuItem item : menu.menuItems) {
Button b = new Button();
b.setText(item.getTitle());
b.setStyleName(Res.R.style().menuItem());
b.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
hideMenu();
onOptionsItemSelected(item);
}
});
fp.add(b);
}
menuPanel.setWidget(fp);
menuPanel.setAutoHideEnabled(true);
}
}
}
void hideMenu() {
if (menuPanel != null && menuPanel.isShowing()) {
menuPanel.hide();
}
}
public void openOptionsMenu() {
if (menuPanel != null) {
menuPanel.center();
menuPanel.show();
}
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Context getApplicationContext() {
// not very correct, but it's a context and at the moment we do not
// differentiate among contexts
return this;
}
public void finish() {
ActivityManager.finish(this);
}
public void setContentView(TextResource content) {
contentPanel = new HTMLPanel(content.getText());
RootPanel.get(ACTIVITY_ID).add(contentPanel);
}
public void setContentView(Widget htmlPanel) {
contentPanel = htmlPanel;
RootPanel.get(ACTIVITY_ID).add(contentPanel);
}
protected void onSaveInstanceState(Bundle outState) {
}
public void startActivityForResult(Intent intent, int requestCode) {
ActivityManager.startActivity(intent, requestCode);
}
public void setResult(int resultCode, Intent resultData) {
this.resultCode = resultCode;
this.resultData = resultData;
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
}
public void onBackPressed() {
}
public View findViewById(String id) {
return ViewFactory.findViewById(contentPanel.getElement(), id);
}
public Intent getIntent() {
return null;
}
}
|
package androidemu.widget;
import androidemu.Res;
import androidemu.content.Context;
import androidemu.view.Gravity;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.PopupPanel;
public class Toast {
public final static int LENGTH_LONG = 1;
public final static int LENGTH_SHORT = 0;
String message;
int gravity;
int duration;
public static Toast makeText(Context context, String message, int duration) {
Toast toast = new Toast();
toast.setMessage(message);
toast.setDuration(duration);
return toast;
}
public void show() {
final PopupPanel panel = new PopupPanel();
panel.setStyleName(Res.R.style().toast());
HTML label = new HTML(message.replace("\n", "<br/>"));
panel.setWidget(label);
panel.setPopupPositionAndShow(new PopupPanel.PositionCallback() {
public void setPosition(int offsetWidth, int offsetHeight) {
int left = (Window.getClientWidth() - offsetWidth) / 2;
int top = 0;
switch (gravity) {
case Gravity.TOP:
top = (Window.getClientHeight() - offsetHeight) / 10;
break;
case Gravity.CENTER:
top = (Window.getClientHeight() - offsetHeight) / 2;
break;
}
panel.setPopupPosition(left, top);
}
});
// Create a new timer that calls Window.alert().
Timer t = new Timer() {
public void run() {
panel.hide();
}
};
if (duration == LENGTH_SHORT) {
t.schedule(1000);
} else {
t.schedule(2000);
}
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public int getDuration() {
return duration;
}
public void setDuration(int duration) {
this.duration = duration;
}
public void setGravity(int gravity) {
this.gravity = gravity;
}
public int getGravity() {
return gravity;
}
public void setGravity(int gravity, int xOffset, int yOffset) {
this.gravity = gravity;
}
}
|
//-*-Mode:java;coding:utf-8;tab-width:4;c-basic-offset:4;indent-tabs-mode:()-*-
// ex: set ft=java fenc=utf-8 sts=4 ts=4 sw=4 et nomod:
// modification, are permitted provided that the following conditions are met:
// the documentation and/or other materials provided with the
// distribution.
// * All advertising materials mentioning features or use of this
// software must display the following acknowledgment:
// This product includes software developed by Michael Truog
// * The name of the author may not be used to endorse or promote
// products derived from this software without specific prior
// CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
package org.cloudi;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.LinkedList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.UUID;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.BufferUnderflowException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.Math;
import java.lang.Thread;
import com.ericsson.otp.erlang.OtpExternal;
import com.ericsson.otp.erlang.OtpOutputStream;
import com.ericsson.otp.erlang.OtpInputStream;
import com.ericsson.otp.erlang.OtpErlangDecodeException;
import com.ericsson.otp.erlang.OtpErlangRangeException;
import com.ericsson.otp.erlang.OtpErlangObject;
import com.ericsson.otp.erlang.OtpErlangAtom;
import com.ericsson.otp.erlang.OtpErlangPid;
import com.ericsson.otp.erlang.OtpErlangString;
import com.ericsson.otp.erlang.OtpErlangBinary;
import com.ericsson.otp.erlang.OtpErlangUInt;
import com.ericsson.otp.erlang.OtpErlangInt;
import com.ericsson.otp.erlang.OtpErlangTuple;
public class API
{
// unbuffered output is with API.err.format(), etc.
private static PrintStream unbuffered(final PrintStream stream)
{
try
{
return new PrintStream(stream, true, "UTF-8");
}
catch (UnsupportedEncodingException e)
{
return new PrintStream(stream, true);
}
}
public static final PrintStream out = unbuffered(System.out);
public static final PrintStream err = unbuffered(System.err);
public static final int ASYNC = 1;
public static final int SYNC = -1;
private static final int MESSAGE_INIT = 1;
private static final int MESSAGE_SEND_ASYNC = 2;
private static final int MESSAGE_SEND_SYNC = 3;
private static final int MESSAGE_RECV_ASYNC = 4;
private static final int MESSAGE_RETURN_ASYNC = 5;
private static final int MESSAGE_RETURN_SYNC = 6;
private static final int MESSAGE_RETURNS_ASYNC = 7;
private static final int MESSAGE_KEEPALIVE = 8;
private static final int MESSAGE_REINIT = 9;
private static final int MESSAGE_SUBSCRIBE_COUNT = 10;
private static final int MESSAGE_TERM = 11;
private final FileDescriptor fd_in;
private final FileDescriptor fd_out;
private final boolean use_header;
private final FileOutputStream output;
private final FileInputStream input;
private final ExecutorService poll_timer_executor;
private boolean initialization_complete;
private boolean terminate;
private final HashMap<String, LinkedList<FunctionInterface9>> callbacks;
private final int buffer_size;
private long request_timer;
private Integer request_timeout;
private int process_index;
private int process_count;
private int process_count_max;
private int process_count_min;
private String prefix;
private int timeout_initialize;
private int timeout_async;
private int timeout_sync;
private int timeout_terminate;
private byte priority_default;
private boolean request_timeout_adjustment;
public API(final int thread_index)
throws InvalidInputException,
MessageDecodingException,
TerminateException
{
final String protocol = System.getenv("CLOUDI_API_INIT_PROTOCOL");
if (protocol == null)
throw new InvalidInputException();
final String buffer_size_str =
System.getenv("CLOUDI_API_INIT_BUFFER_SIZE");
if (buffer_size_str == null)
throw new InvalidInputException();
if (protocol.compareTo("tcp") == 0)
{
this.fd_in = this.fd_out = API.storeFD(thread_index + 3);
this.use_header = true;
}
else if (protocol.compareTo("udp") == 0)
{
this.fd_in = this.fd_out = API.storeFD(thread_index + 3);
this.use_header = false;
}
else if (protocol.compareTo("local") == 0)
{
this.fd_in = this.fd_out = API.storeFD(thread_index + 3);
this.use_header = true;
}
else
{
throw new InvalidInputException();
}
assert this.fd_in != null;
assert this.fd_out != null;
this.output = new FileOutputStream(this.fd_out);
this.input = new FileInputStream(this.fd_in);
this.poll_timer_executor = Executors.newFixedThreadPool(1);
this.initialization_complete = false;
this.terminate = false;
this.callbacks = new HashMap<String, LinkedList<FunctionInterface9>>();
this.buffer_size = Integer.parseInt(buffer_size_str);
this.process_index = 0;
this.process_count = 0;
this.process_count_max = 0;
this.process_count_min = 0;
this.timeout_initialize = 5000;
this.timeout_async = 5000;
this.timeout_sync = 5000;
this.timeout_terminate = 1000; // TIMEOUT_TERMINATE_MIN
this.priority_default = 0;
// send the initialization message to the managing Erlang process
OtpOutputStream init = new OtpOutputStream();
init.write(OtpExternal.versionTag);
init.write_any(new OtpErlangAtom("init"));
send(init);
poll_request(null, false);
}
/**
* @return the number of threads to create per operating system process
*/
public static int thread_count()
throws InvalidInputException
{
final String s = System.getenv("CLOUDI_API_INIT_THREAD_COUNT");
if (s == null)
throw new InvalidInputException();
final int thread_count = Integer.parseInt(s);
return thread_count;
}
/**
* Subscribes an object method to a service name pattern.
*
* @param pattern the service name pattern
* @param instance the object instance
* @param methodName the object method to handle matching requests
*/
public final void subscribe(final String pattern,
final Object instance,
final String methodName)
throws NoSuchMethodException
{
this.subscribe(pattern, new FunctionObject9(instance, methodName));
}
/**
* Subscribes an object method to a service name pattern.
*
* @param pattern the service name pattern
* @param callback method reference for callback (Java 8 or higher)
*/
public final void subscribe(final String pattern,
final FunctionInterface9 callback)
{
final String s = this.prefix + pattern;
LinkedList<FunctionInterface9> callback_list = this.callbacks.get(s);
if (callback_list == null)
{
callback_list = new LinkedList<FunctionInterface9>();
callback_list.addLast(callback);
this.callbacks.put(s, callback_list);
}
else
{
callback_list.addLast(callback);
}
OtpOutputStream subscribe = new OtpOutputStream();
subscribe.write(OtpExternal.versionTag);
final OtpErlangObject[] tuple = {new OtpErlangAtom("subscribe"),
new OtpErlangString(pattern)};
subscribe.write_any(new OtpErlangTuple(tuple));
send(subscribe);
}
/**
* Determine how may service name pattern subscriptions have occurred.
*
* @param pattern the service name pattern
*/
public int subscribe_count(final String pattern)
throws InvalidInputException,
MessageDecodingException,
TerminateException
{
OtpOutputStream subscribe_count = new OtpOutputStream();
subscribe_count.write(OtpExternal.versionTag);
final OtpErlangObject[] tuple = {new OtpErlangAtom("subscribe_count"),
new OtpErlangString(pattern)};
subscribe_count.write_any(new OtpErlangTuple(tuple));
send(subscribe_count);
try
{
return (Integer) poll_request(null, false);
}
catch (MessageDecodingException e)
{
e.printStackTrace(API.err);
return -1;
}
}
/**
* Unsubscribes from a service name pattern.
*
* @param pattern the service name pattern
*/
public final void unsubscribe(final String pattern)
throws InvalidInputException
{
final String s = this.prefix + pattern;
LinkedList<FunctionInterface9> callback_list = this.callbacks.get(s);
if (callback_list == null)
{
throw new InvalidInputException();
}
else
{
callback_list.removeFirst();
if (callback_list.isEmpty())
{
this.callbacks.remove(s);
}
}
OtpOutputStream unsubscribe = new OtpOutputStream();
unsubscribe.write(OtpExternal.versionTag);
final OtpErlangObject[] tuple = {new OtpErlangAtom("unsubscribe"),
new OtpErlangString(pattern)};
unsubscribe.write_any(new OtpErlangTuple(tuple));
send(unsubscribe);
}
/**
* Asynchronous point-to-point communication to a service
* subscribed that matches the destination service <code>name</code>.
*
* @param name the destination service name
* @param request the request data
* @return a transaction ID
*/
public TransId send_async(final String name,
final byte[] request)
throws InvalidInputException,
MessageDecodingException,
TerminateException
{
return send_async(name, ("").getBytes(), request,
this.timeout_async, this.priority_default);
}
/**
* Asynchronous point-to-point communication to a service
* subscribed that matches the destination service <code>name</code>.
*
* @param name the destination service name
* @param request_info any request metadata
* @param request the request data
* @param timeout the request timeout in milliseconds
* @param priority the request priority
* @return a transaction ID
*/
public TransId send_async(final String name,
final byte[] request_info,
final byte[] request,
final Integer timeout,
final Byte priority)
throws InvalidInputException,
MessageDecodingException,
TerminateException
{
try
{
OtpOutputStream send_async = new OtpOutputStream();
send_async.write(OtpExternal.versionTag);
final OtpErlangObject[] tuple = {new OtpErlangAtom("send_async"),
new OtpErlangString(name),
new OtpErlangBinary(request_info),
new OtpErlangBinary(request),
new OtpErlangUInt(timeout),
new OtpErlangInt(priority)};
send_async.write_any(new OtpErlangTuple(tuple));
send(send_async);
return (TransId) poll_request(null, false);
}
catch (OtpErlangRangeException e)
{
e.printStackTrace(API.err);
return null;
}
}
/**
* Synchronous point-to-point communication to a service
* subscribed that matches the destination service <code>name</code>.
*
* @param name the destination service name
* @param request the request data
* @return the response
*/
public Response send_sync(final String name,
final byte[] request)
throws InvalidInputException,
MessageDecodingException,
TerminateException
{
return send_sync(name, ("").getBytes(), request,
this.timeout_sync, this.priority_default);
}
/**
* Synchronous point-to-point communication to a service
* subscribed that matches the destination service <code>name</code>.
*
* @param name the destination service name
* @param request_info any request metadata
* @param request the request data
* @param timeout the request timeout in milliseconds
* @param priority the request priority
* @return the response
*/
public Response send_sync(final String name,
final byte[] request_info,
final byte[] request,
final Integer timeout,
final Byte priority)
throws InvalidInputException,
MessageDecodingException,
TerminateException
{
try
{
OtpOutputStream send_sync = new OtpOutputStream();
send_sync.write(OtpExternal.versionTag);
final OtpErlangObject[] tuple = {new OtpErlangAtom("send_sync"),
new OtpErlangString(name),
new OtpErlangBinary(request_info),
new OtpErlangBinary(request),
new OtpErlangUInt(timeout),
new OtpErlangInt(priority)};
send_sync.write_any(new OtpErlangTuple(tuple));
send(send_sync);
return (Response) poll_request(null, false);
}
catch (OtpErlangRangeException e)
{
e.printStackTrace(API.err);
return null;
}
}
/**
* Asynchronous point-multicast communication to services
* subscribed that matches the destination service <code>name</code>.
*
* @param name the destination service name
* @param request the request data
* @return transaction IDs
*/
public List<TransId> mcast_async(final String name,
final byte[] request)
throws InvalidInputException,
MessageDecodingException,
TerminateException
{
return mcast_async(name, new byte[0], request,
this.timeout_async, this.priority_default);
}
/**
* Asynchronous point-multicast communication to services
* subscribed that matches the destination service <code>name</code>.
*
* @param name the destination service name
* @param request_info any request metadata
* @param request the request data
* @param timeout the request timeout in milliseconds
* @param priority the priority of this request
* @return transaction IDs
*/
@SuppressWarnings("unchecked")
public List<TransId> mcast_async(final String name,
final byte[] request_info,
final byte[] request,
final Integer timeout,
final Byte priority)
throws InvalidInputException,
MessageDecodingException,
TerminateException
{
try
{
OtpOutputStream mcast_async = new OtpOutputStream();
mcast_async.write(OtpExternal.versionTag);
final OtpErlangObject[] tuple = {new OtpErlangAtom("mcast_async"),
new OtpErlangString(name),
new OtpErlangBinary(request_info),
new OtpErlangBinary(request),
new OtpErlangUInt(timeout),
new OtpErlangInt(priority)};
mcast_async.write_any(new OtpErlangTuple(tuple));
send(mcast_async);
return (List<TransId>) poll_request(null, false);
}
catch (OtpErlangRangeException e)
{
e.printStackTrace(API.err);
return null;
}
}
/**
* Forward a message to another service
* subscribed that matches the destination service <code>name</code>.
*
* @param command constant API.SYNC or API.ASYNC
* @param name the destination service name
* @param request_info any request metadata
* @param request the request data
* @param timeout the request timeout in milliseconds
* @param priority the priority of this request
* @param trans_id the transaction ID
* @param pid the request's source process ID
*/
public final void forward_(final Integer command,
final String name,
final byte[] request_info,
final byte[] request,
final Integer timeout,
final Byte priority,
final byte[] trans_id,
final OtpErlangPid pid)
throws ForwardAsyncException,
ForwardSyncException,
InvalidInputException
{
if (command == API.ASYNC)
forward_async(name, request_info, request,
timeout, priority, trans_id, pid);
else if (command == API.SYNC)
forward_sync(name, request_info, request,
timeout, priority, trans_id, pid);
else
throw new InvalidInputException();
}
/**
* Asynchronously forward a message to another service
* subscribed that matches the destination service <code>name</code>.
*
* @param name the destination service name
* @param request_info any request metadata
* @param request the request data
* @param timeout the request timeout in milliseconds
* @param priority the priority of this request
* @param trans_id the transaction ID
* @param pid the request's source process ID
*/
public final void forward_async(final String name,
final byte[] request_info,
final byte[] request,
Integer timeout,
final Byte priority,
final byte[] trans_id,
final OtpErlangPid pid)
throws ForwardAsyncException
{
if (this.request_timeout_adjustment)
{
if (timeout == this.request_timeout)
{
final int elapsed = (int) java.lang.Math.max(0,
((System.nanoTime() - this.request_timer) * 1e-6));
if (elapsed > timeout)
{
timeout = 0;
}
else
{
timeout -= elapsed;
}
}
}
try
{
OtpOutputStream forward_async = new OtpOutputStream();
forward_async.write(OtpExternal.versionTag);
final OtpErlangObject[] tuple = {new OtpErlangAtom("forward_async"),
new OtpErlangString(name),
new OtpErlangBinary(request_info),
new OtpErlangBinary(request),
new OtpErlangUInt(timeout),
new OtpErlangInt(priority),
new OtpErlangBinary(trans_id),
pid};
forward_async.write_any(new OtpErlangTuple(tuple));
send(forward_async);
}
catch (OtpErlangRangeException e)
{
e.printStackTrace(API.err);
return;
}
throw new ForwardAsyncException();
}
/**
* Synchronously forward a message to another service
* subscribed that matches the destination service <code>name</code>.
*
* @param name the destination service name
* @param request_info any request metadata
* @param request the request data
* @param timeout the request timeout in milliseconds
* @param priority the priority of this request
* @param trans_id the transaction ID
* @param pid the request's source process ID
*/
public final void forward_sync(final String name,
final byte[] request_info,
final byte[] request,
Integer timeout,
final Byte priority,
final byte[] trans_id,
final OtpErlangPid pid)
throws ForwardSyncException
{
if (this.request_timeout_adjustment)
{
if (timeout == this.request_timeout)
{
final int elapsed = (int) java.lang.Math.max(0,
((System.nanoTime() - this.request_timer) * 1e-6));
if (elapsed > timeout)
{
timeout = 0;
}
else
{
timeout -= elapsed;
}
}
}
try
{
OtpOutputStream forward_sync = new OtpOutputStream();
forward_sync.write(OtpExternal.versionTag);
final OtpErlangObject[] tuple = {new OtpErlangAtom("forward_sync"),
new OtpErlangString(name),
new OtpErlangBinary(request_info),
new OtpErlangBinary(request),
new OtpErlangUInt(timeout),
new OtpErlangInt(priority),
new OtpErlangBinary(trans_id),
pid};
forward_sync.write_any(new OtpErlangTuple(tuple));
send(forward_sync);
}
catch (OtpErlangRangeException e)
{
e.printStackTrace(API.err);
return;
}
throw new ForwardSyncException();
}
/**
* Returns a response from a service request.
*
* @param command constant API.SYNC or API.SYNC
* @param name the service name
* @param pattern the service name pattern
* @param response_info any response metadata
* @param response the response data
* @param timeout the request timeout in milliseconds
* @param trans_id the transaction ID
* @param pid the request's source process ID
*/
public final void return_(final Integer command,
final String name,
final String pattern,
final byte[] response_info,
final byte[] response,
final Integer timeout,
final byte[] trans_id,
final OtpErlangPid pid)
throws ReturnAsyncException,
ReturnSyncException,
InvalidInputException
{
if (command == API.ASYNC)
return_async(name, pattern, response_info, response,
timeout, trans_id, pid);
else if (command == API.SYNC)
return_sync(name, pattern, response_info, response,
timeout, trans_id, pid);
else
throw new InvalidInputException();
}
/**
* Asynchronously returns a response from a service request.
*
* @param name the service name
* @param pattern the service name pattern
* @param response_info any response metadata
* @param response the response data
* @param timeout the request timeout in milliseconds
* @param trans_id the transaction ID
* @param pid the request's source process ID
*/
public final void return_async(final String name,
final String pattern,
byte[] response_info,
byte[] response,
Integer timeout,
final byte[] trans_id,
final OtpErlangPid pid)
throws ReturnAsyncException
{
if (this.request_timeout_adjustment)
{
if (timeout == this.request_timeout)
{
final int elapsed = (int) java.lang.Math.max(0,
((System.nanoTime() - this.request_timer) * 1e-6));
if (elapsed > timeout)
{
response_info = new byte[0];
response = new byte[0];
timeout = 0;
}
else
{
timeout -= elapsed;
}
}
}
try
{
OtpOutputStream return_async = new OtpOutputStream();
return_async.write(OtpExternal.versionTag);
final OtpErlangObject[] tuple = {new OtpErlangAtom("return_async"),
new OtpErlangString(name),
new OtpErlangString(pattern),
new OtpErlangBinary(response_info),
new OtpErlangBinary(response),
new OtpErlangUInt(timeout),
new OtpErlangBinary(trans_id),
pid};
return_async.write_any(new OtpErlangTuple(tuple));
send(return_async);
}
catch (OtpErlangRangeException e)
{
e.printStackTrace(API.err);
return;
}
throw new ReturnAsyncException();
}
/**
* Synchronously returns a response from a service request.
*
* @param name the service name
* @param pattern the service name pattern
* @param response_info any response metadata
* @param response the response data
* @param timeout the request timeout in milliseconds
* @param trans_id the transaction ID
* @param pid the request's source process ID
*/
public final void return_sync(final String name,
final String pattern,
byte[] response_info,
byte[] response,
Integer timeout,
final byte[] trans_id,
final OtpErlangPid pid)
throws ReturnSyncException
{
if (this.request_timeout_adjustment)
{
if (timeout == this.request_timeout)
{
final int elapsed = (int) java.lang.Math.max(0,
((System.nanoTime() - this.request_timer) * 1e-6));
if (elapsed > timeout)
{
response_info = new byte[0];
response = new byte[0];
timeout = 0;
}
else
{
timeout -= elapsed;
}
}
}
try
{
OtpOutputStream return_sync = new OtpOutputStream();
return_sync.write(OtpExternal.versionTag);
final OtpErlangObject[] tuple = {new OtpErlangAtom("return_sync"),
new OtpErlangString(name),
new OtpErlangString(pattern),
new OtpErlangBinary(response_info),
new OtpErlangBinary(response),
new OtpErlangUInt(timeout),
new OtpErlangBinary(trans_id),
pid};
return_sync.write_any(new OtpErlangTuple(tuple));
send(return_sync);
}
catch (OtpErlangRangeException e)
{
e.printStackTrace(API.err);
return;
}
throw new ReturnSyncException();
}
/**
* Asynchronously receive a response.
*
* @return the response
*/
public Response recv_async()
throws InvalidInputException,
MessageDecodingException,
TerminateException
{
return recv_async(this.timeout_sync, TransIdNull, true);
}
/**
* Asynchronously receive a response.
*
* @param timeout the receive timeout in milliseconds
* @return the response
*/
public Response recv_async(final Integer timeout)
throws InvalidInputException,
MessageDecodingException,
TerminateException
{
return recv_async(timeout, TransIdNull, true);
}
/**
* Asynchronously receive a response.
*
* @param trans_id the transaction ID to receive
* @return the response
*/
public Response recv_async(final byte[] trans_id)
throws InvalidInputException,
MessageDecodingException,
TerminateException
{
return recv_async(this.timeout_sync, trans_id, true);
}
/**
* Asynchronously receive a response.
*
* @param consume if <code>true</code>, will consume the service request
* so it is not accessible with the same function call in
* the future
* @return the response
*/
public Response recv_async(final boolean consume)
throws InvalidInputException,
MessageDecodingException,
TerminateException
{
return recv_async(this.timeout_sync, TransIdNull, consume);
}
/**
* Asynchronously receive a response.
*
* @param timeout the receive timeout in milliseconds
* @param trans_id the transaction ID to receive
* @return the response
*/
public Response recv_async(final Integer timeout,
final byte[] trans_id)
throws InvalidInputException,
MessageDecodingException,
TerminateException
{
return recv_async(timeout, trans_id, true);
}
/**
* Asynchronously receive a response.
*
* @param timeout the receive timeout in milliseconds
* @param consume if <code>true</code>, will consume the service request
* so it is not accessible with the same function call in
* the future
* @return the response
*/
public Response recv_async(final Integer timeout,
final boolean consume)
throws InvalidInputException,
MessageDecodingException,
TerminateException
{
return recv_async(timeout, TransIdNull, consume);
}
/**
* Asynchronously receive a response.
*
* @param trans_id the transaction ID to receive
* @param consume if <code>true</code>, will consume the service request
* so it is not accessible with the same function call in
* the future
* @return the response
*/
public Response recv_async(final byte[] trans_id,
final boolean consume)
throws InvalidInputException,
MessageDecodingException,
TerminateException
{
return recv_async(this.timeout_sync, trans_id, consume);
}
/**
* Asynchronously receive a response.
*
* @param timeout the receive timeout in milliseconds
* @param trans_id the transaction ID to receive
* @param consume if <code>true</code>, will consume the service request
* so it is not accessible with the same function call in
* the future
* @return the response
*/
public Response recv_async(final Integer timeout,
final byte[] trans_id,
final boolean consume)
throws InvalidInputException,
MessageDecodingException,
TerminateException
{
try
{
OtpOutputStream recv_async = new OtpOutputStream();
recv_async.write(OtpExternal.versionTag);
final OtpErlangObject[] tuple = {new OtpErlangAtom("recv_async"),
new OtpErlangUInt(timeout),
new OtpErlangBinary(trans_id),
consume ?
new OtpErlangAtom("true") :
new OtpErlangAtom("false")};
recv_async.write_any(new OtpErlangTuple(tuple));
send(recv_async);
return (Response) poll_request(null, false);
}
catch (OtpErlangRangeException e)
{
e.printStackTrace(API.err);
return null;
}
}
public final int process_index()
{
return this.process_index;
}
public final int process_count()
{
return this.process_count;
}
public final int process_count_max()
{
return this.process_count_max;
}
public final int process_count_min()
{
return this.process_count_min;
}
public final String prefix()
{
return this.prefix;
}
public final int timeout_initialize()
{
return this.timeout_initialize;
}
public final int timeout_async()
{
return this.timeout_async;
}
public final int timeout_sync()
{
return this.timeout_sync;
}
public final int timeout_terminate()
{
return this.timeout_terminate;
}
private void callback(final int command,
final String name,
final String pattern,
final byte[] request_info,
final byte[] request,
final Integer timeout,
final Byte priority,
final byte[] trans_id,
final OtpErlangPid pid)
throws InvalidInputException,
MessageDecodingException,
TerminateException
{
long request_time_start = 0;
if (this.request_timeout_adjustment)
{
this.request_timer = System.nanoTime();
this.request_timeout = timeout;
}
LinkedList<FunctionInterface9> callback_list =
this.callbacks.get(pattern);
callback_list.addLast(callback_list.removeFirst());
FunctionInterface9 callback = callback_list.peekLast();
if (command == MESSAGE_SEND_ASYNC)
{
try
{
Object response = callback.invoke(API.ASYNC, name, pattern,
request_info, request,
timeout, priority,
trans_id, pid);
if (response.getClass() == byte[][].class)
{
byte [][] response_array = (byte[][]) response;
assert response_array.length == 2 : "invalid response";
return_async(name, pattern,
response_array[0],
response_array[1],
timeout, trans_id, pid);
}
else if (response.getClass() == byte[].class)
{
return_async(name, pattern,
("").getBytes(),
(byte[]) response,
timeout, trans_id, pid);
}
else
{
return_async(name, pattern,
("").getBytes(),
response.toString().getBytes(),
timeout, trans_id, pid);
}
return;
}
catch (InvalidInputException e)
{
throw e;
}
catch (MessageDecodingException e)
{
throw e;
}
catch (TerminateException e)
{
throw e;
}
catch (ReturnAsyncException e_return)
{
return;
}
catch (ForwardAsyncException e_forward)
{
return;
}
catch (Throwable e)
{
e.printStackTrace(API.err);
try
{
return_async(name, pattern,
("").getBytes(),
("").getBytes(),
timeout, trans_id, pid);
}
catch (ReturnAsyncException e_return)
{
}
return;
}
}
else if (command == MESSAGE_SEND_SYNC)
{
try
{
Object response = callback.invoke(API.SYNC, name, pattern,
request_info, request,
timeout, priority,
trans_id, pid);
if (response.getClass() == byte[][].class)
{
byte [][] response_array = (byte[][]) response;
assert response_array.length == 2 : "invalid response";
return_sync(name, pattern,
response_array[0],
response_array[1],
timeout, trans_id, pid);
}
else if (response.getClass() == byte[].class)
{
return_sync(name, pattern,
("").getBytes(),
(byte[]) response,
timeout, trans_id, pid);
}
else
{
return_sync(name, pattern,
("").getBytes(),
response.toString().getBytes(),
timeout, trans_id, pid);
}
return;
}
catch (InvalidInputException e)
{
throw e;
}
catch (MessageDecodingException e)
{
throw e;
}
catch (TerminateException e)
{
throw e;
}
catch (ReturnSyncException e_return)
{
return;
}
catch (ForwardSyncException e_forward)
{
return;
}
catch (Throwable e)
{
e.printStackTrace(API.err);
try
{
return_sync(name, pattern,
("").getBytes(),
("").getBytes(),
timeout, trans_id, pid);
}
catch (ReturnSyncException e_return)
{
}
return;
}
}
else
{
throw new MessageDecodingException();
}
}
private boolean handle_events(final boolean external,
final ByteBuffer buffer)
throws MessageDecodingException,
TerminateException
{
return handle_events(external, buffer, 0);
}
private boolean handle_events(final boolean external,
final ByteBuffer buffer,
int command)
throws MessageDecodingException,
TerminateException,
BufferUnderflowException
{
if (command == 0)
{
command = buffer.getInt();
}
while (true)
{
switch (command)
{
case MESSAGE_TERM:
{
this.terminate = true;
if (external)
return false;
else
throw new TerminateException(this.timeout_terminate);
}
case MESSAGE_REINIT:
{
this.process_count = buffer.getInt();
break;
}
case MESSAGE_KEEPALIVE:
{
OtpOutputStream keepalive = new OtpOutputStream();
keepalive.write(OtpExternal.versionTag);
keepalive.write_any(new OtpErlangAtom("keepalive"));
send(keepalive);
break;
}
default:
throw new MessageDecodingException();
}
if (! buffer.hasRemaining())
return true;
command = buffer.getInt();
}
}
private Object poll_request(Integer timeout,
final boolean external)
throws InvalidInputException,
MessageDecodingException,
TerminateException
{
if (this.terminate)
{
return Boolean.FALSE;
}
else if (external && ! this.initialization_complete)
{
OtpOutputStream polling = new OtpOutputStream();
polling.write(OtpExternal.versionTag);
polling.write_any(new OtpErlangAtom("polling"));
send(polling);
this.initialization_complete = true;
}
final int timeout_min = 10;
Integer timeout_value = null;
Long poll_timer = null;
if (timeout == null || timeout < 0)
{
// blocking on read without a timeout
}
else if (timeout >= 0)
{
poll_timer = System.nanoTime();
timeout_value = java.lang.Math.max(timeout_min, timeout);
}
try
{
ByteBuffer buffer = null;
buffer = recv(buffer, timeout_value);
if (buffer == null)
return Boolean.TRUE;
while (true)
{
int command;
switch (command = buffer.getInt())
{
case MESSAGE_INIT:
{
this.process_index = buffer.getInt();
this.process_count = buffer.getInt();
this.process_count_max = buffer.getInt();
this.process_count_min = buffer.getInt();
int prefix_size = buffer.getInt();
this.prefix = API.getString(buffer, prefix_size);
this.timeout_initialize = buffer.getInt();
this.timeout_async = buffer.getInt();
this.timeout_sync = buffer.getInt();
this.timeout_terminate = buffer.getInt();
this.priority_default = buffer.get();
this.request_timeout_adjustment =
(buffer.get() & 0xFF) != 0;
if (buffer.hasRemaining())
{
assert ! external;
handle_events(external, buffer);
}
return Boolean.FALSE;
}
case MESSAGE_SEND_ASYNC:
case MESSAGE_SEND_SYNC:
{
int name_size = buffer.getInt();
String name = API.getString(buffer, name_size);
int pattern_size = buffer.getInt();
String pattern = API.getString(buffer, pattern_size);
int request_info_size = buffer.getInt();
byte[] request_info = API.getBytes(buffer,
request_info_size);
buffer.get();
int request_size = buffer.getInt();
byte[] request = API.getBytes(buffer, request_size);
buffer.get();
int request_timeout = buffer.getInt();
byte priority = buffer.get();
byte[] trans_id = API.getBytes(buffer, 16);
int pid_size = buffer.getInt();
OtpErlangPid pid = API.getPid(buffer, pid_size);
if (buffer.hasRemaining())
{
assert external;
if (! handle_events(external, buffer))
return Boolean.FALSE;
}
callback(command, name, pattern, request_info, request,
request_timeout, priority, trans_id, pid);
break;
}
case MESSAGE_RECV_ASYNC:
case MESSAGE_RETURN_SYNC:
{
int response_info_size = buffer.getInt();
byte[] response_info = API.getBytes(buffer,
response_info_size);
buffer.get();
int response_size = buffer.getInt();
byte[] response = API.getBytes(buffer, response_size);
buffer.get();
byte[] trans_id = API.getBytes(buffer, 16);
if (buffer.hasRemaining())
{
assert ! external;
handle_events(external, buffer);
}
return new Response(response_info, response, trans_id);
}
case MESSAGE_RETURN_ASYNC:
{
byte[] trans_id = API.getBytes(buffer, 16);
if (buffer.hasRemaining())
{
assert ! external;
handle_events(external, buffer);
}
return new TransId(trans_id);
}
case MESSAGE_RETURNS_ASYNC:
{
int trans_id_count = buffer.getInt();
List<TransId> trans_ids = new ArrayList<TransId>();
for (int i = 0; i < trans_id_count; ++i)
{
byte[] trans_id = API.getBytes(buffer, 16);
trans_ids.add(new TransId(trans_id));
}
if (buffer.hasRemaining())
{
assert ! external;
handle_events(external, buffer);
}
return trans_ids;
}
case MESSAGE_SUBSCRIBE_COUNT:
{
int count = buffer.getInt();
if (buffer.hasRemaining())
{
assert ! external;
handle_events(external, buffer);
}
return count;
}
case MESSAGE_TERM:
{
if (! handle_events(external, buffer, command))
return Boolean.FALSE;
assert false;
break;
}
case MESSAGE_REINIT:
{
this.process_count = buffer.getInt();
if (buffer.hasRemaining())
continue;
break;
}
case MESSAGE_KEEPALIVE:
{
OtpOutputStream keepalive = new OtpOutputStream();
keepalive.write(OtpExternal.versionTag);
keepalive.write_any(new OtpErlangAtom("keepalive"));
send(keepalive);
if (buffer.hasRemaining())
continue;
break;
}
default:
throw new MessageDecodingException();
}
if (poll_timer != null)
{
long poll_timer_new = System.nanoTime();
final int elapsed = (int) java.lang.Math.max(0,
((poll_timer_new - poll_timer) * 1e-6));
poll_timer = poll_timer_new;
if (elapsed >= timeout)
timeout = 0;
else
timeout -= elapsed;
}
if (timeout_value != null)
{
if (timeout == 0)
return Boolean.TRUE;
else if (timeout > 0)
timeout_value = java.lang.Math.max(timeout_min,
timeout);
}
buffer = recv(buffer, timeout_value);
if (buffer == null)
return Boolean.TRUE;
}
}
catch (IOException e)
{
e.printStackTrace(API.err);
throw new MessageDecodingException();
}
catch (BufferUnderflowException e)
{
throw new MessageDecodingException();
}
}
public Object poll()
throws InvalidInputException,
MessageDecodingException,
TerminateException
{
return poll(-1);
}
public Object poll(final int timeout)
throws InvalidInputException,
MessageDecodingException,
TerminateException
{
return poll_request(timeout, true);
}
private final HashMap<String,
List<String>> binary_key_value_parse(final byte[] b)
{
HashMap<String, List<String> > result =
new HashMap<String, List<String> >();
String key = null;
int binary_i = 0;
for (int binary_j = 0; binary_j < b.length; ++binary_j)
{
if (b[binary_j] == 0)
{
if (key == null)
{
key = new String(b, binary_i, binary_j - binary_i);
}
else
{
List<String> value = result.get(key);
final String element = new String(b, binary_i,
binary_j - binary_i);
if (value == null)
{
value = new ArrayList<String>();
value.add(element);
result.put(key, value);
}
else
{
value.add(element);
}
key = null;
}
binary_i = binary_j + 1;
}
}
return result;
}
public final HashMap<String,
List<String>> request_http_qs_parse(final byte[] r)
{
return binary_key_value_parse(r);
}
public final HashMap<String,
List<String>> info_key_value_parse(final byte[] info)
{
return binary_key_value_parse(info);
}
private final void send(final OtpOutputStream command)
{
try
{
if (this.use_header)
{
final long length = command.size();
final byte[] header = {(byte) ((length & 0xff000000) >> 24),
(byte) ((length & 0x00ff0000) >> 16),
(byte) ((length & 0x0000ff00) >> 8),
(byte) ( length & 0x000000ff)};
this.output.write(header);
}
command.writeTo(this.output);
}
catch (IOException e)
{
e.printStackTrace(API.err);
return;
}
}
private final ByteBuffer recv(final ByteBuffer buffer_in,
final Integer timeout)
throws IOException
{
final ByteArrayOutputStream output =
new ByteArrayOutputStream(this.buffer_size);
int i = 0;
if (buffer_in != null && buffer_in.hasRemaining())
{
i += buffer_in.limit() - buffer_in.position();
output.write(buffer_in.array(),
buffer_in.position(),
buffer_in.limit());
}
int read = 0;
final byte[] bytes = new byte[this.buffer_size];
boolean consume;
if (i == 0 && timeout != null)
{
// simulate poll
final FileInputStream input = this.input;
Callable<Boolean> poll_timer_task = new Callable<Boolean>()
{
@Override
public Boolean call() throws Exception
{
while (input.available() == 0)
Thread.sleep(10);
return Boolean.TRUE;
}
};
Future<Boolean> poll_timer_future =
poll_timer_executor.submit(poll_timer_task);
try
{
poll_timer_future.get(timeout, TimeUnit.MILLISECONDS);
}
catch (TimeoutException e)
{
return null;
}
catch (Exception e)
{
e.printStackTrace(API.err);
throw new IOException("poll exception");
}
}
if (this.use_header)
consume = (i < 4);
else
consume = (i < this.buffer_size);
while (consume)
{
while ((read = this.input.read(bytes)) == this.buffer_size &&
this.input.available() > 0)
{
i += this.buffer_size;
output.write(bytes, 0, this.buffer_size);
}
if (read == -1)
{
throw new IOException("consume read eof");
}
else if (read > 0)
{
i += read;
output.write(bytes, 0, read);
}
if (this.use_header == false)
consume = false;
else if (i >= 4)
consume = false;
}
final byte[] result = output.toByteArray();
ByteBuffer buffer_out = null;
if (this.use_header)
{
final int length = ((result[0] & 0xff) << 24) |
((result[1] & 0xff) << 16) |
((result[2] & 0xff) << 8) |
(result[3] & 0xff);
if (length < 0)
throw new IOException("negative length");
i -= 4;
if (i < length)
{
buffer_out = ByteBuffer.allocate(length);
buffer_out.put(result, 4, i);
while (i < length)
{
read = this.input.read(bytes, 0,
Math.min(length - i, this.buffer_size));
if (read == -1)
{
throw new IOException("remaining read eof");
}
else if (read > 0)
{
i += read;
buffer_out.put(bytes, 0, read);
}
}
buffer_out.rewind();
}
else
{
buffer_out = ByteBuffer.wrap(result, 4, i);
}
}
else
{
buffer_out = ByteBuffer.wrap(result);
}
buffer_out.order(ByteOrder.nativeOrder());
return buffer_out;
}
private static String getString(final ByteBuffer buffer, final int size)
{
final String value = new String(API.getBytes(buffer, size - 1));
buffer.position(buffer.position() + 1); // skip the '\0' terminator
return value;
}
private static OtpErlangPid getPid(final ByteBuffer buffer, final int size)
{
try
{
return (new OtpInputStream(API.getBytes(buffer, size))).read_pid();
}
catch (OtpErlangDecodeException e)
{
e.printStackTrace(API.err);
return null;
}
}
private static byte[] getBytes(final ByteBuffer buffer, final int size)
{
final byte[] data = new byte[size];
buffer.get(data, 0, size);
return data;
}
private static FileDescriptor storeFD(final int fd)
{
final Class<FileDescriptor> clazz = FileDescriptor.class;
final Constructor<FileDescriptor> c;
try
{
Class<?>[] intarg = { Integer.TYPE };
c = clazz.getDeclaredConstructor(intarg);
}
catch (SecurityException e)
{
e.printStackTrace(API.err);
return null;
}
catch (NoSuchMethodException e)
{
e.printStackTrace(API.err);
return null;
}
c.setAccessible(true);
FileDescriptor object;
try
{
object = c.newInstance(new Integer(fd));
}
catch (IllegalArgumentException e)
{
e.printStackTrace(API.err);
return null;
}
catch (InstantiationException e)
{
e.printStackTrace(API.err);
return null;
}
catch (IllegalAccessException e)
{
e.printStackTrace(API.err);
return null;
}
catch (InvocationTargetException e)
{
e.printStackTrace(API.err);
return null;
}
return object;
}
public static class Response
{
public final byte[] response_info;
public final byte[] response;
public final byte[] id;
Response(final byte[] info, final byte[] resp, final byte[] trans_id)
{
this.response_info = info;
this.response = resp;
this.id = trans_id;
}
public final boolean isEmpty()
{
return response.length == 0;
}
public final boolean isTimeout()
{
return Arrays.equals(this.id, API.TransIdNull);
}
public final String toString()
{
StringBuilder result = new StringBuilder();
result.append("('");
result.append(new String(this.response_info));
result.append("', '");
result.append(new String(this.response));
result.append("', '");
result.append(new String(this.id));
result.append("')");
return result.toString();
}
}
public static final byte[] TransIdNull = {0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0};
public static class TransId
{
public final byte[] id;
public TransId(final byte[] trans_id)
{
this.id = trans_id;
}
public final boolean equals(final byte[] bytes)
{
return Arrays.equals(this.id, bytes);
}
public final boolean isTimeout()
{
return equals(API.TransIdNull);
}
public final UUID toObject()
{
return new UUID((((long) (this.id[ 0] & 0xff)) << 56) |
(((long) (this.id[ 1] & 0xff)) << 48) |
(((long) (this.id[ 2] & 0xff)) << 40) |
(((long) (this.id[ 3] & 0xff)) << 32) |
(((long) (this.id[ 4] & 0xff)) << 24) |
(((long) (this.id[ 5] & 0xff)) << 16) |
(((long) (this.id[ 6] & 0xff)) << 8) |
(long) (this.id[7] & 0xff),
(((long) (this.id[ 8] & 0xff)) << 56) |
(((long) (this.id[ 9] & 0xff)) << 48) |
(((long) (this.id[10] & 0xff)) << 40) |
(((long) (this.id[11] & 0xff)) << 32) |
(((long) (this.id[12] & 0xff)) << 24) |
(((long) (this.id[13] & 0xff)) << 16) |
(((long) (this.id[14] & 0xff)) << 8) |
(long) (this.id[15] & 0xff));
}
public final Date toDate()
{
// millisecond resolution
return new Date(toTimestampMicroSeconds() / 1000);
}
public final String toTimestamp()
{
return toTimestampString(false);
}
public final String toTimestampSQL()
{
return toTimestampString(true);
}
public final long toTimestampMicroSeconds()
{
// v1 UUID is limited to 60 bit time value
// (overflows 60 bits after 5236-03-31 21:21:00)
return (((((long) (this.id[6] & 0x0f)) << 56) |
(((long) (this.id[7] & 0xff)) << 48) |
(((long) (this.id[4] & 0xff)) << 40) |
(((long) (this.id[5] & 0xff)) << 32) |
(((long) (this.id[0] & 0xff)) << 24) |
(((long) (this.id[1] & 0xff)) << 16) |
(((long) (this.id[2] & 0xff)) << 8) |
((long) (this.id[3] & 0xff))) -
0x01b21dd213814000L) / 10;
}
private final String toTimestampString(final boolean SQL)
{
// microsecond resolution (ISO8601 datetime in UTC)
final long micro = toTimestampMicroSeconds();
final Date date = new Date(micro / 1000);
final String str =
(new SimpleDateFormat("yyyy-MM-ddHH:mm:ss.SSS")).format(date);
StringBuilder ISO8601 = new StringBuilder();
ISO8601.append(str.substring(0, 10));
if (SQL)
ISO8601.append(" ");
else
ISO8601.append("T");
ISO8601.append(str.substring(10, 22));
ISO8601.append(String.format("%03d", micro % 1000));
ISO8601.append("Z");
return ISO8601.toString();
}
public final String toString()
{
return toObject().toString().replace("-", "");
}
}
public static class InvalidInputException extends Exception
{
private static final long serialVersionUID = 1L;
InvalidInputException()
{
super("Invalid Input");
}
}
public static class ReturnSyncException extends Exception
{
private static final long serialVersionUID = 3L;
ReturnSyncException()
{
super("Synchronous Call Return Invalid");
}
}
public static class ReturnAsyncException extends Exception
{
private static final long serialVersionUID = 3L;
ReturnAsyncException()
{
super("Asynchronous Call Return Invalid");
}
}
public static class ForwardSyncException extends Exception
{
private static final long serialVersionUID = 3L;
ForwardSyncException()
{
super("Synchronous Call Forward Invalid");
}
}
public static class ForwardAsyncException extends Exception
{
private static final long serialVersionUID = 3L;
ForwardAsyncException()
{
super("Asynchronous Call Forward Invalid");
}
}
public static class MessageDecodingException extends Exception
{
private static final long serialVersionUID = 1L;
MessageDecodingException()
{
super("Message Decoding Error");
}
}
public static class TerminateException extends Exception
{
private static final long serialVersionUID = 0L;
private int timeout;
TerminateException(final int timeout)
{
super("Terminate");
this.timeout = timeout;
}
public final int timeout()
{
return this.timeout;
}
}
}
|
// A zorbage example: Calculating the FFT planes of an image.
// Instructions: Use the file chooser to pick an image and see the real and imaginary planes of the FFT.
// This code is in the public domain. Use however you wish.
package fft;
import java.awt.FlowLayout;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import nom.bdezonia.zorbage.algebras.G;
import nom.bdezonia.zorbage.algorithm.FFT;
import nom.bdezonia.zorbage.tuple.Tuple2;
import nom.bdezonia.zorbage.type.data.float64.complex.ComplexFloat64Member;
import nom.bdezonia.zorbage.type.storage.Storage;
import nom.bdezonia.zorbage.type.storage.datasource.IndexedDataSource;
/**
*
* @author Barry DeZonia
*
*/
public class Main {
public static void main(String[] args) {
File file = null;
JFileChooser fc = new JFileChooser();
int returnVal = fc.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
file = fc.getSelectedFile();
}
BufferedImage img = null;
try {
img = ImageIO.read(file);
} catch (Exception e) {
System.out.println(e.getMessage());
}
Tuple2<BufferedImage,BufferedImage> planes = calcFftPlanes(img);
BufferedImage imgR = planes.a();
BufferedImage imgI = planes.b();
JFrame frame = new JFrame();
frame.getContentPane().setLayout(new FlowLayout());
frame.getContentPane().add(new JLabel(new ImageIcon(img)));
frame.getContentPane().add(new JLabel(new ImageIcon(imgR)));
frame.getContentPane().add(new JLabel(new ImageIcon(imgI)));
frame.pack();
frame.setVisible(true);
}
private static Tuple2<BufferedImage,BufferedImage> calcFftPlanes(BufferedImage img) {
long size = FFT.enclosingPowerOf2(img.getHeight() * img.getWidth());
long subSize = (long) Math.ceil(Math.sqrt(size));
ComplexFloat64Member value = G.CDBL.construct();
IndexedDataSource<ComplexFloat64Member> inData = Storage.allocate(size, value);
IndexedDataSource<ComplexFloat64Member> outData = Storage.allocate(size, value);
for (int r = 0, i = 0; r < img.getHeight(); r++) {
for (int c = 0; c < img.getWidth(); c++, i++) {
int rgb = img.getRGB(c, r);
int R = (rgb & 0x00ff0000) >> 16;
int G = (rgb & 0x0000ff00) >> 8;
int B = (rgb & 0x000000ff) >> 0;
double luminance = 0.2126*R + 0.7152*G + 0.0722*B;
value.setR(luminance);
value.setI(0);
inData.set(i, value);
}
}
FFT.compute(G.CDBL, G.DBL, inData, outData);
BufferedImage planeR = new BufferedImage((int) subSize, (int) subSize, BufferedImage.TYPE_INT_ARGB);
BufferedImage planeI = new BufferedImage((int) subSize, (int) subSize, BufferedImage.TYPE_INT_ARGB);
double min = Double.POSITIVE_INFINITY;
double max = Double.NEGATIVE_INFINITY;
for (int i = 0; i < outData.size(); i++) {
outData.get(i, value);
if (value.r() < min) min = value.r();
if (value.i() < min) min = value.i();
if (value.r() > max) max = value.r();
if (value.i() > max) max = value.i();
}
// deal with outliers
if (min < -1000) min = -1000;
if (max > 1000) max = 1000;
int r = 0;
int c = 0;
for (int i = 0; i < outData.size(); i++) {
outData.get(i, value);
int scaledR = (int) Math.round(255.0 * (value.r() - min) / (max - min));
int scaledI = (int) Math.round(255.0 * (value.i() - min) / (max - min));
// deal with outliers
if (scaledR < 0) scaledR = 0;
if (scaledR > 255) scaledR = 255;
if (scaledI < 0) scaledI = 0;
if (scaledI > 255) scaledI = 255;
int rArgb = (0x7f000000) | (scaledR << 16) | (scaledR << 8) | (scaledR << 0);
int iArgb = (0x7f000000) | (scaledI << 16) | (scaledI << 8) | (scaledI << 0);
planeR.setRGB(c, r, rArgb);
planeI.setRGB(c, r, iArgb);
c++;
if (c >= subSize) {
c = 0;
r++;
}
}
return new Tuple2<>(planeR, planeI);
}
}
|
package sc.yhy.data.nosql.mongo;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.cglib.beans.BeanMap;
import org.bson.Document;
import org.bson.conversions.Bson;
import sc.yhy.annotation.annot.Column;
import sc.yhy.util.ReflectUtil;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoIterable;
import com.mongodb.client.model.Projections;
import com.mongodb.client.model.Sorts;
public class MongoRepository {
private ServerAddress serverAddress;
private List<MongoCredential> mongoCredentialList;
MongoClient mongoClient;
MongoDatabase mongoDatabase;
MongoDatabase[] mongoDatabases;
Map<String, Integer> mongoNameIndex = null;
private MongoCollection<Document> collection;
public MongoRepository() {
}
public MongoRepository(ServerAddress serverAddress, List<MongoCredential> mongoCredentialList) {
this.serverAddress = serverAddress;
this.mongoCredentialList = mongoCredentialList;
}
/**
* new MongoClient
*/
void init() {
if (this.mongoClient == null) {
if (mongoCredentialList != null) {
this.mongoClient = new MongoClient(serverAddress, mongoCredentialList);
} else {
this.mongoClient = new MongoClient(serverAddress);
}
}
// String[] dataBaseNames = MongoConfig.dataBaseNames.split(",");
// int len = dataBaseNames.length;
// mongoNameIndex = new ConcurrentHashMap<String, Integer>(len);
// mongoDatabases = new MongoDatabase[len];
// for (int i = 0; i < len; i++) {
// mongoDatabases[i] = mongoDatabase =
// mongoClient.getDatabase(dataBaseNames[i]);
// mongoNameIndex.put(dataBaseNames[i], i);
}
void close() {
if (this.mongoClient != null) {
this.mongoClient.close();
this.mongoClient = null;
}
}
public MongoCollection<Document> getCollection() {
return collection;
}
/**
*
*
* @param collection
* @return MongoCollection<Document>
* @author YHY
*/
public MongoRepository setDataBaseAndCollection(String dataBase, String collection) {
this.setDataBase(dataBase);
this.setCollection(collection);
return this;
}
/**
*
*
* @param collection
* @return MongoCollection<Document>
* @author YHY
*/
public MongoRepository setCollection(String collection) {
this.collection = mongoDatabase.getCollection(collection);
return this;
}
/**
* db
*
* @param dataBase
* @return
*/
public MongoRepository setDataBase(String dataBase) {
// mongoClient
mongoDatabase = mongoClient.getDatabase(dataBase);
// mongoDatabase = mongoDatabases[mongoNameIndex.get(dataBase)];
return this;
}
public Map<String, Object> toMap(Object entity) {
BeanMap beanMap = BeanMap.create(entity);
Class<?> clases = entity.getClass();
Field[] fields = clases.getDeclaredFields();
Map<String, Object> map = new HashMap<String, Object>();
for (Field field : fields) {
String fieldName = field.getName();
if (ReflectUtil.isAnnotation(field, Column.class)) {
Object value = beanMap.get(fieldName);
map.put(fieldName, value);
}
}
return map;
}
public Document document(Map<String, Object> map) {
Document doc = new Document(map);
return doc;
}
public void insert(Object entity) {
insert(document(toMap(entity)));
}
public void insert(Map<String, Object> map) {
collection.insertOne(document(map));
}
public void deleteOne(Bson bson) {
collection.deleteOne(bson);
}
public void deleteMany(Bson bson) {
collection.deleteMany(bson);
}
public void updateOneDocument(Bson bson, Document document) {
collection.updateOne(bson, document);
}
public void updateAllDocument(Bson bson, Document document) {
collection.updateMany(bson, document);
}
public FindIterable<Document> listDocuments() {
return collection.find();
}
public FindIterable<Document> listDocuments(Bson bson) {
return collection.find(bson);
}
public FindIterable<Document> listDocuments(Bson bson, String sort) {
return collection.find(bson).sort(Sorts.descending(sort));
}
public void listAllSpecifiedDocumentFields() {
for (Document document : collection.find().projection(Projections.exclude("_id"))) {
System.out.println(document);
}
}
void listDatabases(MongoClient mongo) {
MongoIterable<String> allDatabases = mongo.listDatabaseNames();
for (String db : allDatabases) {
System.out.println("Database name: " + db);
}
}
void listCollections(MongoDatabase database) {
MongoIterable<String> allCollections = database.listCollectionNames();
for (String collection : allCollections) {
System.out.println("Collection name: " + collection);
}
}
}
|
package app;
import core.framework.module.App;
import core.framework.module.SystemModule;
/**
* @author neo
*/
public class DemoServiceApp extends App {
@Override
protected void initialize() {
http().httpsPort(8443);
load(new SystemModule("sys.properties"));
load(new ProductModule());
load(new JobModule());
// load(new CustomerModule());
}
}
|
package se.bth.libsla.db;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.annotation.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public abstract class DBObject {
/**
* Mark a field as a representation of a table column.
* E.g.
* "private @Column(id) int id;"
* will put the value of table.id into the variable id.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
protected @interface Column {
String value();
}
/**
* Mark field as a reference to another DBObject class using @Column as key.
* E.g.
* "private @Column(foo_id) @References(Foo.class) Foo foo;"
* will create an instance of the class Foo based on the table column
* foo_id. Foo must be a subclass of DBObject and have a matching
* constructor to select based on foo_id.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
protected @interface References {
Class<? extends DBObject> value();
}
/**
* Mark field as a reference to another class using Serializable as a middleman.
* Table column must have the datatype BLOB.
* E.g.
* "private @Column(data) @Serializes(Foo.class) Foo inst;"
* will create an instance of Foo by deserialization of data.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
protected @interface Serializes {
Class<? extends Serializable> value();
}
static public class ColumnData {
/* Field refers to the class members */
public Field field;
public String field_name;
public Class<?> field_datatype;
/* Column refers to the database table */
public String column_name;
public String column_datatype;
public boolean column_nullable;
public boolean column_primary;
public Class<? extends DBObject> reference;
public Class<? extends Serializable> serializes;
@SuppressWarnings("hiding")
public ColumnData(DataLayer db, String table, Field field, Column column) throws SQLException{
this.field_name = field.getName();
this.field_datatype = field.getType();
this.column_name = column.value();
this.reference = null;
this.field = field;
PreparedStatement query = db.prepareStatement(
"SELECT" +
" `DATA_TYPE`,\n" +
" `IS_NULLABLE`,\n" +
" `COLUMN_KEY`\n" +
"FROM" +
" `information_schema`.`COLUMNS`\n" +
"WHERE\n" +
" `TABLE_SCHEMA` = ? AND\n" +
" `TABLE_NAME` = ? AND\n" +
" `COLUMN_NAME` = ?\n" +
"LIMIT 1"
);
query.setString(1, db.dbname());
query.setString(2, table);
query.setString(3, column_name);
query.execute();
ResultSet rs = query.getResultSet();
if ( !rs.next() ){
throw new SQLException(String.format(
"`%s`.`%s` does not exist",
table, column
));
}
/**
* TIMESTAMP and NULL.
* Timestamps handles null values different than other datatypes.
*
* If column is declared "NOT NULL", NULL is still permitted and
* means the same as CURRENT_TIMESTAMP: "[..] and assigning NULL
* assigns the current timestamp" (MySQL Reference 5.0)
*/
column_datatype = rs.getString(1);
column_nullable = rs.getBoolean(2) || column_datatype.equals("timestamp"); /* se note above */
column_primary = rs.getString(3).equals("PRI");
}
}
/* If true, it means that the object has a corresponding row in the
* database, otherwise a new row must be inserted if object saved. */
private boolean _exists = false;
/**
* Instantiate using primary key.
*/
protected DBObject(DBObjectState self, int id){
refresh(self, id);
}
/**
* Initializes database queries. Must be called once for each subclass.
* @param db
* @param table Name of the database table with the data.
* @param custom_fields Additional fields to pull.
* @return A DescriptionTableQuery state object, pass this to other methods.
* @throws SQLException
*/
protected static <T extends DBObject> DBObjectState initialize(Class<T> cls, DataLayer db, String table) throws Exception {
DBObjectState query = new DBObjectState();
query.db = db;
query.table = table;
query.cls = cls;
query.fields = get_fields(cls, db, table);
query.ctor = cls.getConstructors();
/* used by all */
query.all = db.prepareStatement(
"SELECT " +
column_query_from_array(query.fields) +
"FROM " +
" `" + table + "` ");
/* used by from_id_int */
query.by_id = db.prepareStatement(
"SELECT " +
column_query_from_array(query.fields) +
"FROM " +
" `" + table + "` " +
"WHERE " +
" `id` = ? " +
"LIMIT 1");
return query;
}
/**
* Lists all fields in the subclass, marked with the @Column annotation.
*/
private static <T> List<ColumnData> get_fields(Class<?> cls, DataLayer db, String table) throws SQLException {
List<String> available_columns = get_columns(db, table);
List<ColumnData> fields = new ArrayList<ColumnData>();
for ( Field field : cls.getDeclaredFields() ){
Column column = field.getAnnotation(Column.class);
/* Field did not declare the @Column annotation, skip */
if ( column == null ){
continue;
}
/* Ensure that the database table holds a column with the referenced name */
if ( !available_columns.contains(column.value()) ){
throw new RuntimeException(String.format(
"Class %s.%s refers to `%s`.`%s` which is not available",
cls.getName(), field.getName(), table, column.value()
));
}
/* since this class writes data to the fields, it must be accessible */
field.setAccessible(true);
/* Create and fill field wrapper */
ColumnData data = new ColumnData(db, table, field, column);
/* check if a reference (to another DBObject class) was requested */
References ref = field.getAnnotation(References.class);
if ( ref != null ){
data.reference = ref.value();
}
/* check if a serialization was requested */
Serializes serializes = field.getAnnotation(Serializes.class);
if ( serializes != null ){
if ( !data.column_datatype.equals("blob") ){
throw new RuntimeException(String.format(
"Class %s.%s (serialized) refers to `%s`.`%s` which has datatype `%s', but is required to be `%s' when serializing.",
cls.getName(), field.getName(), table, column.value(), data.column_datatype, "blob"
));
}
data.serializes = serializes.value();
}
/* store */
fields.add(data);
}
return fields;
}
@SuppressWarnings("unused")
private static List<String> get_primary_key(DataLayer db, String table) throws SQLException{
/* Based on BasicObject by edruid */
PreparedStatement query = db.prepareStatement(
"SELECT " +
" `COLUMN_NAME` " +
"FROM " +
" `information_schema`.`key_column_usage` JOIN " +
" `information_schema`.`table_constraints` USING (`CONSTRAINT_NAME`, `CONSTRAINT_SCHEMA`, `TABLE_NAME`) " +
"WHERE " +
" `table_constraints`.`CONSTRAINT_TYPE` = 'PRIMARY KEY' AND " +
" `table_constraints`.`CONSTRAINT_SCHEMA` = ? AND " +
" `table_constraints`.`TABLE_NAME` = ?"
);
query.setString(1, db.dbname());
query.setString(2, table);
query.execute();
ResultSet rs = query.getResultSet();
List<String> result = new ArrayList<String>();
while ( rs.next() ){
result.add( rs.getString(1) );
}
return result;
}
/**
* Get a list of all columns in the selected table.
*/
private static List<String> get_columns(DataLayer db, String table) throws SQLException {
/* Based on BasicObject by edruid */
PreparedStatement query = db.prepareStatement(
"SELECT `COLUMN_NAME`\n" +
"FROM `information_schema`.`COLUMNS`\n" +
"WHERE\n" +
" `TABLE_SCHEMA` = ? AND\n" +
" `table_name` = ?"
);
query.setString(1, db.dbname());
query.setString(2, table);
query.execute();
ResultSet rs = query.getResultSet();
List<String> result = new ArrayList<String>();
while ( rs.next() ){
result.add( rs.getString(1) );
}
return result;
}
private static String column_query_from_array(List<ColumnData> fields){
List<String> tmp = new ArrayList<String>(fields.size());
for ( ColumnData f : fields ){
tmp.add(String.format("\t`%s`", f.column_name));
}
return array_join(tmp, ",\n") + "\n"; /* append a space after so it doesn't choke
* on the next SQL line, eg: "`foo`FROM"
*/
}
private static String column_update_from_array(List<ColumnData> fields){
List<String> tmp = new ArrayList<String>(fields.size());
for ( ColumnData f : fields ){
/* column is primary_key, ignore */
if ( f.column_primary ){
continue;
}
tmp.add(String.format("\t`%s` = ?", f.column_name));
}
return array_join(tmp, ",\n") + "\n"; /* append a space after so it doesn't choke
* on the next SQL line, eg: "`foo`FROM"
*/
}
@SuppressWarnings("unused")
private static List<String> string_map_format(Collection<String> array, String fmt){
List<String> tmp = new ArrayList<String>(array.size());
for ( String str : array ){
tmp.add(String.format(fmt, str));
}
return tmp;
}
/**
* Join an array of strings with a delimiter.
* E.g join(new String[]{"foo", "bar", "baz"]}, "|") becomes "foo|bar|baz"
*
* @param s Input strings
* @param delimiter What string to put inbetween elements
* @return
*/
private static String array_join(Collection<String> s, String delimiter){
if ( s.isEmpty() ) return "";
Iterator<String> iter = s.iterator();
StringBuilder buffer = new StringBuilder(iter.next());
while (iter.hasNext()){
while (iter.hasNext()) buffer.append(delimiter).append(iter.next());
}
return buffer.toString();
}
/**
* TODO This *should* be private, but as a hack I made it protected so it
* would be possible to write a custom query which wasn't possible to write
* using the selection api.
*
* @note DO NOT USE OUTSIDE THIS CLASS! CONSIDER IT PRIVATE!
*/
@SuppressWarnings("unchecked")
protected static <T extends DBObject> T instantiate(DBObjectState query, ResultSet rs, Object[] args) throws Exception {
Constructor<?> ctor = null;
/* try to find a constructor matching args */
outer:
for ( Constructor<?> candidate : query.ctor ){
Class<?>[] p = candidate.getParameterTypes();
/* match length of expected parameters and passed args */
if ( p.length != args.length ){
continue;
}
/* match class types */
for ( int i = 0; i < p.length; i++ ){
try {
p[i].cast(args[i]);
} catch ( ClassCastException e ){
continue outer;
}
}
ctor = candidate;
break;
}
/* no matching constructor found */
if ( ctor == null ){
StringBuilder prototype = new StringBuilder();
prototype.append(query.cls.getName());
prototype.append('(');
for ( Object a : args ){
prototype.append(a.getClass().getName());
prototype.append(", ");
}
prototype.append(')');
throw new NoSuchMethodException(String.format(
"Could not find a constructor matching '%s'",
prototype.toString()
));
}
/* create a new instance of T */
T item = (T) ctor.newInstance(args);
/* fill in all fields from the database query */
item.update_fields(query, rs);
/* mark it as existing (in db) */
item._exists = true;
/* done */
return item;
}
private void update_fields(DBObjectState self, ResultSet rs) throws Exception {
for ( ColumnData field : self.fields ){
Object value = rs.getObject(field.column_name);
if ( field.reference != null ){ /* reference column */
try {
Class<? extends DBObject> ref_cls = field.reference;
Constructor<? extends DBObject> ctor = ref_cls.getConstructor(value.getClass());
value = ctor.newInstance(value);
} catch ( Exception e ){
e.printStackTrace();
value = null;
}
}
if ( field.serializes != null ){ /* serialized column */
try {
ByteArrayInputStream bis = new ByteArrayInputStream((byte[]) value);
ObjectInputStream in = new ObjectInputStream(bis);
value = in.readObject();
} catch ( Exception e ){
e.printStackTrace();
value = null;
}
}
field.field.set(this, value);
}
}
/**
* Refresh all values (based on primary key) with values from database.
*/
public void refresh(DBObjectState self){
refresh(self, id()); /* TODO hardcoded primary key */
}
/* TODO hardcoded primary key */
private void refresh(DBObjectState self, int id){
try {
/* execute query */
self.by_id.setInt(1, id);
self.by_id.execute();
ResultSet rs = self.by_id.getResultSet();
/* no matching row */
if ( !rs.next() ){
throw new RuntimeException("Invalid object referece, primary key not found in database");
}
update_fields(self, rs);
} catch ( Exception e ){
e.printStackTrace();
}
}
/**
* Same as from_id_int(query, id, new Object[0])
*/
protected static <T extends DBObject> T from_id_int(DBObjectState query, int id) {
return from_id_int(query, id, new Object[0]);
}
/**
* Get row from ID.
*
* Sample usage:
* Metric x = from_id_int(Metric.class, query, id);
*
* @param <T> Type of the subclass
* @param cls Class-object of the subclass
* @param query State object from initialize_queries
* @param id ID of the row to request.
* @return new instance of T, or null if not found.
*/
protected static <T extends DBObject> T from_id_int(DBObjectState query, int id, Object[] args) {
try {
/* execute query */
query.by_id.setInt(1, id);
query.by_id.execute();
ResultSet rs = query.by_id.getResultSet();
/* no matching row */
if ( !rs.next() ){
return null;
}
return instantiate(query, rs, args);
} catch ( Exception e ){
e.printStackTrace();
return null;
}
}
/**
* Same as all(self, new Object[0]);
*/
protected static <T extends DBObject> List<T> all(DBObjectState self){
return all(self, new Object[0]);
}
protected static <T extends DBObject> List<T> all(DBObjectState self, Object[] args){
/* allocate list */
List<T> result = new ArrayList<T>();
try {
/* execute query */
self.all.execute();
ResultSet rs = self.all.getResultSet();
while ( rs.next() ){
T item = instantiate(self, rs, args);
result.add(item);
}
} catch ( Exception e ){
e.printStackTrace();
}
return result;
}
/**
* Same as selection(self, criteria, new Object[0]);
*/
protected static <T extends DBObject> List<T> selection(DBObjectState self, TupleList criteria){
return selection(self, criteria, new Object[0]);
}
protected static <T extends DBObject> List<T> selection(DBObjectState self, TupleList criteria, Object[] args){
List<T> result = new ArrayList<T>();
StringBuilder sql = new StringBuilder("SELECT\n" +
column_query_from_array(self.fields) +
"FROM\n" +
String.format("\t`%s`\n", self.table));
String limit[] = {null};
StringBuilder where = new StringBuilder();
List<Object> values = selection_build_where(where, criteria, limit, "AND");
/* only add WHERE-clauses if criteria was specified */
if ( !where.toString().equals("\n") ){
sql.append("WHERE\n");
sql.append(where.toString());
}
/* append LIMIT */
if ( limit[0] != null ){
sql.append(limit[0]);
sql.append("\n");
}
try {
PreparedStatement query = self.db.prepareStatement(sql.toString());
int i = 1;
for ( Object value: values ){
query.setObject(i++, value);
}
query.execute();
ResultSet rs = query.getResultSet();
while ( rs.next() ){
T item = instantiate(self, rs, args);
result.add(item);
}
} catch (Exception e) {
e.printStackTrace();
System.err.println("\nWhen executing selection query:\n" + sql);
System.err.println("Args was:\n" + Arrays.toString(args) + "\n");
System.err.println("Available constructors:\n" + Arrays.toString(self.ctor) + "\n");
}
return result;
}
private static List<Object> selection_build_where(StringBuilder dst, TupleList criteria, String[] limit, String glue){
List<String> clause = new ArrayList<String>();
List<Object> values = new ArrayList<Object>();
for ( Map.Entry<String, Object> entry : criteria.entrySet() ){
String key = entry.getKey();
Object value = entry.getValue();
if ( key.startsWith("@") ){
if ( key.equals("@or") ){
TupleList inner = (TupleList)value;
StringBuilder sub_clause = new StringBuilder("(\n");
List<Object> sub_values = selection_build_where(sub_clause, inner, null, "OR");
sub_clause.append(")");
clause.add(sub_clause.toString());
values.addAll(sub_values);
} else if ( key.equals("@and") ){
TupleList inner = (TupleList)value;
StringBuilder sub_clause = new StringBuilder("(\n");
List<Object> sub_values = selection_build_where(sub_clause, inner, null, "AND");
sub_clause.append(")");
clause.add(sub_clause.toString());
values.addAll(sub_values);
} else if ( key.equals("@limit") ){
if ( limit[0] != null ){
throw new RuntimeException("Got multiple limit-keywords");
}
if ( !(value instanceof Integer) ){
throw new RuntimeException("Limit expected numerical value, got " + value.getClass().getName());
}
limit[0] = "LIMIT " + value.toString();
} else {
throw new RuntimeException("Unknown keyword " + key + " passed as criteria");
}
continue;
}
if ( value == null || value.equals("@null") ){
clause.add(String.format("\t`%s` IS NULL", key));
} else if ( value.equals("@not_null") ){
clause.add(String.format("\t`%s` IS NOT NULL", key));
} else {
clause.add(String.format("\t`%s` = ?", key));
values.add(value);
}
}
//parts.addAll(string_map_format(columns.keySet(), "\t`%s` = ?"));
String where_sql = array_join(clause, " " + glue + " \n");
/* append WHERE */
dst.append(where_sql);
dst.append("\n");
return values;
}
public DBObject() {
super();
}
public abstract int id();
public int primary_key(){ return id(); }
public void remove() {
// TODO Auto-generated method stub
}
private Object value_from_column(ColumnData column) throws Exception {
Object value = null;
try {
value = column.field.get(this);
/* return null without checking references if the value is unset */
if ( value == null ){
return null;
}
/* for references the primary key is stored */
if ( column.reference != null ){
value = ((DBObject)value).primary_key();
}
/* serialize object if serialization is requested */
if ( column.serializes != null ){
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bos);
out.writeObject(value);
out.close();
value = bos.toByteArray();
}
} catch ( Exception ei ){
System.err.println("Exception raised when reading column " + column.column_name + ":");
throw ei;
}
return value;
}
/**
* Store this object in the table. If it is a new object it is INSERT'ed
* and if it was queried from the database it will be UPDATE'd.
* @param self State object.
* @return Whenever successful or not.
*/
protected boolean persist(DBObjectState self) {
PreparedStatement query = null;
String sql = null;
try {
sql = persist_query_store(self);
query = self.db.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
int i = 1;
/* Fill all column values */
for ( ColumnData f : self.fields ){
/* column is primary_key, ignore */
if ( f.column_primary ){
continue;
}
Object value = value_from_column(f);
if ( value == null && !f.column_nullable ){
throw new SQLException(String.format(
"Field %s.%s cannot be null, `%s`.`%s` declared 'NOT NULL'",
self.cls.getName(), f.field_name, self.table, f.column_name
));
}
query.setObject(i++, value);
}
/* if the object exists add the primary key to the WHERE clause */
if ( _exists ){
query.setInt(i++, primary_key());
}
query.execute();
/* update fields in object if a new object was created */
if ( !_exists ){
ResultSet rs = query.getGeneratedKeys();
rs.next();
/* TODO again, match primary key, not hardcoded */
refresh(self, rs.getInt(1));
}
/* mark as existing, since it is definitely saved now */
_exists = true;
return true;
} catch ( Exception e ){
e.printStackTrace();
System.err.println("\nWhen executing selection query:\n" + sql);
return false;
}
}
/**
* Create the query used by persist()
*/
private String persist_query_store(DBObjectState self){
StringBuilder dst = new StringBuilder();
if ( _exists ){
dst.append("UPDATE ");
} else {
dst.append("INSERT INTO ");
}
dst.append("`" + self.table + "` SET\n");
dst.append(column_update_from_array(self.fields));
if ( _exists ){
dst.append("WHERE\n");
dst.append("\t`id` = ?;\n");
} else {
dst.append(";\n");
}
return dst.toString();
}
}
|
package de.dakror.spamwars.game.entity;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.geom.AffineTransform;
import java.io.IOException;
import de.dakror.gamesetup.util.Helper;
import de.dakror.gamesetup.util.Vector;
import de.dakror.spamwars.game.Game;
import de.dakror.spamwars.game.weapon.Handgun;
import de.dakror.spamwars.game.weapon.Weapon;
import de.dakror.spamwars.net.User;
import de.dakror.spamwars.net.packet.Packet5PlayerData;
/**
* @author Dakror
*/
public class Player extends Entity
{
public boolean left, right, up, down;
boolean lookingLeft = false;
private int style = 0;
private Weapon weapon;
/**
* 0 stand, 0-10 = walking, 11 = jump
*/
public int frame = 0;
Point hand = new Point(0, 0);
Point mouse = new Point(0, 0);
User user;
public Player(float x, float y, User user)
{
super(x, y, 72, 97);
style = (int) (Math.random() * 3 + 1);
bump = new Rectangle(10, 7, 44, 84);
gravity = true;
this.user = user;
setWeapon(new Handgun());
}
@Override
public void draw(Graphics2D g)
{
float mx = x + Game.world.x;
float my = y + Game.world.y;
Font oldF = g.getFont();
g.setFont(new Font("", Font.PLAIN, 25));
Color o = g.getColor();
g.setColor(Color.darkGray);
Helper.drawHorizontallyCenteredString(Game.user.getUsername(), (int) mx, width, (int) my - 5, g, 20);
g.setFont(oldF);
g.setColor(o);
AffineTransform old = g.getTransform();
if (lookingLeft)
{
AffineTransform at = g.getTransform();
at.translate((mx + width / 2) * 2, 0);
at.scale(-1, 1);
g.setTransform(at);
}
if (frame >= 0 && frame <= 10)
{
String frame = (this.frame + 1) + "";
if (frame.length() == 1) frame = "0" + frame;
g.drawImage(Game.getImage("entity/player/p" + getStyle() + "/p" + getStyle() + "_walk" + frame + ".png"), (int) mx, (int) my, Game.w);
}
else if (frame == 11)
{
g.drawImage(Game.getImage("entity/player/p" + getStyle() + "/p" + getStyle() + "_jump.png"), (int) mx, (int) my, Game.w);
}
g.setTransform(old);
old = g.getTransform();
AffineTransform at = g.getTransform();
at.translate(hand.x + mx, hand.y + my);
g.setTransform(at);
getWeapon().draw(g);
g.setTransform(old);
}
@Override
public void mouseMoved(MouseEvent e)
{
lookingLeft = e.getX() < x + width / 2;
mouse = e.getPoint();
Vector dif = new Vector(e.getPoint()).sub(getWeaponPoint());
getWeapon().rot2 = (float) Math.toRadians(dif.getAngleOnXAxis() * (lookingLeft ? -1 : 1));
}
public Vector getWeaponPoint()
{
Vector exit = new Vector(getWeapon().getExit()).mul(Weapon.scale);
exit.x = 0;
Vector point = getPos().add(new Vector(hand)).sub(new Vector(getWeapon().getGrab()).mul(Weapon.scale)).add(exit);
return point;
}
@Override
public void mousePressed(MouseEvent e)
{
lookingLeft = e.getX() < x + width / 2;
mouse = e.getPoint();
Vector dif = new Vector(e.getPoint()).sub(getWeaponPoint());
getWeapon().rot2 = (float) Math.toRadians(dif.getAngleOnXAxis() * (lookingLeft ? -1 : 1));
getWeapon().shoot(new Vector(e.getPoint()));
}
@Override
public void keyPressed(KeyEvent e)
{
switch (e.getKeyCode())
{
case KeyEvent.VK_A:
{
left = true;
break;
}
case KeyEvent.VK_D:
{
right = true;
break;
}
case KeyEvent.VK_SPACE:
{
if (!airborne) getVelocity().y = -15;
up = true;
break;
}
// case KeyEvent.VK_SHIFT:
// down = true;
// break;
}
}
@Override
public void keyReleased(KeyEvent e)
{
switch (e.getKeyCode())
{
case KeyEvent.VK_A:
{
left = false;
break;
}
case KeyEvent.VK_D:
{
right = false;
break;
}
case KeyEvent.VK_SPACE:
{
up = false;
break;
}
// case KeyEvent.VK_S:
// down = false;
// break;
}
}
@Override
protected void tick(int tick)
{
int speed = airborne ? 3 : 4;
if (left) getVelocity().x = -speed;
if (right) getVelocity().x = speed;
if (!airborne && getVelocity().x != 0 && tick % 4 == 0)
{
frame = frame < 0 ? 0 : frame;
frame = (frame + 1) % 6;
}
else if (airborne)
{
frame = 11;
}
if (!left && !right)
{
frame = 3;
getVelocity().x = 0;
}
int mx = (Game.getWidth() - width) / 2;
int my = (Game.getHeight() - height) / 2;
if (user.getUsername().equals(Game.user.getUsername()))
{
if (x > mx && Game.world.width - x > (Game.getWidth() + width) / 2) Game.world.x = -x + mx;
if (y > my) Game.world.y = -y + my;
}
getWeapon().left = lookingLeft;
if (lookingLeft) hand = new Point(0, 60);
else hand = new Point(65, 60);
try
{
if (user.getUsername().equals(Game.user.getUsername())) Game.client.sendPacket(new Packet5PlayerData(this));
}
catch (IOException e)
{
e.printStackTrace();
}
}
public int getStyle()
{
return style;
}
public void setStyle(int style2)
{
style = style2;
}
public User getUser()
{
return user;
}
public Weapon getWeapon()
{
return weapon;
}
public void setWeapon(Weapon weapon)
{
this.weapon = weapon;
}
}
|
package de.epiceric.shopchest.utils;
import java.util.Map;
import org.apache.commons.lang.WordUtils;
import org.bukkit.DyeColor;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.BookMeta;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.LeatherArmorMeta;
import com.google.common.collect.ImmutableMap;
public class ItemNames {
private static final Map<String,String> map = ImmutableMap.<String,String>builder()
.put("1", "Stone")
.put("1:1", "Granite")
.put("1:2", "Polished Granite")
.put("1:3", "Diorite")
.put("1:4", "Polished Diorite")
.put("1:5", "Andesite")
.put("1:6", "Polished Andesite")
.put("2", "Grass Block")
.put("3", "Dirt")
.put("3:1", "Coarse Dirt")
.put("3:2", "Podzol")
.put("4", "Cobblestone")
.put("5", "Oak Wood Planks")
.put("5:1", "Spruce Wood Planks")
.put("5:2", "Birch Wood Planks")
.put("5:3", "Jungle Wood Planks")
.put("5:4", "Acacia Wood Planks")
.put("5:5", "Dark Oak Wood Planks")
.put("6", "Oak Sapling")
.put("6:1", "Spruce Sapling")
.put("6:2", "Birch Sapling")
.put("6:3", "Jungle Sapling")
.put("6:4", "Acacia Sapling")
.put("6:5", "Dark Oak Sapling")
.put("7", "Bedrock")
.put("8", "Water (No Spread)")
.put("9", "Water")
.put("10", "Lava (No Spread)")
.put("11", "Lava")
.put("12", "Sand")
.put("12:1", "Red Sand")
.put("13", "Gravel")
.put("14", "Gold Ore")
.put("15", "Iron Ore")
.put("16", "Coal Ore")
.put("17", "Oak Wood")
.put("17:1", "Spruce Wood")
.put("17:2", "Birch Wood")
.put("17:3", "Jungle Wood")
.put("18", "Oak Leaves")
.put("18:1", "Spruce Leaves")
.put("18:2", "Birch Leaves")
.put("18:3", "Jungle Leaves")
.put("19", "Sponge")
.put("19:1", "Wet Sponge")
.put("20", "Glass")
.put("21", "Lapis Lazuli Ore")
.put("22", "Lapis Lazuli Block")
.put("23", "Dispenser")
.put("24", "Sandstone")
.put("24:1", "Chiseled Sandstone")
.put("24:2", "Smooth Sandstone")
.put("25", "Note Block")
.put("26", "Bed")
.put("27", "Powered Rail")
.put("28", "Detector Rail")
.put("29", "Sticky Piston")
.put("30", "Web")
.put("31", "Shrub")
.put("31:1", "Grass")
.put("31:2", "Fern")
.put("32", "Dead Bush")
.put("33", "Piston")
.put("34", "Piston (Head)")
.put("35", "Wool")
.put("35:1", "Orange Wool")
.put("35:2", "Magenta Wool")
.put("35:3", "Light Blue Wool")
.put("35:4", "Yellow Wool")
.put("35:5", "Lime Wool")
.put("35:6", "Pink Wool")
.put("35:7", "Gray Wool")
.put("35:8", "Light Gray Wool")
.put("35:9", "Cyan Wool")
.put("35:10", "Purple Wool")
.put("35:11", "Blue Wool")
.put("35:12", "Brown Wool")
.put("35:13", "Green Wool")
.put("35:14", "Red Wool")
.put("35:15", "Black Wool")
.put("37", "Dandelion")
.put("38", "Rose")
.put("38:1", "Blue Orchid")
.put("38:2", "Allium")
.put("38:3", "Azure Bluet")
.put("38:4", "Red Tulip")
.put("38:5", "Orange Tulip")
.put("38:6", "White Tulip")
.put("38:7", "Pink Tulip")
.put("38:8", "Oxeye Daisy")
.put("39", "Brown Mushroom")
.put("40", "Red Mushroom")
.put("41", "Gold Block")
.put("42", "Iron Block")
.put("43", "Stone Slab (Double)")
.put("43:1", "Sandstone Slab (Double)")
.put("43:2", "Wooden Slab (Double)")
.put("43:3", "Cobblestone Slab (Double)")
.put("43:4", "Brick Slab (Double)")
.put("43:5", "Stone Brick Slab (Double)")
.put("43:6", "Nether Brick Slab (Double)")
.put("43:7", "Quartz Slab (Double)")
.put("43:8", "Smooth Stone Slab (Double)")
.put("43:9", "Smooth Sandstone Slab (Double)")
.put("44", "Stone Slab")
.put("44:1", "Sandstone Slab")
.put("44:2", "Wooden Slab")
.put("44:3", "Cobblestone Slab")
.put("44:4", "Brick Slab")
.put("44:5", "Stone Brick Slab")
.put("44:6", "Nether Brick Slab")
.put("44:7", "Quartz Slab")
.put("45", "Brick")
.put("46", "TNT")
.put("47", "Bookcase")
.put("48", "Moss Stone")
.put("49", "Obsidian")
.put("50", "Torch")
.put("51", "Fire")
.put("52", "Mob Spawner")
.put("53", "Oak Wood Stairs")
.put("54", "Chest")
.put("55", "Redstone Wire")
.put("56", "Diamond Ore")
.put("57", "Diamond Block")
.put("58", "Crafting Table")
.put("59", "Wheat (Crop)")
.put("60", "Farmland")
.put("61", "Furnace")
.put("62", "Furnace (Smelting)")
.put("63", "Sign (Block)")
.put("64", "Wood Door (Block)")
.put("65", "Ladder")
.put("66", "Rails")
.put("67", "Stone Stairs")
.put("68", "Sign (Wall Block)")
.put("69", "Lever")
.put("70", "Pressure Plate")
.put("71", "Iron Door (Block)")
.put("72", "Pressure Plate")
.put("73", "Redstone Ore")
.put("74", "Redstone Ore (Glowing)")
.put("75", "Redstone Torch (Off)")
.put("76", "Redstone Torch")
.put("77", "Button")
.put("78", "Snow")
.put("79", "Ice")
.put("80", "Snow Block")
.put("81", "Cactus")
.put("82", "Clay Block")
.put("83", "Sugar Cane (Block)")
.put("84", "Jukebox")
.put("85", "Fence")
.put("86", "Pumpkin")
.put("87", "Netherrack")
.put("88", "Soul Sand")
.put("89", "Glowstone")
.put("90", "Portal")
.put("91", "Jack-O-Lantern")
.put("92", "Cake (Block)")
.put("93", "Redstone Repeater (Block Off)")
.put("94", "Redstone Repeater (Block On)")
.put("95", "Stained Glass")
.put("96", "Wooden Trapdoor")
.put("97", "Stone Monster Egg")
.put("97:1", "Cobblestone Monster Egg")
.put("97:2", "Stone Brick Monster Egg")
.put("97:3", "Mossy Stone Brick Monster Egg")
.put("97:4", "Cracked Stone Brick Monster Egg")
.put("97:5", "Chiseled Stone Brick Monster Egg")
.put("98", "Stone Bricks")
.put("98:1", "Mossy Stone Bricks")
.put("98:2", "Cracked Stone Bricks")
.put("98:3", "Chiseled Stone Bricks")
.put("99", "Brown Mushroom (Block)")
.put("100", "Red Mushroom (Block)")
.put("101", "Iron Bars")
.put("102", "Glass Pane")
.put("103", "Melon (Block)")
.put("104", "Pumpkin Vine")
.put("105", "Melon Vine")
.put("106", "Vines")
.put("107", "Fence Gate")
.put("108", "Brick Stairs")
.put("109", "Stone Brick Stairs")
.put("110", "Mycelium")
.put("111", "Lily Pad")
.put("112", "Nether Brick")
.put("113", "Nether Brick Fence")
.put("114", "Nether Brick Stairs")
.put("115", "Nether Wart")
.put("116", "Enchantment Table")
.put("117", "Brewing Stand (Block)")
.put("118", "Cauldron (Block)")
.put("119", "End Portal")
.put("120", "End Portal Frame")
.put("121", "End Stone")
.put("122", "Dragon Egg")
.put("123", "Redstone Lamp (Inactive)")
.put("124", "Redstone Lamp (Active)")
.put("125", "Double Wood Slab")
.put("126", "Oak Wood Slab")
.put("126:1", "Spruce Wood Slab")
.put("126:2", "Birch Slab")
.put("126:3", "Jungle Slab")
.put("126:4", "Acacia Wood Slab")
.put("126:5", "Dark Oak Wood Slab")
.put("127", "Cocoa Plant")
.put("128", "Sandstone Stairs")
.put("129", "Emerald Ore")
.put("130", "Ender Chest")
.put("131", "Tripwire Hook")
.put("132", "Tripwire")
.put("133", "Emerald Block")
.put("134", "Spruce Wood Stairs")
.put("135", "Birch Wood Stairs")
.put("136", "Jungle Wood Stairs")
.put("137", "Command Block")
.put("138", "Beacon Block")
.put("139", "Cobblestone Wall")
.put("139:1", "Mossy Cobblestone Wall")
.put("140", "Flower Pot")
.put("141", "Carrots")
.put("142", "Potatoes")
.put("143", "Button")
.put("144", "Head")
.put("145", "Anvil")
.put("146", "Trapped Chest")
.put("147", "Weighted Pressure Plate (Light)")
.put("148", "Weighted Pressure Plate (Heavy)")
.put("149", "Redstone Comparator (inactive)")
.put("150", "Redstone Comparator (active)")
.put("151", "Daylight Sensor")
.put("152", "Redstone Block")
.put("153", "Nether Quartz Ore")
.put("154", "Hopper")
.put("155", "Quartz Block")
.put("155:1", "Chiseled Quartz Block")
.put("155:2", "Pillar Quartz Block")
.put("156", "Quartz Stairs")
.put("157", "Activator Rail")
.put("158", "Dropper")
.put("159", "Stained Clay")
.put("160", "Stained Glass Pane")
.put("161", "Acacia Leaves")
.put("161:1", "Dark Oak Leaves")
.put("162", "Acacia Wood")
.put("162:1", "Dark Oak Wood")
.put("163", "Acacia Wood Stairs")
.put("164", "Dark Oak Wood Stairs")
.put("165", "Slime Block")
.put("166", "Barrier")
.put("167", "Iron Trapdoor")
.put("168", "Prismarine")
.put("168:1", "Prismarine Bricks")
.put("168:2", "Dark Prismarine")
.put("169", "Sea Lantern")
.put("170", "Hay Block")
.put("171", "Carpet")
.put("172", "Hardened Clay")
.put("173", "Block of Coal")
.put("174", "Packed Ice")
.put("175", "Sunflower")
.put("175:1", "Lilac")
.put("175:2", "Double Tallgrass")
.put("175:3", "Large Fern")
.put("175:4", "Rose Bush")
.put("175:5", "Peony")
.put("178", "Daylight Sensor (Inverted)")
.put("179", "Red Sandstone")
.put("179:1", "Chiseled Red Sandstone")
.put("179:2", "Smooth Red Sandstone")
.put("180", "Red Sandstone Stairs")
.put("182", "Red Sandstone Slab")
.put("183", "Spruce Fence Gate")
.put("184", "Birch Fence Gate")
.put("185", "Jungle Fence Gate")
.put("186", "Dark Oak Fence Gate")
.put("187", "Acacia Fence Gate")
.put("188", "Spruce Fence")
.put("189", "Birch Fence")
.put("190", "Jungle Fence")
.put("191", "Dark Oak Fence")
.put("192", "Acacia Fence")
.put("198", "End Rod")
.put("199", "Chorus Plant")
.put("200", "Chorus Flower")
.put("201", "Purpur Block")
.put("202", "Purpur Pillar")
.put("203", "Purpur Stairs")
.put("204", "Purpur Slab (Double)")
.put("205", "Purpur Slab")
.put("206", "End Stone Bricks")
.put("208", "Grass Path")
.put("209", "End Gateway")
.put("210", "Repeating Command Block")
.put("211", "Chain Command Block")
.put("212", "Frosted Ice")
.put("255", "Structure Block")
.put("256", "Iron Shovel")
.put("257", "Iron Pickaxe")
.put("258", "Iron Axe")
.put("259", "Flint and Steel")
.put("260", "Apple")
.put("261", "Bow")
.put("262", "Arrow")
.put("263", "Coal")
.put("263:1", "Charcoal")
.put("264", "Diamond")
.put("265", "Iron Ingot")
.put("266", "Gold Ingot")
.put("267", "Iron Sword")
.put("268", "Wooden Sword")
.put("269", "Wooden Shovel")
.put("270", "Wooden Pickaxe")
.put("271", "Wooden Axe")
.put("272", "Stone Sword")
.put("273", "Stone Shovel")
.put("274", "Stone Pickaxe")
.put("275", "Stone Axe")
.put("276", "Diamond Sword")
.put("277", "Diamond Shovel")
.put("278", "Diamond Pickaxe")
.put("279", "Diamond Axe")
.put("280", "Stick")
.put("281", "Bowl")
.put("282", "Mushroom Stew")
.put("283", "Gold Sword")
.put("284", "Gold Shovel")
.put("285", "Gold Pickaxe")
.put("286", "Gold Axe")
.put("287", "String")
.put("288", "Feather")
.put("289", "Gunpowder")
.put("290", "Wooden Hoe")
.put("291", "Stone Hoe")
.put("292", "Iron Hoe")
.put("293", "Diamond Hoe")
.put("294", "Gold Hoe")
.put("295", "Seeds")
.put("296", "Wheat")
.put("297", "Bread")
.put("298", "Leather Helmet")
.put("299", "Leather Chestplate")
.put("300", "Leather Leggings")
.put("301", "Leather Boots")
.put("302", "Chainmail Helmet")
.put("303", "Chainmail Chestplate")
.put("304", "Chainmail Leggings")
.put("305", "Chainmail Boots")
.put("306", "Iron Helmet")
.put("307", "Iron Chestplate")
.put("308", "Iron Leggings")
.put("309", "Iron Boots")
.put("310", "Diamond Helmet")
.put("311", "Diamond Chestplate")
.put("312", "Diamond Leggings")
.put("313", "Diamond Boots")
.put("314", "Gold Helmet")
.put("315", "Gold Chestplate")
.put("316", "Gold Leggings")
.put("317", "Gold Boots")
.put("318", "Flint")
.put("319", "Raw Porkchop")
.put("320", "Cooked Porkchop")
.put("321", "Painting")
.put("322", "Gold Apple")
.put("322:1", "Gold Apple (Enchanted)")
.put("323", "Sign")
.put("324", "Wooden Door")
.put("325", "Bucket")
.put("326", "Water Bucket")
.put("327", "Lava Bucket")
.put("328", "Minecart")
.put("329", "Saddle")
.put("330", "Iron Door")
.put("331", "Redstone")
.put("332", "Snowball")
.put("333", "Boat")
.put("334", "Leather")
.put("335", "Milk Bucket")
.put("336", "Brick")
.put("337", "Clay")
.put("338", "Sugar Cane")
.put("339", "Paper")
.put("340", "Book")
.put("341", "Slime Ball")
.put("342", "Storage Minecart")
.put("343", "Powered Minecart")
.put("344", "Egg")
.put("345", "Compass")
.put("346", "Fishing Rod")
.put("347", "Watch")
.put("348", "Glowstone Dust")
.put("349", "Raw Fish")
.put("349:1", "Raw Salmon")
.put("349:2", "Clownfish")
.put("349:3", "Pufferfish")
.put("350", "Cooked Fish")
.put("350:1", "Cooked Salmon")
.put("351", "Ink Sack [Black Dye]")
.put("351:1", "Rose Red [Red Dye]")
.put("351:2", "Cactus Green [Green Dye]")
.put("351:3", "Cocoa Bean [Brown Dye]")
.put("351:4", "Lapis Lazuli [Blue Dye]")
.put("351:5", "Purple Dye")
.put("351:6", "Cyan Dye")
.put("351:7", "Light Gray Dye")
.put("351:8", "Gray Dye")
.put("351:9", "Pink Dye")
.put("351:10", "Lime Dye")
.put("351:11", "Dandelion Yellow [Yellow Dye]")
.put("351:12", "Light Blue Dye")
.put("351:13", "Magenta Dye")
.put("351:14", "Orange Dye")
.put("351:15", "Bone Meal [White Dye]")
.put("352", "Bone")
.put("353", "Sugar")
.put("354", "Cake")
.put("355", "Bed")
.put("356", "Redstone Repeater")
.put("357", "Cookie")
.put("358", "Map")
.put("359", "Shears")
.put("360", "Melon")
.put("361", "Pumpkin Seeds")
.put("362", "Melon Seeds")
.put("363", "Raw Beef")
.put("364", "Steak")
.put("365", "Raw Chicken")
.put("366", "Roast Chicken")
.put("367", "Rotten Flesh")
.put("368", "Ender Pearl")
.put("369", "Blaze Rod")
.put("370", "Ghast Tear")
.put("371", "Gold Nugget")
.put("372", "Nether Wart")
.put("373", "Water Bottle")
.put("373:16", "Awkward Potion")
.put("373:32", "Thick Potion")
.put("373:64", "Mundane Potion")
.put("373:8193", "Regeneration Potion (0:45)")
.put("373:8194", "Swiftness Potion (3:00)")
.put("373:8195", "Fire Resistance Potion (3:00)")
.put("373:8196", "Poison Potion (0:45)")
.put("373:8197", "Healing Potion")
.put("373:8200", "Weakness Potion (1:30)")
.put("373:8201", "Strength Potion (3:00)")
.put("373:8202", "Slowness Potion (1:30)")
.put("373:8203", "Potion of Leaping (3:00)")
.put("373:8204", "Harming Potion")
.put("373:8225", "Regeneration Potion II (0:22)")
.put("373:8226", "Swiftness Potion II (1:30)")
.put("373:8228", "Poison Potion II (0:22)")
.put("373:8229", "Healing Potion II")
.put("373:8230", "Night Vision Potion (3:00)")
.put("373:8233", "Strength Potion II (1:30)")
.put("373:8235", "Potion of Leaping (1:30)")
.put("373:8236", "Harming Potion II")
.put("373:8237", "Water Breathing Potion (3:00)")
.put("373:8238", "Invisibility Potion (3:00)")
.put("373:8257", "Regeneration Potion (2:00)")
.put("373:8258", "Swiftness Potion (8:00)")
.put("373:8259", "Fire Resistance Potion (8:00)")
.put("373:8260", "Poison Potion (2:00)")
.put("373:8262", "Night Vision Potion (8:00)")
.put("373:8264", "Weakness Potion (4:00)")
.put("373:8265", "Strength Potion (8:00)")
.put("373:8266", "Slowness Potion (4:00)")
.put("373:8269", "Water Breathing Potion (8:00)")
.put("373:8270", "Invisibility Potion (8:00)")
.put("373:16378", "Fire Resistance Splash (2:15)")
.put("373:16385", "Regeneration Splash (0:33)")
.put("373:16386", "Swiftness Splash (2:15)")
.put("373:16388", "Poison Splash (0:33)")
.put("373:16389", "Healing Splash")
.put("373:16392", "Weakness Splash (1:07)")
.put("373:16393", "Strength Splash (2:15)")
.put("373:16394", "Slowness Splash (1:07)")
.put("373:16396", "Harming Splash")
.put("373:16418", "Swiftness Splash II (1:07)")
.put("373:16420", "Poison Splash II (0:16)")
.put("373:16421", "Healing Splash II")
.put("373:16422", "Night Vision Splash (2:15)")
.put("373:16425", "Strength Splash II (1:07)")
.put("373:16428", "Harming Splash II")
.put("373:16429", "Water Breathing Splash (2:15)")
.put("373:16430", "Invisibility Splash (2:15)")
.put("373:16449", "Regeneration Splash (1:30)")
.put("373:16450", "Swiftness Splash (6:00)")
.put("373:16451", "Fire Resistance Splash (6:00)")
.put("373:16452", "Poison Splash (1:30)")
.put("373:16454", "Night Vision Splash (6:00)")
.put("373:16456", "Weakness Splash (3:00)")
.put("373:16457", "Strength Splash (6:00)")
.put("373:16458", "Slowness Splash (3:00)")
.put("373:16461", "Water Breathing Splash (6:00)")
.put("373:16462", "Invisibility Splash (6:00)")
.put("373:16471", "Regeneration Splash II (0:16)")
.put("374", "Glass Bottle")
.put("375", "Spider Eye")
.put("376", "Fermented Spider Eye")
.put("377", "Blaze Powder")
.put("378", "Magma Cream")
.put("379", "Brewing Stand")
.put("380", "Cauldron")
.put("381", "Eye of Ender")
.put("382", "Glistering Melon")
.put("383", "Spawn Egg")
.put("383:50", "Spawn Creeper")
.put("383:51", "Spawn Skeleton")
.put("383:52", "Spawn Spider")
.put("383:54", "Spawn Zombie")
.put("383:55", "Spawn Slime")
.put("383:56", "Spawn Ghast")
.put("383:57", "Spawn Pigman")
.put("383:58", "Spawn Enderman")
.put("383:59", "Spawn Cave Spider")
.put("383:60", "Spawn Silverfish")
.put("383:61", "Spawn Blaze")
.put("383:62", "Spawn Magma Cube")
.put("383:65", "Spawn Bat")
.put("383:66", "Spawn Witch")
.put("383:67", "Spawn Endermite")
.put("383:68", "Spawn Guardian")
.put("383:90", "Spawn Pig")
.put("383:91", "Spawn Sheep")
.put("383:92", "Spawn Cow")
.put("383:93", "Spawn Chicken")
.put("383:94", "Spawn Squid")
.put("383:95", "Spawn Wolf")
.put("383:96", "Spawn Mooshroom")
.put("383:98", "Spawn Ocelot")
.put("383:100", "Spawn Horse")
.put("383:101", "Spawn Rabbit")
.put("383:120", "Spawn Villager")
.put("384", "Bottle o' Enchanting")
.put("385", "Fire Charge")
.put("386", "Book and Quill")
.put("387", "Written Book")
.put("388", "Emerald")
.put("389", "Item Frame")
.put("390", "Flower Pot")
.put("391", "Carrot")
.put("392", "Potato")
.put("393", "Baked Potato")
.put("394", "Poisonous Potato")
.put("395", "Empty Map")
.put("396", "Golden Carrot")
.put("397", "Skull Item")
.put("397:0", "Skeleton Skull")
.put("397:1", "Wither Skeleton Skull")
.put("397:2", "Zombie Head")
.put("373:3", "Head")
.put("373:4", "Creeper Head")
.put("398", "Carrot on a Stick")
.put("399", "Nether Star")
.put("400", "Pumpkin Pie")
.put("401", "Firework Rocket")
.put("402", "Firework Star")
.put("403", "Enchanted Book")
.put("404", "Redstone Comparator")
.put("405", "Nether Brick")
.put("406", "Nether Quartz")
.put("407", "Minecart with TNT")
.put("408", "Minecart with Hopper")
.put("409", "Prismarine Shard")
.put("410", "Prismarine Crystals")
.put("411", "Raw Rabbit")
.put("412", "Cooked Rabbit")
.put("413", "Rabbit Stew")
.put("414", "Rabbit Foot")
.put("415", "Rabbit Hide")
.put("417", "Iron Horse Armor")
.put("418", "Gold Horse Armor")
.put("419", "Diamond Horse Armor")
.put("420", "Lead")
.put("421", "Name Tag")
.put("422", "Minecart with Command Block")
.put("423", "Raw Mutton")
.put("424", "Cooked Mutton")
.put("425", "Banner")
.put("426", "End Crystal")
.put("427", "Spruce Door")
.put("428", "Birch Door")
.put("429", "Jungle Door")
.put("430", "Acacia Door")
.put("431", "Dark Oak Door")
.put("432", "Chorus Fruit")
.put("433", "Popped Chorus Fruit")
.put("434", "Beetroot")
.put("435", "Beetroot Seeds")
.put("436", "Beetroot Soup")
.put("437", "Dragon Breath")
.put("438", "Splash Potion")
.put("439", "Spectral Arrow")
.put("440", "Tipped Arrow")
.put("441", "Lingering Potion")
.put("442", "Shield")
.put("443", "Elytra")
.put("444", "Spruce Boat")
.put("445", "Birch Boat")
.put("446", "Jungle Boat")
.put("447", "Acacia Boat")
.put("448", "Dark Oak Boat")
.put("2256", "Music Disk (13)")
.put("2257", "Music Disk (Cat)")
.put("2258", "Music Disk (Blocks)")
.put("2259", "Music Disk (Chirp)")
.put("2260", "Music Disk (Far)")
.put("2261", "Music Disk (Mall)")
.put("2262", "Music Disk (Mellohi)")
.put("2263", "Music Disk (Stal)")
.put("2264", "Music Disk (Strad)")
.put("2265", "Music Disk (Ward)")
.put("2266", "Music Disk (11)")
.put("2267", "Music Disk (wait)")
.build();
public static String lookup(ItemStack stack) {
if (stack.hasItemMeta()) {
ItemMeta meta = stack.getItemMeta();
if (meta.getDisplayName() != null) {
return meta.getDisplayName();
} else if (meta instanceof BookMeta) {
return ((BookMeta)meta).getTitle();
}
}
String result;
String key = Integer.toString(stack.getTypeId());
Material mat = stack.getType();
if ((mat == Material.WOOL || mat == Material.CARPET) && stack.getDurability() == 0) {
// special case: white wool/carpet is just called "Wool" or "Carpet"
result = map.get(key);
} else if (mat == Material.WOOL || mat == Material.CARPET || mat == Material.STAINED_CLAY || mat == Material.STAINED_GLASS || mat == Material.STAINED_GLASS_PANE) {
DyeColor dc = DyeColor.getByWoolData((byte)stack.getDurability());
result = dc == null ? map.get(key) : WordUtils.capitalizeFully(dc.toString().replace("_", " ")) + " " + map.get(key);
} else if (mat == Material.LEATHER_HELMET || mat == Material.LEATHER_CHESTPLATE || mat == Material.LEATHER_LEGGINGS || mat == Material.LEATHER_BOOTS) {
LeatherArmorMeta leatherArmorMeta = (LeatherArmorMeta) stack.getItemMeta();
DyeColor dc = DyeColor.getByColor(leatherArmorMeta.getColor());
result = dc == null ? map.get(key) : WordUtils.capitalizeFully(dc.toString()).replace("_", " ") + " " + map.get(key);
} else if (stack.getDurability() != 0) {
result = map.get(key + ":" + stack.getDurability());
if (result == null) {
result = map.get(key);
}
} else {
result = map.containsKey(key) ? map.get(key) : stack.getType().toString();
}
return result;
}
}
|
/** This class is parent class for RunDebugger and CompileDebugger which
produces info object what was done.
*/
// HYVIN kesken edelleen
public class Debugger extends Translatable{
// define methods like 'ALU happened, parameters x, y, z' and
// a 'command cycle complete', which returns the delta object for
// the gui. Contains eg. the commentary. Processor can then return it
// back to ControlBridge.
/** Constructor for Debugger.
*/
public static final short NOOPERATION = 0;
public static final short BASIC_OPERATION = 1;
public static final short ALU_OPERATION = 2;
public static final short JUMP_OPERATION = 3;
public static final short OTHER_OPERATION = 4;
public Debugger(){}
/** This method tells debugger that a new cycle has been started. It
initiates parameter values and stores old PC and IR. */
public void cycleStart(int lineNumber, int oldPC, int newPC, int IR, int SP,
int FP, String lineContents){ }
// joitain viel puutuu
public void memoryFetchType(int i){ }
/** This method tells debugger that a value was loaded to a given register.
*/
public void immediate(int register, int value){ }
/** This method tells debugger that direct memoryfetch was made. */
public void direct(int register, int where, int value){ }
public void directRegister(int toregister, int fromregister, int where,
int value){ }
public void indirectRegister(int toregister, int fromregister, int ...){ }
/** This method tells debugger that an indexed direct memoryfetch was used. */
public void indexedDirect(int toregister, int index, int where, int value){ }
/** This method tells debugger that an indexed direct from register
memoryfetch was used. */
public void indexedDirectRegister(int toregister, int index,
int fromregister, int where, int value){ }
/** This method tells debugger that an indirect memoryfetch was used. */
public void indirect(int toregister, int first, int second, int value){ }
/** This method tells debugger that an indexed indirect memoryfetch was
used. */
public void indexedIndirect(int toregister, int index, int first,
int second, int value){ }
public void noOperation(){ }
/** Store/Load */
public void store(String command, int Ri, int Rj){}
public void load(String command, int Ri, int Rj){}
public void in(String command, int device, int value){ }
public void out(String command, int device, int value){ }
/* ALU */
public void alu(String command, String symbol, int result){}
public void compare(String command, int SR, int Ri, int Rj){ }
public void jump(String command, int where){ }
public void conditionalJump(int SRIndex, String command, int where,
boolean conditionTrue) {}
/* Other */
public void call(String command, int newSP, int newFP){}
public void exit(String command, int newSP, int newFP){}
public void push(String command, int newSP, int value){}
public void pop(String command, int newSP, int value){}
public void pushr(String command, int newSP, int[] values){}
public void popr(String command, int newSP, int[] values){}
public void svc(String command, int serviceid){}
/** This method tells debugger that a command cycle was completed and it
should return a debuginfo package.
@returns DebugInfo
*/
public RunInfo cycleComplete(){ }
}
|
package example;
//-*- mode:java; encoding:utf8n; coding:utf-8 -*-
// vim:set fileencoding=utf-8:
//@homepage@
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
public class MainPanel extends JPanel {
private static final Color evenColor = new Color(250, 250, 250);
private final JCheckBox modelCheck = new JCheckBox("edit the cell on single click");
private final TestModel model = new TestModel();
public MainPanel() {
super(new BorderLayout());
model.addTest(new Test("Name 1", "Comment..."));
model.addTest(new Test("Name 2", "Test "));
model.addTest(new Test("Name d", ""));
model.addTest(new Test("Name c", "Test cc"));
model.addTest(new Test("Name b", "Test bb"));
model.addTest(new Test("Name a", ""));
model.addTest(new Test("Name 0", "Test aa"));
model.addTest(new Test("Name 0", ""));
final JTable table = new JTable(model) {
@Override public Component prepareRenderer(TableCellRenderer tcr, int row, int column) {
Component c = super.prepareRenderer(tcr, row, column);
if(isRowSelected(row)) {
c.setForeground(getSelectionForeground());
c.setBackground(getSelectionBackground());
}else{
c.setForeground(getForeground());
c.setBackground((row%2==0)?evenColor:getBackground());
}
return c;
}
};
table.setRowSelectionAllowed(true);
table.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
//table.setFillsViewportHeight(true);
table.setIntercellSpacing(new Dimension());
table.setShowGrid(false);
//table.setShowHorizontalLines(false);
//table.setShowVerticalLines(false);
table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
JTableHeader tableHeader = table.getTableHeader();
tableHeader.setReorderingAllowed(false);
TableColumn col = table.getColumnModel().getColumn(0);
col.setMinWidth(50);
col.setMaxWidth(50);
col.setResizable(false);
final DefaultTableCellRenderer defalutRenderer = (DefaultTableCellRenderer)table.getDefaultRenderer(Object.class);
final UnderlineCellRenderer underlineRenderer = new UnderlineCellRenderer();
final DefaultCellEditor ce = (DefaultCellEditor)table.getDefaultEditor(Object.class);
modelCheck.addActionListener(new ActionListener() {
@Override public void actionPerformed(ActionEvent e) {
if(modelCheck.isSelected()) {
table.setDefaultRenderer(Object.class, underlineRenderer);
table.addMouseListener(underlineRenderer);
table.addMouseMotionListener(underlineRenderer);
ce.setClickCountToStart(1);
}else{
table.setDefaultRenderer(Object.class, defalutRenderer);
table.removeMouseListener(underlineRenderer);
table.removeMouseMotionListener(underlineRenderer);
ce.setClickCountToStart(2);
}
}
});
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.getViewport().setBackground(Color.WHITE);
add(modelCheck, BorderLayout.NORTH);
add(scrollPane);
setPreferredSize(new Dimension(320, 240));
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
try{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}catch(Exception e) {
e.printStackTrace();
}
JFrame frame = new JFrame("@title@");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class UnderlineCellRenderer extends DefaultTableCellRenderer implements MouseListener, MouseMotionListener {
private int row = -1;
private int col = -1;
@Override public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus,
int row, int column) {
super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if(!table.isEditing() && this.row==row && this.col==column) {
setText("<html><u>"+value.toString());
}else{
setText(value.toString());
}
//setForeground(table.getForeground());
return this;
}
@Override public void mouseMoved(MouseEvent e) {
JTable table = (JTable)e.getSource();
Point pt = e.getPoint();
row = table.rowAtPoint(pt);
col = table.columnAtPoint(pt);
if(row<0 || col<0) row = col = -1;
table.repaint();
}
@Override public void mouseExited(MouseEvent e) {
JComponent c = (JComponent)e.getSource();
row = col = -1;
c.repaint();
}
@Override public void mouseDragged(MouseEvent e) {}
@Override public void mouseClicked(MouseEvent e) {}
@Override public void mouseEntered(MouseEvent e) {}
@Override public void mousePressed(MouseEvent e) {}
@Override public void mouseReleased(MouseEvent e) {}
}
|
package com.lion.rmtsndcli;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
public class MainActivity extends Activity {
public final static String EXTRA_MESSAGE = "com.lion.rmtsndcli.MESSAGE";
private ListView listView;
private ArrayList<String> listNames;
private ArrayList<String> listIps;
private StableArrayAdapter adapter;
MainActivity mainActPtr;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView)findViewById(R.id.listView1);
listNames = new ArrayList<String>();
listIps = new ArrayList<String>();
mainActPtr = this;
readDataFromFile();
adapter = new StableArrayAdapter(this,
android.R.layout.simple_list_item_1, listNames);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, final View view,
int position, long id) {
String message = listIps.get(position);
startClientActivity(message);
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
final int positionInList = position;
AlertDialog.Builder alert = new AlertDialog.Builder(mainActPtr);
alert.setTitle("Delete");
String item = (String) parent.getItemAtPosition(positionInList);
alert.setMessage(item);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
listNames.remove(positionInList);
listIps.remove(positionInList);
writeDataToFile();
adapter.updateMap(listNames);
adapter.notifyDataSetChanged();
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert.show();
return true;
}
});
}
private void readDataFromFile() {
// write to "addrList.txt";
String filename = "addrList.txt";
String string = "";
FileInputStream inputStream;
try {
inputStream = openFileInput(filename);
//inputStream.write(string.getBytes());
byte buffer[] = new byte[64];
int bytesAvailable = 0;
while((bytesAvailable = inputStream.read(buffer)) > 0){
string += new String(buffer, 0, bytesAvailable, Charset.defaultCharset());
}
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
//process string
while(string.length() > 0){
//find first pc
int sep = string.indexOf(',');
if(sep<0)break;
int eol = string.indexOf('\n');
if(eol<0 || eol<sep)break;
String name = string.substring(0, sep);
listNames.add(name);
String ip = string.substring(sep+1, eol);
listIps.add(ip);
string = string.substring(eol+1);
}
}
private class StableArrayAdapter extends ArrayAdapter<String> {
HashMap<String, Integer> mIdMap = new HashMap<String, Integer>();
public StableArrayAdapter(Context context, int textViewResourceId,
List<String> objects) {
super(context, textViewResourceId, objects);
for (int i = 0; i < objects.size(); ++i) {
mIdMap.put(objects.get(i), i);
}
}
@Override
public long getItemId(int position) {
String item = getItem(position);
return mIdMap.get(item);
}
public void updateMap(List<String> objects){
mIdMap.clear();
for (int i = 0; i < objects.size(); ++i) {
mIdMap.put(objects.get(i), i);
}
}
@Override
public boolean hasStableIds() {
return true;
}
}
/** Called when the user clicks the Send button */
public void onAddNewPCBtn(View view) {
getNameIpFromUser();
}
private int getNameIpFromUser(){
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Add new PC");
alert.setMessage("Name, IP Address:");
// Set an EditText view to get user input
final LinearLayout linlay = new LinearLayout(this);
linlay.setOrientation(1); //vertical
final EditText nameInp = new EditText(this);
nameInp.setSingleLine();
final EditText adrInp = new EditText(this);
adrInp.setSingleLine();
linlay.addView(nameInp);
linlay.addView(adrInp);
alert.setView(linlay);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String namesValue = nameInp.getText().toString();
String ipValue = adrInp.getText().toString();
// Do something with value!
listNames.add(namesValue);
listIps.add(ipValue);
writeDataToFile();
adapter.updateMap(listNames);
adapter.notifyDataSetChanged();
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert.show();
return 0;
}
protected void writeDataToFile() {
// write to "addrList.txt";
String filename = "addrList.txt";
String string = "";
FileOutputStream outputStream;
for(int i = 0; i < listNames.size() ; i++)
{
string += listNames.get(i);
string += ",";
string += listIps.get(i);
string += "\n";
}
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void startClientActivity(String message) {
// create new activity
Intent intent = new Intent(this, ClientActivity.class);
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
|
package edu.rpi.phil.legup.newgui;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FileDialog;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.GroupLayout;
import java.awt.Insets;
import java.io.File;
import java.io.FilenameFilter;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.ArrayList;
import java.util.LinkedList;
import javax.swing.AbstractButton;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JDesktopPane;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.SwingConstants;
import javax.swing.JTextArea;
import javax.swing.JToggleButton;
import javax.swing.JToolBar;
import javax.swing.event.InternalFrameEvent;
import javax.swing.event.InternalFrameListener;
import edu.rpi.phil.legup.BoardState;
import edu.rpi.phil.legup.Legup;
import edu.rpi.phil.legup.PuzzleModule;
import edu.rpi.phil.legup.PuzzleGeneration;
import edu.rpi.phil.legup.Selection;
import edu.rpi.phil.legup.Submission;
import edu.rpi.phil.legup.saveable.SaveableProof;
import edu.rpi.phil.legup.ILegupGui;
//import edu.rpi.phil.legup.newgui.TreeFrame;
import javax.swing.plaf.ToolBarUI;
import javax.swing.plaf.basic.BasicToolBarUI;
import java.awt.Color;
import java.awt.Point;
import java.io.IOException;
import javax.swing.BorderFactory;
//import javax.swing.border.Border;
import javax.swing.border.TitledBorder;
public class LEGUP_Gui extends JFrame implements ActionListener, TreeSelectionListener, ILegupGui, WindowListener
{
private static final long serialVersionUID = -2304281047341398965L;
/**
* Daniel Ploch - Added 09/25/2009
* Integrated variables for different Proof Modes in LEGUP
* The PROOF_CONFIG environment variable stores the settings as bitwise flags
*
* AllOW_JUST: Allows the user to use the Justification Panel to verify answers.
* ALLOW_HINTS: Allow the user to query the tutor for hints (no "Oops - I gave you the answer" step)
* ALLOW_DEFAPP: Allow the user to use default-applications (have the AI auto-infer parts of the solution)
* ALLOW_FULLAI: Gives user full access to the AI menu, including use of the AI solving algorithm (includes "Oops" tutor step).
* REQ_STEP_JUST: Requires the user to justify (correct not necessary) the latest transition before making a new one (safety/training device)
* IMD_FEEDBACK: Shows green and red arrows in Proof-Tree for correct/incorrect justifications in real-time.
* INTERN_RO: Internal nodes (in the Proof-Tree) are Read-Only, only leaf nodes can be modified. Ideal safety feature
* AUTO_JUST: AI automatically justifies moves as you make them.
*/
private static int CONFIG_INDEX = 0;
public static final int ALLOW_HINTS = 1;
public static final int ALLOW_DEFAPP = 2;
public static final int ALLOW_FULLAI = 4;
public static final int ALLOW_JUST = 8;
public static final int REQ_STEP_JUST = 16;
public static final int IMD_FEEDBACK = 32;
public static final int INTERN_RO = 64;
public static final int AUTO_JUST = 128;
public static boolean profFlag( int flag ){
return !((PROF_FLAGS[CONFIG_INDEX] & flag) == 0);
}
private static final String[] PROFILES = {
"No Assistance",
"Rigorous Proof",
"Casual Proof",
"Assisted Proof",
"Guided Proof",
"Training-Wheels Proof",
"No Restrictions" };
private static final int[] PROF_FLAGS = {
0,
ALLOW_JUST | REQ_STEP_JUST,
ALLOW_JUST,
ALLOW_HINTS | ALLOW_JUST | AUTO_JUST,
ALLOW_HINTS | ALLOW_JUST | REQ_STEP_JUST,
ALLOW_HINTS | ALLOW_DEFAPP | ALLOW_JUST | IMD_FEEDBACK | INTERN_RO,
ALLOW_HINTS | ALLOW_DEFAPP | ALLOW_FULLAI | ALLOW_JUST };
PickGameDialog pgd = null;
Legup legupMain = null;
private final FileDialog fileChooser;
private edu.rpi.phil.legup.AI myAI = new edu.rpi.phil.legup.AI();
/*** TOOLBAR CONSTANTS ***/
private static final int TOOLBAR_NEW = 0;
private static final int TOOLBAR_OPEN = 1;
private static final int TOOLBAR_SAVE = 2;
private static final int TOOLBAR_UNDO = 3;
private static final int TOOLBAR_REDO = 4;
private static final int TOOLBAR_CONSOLE = 5;
private static final int TOOLBAR_HINT = 6;
private static final int TOOLBAR_CHECK = 7;
private static final int TOOLBAR_SUBMIT = 8;
private static final int TOOLBAR_DIRECTIONS = 9;
private static final int TOOLBAR_ZOOMIN = 10;
private static final int TOOLBAR_ZOOMOUT = 11;
private static final int TOOLBAR_ZOOMRESET = 12;
private static final int TOOLBAR_ZOOMFIT = 13;
private static final int TOOLBAR_ANNOTATIONS = 14;
final static String[] toolBarNames =
{
"Open Puzzle",
"Open Proof",
"Save",
"Undo",
"Redo",
"Console",
"Hint",
"Check",
"Submit",
"Directions",
"Zoom In",
"Zoom Out",
"Normal Zoom",
"Best Fit",
"Annotations"
};
AbstractButton[] toolBarButtons =
{
new JButton(toolBarNames[0], new ImageIcon("images/" + toolBarNames[0] + ".png")),
new JButton(toolBarNames[1], new ImageIcon("images/" + toolBarNames[1] + ".png")),
new JButton(toolBarNames[2], new ImageIcon("images/" + toolBarNames[2] + ".png")),
new JButton(toolBarNames[3], new ImageIcon("images/" + toolBarNames[3] + ".png")),
new JButton(toolBarNames[4], new ImageIcon("images/" + toolBarNames[4] + ".png")),
new JButton(toolBarNames[5], new ImageIcon("images/" + toolBarNames[5] + ".png")),
new JButton(toolBarNames[6], new ImageIcon("images/" + toolBarNames[6] + ".png")),
new JButton(toolBarNames[7], new ImageIcon("images/" + toolBarNames[7] + ".png")), //Check
new JButton(toolBarNames[8], new ImageIcon("images/" + toolBarNames[8] + ".png")), //Submit
new JButton(toolBarNames[9], new ImageIcon("images/" + toolBarNames[9] + ".png")), //Directions
new JButton(/*toolBarNames[10],*/ new ImageIcon("images/" + toolBarNames[10] + ".png")),
new JButton(/*toolBarNames[11],*/ new ImageIcon("images/" + toolBarNames[11] + ".png")),
new JButton(/*toolBarNames[12],*/ new ImageIcon("images/" + toolBarNames[12] + ".png")),
new JButton(/*toolBarNames[13],*/ new ImageIcon("images/" + toolBarNames[13] + ".png")),
new JButton(toolBarNames[14], new ImageIcon("images/" + toolBarNames[14] + ".png")) //Toggle annotations
};
final static int[] toolbarSeperatorBefore =
{
3, 5, 9, 10
};
public void repaintBoard()
{
if (getBoard() != null) getBoard().boardDataChanged(null);
}
public LEGUP_Gui(Legup legupMain)
{
this.legupMain = legupMain;
legupMain.getSelections().addTreeSelectionListener(this);
setTitle("LEGUP");
setLayout( new BorderLayout() );
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setupMenu();
setupToolBar();
setupContent();
pack();
setVisible(true);
// Centers the window
setLocationRelativeTo( null );
fileChooser = new FileDialog(this);
}
// menubar related fields
private JMenuBar bar = new JMenuBar();
private JMenu file = new JMenu("File");
private JMenuItem newPuzzle = new JMenuItem("New Puzzle");
private JMenuItem genPuzzle = new JMenuItem("Puzzle Generators");
private JMenuItem openProof = new JMenuItem("Open LEGUP Proof");
private JMenuItem saveProof = new JMenuItem("Save LEGUP Proof");
private JMenuItem exit = new JMenuItem("Exit");
private JMenu edit = new JMenu("Edit");
private JMenuItem undo = new JMenuItem("Undo");
private JMenuItem redo = new JMenuItem("Redo");
// no entries yet
/* private JMenu view = new JMenu("View"); */
private JMenu proof = new JMenu("Proof");
private JCheckBoxMenuItem allowDefault = new JCheckBoxMenuItem("Allow Default Rule Applications",false);
public boolean checkAllowDefault() { return allowDefault.getState(); }
private JCheckBoxMenuItem caseRuleGen = new JCheckBoxMenuItem("Automatically generate cases for CaseRule",false);
public boolean checkCaseRuleGen() { return caseRuleGen.getState(); }
//public boolean autoGenCaseRules = false;
private JCheckBoxMenuItem imdFeedback = new JCheckBoxMenuItem("Provide immediate feedback",false);
public boolean checkImmediateFeedback() { return imdFeedback.getState(); }
//public boolean imdFeedbackFlag = false;
private JMenu proofMode = new JMenu("Proof Mode");
private JCheckBoxMenuItem[] proofModeItems = new JCheckBoxMenuItem[PROF_FLAGS.length];
private JMenu AI = new JMenu("AI");
private JMenuItem Run = new JMenuItem("Run AI to completion");
private JMenuItem Step = new JMenuItem("Run AI one Step");
private JMenuItem Test = new JMenuItem("Test AI!");
private JMenuItem hint = new JMenuItem("Hint");
private JMenu help = new JMenu("Help");
// contains all the code to setup the menubar
private void setupMenu(){
bar.add(file);
file.add(newPuzzle);
newPuzzle.addActionListener(this);
newPuzzle.setAccelerator(KeyStroke.getKeyStroke('N',2));
file.add(genPuzzle);
genPuzzle.addActionListener(this);
file.addSeparator();
file.add(openProof);
openProof.addActionListener(this);
openProof.setAccelerator(KeyStroke.getKeyStroke('O',2));
file.add(saveProof);
saveProof.addActionListener(this);
saveProof.setAccelerator(KeyStroke.getKeyStroke('S',2));
file.addSeparator();
file.add(exit);
exit.addActionListener(this);
exit.setAccelerator(KeyStroke.getKeyStroke('Q',2));
bar.add(edit);
edit.add(undo);
undo.addActionListener(this);
undo.setAccelerator(KeyStroke.getKeyStroke('Z',2));
edit.add(redo);
redo.addActionListener(this);
redo.setAccelerator(KeyStroke.getKeyStroke('Y',2));
// no entries yet
/* bar.add(view); */
bar.add(proof);
proof.add(allowDefault);
allowDefault.addActionListener(this);
proof.add(caseRuleGen);
caseRuleGen.addActionListener(this);
caseRuleGen.setState(true);
proof.add(imdFeedback);
imdFeedback.addActionListener(this);
imdFeedback.setState(true);
/*proof.add(proofMode);
for (int i = 0; i < PROF_FLAGS.length; i++)
{
proofModeItems[i] = new JCheckBoxMenuItem(PROFILES[i], i == CONFIG_INDEX);
proofModeItems[i].addActionListener(this);
proofMode.add(proofModeItems[i]);
}*/
/*bar.add(AI);
AI.add(Step);
Step.addActionListener(this);
Step.setAccelerator(KeyStroke.getKeyStroke("F9"));
AI.add(Run);
Run.addActionListener(this);
Run.setAccelerator(KeyStroke.getKeyStroke("F10"));
AI.add(Test);
Test.addActionListener(this);
AI.add(hint);
hint.addActionListener(this);
hint.setAccelerator(KeyStroke.getKeyStroke('H',0));*/
bar.add(help);
setJMenuBar(bar);
this.addWindowListener(this);
this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
System.out.println("listener initialized");
}
// toolbar related fields
private JToolBar toolBar;
// contains all the code to setup the toolbar
private void setupToolBar(){
toolBar = new JToolBar();
toolBar.setFloatable( false );
toolBar.setRollover( true );
for (int x = 0; x < toolBarButtons.length; ++x){
for (int y = 0; y < toolbarSeperatorBefore.length; ++y){
if (x == toolbarSeperatorBefore[y]){
toolBar.addSeparator();
}
}
toolBar.add(toolBarButtons[x]);
toolBarButtons[x].addActionListener(this);
toolBarButtons[x].setToolTipText(toolBarNames[x]);
// TODO text under icons
toolBarButtons[x].setVerticalTextPosition( SwingConstants.BOTTOM );
toolBarButtons[x].setHorizontalTextPosition( SwingConstants.CENTER );
}
// TODO disable buttons
toolBarButtons[TOOLBAR_SAVE].setEnabled(false);
toolBarButtons[TOOLBAR_UNDO].setEnabled(false);
toolBarButtons[TOOLBAR_REDO].setEnabled(false);
toolBarButtons[TOOLBAR_HINT].setEnabled(false);
toolBarButtons[TOOLBAR_CHECK].setEnabled(false);
toolBarButtons[TOOLBAR_SUBMIT].setEnabled(false);
toolBarButtons[TOOLBAR_DIRECTIONS].setEnabled(false);
toolBarButtons[TOOLBAR_ANNOTATIONS].setEnabled(false);
add( toolBar, BorderLayout.NORTH );
}
// TODO
private JustificationFrame justificationFrame;
private Tree tree;
public Tree getTree() {return tree;}
private Console console;
private Board board;
private TitledBorder boardBorder;
private JSplitPane test, test2;
public JustificationFrame getJustificationFrame()
{
return justificationFrame;//((JustificationFrame)test.getLeftComponent());
}
public Board getBoard()
{
return board;//((Board)test.getRightComponent());
}
private LinkedList<Board> boardStack = new LinkedList<Board>();
public void pushBoard(Board b)
{
b.setBorder(boardBorder);
boardStack.push(board);
int z1 = board.getZoom();
double z2 = ((double)z1) / 100;
b.zoomTo(z2);
b.getViewport().setViewPosition(board.getViewport().getViewPosition());
//b.zoomTo(board.getZoom());
board = b;
test.setRightComponent(b);
}
public void popBoard()// throws java.util.NoSuchElementException
{
Board b = boardStack.pop();
int z1 = board.getZoom();
double z2 = ((double)z1) / 100;
b.zoomTo(z2);
b.getViewport().setViewPosition(board.getViewport().getViewPosition());
//b.zoomTo(board.getZoom());
board = b;
test.setRightComponent(b);
}
// contains all the code to setup the main content
private void setupContent(){
JPanel consoleBox = new JPanel( new BorderLayout() );
JPanel treeBox = new JPanel( new BorderLayout() );
JPanel ruleBox = new JPanel( new BorderLayout() );
// TODO Console
console = new Console();
//consoleBox.add( console, BorderLayout.SOUTH );
// TODO experimental floating toolbar
//((BasicToolBarUI) console.getUI()).setFloatingLocation(500,500);
//((BasicToolBarUI) console.getUI()).setFloating(true, new Point(500,500));
// TODO
tree = new Tree( this );
//treeBox.add( tree, BorderLayout.SOUTH );
justificationFrame = new JustificationFrame( this );
//ruleBox.add( justificationFrame, BorderLayout.WEST );
board = new NormalBoard( this );
board.setPreferredSize( new Dimension( 600, 400 ) );
JPanel boardPanel = new JPanel( new BorderLayout() );
//boardPanel.add(board.pop);
//boardPanel.add( board );
//split pane fun :)
test = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true, justificationFrame, board);
test2 = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true, test, tree);
test.setPreferredSize(new Dimension(600, 400));
test2.setPreferredSize(new Dimension(600, 600));
//boardPanel.add(test);
boardPanel.add(test2);
//no more fun :(
boardBorder = BorderFactory.createTitledBorder("Board");
boardBorder.setTitleJustification(TitledBorder.CENTER);
board.setBorder(boardBorder);
ruleBox.add( boardPanel );
treeBox.add( ruleBox );
consoleBox.add( treeBox );
add( consoleBox );
//JLabel placeholder = new JLabel( "Nothing." );
//placeholder.setPreferredSize( new Dimension( 600, 400 ) );
//add( placeholder );
/*JPanel panel = new JPanel();
GroupLayout layout = new GroupLayout(panel);
panel.setLayout(layout);
tree = new Tree( this );
panel.add(tree);
justificationFrame = new JustificationFrame( this );
panel.add(tree);
board = new Board( this );
board.setPreferredSize( new Dimension( 600, 400 ) );
//JPanel boardPanel = new JPanel( new BorderLayout() );
//test = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true, justificationFrame, board);
//test2 = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true, test, tree);
//test.setPreferredSize(new Dimension(600, 400));
//test2.setPreferredSize(new Dimension(600, 600));
//boardPanel.add(test2);
TitledBorder title = BorderFactory.createTitledBorder("Board");
title.setTitleJustification(TitledBorder.CENTER);
board.setBorder(title);
panel.add(board);
layout.setHorizontalGroup( layout.createParallelGroup()
.addGroup(layout.createSequentialGroup()
.addComponent(justificationFrame)
.addComponent(board)
)
.addComponent(tree)
);
layout.setVerticalGroup( layout.createSequentialGroup()
.addGroup(layout.createParallelGroup()
.addComponent(justificationFrame)
.addComponent(board)
)
.addComponent(tree)
);
add(panel);*/
}
class proofFilter implements FilenameFilter
{
public boolean accept(File dir, String name)
{
System.out.println("proofFilter " + ((name.contains(".proof")) ? "accepts" : "rejects") + " \"" + name + "\"");
if(name.contains(".proof"))return true;
return false;
}
}
private void openProof()
{
if(Legup.getInstance().getInitialBoardState() != null){if(!noquit("opening a new proof?"))return;}
JFileChooser proofchooser = new JFileChooser("boards");
fileChooser.setMode(FileDialog.LOAD);
fileChooser.setTitle("Select Proof");
fileChooser.setVisible(true);
//proofFilter filter = new proofFilter();
//fileChooser.setFilenameFilter(filter);
String filename = fileChooser.getFile();
if (filename != null) // user didn't press cancel
{
filename = fileChooser.getDirectory() + filename;
if (!filename.toLowerCase().endsWith(".proof"))
{
JOptionPane.showMessageDialog(null,"File selected does not have the suffix \".proof\".");
return;
}
Legup.getInstance().loadProofFile(filename);
}
}
public void saveProof()
{
BoardState root = legupMain.getInitialBoardState();
if (root == null){return;}
fileChooser.setMode(FileDialog.SAVE);
fileChooser.setTitle("Select Proof");
fileChooser.setVisible(true);
//proofFilter filter = new proofFilter();
//fileChooser.setFilenameFilter(filter);
String filename = fileChooser.getFile();
if (filename != null) // user didn't pressed cancel
{
filename = fileChooser.getDirectory() + filename;
if (!filename.toLowerCase().endsWith(".proof"))
filename = filename + ".proof";
try {
SaveableProof.saveProof(root, filename);
getTree().modifiedSinceSave = false;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void checkProof()
{
BoardState root = legupMain.getInitialBoardState();
boolean delayStatus = root.evalDelayStatus();
repaintAll();
PuzzleModule pm = legupMain.getPuzzleModule();
if (pm.checkProof(root) && delayStatus)
{
int confirm = JOptionPane.showConfirmDialog(null, "Congratulations! Your proof is correct. Would you like to submit?", "Proof Submission", JOptionPane.YES_NO_OPTION);
if (confirm == 0)
{
Submission submit = new Submission(root, true);
}
showStatus("Your proof is correct.", false);
}
else
{
String message = "";
if(root.getFinalState() != null)
{
if(!delayStatus)message += "\nThere are invalid steps, which have been colored red.";
if(!pm.checkProof(root))message += "\nThe board is not solved.";
}
else message += "There is not a unique non-condradictory leaf state. Incomplete case rules are pale green.";
showStatus(message, true);
}
}
private void submit()
{
BoardState root = legupMain.getInitialBoardState();
boolean delayStatus = root.evalDelayStatus();
repaintAll();
PuzzleModule pm = legupMain.getPuzzleModule();
if (pm.checkProof(root) && delayStatus)
{
// 0 means yes, 1 means no (Java's fault...)
int confirm = JOptionPane.showConfirmDialog(null, "Are you sure you wish to submit?", "Proof Submission", JOptionPane.YES_NO_OPTION);
if (confirm == 0)
{
Submission submit = new Submission(root, true);
}
}
else
{
JOptionPane.showConfirmDialog(null, "Your proof is incorrect! Are you sure you wish to submit?", "Proof Submission", JOptionPane.YES_NO_OPTION);
Submission submit = new Submission(root, false);
}
}
private void directions()
{
JOptionPane.showMessageDialog(null, "For ever move you make, you must provide a justification for it (located in the Rules panel).\n"
+ "While working on the puzzle, you may click on the \"Check\" button to test your proof for correctness.",
"Directions", JOptionPane.PLAIN_MESSAGE);
}
private void showAll() {
getBoard().initSize();
// TODO disable buttons
toolBarButtons[TOOLBAR_SAVE].setEnabled(true);
toolBarButtons[TOOLBAR_UNDO].setEnabled(false);
toolBarButtons[TOOLBAR_REDO].setEnabled(false);
toolBarButtons[TOOLBAR_HINT].setEnabled(true);
toolBarButtons[TOOLBAR_CHECK].setEnabled(true);
toolBarButtons[TOOLBAR_SUBMIT].setEnabled(true);
toolBarButtons[TOOLBAR_DIRECTIONS].setEnabled(true);
toolBarButtons[TOOLBAR_ANNOTATIONS].setEnabled(true);
this.pack();
}
private void repaintAll(){
getBoard().repaint();
getJustificationFrame().repaint();
tree.repaint();
}
/*
* ILegupGui interface methods
* @see edu.rpi.phil.legup.ILegupGui
*/
public void showStatus(String status, boolean error)
{
showStatus(status,error,1);
}
public void showStatus(String status, boolean error, int timer)
{
getTree().updateStatusTimer = timer;
getJustificationFrame().setStatus(!error,status);
// TODO console
console.println( "Status: " + status );
}
public void errorEncountered(String error)
{
JOptionPane.showMessageDialog(null,error);
}
public void promptPuzzle(){
if(Legup.getInstance().getInitialBoardState() != null){
if(!noquit("opening a new puzzle?")) return;
}
JFileChooser newPuzzle = new JFileChooser("boards");
FileNameExtensionFilter filetype = new FileNameExtensionFilter( "LEGUP Puzzles", "xml" );
newPuzzle.setFileFilter( filetype );
if( newPuzzle.showOpenDialog(this) == JFileChooser.APPROVE_OPTION ){
legupMain.loadBoardFile( newPuzzle.getSelectedFile().getAbsolutePath() );
PuzzleModule pm = legupMain.getPuzzleModule();
if( pm != null ){
getJustificationFrame().setJustifications(pm);
// AI setup
myAI.setBoard(pm);
}
// show them all
showAll();
} else {
//System.out.println("Cancel Pressed");
}
}
public void reloadGui()
{
getJustificationFrame().setJustifications(Legup.getInstance().getPuzzleModule());
getJustificationFrame().resetSize();
// AI setup
myAI.setBoard(Legup.getInstance().getPuzzleModule());
// show them all
showAll();
}
/*
* Events
*/
//ask to save current proof
public boolean noquit(String instr)
{
if(!getTree().modifiedSinceSave)return true;
String quest = "Would you like to save your proof before ";
quest += instr;
LEGUP_Gui curgui = Legup.getInstance().getGui();
//System.out.println("Attempting to save good sirs...");
Object[] options = {"Save Proof", "Do Not Save Proof", "Cancel"};
int n = JOptionPane.showOptionDialog(bar, quest, "Save", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1]);
switch(n)
{
case JOptionPane.YES_OPTION:
curgui.saveProof();
return true;
case JOptionPane.NO_OPTION:
return true;
case JOptionPane.CANCEL_OPTION:
return false;
case JOptionPane.CLOSED_OPTION:
//pick an option!
return noquit(instr);
default:
return true;
}
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == newPuzzle || e.getSource() == toolBarButtons[TOOLBAR_NEW])
{
promptPuzzle();
}
else if (e.getSource() == openProof || e.getSource() == toolBarButtons[TOOLBAR_OPEN])
{
openProof();
int x = 0; //breakpoint
x = x + 1; //suppresses warnings of x not being used
}
else if (e.getSource() == saveProof || e.getSource() == toolBarButtons[TOOLBAR_SAVE])
{
saveProof();
}
else if (e.getSource() == genPuzzle)
{
PuzzleGeneratorDialog pgd = new PuzzleGeneratorDialog(this);
pgd.setVisible(true);
if (pgd.getChoice() == PuzzleGeneratorDialog.PUZZLE_CHOSEN)
{
PuzzleModule module = PuzzleGeneration.getModule(pgd.puzzleChosen());
BoardState puzzle = PuzzleGeneration.makePuzzle(pgd.puzzleChosen(), pgd.difficultyChosen(), this);
legupMain.initializeGeneratedPuzzle(module, puzzle);
getJustificationFrame().setJustifications(module);
// AI setup
myAI.setBoard(module);
// show them all
showAll();
}
}
else if (e.getSource() == exit)
{
System.exit(0);
}
else if (e.getSource() == undo || e.getSource() == toolBarButtons[TOOLBAR_UNDO])
{
getTree().undo();
resetUndoRedo();
//System.out.println("Undo!");
}
else if (e.getSource() == redo || e.getSource() == toolBarButtons[TOOLBAR_REDO])
{
getTree().redo();
resetUndoRedo();
//System.out.println("Redo!");
}
else if (e.getSource() == toolBarButtons[TOOLBAR_CONSOLE])
{
console.setVisible(!console.isVisible());
pack();
}
else if (e.getSource() == toolBarButtons[TOOLBAR_CHECK])
{
checkProof();
}
else if (e.getSource() == toolBarButtons[TOOLBAR_SUBMIT])
{
submit();
}
else if (e.getSource() == toolBarButtons[TOOLBAR_DIRECTIONS])
{
directions();
}
else if (e.getSource() == hint || e.getSource() == toolBarButtons[TOOLBAR_HINT])
{
// Is this really necessary? It's already being set when the puzzle loads...
//myAI.setBoard(Legup.getInstance().getPuzzleModule());
// TODO console
console.println("Tutor: " + myAI.findRuleApplication(Legup.getInstance().getSelections().getFirstSelection().getState()) );
}
else if (e.getSource() == toolBarButtons[TOOLBAR_ZOOMIN]){
// TODO - kueblc
/*/ DEBUG - Not actual actions!
((BasicToolBarUI) justificationFrame.getUI()).setFloatingLocation(500,500);
((BasicToolBarUI) justificationFrame.getUI()).setFloating(true, new Point(500,500));*/
getBoard().zoomIn();
}
else if (e.getSource() == toolBarButtons[TOOLBAR_ZOOMOUT]){
getBoard().zoomOut();
}
else if (e.getSource() == toolBarButtons[TOOLBAR_ZOOMRESET]){
getBoard().zoomTo(1.0);
}
else if (e.getSource() == toolBarButtons[TOOLBAR_ZOOMFIT]){
getBoard().zoomFit();
}
else if (e.getSource() == toolBarButtons[TOOLBAR_ANNOTATIONS])
{
legupMain.getPuzzleModule().toggleAnnotations();
repaintAll();
}
else if (e.getSource() == allowDefault)
{
//Change default applications on, nothing, checks menu checked state everywhere
}
else if (e.getSource() == caseRuleGen)
{
//autoGenCaseRules = caseRuleGen.getState();
}
else if (e.getSource() == imdFeedback)
{
//imdFeedbackFlag = imdFeedback.getState();
Tree.colorTransitions();
}
else if (e.getSource() == Step)
{
if (myAI.loaded()) {
BoardState current = legupMain.getSelections().getFirstSelection().getState();
myAI.step(current);
}
}
else if (e.getSource() == Run)
{
if (myAI.loaded()) {
BoardState current = legupMain.getSelections().getFirstSelection().getState();
myAI.stepToCompletion(current);
}
}
else if (e.getSource() == Test)
{
if (myAI.loaded()) {
//PuzzleModule current = legupMain.getPuzzleModule();
//myAI.test(current);
BoardState current = legupMain.getSelections().getFirstSelection().getState();
myAI.findRuleApplication(current);
}
}
else
{
for (int x = 0; x < PROF_FLAGS.length; ++x)
{
if (e.getSource() == proofModeItems[x]) processConfig(x);
}
}
}
public void resetUndoRedo()
{
undo.setEnabled(getTree().undoStack.size() > 1);
toolBarButtons[TOOLBAR_UNDO].setEnabled(getTree().undoStack.size() > 1);
redo.setEnabled(getTree().redoStack.size() > 0);
toolBarButtons[TOOLBAR_REDO].setEnabled(getTree().redoStack.size() > 0);
}
public void treeSelectionChanged(ArrayList <Selection> s)
{
resetUndoRedo();
repaintAll();
}
public void processConfig(int index)
{
proofModeItems[CONFIG_INDEX].setState(false);
CONFIG_INDEX = index;
proofModeItems[CONFIG_INDEX].setState(true);
int flags = PROF_FLAGS[index];
if (!profFlag(ALLOW_DEFAPP)) allowDefault.setState(false);
allowDefault.setEnabled(profFlag(ALLOW_DEFAPP));
AI.setEnabled(profFlag(ALLOW_FULLAI));
getJustificationFrame().setStatus(true, "Proof mode "+PROFILES[index]+" has been activated");
}
public void windowActivated(WindowEvent e) {
// TODO Auto-generated method stub
}
public void windowClosed(WindowEvent e) {
// TODO Auto-generated method stub
}
public void windowClosing(WindowEvent e) {
// TODO Auto-generated method stub
if(Legup.getInstance().getInitialBoardState() != null)
{
if(noquit("exiting LEGUP?"))
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
else
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void windowDeactivated(WindowEvent e) {
// TODO Auto-generated method stub
}
public void windowDeiconified(WindowEvent e) {
// TODO Auto-generated method stub
}
public void windowIconified(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
public void windowOpened(WindowEvent e) {
// TODO Auto-generated method stub
}
}
|
package edacc.experiment;
import edacc.EDACCApp;
import edacc.EDACCExperimentMode;
import edacc.EDACCSolverConfigEntry;
import edacc.EDACCSolverConfigPanel;
import edacc.model.DatabaseConnector;
import edacc.model.Experiment;
import edacc.model.ExperimentDAO;
import edacc.model.ExperimentHasGridQueue;
import edacc.model.ExperimentHasGridQueueDAO;
import edacc.model.ExperimentHasInstance;
import edacc.model.ExperimentHasInstanceDAO;
import edacc.model.ExperimentResult;
import edacc.model.ExperimentResultDAO;
import edacc.model.GridQueue;
import edacc.model.GridQueueDAO;
import edacc.model.Instance;
import edacc.model.InstanceClass;
import edacc.model.InstanceClassDAO;
import edacc.model.InstanceDAO;
import edacc.model.NoConnectionToDBException;
import edacc.model.Solver;
import edacc.model.SolverConfiguration;
import edacc.model.SolverConfigurationDAO;
import edacc.model.SolverDAO;
import edacc.model.Tasks;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Date;
import java.sql.SQLException;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.Vector;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
import javax.swing.JFileChooser;
/**
* Experiment design more controller class, handles requests by the GUI
* for creating, removing, loading, etc. experiments
* @author daniel
*/
public class ExperimentController {
EDACCExperimentMode main;
EDACCSolverConfigPanel solverConfigPanel;
private Experiment activeExperiment;
private Vector<Experiment> experiments;
private Vector<Instance> instances;
private Vector<Solver> solvers;
private Vector<InstanceClass> instanceClasses;
private static RandomNumberGenerator rnd = new JavaRandom();
/**
* Creates a new experiment Controller
* @param experimentMode
* @param solverConfigPanel
*/
public ExperimentController(EDACCExperimentMode experimentMode, EDACCSolverConfigPanel solverConfigPanel) {
this.main = experimentMode;
this.solverConfigPanel = solverConfigPanel;
}
/**
* Initializes the experiment controller. Loads the experiments and the instances classes.
* @throws SQLException
*/
public void initialize() throws SQLException {
Vector<Experiment> v = new Vector<Experiment>();
v.addAll(ExperimentDAO.getAll());
experiments = v;
main.expTableModel.setExperiments(experiments);
instances = new Vector<Instance>();
Vector<InstanceClass> vic = new Vector<InstanceClass>();
vic.addAll(InstanceClassDAO.getAll());
instanceClasses = vic;
main.instanceClassModel.addClasses(instanceClasses);
}
/**
* Loads an experiment, the solvers and the solver configurations.
* @param id
* @throws SQLException
*/
public void loadExperiment(int id) throws SQLException {
if (activeExperiment != null) {
// TODO! messagedlg,..
solverConfigPanel.removeAll();
}
activeExperiment = ExperimentDAO.getById(id);
Vector<Solver> vs = new Vector<Solver>();
vs.addAll(SolverDAO.getAll());
solvers = vs;
main.solTableModel.setSolvers(solvers);
Vector<SolverConfiguration> vss = SolverConfigurationDAO.getSolverConfigurationByExperimentId(id);
main.solverConfigPanel.beginUpdate();
for (int i = 0; i < vss.size(); i++) {
main.solverConfigPanel.addSolverConfiguration(vss.get(i));
for (int k = 0; k < main.solTableModel.getRowCount(); k++) {
if (((Solver) main.solTableModel.getValueAt(k, 5)).getId() == vss.get(i).getSolver_id()) {
main.solTableModel.setValueAt(true, k, 4);
}
}
}
main.solverConfigPanel.endUpdate();
main.insTableModel.setExperimentHasInstances(ExperimentHasInstanceDAO.getExperimentHasInstanceByExperimentId(activeExperiment.getId()));
if (instances.size() > 0) {
main.sorter.setRowFilter(main.rowFilter);
}
main.afterExperimentLoaded();
}
/**
* Removes an experiment form the db.
* @param id
* @return
* @throws SQLException
*/
public void removeExperiment(int id) throws SQLException {
Experiment e = ExperimentDAO.getById(id);
if (e.equals(activeExperiment)) {
unloadExperiment();
}
ExperimentDAO.removeExperiment(e);
initialize();
}
/**
* returns a reference to the currently loaded experiment or null, if none
* @return active experiment reference
*/
public Experiment getActiveExperiment() {
return activeExperiment;
}
/**
* unloads the currently loaded experiment, i.e. sets activeExperiment to null
* and calls UI functions to disable the experiment design tabs
*/
public void unloadExperiment() {
activeExperiment = null;
main.afterExperimentUnloaded();
}
/**
* invoked by the UI to create a new experiment, also calls initialize to load
* instances and solvers
* @param name
* @param date
* @param description
* @throws SQLException
*/
public void createExperiment(String name, String description) throws SQLException {
java.util.Date d = new java.util.Date();
ExperimentDAO.createExperiment(name, new Date(d.getTime()), description);
initialize();
}
/**
* Saves all solver configurations with parameter instances in the solver
* config panel.
* @throws SQLException
*/
public void saveSolverConfigurations() throws SQLException {
for (int i = 0; i < solverConfigPanel.getComponentCount(); i++) {
EDACCSolverConfigEntry entry = (EDACCSolverConfigEntry) solverConfigPanel.getComponent(i);
int seed_group = 0;
try {
seed_group = Integer.valueOf(entry.getSeedGroup().getText());
} catch (NumberFormatException e) {
seed_group = 0;
entry.getSeedGroup().setText("0");
javax.swing.JOptionPane.showMessageDialog(null, "Seed groups have to be integers, defaulted to 0", "Expected integer for seed groups", javax.swing.JOptionPane.ERROR_MESSAGE);
}
if (entry.getSolverConfiguration() == null) {
entry.setSolverConfiguration(SolverConfigurationDAO.createSolverConfiguration(entry.getSolverId(), activeExperiment.getId(), seed_group));
} else {
entry.getSolverConfiguration().setSeed_group(seed_group);
entry.getSolverConfiguration().setModified();
}
entry.saveParameterInstances();
}
SolverConfigurationDAO.saveAll();
}
/**
* saves the instances selection of the currently loaded experiment
* @throws SQLException
*/
public void saveExperimentHasInstances() throws SQLException {
for (int i = 0; i < main.insTableModel.getRowCount(); i++) {
if ((Boolean) main.insTableModel.getValueAt(i, 5)) {
if ((ExperimentHasInstance) main.insTableModel.getValueAt(i, 6) == null) {
main.insTableModel.setExperimentHasInstance(ExperimentHasInstanceDAO.createExperimentHasInstance(activeExperiment.getId(), ((Instance) main.insTableModel.getValueAt(i, 7)).getId()), i);
}
} else {
ExperimentHasInstance ei = (ExperimentHasInstance) main.insTableModel.getValueAt(i, 6);
if (ei != null) {
ExperimentHasInstanceDAO.removeExperimentHasInstance(ei);
main.insTableModel.setExperimentHasInstance(null, i);
}
}
}
}
/**
* method used for auto seed generation, uses the random number generator
* referenced by this.rnd
* @return integer between 0 and max inclusively
*/
private int generateSeed(int max) {
return rnd.nextInt(max + 1);
}
/**
* generates the ExperimentResults (jobs) in the database for the currently active experiment
* This is the cartesian product of the set of solver configs and the set of the selected instances
* Doesn't overwrite existing jobs
* @throws SQLException
* @param numRuns
* @param timeout
* @param generateSeeds
* @param maxSeed
* @return number of jobs added to the experiment results table
* @throws SQLException
*/
public int generateJobs(int numRuns, int timeout, boolean generateSeeds, int maxSeed, boolean linkSeeds, Tasks task) throws SQLException {
activeExperiment.setAutoGeneratedSeeds(generateSeeds);
activeExperiment.setNumRuns(numRuns);
activeExperiment.setTimeOut(timeout);
ExperimentDAO.setModified(activeExperiment);
ExperimentDAO.save(activeExperiment);
// get instances of this experiment
LinkedList<Instance> listInstances = InstanceDAO.getAllByExperimentId(activeExperiment.getId());
// get solver configurations of this experiment
Vector<SolverConfiguration> vsc = SolverConfigurationDAO.getSolverConfigurationByExperimentId(activeExperiment.getId());
int experiments_added = 0;
Hashtable<SeedGroup, Integer> linked_seeds = new Hashtable<SeedGroup, Integer>();
Vector<ExperimentResult> experiment_results = new Vector<ExperimentResult>();
if (generateSeeds && linkSeeds) {
// first pass over already existing jobs to accumulate existing linked seeds
for (Instance i : listInstances) {
for (SolverConfiguration c : vsc) {
for (int run = 0; run < numRuns; ++run) {
task.setStatus("Preparing job generation");
if (ExperimentResultDAO.jobExists(run, c.getId(), i.getId(), activeExperiment.getId())) {
// use the already existing jobs to populate the seed group hash table so jobs of newly added solver configs use
// the same seeds as already existing jobs
int seed = ExperimentResultDAO.getSeedValue(run, c.getId(), i.getId(), activeExperiment.getId());
SeedGroup sg = new SeedGroup(c.getSeed_group(), i.getId(), run);
if (!linked_seeds.contains(sg)) {
linked_seeds.put(sg, new Integer(seed));
}
}
}
}
}
}
int elements = listInstances.size() * vsc.size() * numRuns;
int done = 1;
// cartesian product
for (Instance i : listInstances) {
for (SolverConfiguration c : vsc) {
for (int run = 0; run < numRuns; ++run) {
task.setTaskProgress((float) done / (float) elements);
task.setStatus("Adding Job " + done + " of " + elements);
// check if job already exists
if (ExperimentResultDAO.jobExists(run, c.getId(), i.getId(), activeExperiment.getId()) == false) {
if (generateSeeds && linkSeeds) {
Integer seed = linked_seeds.get(new SeedGroup(c.getSeed_group(), i.getId(), run));
if (seed != null) {
experiment_results.add(ExperimentResultDAO.createExperimentResult(run, -1, seed.intValue(), "", 0, -1, c.getId(), activeExperiment.getId(), i.getId()));
} else {
Integer new_seed = new Integer(generateSeed(maxSeed));
linked_seeds.put(new SeedGroup(c.getSeed_group(), i.getId(), run), new_seed);
experiment_results.add(ExperimentResultDAO.createExperimentResult(run, -1, new_seed.intValue(), "", 0, -1, c.getId(), activeExperiment.getId(), i.getId()));
}
} else if (generateSeeds && !linkSeeds) {
experiment_results.add(ExperimentResultDAO.createExperimentResult(run, -1, generateSeed(maxSeed), "", 0, -1, c.getId(), activeExperiment.getId(), i.getId()));
} else {
experiment_results.add(ExperimentResultDAO.createExperimentResult(run, -1, 0, "", 0, -1, c.getId(), activeExperiment.getId(), i.getId()));
}
experiments_added++;
}
done++;
}
}
}
ExperimentResultDAO.batchSave(experiment_results);
return experiments_added;
}
/**
* returns the number of jobs in the database for the given experiment
* @return
*/
public int getNumJobs() {
try {
return ExperimentResultDAO.getCountByExperimentId(activeExperiment.getId());
} catch (Exception e) {
return 0;
}
}
/**
* returns the number of instances shown in the instance selection tab
* @return
*/
public int getNumInstances() {
return instances.size();
}
public void loadJobs() {
try {
main.jobsTableModel.jobs = ExperimentResultDAO.getAllByExperimentId(activeExperiment.getId());
main.jobsTableModel.fireTableDataChanged();
} catch (Exception e) {
// TODO: shouldn't happen but show message if it does
}
}
private JFileChooser packageFileChooser;
/**
* Generates a ZIP archive with the necessary files for the grid.
*/
public void generatePackage() throws FileNotFoundException, IOException, NoConnectionToDBException, SQLException, ClientBinaryNotFoundException {
final String fileSep = System.getProperty("file.separator");
if (packageFileChooser == null) {
packageFileChooser = new JFileChooser();
packageFileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
}
if (packageFileChooser.showDialog(main, "Select Package Location") != JFileChooser.APPROVE_OPTION)
return;
File zipFile = new File(packageFileChooser.getSelectedFile().getAbsolutePath() + fileSep + activeExperiment.getDate().toString() + " - " + activeExperiment.getName() + ".zip");
if (zipFile.exists()) {
zipFile.delete();
}
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile));
ZipEntry entry;
// add solvers to zip file
Vector<Solver> solvers = ExperimentDAO.getSolversInExperiment(activeExperiment);
for (Solver s : solvers) {
File bin = SolverDAO.getBinaryFileOfSolver(s);
entry = new ZipEntry("solvers" + fileSep + s.getBinaryName());
addFileToZIP(bin, entry, zos);
}
// add instances to zip file
LinkedList<Instance> instances = InstanceDAO.getAllByExperimentId(activeExperiment.getId());
for (Instance i : instances) {
File f = InstanceDAO.getBinaryFileOfInstance(i);
entry = new ZipEntry("instances" + fileSep + i.getId() + "_" + i.getName());
addFileToZIP(f, entry, zos);
}
// add PBS script
// TODO extend to multiple queue support
Vector<ExperimentHasGridQueue> eqs = ExperimentHasGridQueueDAO.getExperimentHasGridQueueByExperiment(activeExperiment);
ExperimentHasGridQueue eq = eqs.get(eqs.size() - 1);
GridQueue q = GridQueueDAO.getById(eq.getIdGridQueue());
File f = GridQueueDAO.getPBS(q);
entry = new ZipEntry("start_client.pbs");
addFileToZIP(f, entry, zos);
// add configuration File
addConfigurationFile(zos, activeExperiment, q);
// add run script
addRunScript(zos, q);
// add client binary
addClient(zos);
// add empty result library
entry = new ZipEntry("result" + fileSep + "~");
zos.putNextEntry(entry);
zos.close();
// delete tmp directory
deleteDirectory(new File("tmp"));
}
private boolean deleteDirectory(File dir) {
if (dir.exists()) {
File[] files = dir.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
deleteDirectory(files[i]);
} else {
files[i].delete();
}
}
}
return (dir.delete());
}
/**
* Adds a file to an open zip file.
* @param f the location of the file to be added.
* @param entry the zip entry to be created.
* @param zos the open ZIPOutputStream of the zip file.
*/
private void addFileToZIP(File f, ZipEntry entry, ZipOutputStream zos) throws FileNotFoundException, IOException {
FileInputStream in = new FileInputStream(f);
zos.putNextEntry(entry);
int data;
while ((data = in.read()) > -1) {
zos.write(data);
}
zos.closeEntry();
in.close();
}
/**
* Assigns a gridQueue to the active experiment.
* This means: It creates a new ExperimentHasGridQueue object and persists it in the db.
* @param q
* @throws SQLException
*/
public void assignQueueToExperiment(GridQueue q) throws SQLException {
// check if assignment already exists
if (ExperimentHasGridQueueDAO.getByExpAndQueue(activeExperiment, q) != null) {
return;
}
ExperimentHasGridQueue eq = ExperimentHasGridQueueDAO.createExperimentHasGridQueue(activeExperiment, q);
}
void addInstancesToVector(Vector<Instance> instances) {
this.instances.addAll(instances);
}
void removeAllInstancesFromVector() {
this.instances.clear();
}
public void selectAllInstanceClasses() {
for (int i = 0; i
< main.instanceClassModel.getRowCount(); i++) {
main.instanceClassModel.setInstanceClassSelected(i);
}
}
public void deselectAllInstanceClasses() {
for (int i = 0; i
< main.instanceClassModel.getRowCount(); i++) {
main.instanceClassModel.setInstanceClassDeselected(i);
}
}
private void addConfigurationFile(ZipOutputStream zos, Experiment activeExperiment, GridQueue activeQueue) throws IOException {
// generate content of config file
String sConf = "host = $host\n"
+ "username = $user\n"
+ "password = $pwd\n"
+ "database = $db\n"
+ "experiment = $exp\n"
+ "gridqueue = $q\n";
DatabaseConnector con = DatabaseConnector.getInstance();
sConf = sConf.replace("$host", con.getHostname());
sConf = sConf.replace("$user", con.getUsername());
sConf = sConf.replace("$pwd", con.getPassword());
sConf = sConf.replace("$db", con.getDatabase());
sConf = sConf.replace("$exp", String.valueOf(activeExperiment.getId()));
sConf = sConf.replace("$q", String.valueOf(activeQueue.getId()));
// write file into zip archive
ZipEntry entry = new ZipEntry("config");
zos.putNextEntry(entry);
zos.write(sConf.getBytes());
zos.closeEntry();
}
private void addRunScript(ZipOutputStream zos, GridQueue q) throws IOException {
String sRun = "#!/bin/bash\n"
+ "for (( i = 1; i < " + q.getNumNodes() + "; i++ ))\n"
+ "do\n"
+ " qsub start_client.pbs\n"
+ "done\n";
// write file into zip archive
ZipEntry entry = new ZipEntry("run.sh");
zos.putNextEntry(entry);
zos.write(sRun.getBytes());
zos.closeEntry();
}
private void addClient(ZipOutputStream zos) throws IOException, ClientBinaryNotFoundException {
InputStream in = EDACCApp.class.getClassLoader().getResourceAsStream("client");
if (in == null)
throw new ClientBinaryNotFoundException();
ZipEntry entry = new ZipEntry("client");
zos.putNextEntry(entry);
int data;
while ((data = in.read()) > -1) {
zos.write(data);
}
zos.closeEntry();
in.close();
}
}
|
package edu.cmu.pocketsphinx;
import static java.lang.String.format;
import java.io.File;
import java.util.Collection;
import java.util.HashSet;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder.AudioSource;
import android.os.*;
import android.util.Log;
import edu.cmu.pocketsphinx.Config;
import edu.cmu.pocketsphinx.Decoder;
import edu.cmu.pocketsphinx.Hypothesis;
public class SpeechRecognizer {
protected static final String TAG = SpeechRecognizer.class.getSimpleName();
private static final int BUFFER_SIZE = 1024;
private final Config config;
private final Decoder decoder;
private Thread recognizerThread;
private final Handler mainHandler = new Handler(Looper.getMainLooper());
private final Collection<RecognitionListener> listeners =
new HashSet<RecognitionListener>();
private final int sampleRate;
protected SpeechRecognizer(Config config) {
sampleRate = (int) config.getFloat("-samprate");
if (config.getFloat("-samprate") != sampleRate)
throw new IllegalArgumentException("sampling rate must be integer");
this.config = config;
decoder = new Decoder(config);
}
/**
* Adds listener.
*/
public void addListener(RecognitionListener listener) {
synchronized (listeners) {
listeners.add(listener);
}
}
/**
* Removes listener.
*/
public void removeListener(RecognitionListener listener) {
synchronized (listeners) {
listeners.remove(listener);
}
}
/**
* Starts recognition. Does nothing if recognition is active.
*
* @return true if recognition was actually started
*/
public boolean startListening(String searchName) {
if (null != recognizerThread)
return false;
Log.i(TAG, format("Start recognition \"%s\"", searchName));
decoder.setSearch(searchName);
recognizerThread = new RecognizerThread();
recognizerThread.start();
return true;
}
private boolean stopRecognizerThread() {
if (null == recognizerThread)
return false;
try {
recognizerThread.interrupt();
recognizerThread.join();
} catch (InterruptedException e) {
// Restore the interrupted status.
Thread.currentThread().interrupt();
}
recognizerThread = null;
return true;
}
/**
* Stops recognition. All listeners should receive final result if there is
* any. Does nothing if recognition is not active.
*
* @return true if recognition was actually stopped
*/
public boolean stop() {
boolean result = stopRecognizerThread();
if (result)
Log.i(TAG, "Stop recognition");
return result;
}
/**
* Cancels recogition. Listeners do not recevie final result. Does nothing
* if recognition is not active.
*
* @return true if recognition was actually canceled
*/
public boolean cancel() {
boolean result = stopRecognizerThread();
if (result) {
Log.i(TAG, "Cancel recognition");
mainHandler.removeCallbacksAndMessages(null);
}
return result;
}
/**
* Gets name of the currently active search.
*
* @return active search name or null if no search was started
*/
public String getSearchName() {
return decoder.getSearch();
}
public void addFsgSearch(String searchName, FsgModel fsgModel) {
decoder.setFsg(searchName, fsgModel);
}
/**
* Adds searches based on JSpeech grammar.
*
* @param name search name
* @param file JSGF file
*/
public void addGrammarSearch(String name, File file) {
Log.i(TAG, format("Load JSGF %s", file));
decoder.setJsgfFile(name, file.getPath());
}
/**
* Adds search based on N-gram language model.
*
* @param name search name
* @param file N-gram model file
*/
public void addNgramSearch(String name, File file) {
Log.i(TAG, format("Load N-gram model %s", file));
decoder.setLmFile(name, file.getPath());
}
/**
* Adds search based on a single phrase.
*
* @param name search name
* @param phrase search phrase
*/
public void addKeywordSearch(String name, String phrase) {
decoder.setKws(name, phrase);
}
private final class RecognizerThread extends Thread {
@Override public void run() {
AudioRecord recorder =
new AudioRecord(AudioSource.VOICE_RECOGNITION,
sampleRate,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT,
8192); // TODO:calculate properly
decoder.startUtt(null);
recorder.startRecording();
short[] buffer = new short[BUFFER_SIZE];
boolean vadState = decoder.getVadState();
while (!interrupted()) {
int nread = recorder.read(buffer, 0, buffer.length);
if (-1 == nread) {
throw new RuntimeException("error reading audio buffer");
} else if (nread > 0) {
decoder.processRaw(buffer, nread, false, false);
if (decoder.getVadState() != vadState) {
vadState = decoder.getVadState();
mainHandler.post(new VadStateChangeEvent(vadState));
}
final Hypothesis hypothesis = decoder.hyp();
if (null != hypothesis)
mainHandler.post(new ResultEvent(hypothesis, false));
}
}
recorder.stop();
int nread = recorder.read(buffer, 0, buffer.length);
recorder.release();
decoder.processRaw(buffer, nread, false, false);
decoder.endUtt();
// Remove all pending notifications.
mainHandler.removeCallbacksAndMessages(null);
final Hypothesis hypothesis = decoder.hyp();
if (null != hypothesis)
mainHandler.post(new ResultEvent(hypothesis, true));
}
}
private abstract class RecognitionEvent implements Runnable {
public void run() {
RecognitionListener[] emptyArray = new RecognitionListener[0];
for (RecognitionListener listener : listeners.toArray(emptyArray))
execute(listener);
}
protected abstract void execute(RecognitionListener listener);
}
private class VadStateChangeEvent extends RecognitionEvent {
private final boolean state;
VadStateChangeEvent(boolean state) {
this.state = state;
}
@Override protected void execute(RecognitionListener listener) {
if (state)
listener.onBeginningOfSpeech();
else
listener.onEndOfSpeech();
}
}
private class ResultEvent extends RecognitionEvent {
protected final Hypothesis hypothesis;
private final boolean finalResult;
ResultEvent(Hypothesis hypothesis, boolean finalResult) {
this.hypothesis = hypothesis;
this.finalResult = finalResult;
}
@Override protected void execute(RecognitionListener listener) {
if (finalResult)
listener.onResult(hypothesis);
else
listener.onPartialResult(hypothesis);
}
}
}
/* vim: set ts=4 sw=4: */
|
package eigthqueentest;
import java.util.ArrayList;
import algorithm.GeneticAlgorithm;
import algorithm.Genotype;
import algorithm.Population;
import genotypes.PermutationGenotype;
import selection.RandomSelection;
public class GAFrameworkApplication {
public static void main(String[] args) {
int populationSize = 10;
int numberOfPopulations = 1;
int numberOfGenes = 8;
double targetFitness = 0;
GeneticAlgorithm<PermutationGenotype> algorithm;
ArrayList<Population<PermutationGenotype>> populations = new ArrayList<Population<PermutationGenotype>>();
for (int i = 0; i < numberOfPopulations; i++) {
PermutationGenotype[] genotypes = new PermutationGenotype[populationSize];
for (int j = 0; j < populationSize; j++) {
genotypes[j] = new PermutationGenotype(numberOfGenes);
}
populations.add(new Population<PermutationGenotype>(genotypes,new RandomSelection(),new EightQueenFitness()));
}
long startTime=0,endTime = 0;
algorithm = new GeneticAlgorithm<>(populations, targetFitness);
algorithm.start();
startTime = System.currentTimeMillis();
try {
algorithm.join();
endTime = System.currentTimeMillis();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Genotype solution = algorithm.getBestSolutionFound();
if(solution != null)
{
int [] genes = ((PermutationGenotype)solution).getGenes();
for (int i = 0; i < genes.length; i++) {
System.out.print(genes[i]+" ");
}
}
System.out.println("Elapsed time (milliseconds): "+(endTime - startTime));
}
}
|
package se.llbit.tinytemplate;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.LinkedList;
import se.llbit.io.LookaheadReader;
public class TemplateParser {
/**
* Thrown when there is a syntax error a parsed template file
*/
@SuppressWarnings("serial")
public class SyntaxError extends Exception {
/**
* @param line Line where the error occurred
* @param msg Error message
*/
public SyntaxError(int line, String msg) {
super("Parse error at line " + line + ": " + msg);
}
/**
* @param msg Error message
*/
public SyntaxError(String msg) {
super(msg);
}
}
private final TinyTemplate templates;
private final LookaheadReader in;
private int line = 1;
/**
* @param tt
* @param is
*/
public TemplateParser(TinyTemplate tt, InputStream is) {
templates = tt;
in = new LookaheadReader(is, 2);
}
/**
* @throws SyntaxError Indicates that there occurred a syntax error during
* parsing
*/
public void parse() throws SyntaxError {
try {
while (in.peek(0) != -1) {
parseTemplates();
}
} catch (IOException e) {
throw new SyntaxError("IO error during template parsing: " +
e.getMessage());
}
}
private void parseTemplates() throws IOException, SyntaxError {
Collection<String> names = new LinkedList<String>();
while (true) {
skipWhitespace();
if (isEOF()) {
if (!names.isEmpty()) {
throw new SyntaxError(line,
"missing template body at end of file");
}
break;
} else if (isWhitespace()) {
skipWhitespace();
} else if (isNewline()) {
skipNewline();
} else if (isLinecomment()) {
skipLinecomment();
} else if (isAssign()) {
if (names.isEmpty()) {
throw new SyntaxError(line, "misplaced '='");
}
// skip the =
in.pop();
} else if (isTemplateStart()) {
if (names.isEmpty()) {
throw new SyntaxError(line, "missing template name");
}
Template template = parseTemplate();
for (String name: names) {
templates.addTemplate(name, template);
}
names.clear();
} else {
names.add(nextName());
}
}
}
private void skipLinecomment() throws IOException {
in.pop();
while (!isNewline() && !isEOF()) {
in.pop();
}
}
private void skipWhitespace() throws IOException {
while (isWhitespace()) {
in.pop();
}
}
private boolean isTemplateStart() throws IOException, SyntaxError {
if (in.peek(0) == '[') {
if (in.peek(1) == '[') {
return true;
} else {
throw new SyntaxError(line, "misplaced '['");
}
} else if (in.peek(0) == ']') {
throw new SyntaxError(line, "misplaced ']'");
}
return false;
}
private boolean isTemplateEnd() throws IOException {
return in.peek(0) == ']' && in.peek(1) == ']';
}
private boolean isAssign() throws IOException {
return in.peek(0) == '=';
}
private boolean isLinecomment() throws IOException {
return in.peek(0) == '
}
private boolean isWhitespace() throws IOException {
return Character.isWhitespace(in.peek(0)) && !isNewline();
}
private boolean isNewline() throws IOException {
return in.peek(0) == '\n' || in.peek(0) == '\r';
}
private boolean isEOF() throws IOException {
return in.peek(0) == -1;
}
private void skipNewline() throws IOException {
if (in.peek(0) == '\r') {
if (in.peek(1) == '\n') {
in.pop();
}
}
in.pop();
line += 1;
}
private String nextName() throws IOException, SyntaxError {
StringBuffer name = new StringBuffer();
while (!isWhitespace() && !isAssign() && !isTemplateStart() &&
!isEOF()) {
name.append((char) in.pop());
}
return name.toString();
}
private Template parseTemplate() throws IOException, SyntaxError {
// skip [[
in.pop();
in.pop();
Template template = new Template();
while (true) {
if (isEOF()) {
throw new SyntaxError(line, "unexpected end of file while parsing template body");
}
if (isVariable()) {
String var = nextReference();
if (var.isEmpty()) {
throw new SyntaxError(line, "empty variable name");
}
template.addVariableRef(var);
} else if (isAttribute()) {
String attr = nextReference();
if (attr.isEmpty()) {
throw new SyntaxError(line, "empty attribute name");
}
for (int i = 0; i < attr.length(); ++i) {
char ch = attr.charAt(i);
if ((i == 0 && !Character.isJavaIdentifierStart(ch)) ||
!Character.isJavaIdentifierPart(ch)) {
throw new SyntaxError(line, "the attribute " + attr +
" is not a valid Java identifier");
}
}
template.addAttributeRef(attr);
} else if (isNewline()) {
template.addNewline();
skipNewline();
} else if (isTemplateEnd()) {
// skip ]]
in.pop();
in.pop();
break;
} else {
template.addString(nextString());
}
}
return template;
}
private String nextString() throws IOException, SyntaxError {
StringBuffer buf = new StringBuffer(512);
while ( !(isEOF() || isVariable() || isAttribute() || isNewline() ||
isTemplateEnd()) ) {
if (in.peek(0) == '[' && in.peek(1) == '[')
throw new SyntaxError(line, "double brackets are not allowed inside templates");
if (in.peek(0) == '#' || in.peek(0) == '$') {
// it's cool - the # or $ was escaped!
// isAttribute() or isVariable() would have been true if not
in.pop();
}
buf.append((char) in.pop());
}
return buf.toString();
}
private String nextReference() throws IOException, SyntaxError {
// skip the
in.pop();
if (in.peek(0) == '(') {
return parseParens();
} else {
return parseSimpleReference();
}
}
private String parseSimpleReference() throws IOException {
StringBuffer buf = new StringBuffer(128);
while ( !isEOF() && Character.isJavaIdentifierPart(in.peek(0)) ) {
buf.append((char) in.pop());
}
return buf.toString();
}
private String parseParens() throws IOException, SyntaxError {
// skip the (
in.pop();
StringBuffer buf = new StringBuffer(128);
int depth = 1;
while (true) {
if (isEOF()) {
throw new SyntaxError(line, "EOF before end of parenthesized reference");
}
int c = in.pop();
if (c == '(') {
depth += 1;
} else if (c == ')') {
depth -= 1;
if (depth == 0) {
break;
}
}
buf.append((char) c);
}
return buf.toString();
}
private boolean isVariable() throws IOException {
// double dollar sign is an escape for single dollar sign
return in.peek(0) == '$' && in.peek(1) != '$';
}
private boolean isAttribute() throws IOException {
// double hash is an escape for single hash
return in.peek(0) == '#' && in.peek(1) != '#';
}
}
|
package acceptance.td;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.treasuredata.client.TDClient;
import io.digdag.client.DigdagClient;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpObject;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.multipart.Attribute;
import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder;
import io.netty.handler.codec.http.multipart.InterfaceHttpData;
import io.netty.handler.codec.http.multipart.InterfaceHttpData.HttpDataType;
import io.netty.util.ReferenceCountUtil;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.littleshoot.proxy.HttpFilters;
import org.littleshoot.proxy.HttpFiltersAdapter;
import org.littleshoot.proxy.HttpFiltersSourceAdapter;
import org.littleshoot.proxy.HttpProxyServer;
import org.littleshoot.proxy.impl.DefaultHttpProxyServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import utils.CommandStatus;
import utils.TemporaryDigdagServer;
import utils.TestUtils;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
import static acceptance.td.Secrets.TD_API_KEY;
import static io.netty.handler.codec.http.HttpHeaders.Names.CONNECTION;
import static io.netty.handler.codec.http.HttpHeaders.Values.CLOSE;
import static io.netty.handler.codec.http.HttpResponseStatus.INTERNAL_SERVER_ERROR;
import static java.nio.file.StandardOpenOption.APPEND;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.isEmptyOrNullString;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertThat;
import static org.junit.Assume.assumeThat;
import static utils.TestUtils.attemptSuccess;
import static utils.TestUtils.copyResource;
import static utils.TestUtils.expect;
import static utils.TestUtils.main;
import static utils.TestUtils.objectMapper;
import static utils.TestUtils.pushAndStart;
public class TdIT
{
private static final Logger logger = LoggerFactory.getLogger(TdIT.class);
@Rule
public TemporaryFolder folder = new TemporaryFolder();
private Path config;
private Path projectDir;
private TDClient client;
private String database;
private Path outfile;
private HttpProxyServer proxyServer;
private TemporaryDigdagServer server;
@Before
public void setUp()
throws Exception
{
assumeThat(TD_API_KEY, not(isEmptyOrNullString()));
projectDir = folder.getRoot().toPath().toAbsolutePath().normalize();
config = folder.newFile().toPath();
Files.write(config, asList("secrets.td.apikey = " + TD_API_KEY));
outfile = projectDir.resolve("outfile");
client = TDClient.newBuilder(false)
.setApiKey(TD_API_KEY)
.build();
database = "tmp_" + UUID.randomUUID().toString().replace('-', '_');
client.createDatabase(database);
}
@After
public void deleteDatabase()
throws Exception
{
if (client != null && database != null) {
client.deleteDatabase(database);
}
}
@After
public void stopProxy()
throws Exception
{
if (proxyServer != null) {
proxyServer.stop();
proxyServer = null;
}
}
@After
public void stopServer()
throws Exception
{
if (server != null) {
server.close();
server = null;
}
}
@Test
public void testRunQuery()
throws Exception
{
copyResource("acceptance/td/td/td.dig", projectDir.resolve("workflow.dig"));
copyResource("acceptance/td/td/query.sql", projectDir.resolve("query.sql"));
runWorkflow();
}
@Test
public void testStoreLastResult()
throws Exception
{
copyResource("acceptance/td/td/td_store_last_result.dig", projectDir.resolve("workflow.dig"));
copyResource("acceptance/td/td/query.sql", projectDir.resolve("query.sql"));
runWorkflow();
JsonNode result = objectMapper().readTree(outfile.toFile());
assertThat(result.get("last_job_id").asInt(), is(not(0)));
assertThat(result.get("last_results").isObject(), is(true));
assertThat(result.get("last_results").get("a").asInt(), is(1));
assertThat(result.get("last_results").get("b").asInt(), is(2));
}
@Test
public void testRunQueryWithEnvProxy()
throws Exception
{
List<FullHttpRequest> requests = Collections.synchronizedList(new ArrayList<>());
proxyServer = startRequestTrackingProxy(requests);
copyResource("acceptance/td/td/td.dig", projectDir.resolve("workflow.dig"));
copyResource("acceptance/td/td/query.sql", projectDir.resolve("query.sql"));
String proxyUrl = "http://" + proxyServer.getListenAddress().getHostString() + ":" + proxyServer.getListenAddress().getPort();
runWorkflow(ImmutableMap.of("http_proxy", proxyUrl), ImmutableList.of("td.use_ssl=false"));
assertThat(requests.stream().filter(req -> req.getUri().contains("/v3/job/issue")).count(), is(greaterThan(0L)));
}
@Test
public void testRunQueryAndPickUpApiKeyFromTdConf()
throws Exception
{
List<FullHttpRequest> requests = Collections.synchronizedList(new ArrayList<>());
proxyServer = startRequestTrackingProxy(requests);
// Write apikey to td.conf
Path tdConf = folder.newFolder().toPath().resolve("td.conf");
Files.write(tdConf, asList(
"[account]",
" user = foo@bar.com",
" apikey = " + TD_API_KEY,
" usessl = false"
));
// Remove apikey from digdag conf
Files.write(config, emptyList());
copyResource("acceptance/td/td/td.dig", projectDir.resolve("workflow.dig"));
copyResource("acceptance/td/td/query.sql", projectDir.resolve("query.sql"));
String proxyUrl = "http://" + proxyServer.getListenAddress().getHostString() + ":" + proxyServer.getListenAddress().getPort();
runWorkflow(
ImmutableMap.of(
"http_proxy", proxyUrl,
"TD_CONFIG_PATH", tdConf.toString()),
ImmutableList.of());
List<FullHttpRequest> issueRequests = requests.stream().filter(req -> req.getUri().contains("/v3/job/issue")).collect(Collectors.toList());
assertThat(issueRequests.size(), is(greaterThan(0)));
for (FullHttpRequest request : issueRequests) {
assertThat(request.headers().get(HttpHeaders.Names.AUTHORIZATION), is("TD1 " + TD_API_KEY));
}
assertThat(requests.stream().filter(req -> req.getUri().contains("/v3/job/issue")).count(), is(greaterThan(0L)));
}
@Test
public void testRunQueryOnServerWithEnvProxy()
throws Exception
{
List<FullHttpRequest> requests = Collections.synchronizedList(new ArrayList<>());
proxyServer = startRequestTrackingProxy(requests);
String proxyUrl = "http://" + proxyServer.getListenAddress().getHostString() + ":" + proxyServer.getListenAddress().getPort();
TemporaryDigdagServer server = TemporaryDigdagServer.builder()
.configuration(Secrets.secretsServerConfiguration())
.environment(ImmutableMap.of("http_proxy", proxyUrl))
.build();
server.start();
copyResource("acceptance/td/td/td.dig", projectDir.resolve("workflow.dig"));
copyResource("acceptance/td/td/query.sql", projectDir.resolve("query.sql"));
int projectId = TestUtils.pushProject(server.endpoint(), projectDir);
DigdagClient digdagClient = DigdagClient.builder()
.host(server.host())
.port(server.port())
.build();
digdagClient.setProjectSecret(projectId, "td.apikey", TD_API_KEY);
long attemptId = pushAndStart(server.endpoint(), projectDir, "workflow", ImmutableMap.of(
"outfile", outfile.toString(),
"td.use_ssl", "false"));
expect(Duration.ofMinutes(5), attemptSuccess(server.endpoint(), attemptId));
assertThat(requests.stream().filter(req -> req.getUri().contains("/v3/job/issue")).count(), is(greaterThan(0L)));
}
public HttpProxyServer startRequestTrackingProxy(final List<FullHttpRequest> requests)
{
return DefaultHttpProxyServer
.bootstrap()
.withPort(0)
.withFiltersSource(new HttpFiltersSourceAdapter()
{
@Override
public int getMaximumRequestBufferSizeInBytes()
{
return 1024 * 1024;
}
@Override
public HttpFilters filterRequest(HttpRequest httpRequest, ChannelHandlerContext channelHandlerContext)
{
return new HttpFiltersAdapter(httpRequest)
{
@Override
public HttpResponse clientToProxyRequest(HttpObject httpObject)
{
assert httpObject instanceof FullHttpRequest;
requests.add(((FullHttpRequest) httpObject).copy());
return null;
}
};
}
}).start();
}
@Test
public void testRunQueryWithPreview()
throws Exception
{
copyResource("acceptance/td/td/td_preview.dig", projectDir.resolve("workflow.dig"));
copyResource("acceptance/td/td/query.sql", projectDir.resolve("query.sql"));
runWorkflow();
}
@Test
public void testRunQueryWithPreviewAndCreateTable()
throws Exception
{
copyResource("acceptance/td/td/td_preview_create_table.dig", projectDir.resolve("workflow.dig"));
copyResource("acceptance/td/td/query.sql", projectDir.resolve("query.sql"));
runWorkflow("td.database=" + database);
}
@Test
public void testRunQueryLegacyApikeyParam()
throws Exception
{
// TODO: Remove this test when the legacy support for td.apikey param is removed
// Replace the "secrets.td.apikey" entry with the legacy "params.td.apikey" entry
Files.write(config, asList("params.td.apikey = " + TD_API_KEY));
copyResource("acceptance/td/td/td.dig", projectDir.resolve("workflow.dig"));
copyResource("acceptance/td/td/query.sql", projectDir.resolve("query.sql"));
runWorkflow();
}
@Test
public void testRunQueryInline()
throws Exception
{
copyResource("acceptance/td/td/td_inline.dig", projectDir.resolve("workflow.dig"));
runWorkflow();
}
@Test
public void testRetries()
throws Exception
{
int failures = 3;
List<FullHttpRequest> jobIssueRequests = Collections.synchronizedList(new ArrayList<>());
proxyServer = DefaultHttpProxyServer
.bootstrap()
.withPort(0)
.withFiltersSource(new HttpFiltersSourceAdapter()
{
@Override
public int getMaximumRequestBufferSizeInBytes()
{
return 1024 * 1024;
}
@Override
public HttpFilters filterRequest(HttpRequest httpRequest, ChannelHandlerContext channelHandlerContext)
{
return new HttpFiltersAdapter(httpRequest)
{
@Override
public HttpResponse clientToProxyRequest(HttpObject httpObject)
{
assert httpObject instanceof FullHttpRequest;
FullHttpRequest fullHttpRequest = (FullHttpRequest) httpObject;
if (httpRequest.getUri().contains("/v3/job/issue")) {
jobIssueRequests.add(fullHttpRequest.copy());
if (jobIssueRequests.size() < failures) {
logger.info("Simulating 500 INTERNAL SERVER ERROR for request: {}", httpRequest);
DefaultFullHttpResponse response = new DefaultFullHttpResponse(httpRequest.getProtocolVersion(), INTERNAL_SERVER_ERROR);
response.headers().set(CONNECTION, CLOSE);
return response;
}
}
logger.info("Passing request: {}", httpRequest);
return null;
}
};
}
}).start();
Files.write(config, asList(
"params.td.use_ssl = false",
"params.td.proxy.enabled = true",
"params.td.proxy.host = " + proxyServer.getListenAddress().getHostString(),
"params.td.proxy.port = " + proxyServer.getListenAddress().getPort()
), APPEND);
copyResource("acceptance/td/td/td_inline.dig", projectDir.resolve("workflow.dig"));
runWorkflow();
for (FullHttpRequest request : jobIssueRequests) {
ReferenceCountUtil.releaseLater(request);
}
assertThat(jobIssueRequests.size(), is(not(0)));
// Verify that all job issue requests reuse the same domain key
verifyDomainKeys(jobIssueRequests);
}
@Test
public void testDomainKeyConflict()
throws Exception
{
List<FullHttpRequest> jobIssueRequests = Collections.synchronizedList(new ArrayList<>());
List<FullHttpResponse> jobIssueResponses = Collections.synchronizedList(new ArrayList<>());
proxyServer = DefaultHttpProxyServer
.bootstrap()
.withPort(0)
.withFiltersSource(new HttpFiltersSourceAdapter()
{
@Override
public int getMaximumRequestBufferSizeInBytes()
{
return 1024 * 1024;
}
@Override
public int getMaximumResponseBufferSizeInBytes()
{
return 1024 * 1024;
}
@Override
public HttpFilters filterRequest(HttpRequest httpRequest, ChannelHandlerContext channelHandlerContext)
{
return new HttpFiltersAdapter(httpRequest)
{
@Override
public HttpResponse clientToProxyRequest(HttpObject httpObject)
{
assert httpObject instanceof FullHttpRequest;
FullHttpRequest fullHttpRequest = (FullHttpRequest) httpObject;
if (httpRequest.getUri().contains("/v3/job/issue")) {
jobIssueRequests.add(fullHttpRequest.copy());
}
return null;
}
@Override
public HttpObject serverToProxyResponse(HttpObject httpObject)
{
assert httpObject instanceof FullHttpResponse;
FullHttpResponse fullHttpResponse = (FullHttpResponse) httpObject;
// Let the first issue request through so that the job is started and the domain key is recorded by the td api but
// simulate a failure for the first request. The td operator will then retry starting the job with the same domain key
// which will result in a conflict response. The td operator should then interpret that as the job having successfully been issued.
if (httpRequest.getUri().contains("/v3/job/issue")) {
jobIssueResponses.add(fullHttpResponse);
if (jobIssueResponses.size() == 1) {
logger.info("Simulating 500 INTERNAL SERVER ERROR for request: {}", httpRequest);
DefaultFullHttpResponse response = new DefaultFullHttpResponse(httpRequest.getProtocolVersion(), INTERNAL_SERVER_ERROR);
response.headers().set(CONNECTION, CLOSE);
return response;
}
}
logger.info("Passing request: {}", httpRequest);
return httpObject;
}
};
}
}).start();
Files.write(config, asList(
"params.td.use_ssl = false",
"params.td.proxy.enabled = true",
"params.td.proxy.host = " + proxyServer.getListenAddress().getHostString(),
"params.td.proxy.port = " + proxyServer.getListenAddress().getPort()
), APPEND);
copyResource("acceptance/td/td/td_inline.dig", projectDir.resolve("workflow.dig"));
runWorkflow();
for (FullHttpRequest request : jobIssueRequests) {
ReferenceCountUtil.releaseLater(request);
}
assertThat(jobIssueRequests.size(), is(not(0)));
assertThat(jobIssueResponses.size(), is(not(0)));
verifyDomainKeys(jobIssueRequests);
}
private void verifyDomainKeys(List<FullHttpRequest> jobIssueRequests)
throws IOException
{
// Verify that all job issue requests reuse the same domain key
FullHttpRequest firstRequest = jobIssueRequests.get(0);
String domainKey = domainKey(firstRequest);
for (int i = 0; i < jobIssueRequests.size(); i++) {
FullHttpRequest request = jobIssueRequests.get(i);
String requestDomainKey = domainKey(request);
assertThat(requestDomainKey, is(domainKey));
}
}
private String domainKey(FullHttpRequest request)
throws IOException
{
FullHttpRequest copy = request.copy();
ReferenceCountUtil.releaseLater(copy);
HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(copy);
List<InterfaceHttpData> keyDatas = decoder.getBodyHttpDatas("domain_key");
assertThat(keyDatas, is(not(nullValue())));
assertThat(keyDatas.size(), is(1));
InterfaceHttpData domainKeyData = keyDatas.get(0);
assertThat(domainKeyData.getHttpDataType(), is(HttpDataType.Attribute));
return ((Attribute) domainKeyData).getValue();
}
private CommandStatus runWorkflow(String... params)
{
return runWorkflow(ImmutableMap.of(), ImmutableList.copyOf(params));
}
private CommandStatus runWorkflow(Map<String, String> env, List<String> params)
{
List<String> args = new ArrayList<>();
args.addAll(asList("run",
"-o", projectDir.toString(),
"--config", config.toString(),
"--project", projectDir.toString(),
"-p", "outfile=" + outfile));
for (String param : params) {
args.add("-p");
args.add(param);
}
args.add("workflow.dig");
CommandStatus runStatus = main(env, args);
assertThat(runStatus.errUtf8(), runStatus.code(), is(0));
assertThat(Files.exists(outfile), is(true));
return runStatus;
}
}
|
package org.easybatch.tutorials.quartz;
import org.easybatch.core.impl.EasyBatchEngine;
import org.easybatch.core.impl.EasyBatchEngineBuilder;
import org.easybatch.flatfile.FlatFileRecordReader;
import org.easybatch.flatfile.dsv.DelimitedRecordMapper;
import org.easybatch.integration.quartz.EasyBatchScheduler;
import org.easybatch.tutorials.common.Greeting;
import org.easybatch.tutorials.common.GreetingProcessor;
import org.easybatch.validation.BeanValidationRecordValidator;
import java.io.File;
import java.util.Date;
/**
* Main class to run the Hello World tutorial repeatedly every minute using easy batch - quartz integration module.<br/>
*
* The {@link org.easybatch.integration.quartz.EasyBatchScheduler} API lets you schedule easy batch executions as follows :
* <ul>
* <li>At a fixed point of time using {@link org.easybatch.integration.quartz.EasyBatchScheduler#scheduleAt(java.util.Date)}</li>
* <li>Repeatedly with predefined interval using {@link org.easybatch.integration.quartz.EasyBatchScheduler#scheduleAtWithInterval(java.util.Date, int)}</li>
* <li>Using unix cron-like expression with {@link org.easybatch.integration.quartz.EasyBatchScheduler#scheduleCron(String)}</li>
* </ul>
*
* @author Mahmoud Ben Hassine (md.benhassine@gmail.com)
*/
public class Launcher {
public static void main(String[] args) throws Exception {
// Build an easy batch engine
EasyBatchEngine easyBatchEngine = new EasyBatchEngineBuilder()
.registerRecordReader(new FlatFileRecordReader(new File(args[0])))
.registerRecordMapper(new DelimitedRecordMapper<Greeting>(Greeting.class, new String[]{"id", "name"}))
.registerRecordValidator(new BeanValidationRecordValidator<Greeting>())
.registerRecordProcessor(new GreetingProcessor())
.build();
// schedule the engine to start now and run every minute
EasyBatchScheduler easyBatchScheduler = new EasyBatchScheduler(easyBatchEngine);
easyBatchScheduler.scheduleAtWithInterval(new Date(), 1);
easyBatchScheduler.start();
}
}
|
package io.github.benas.easybatch.xml;
import io.github.benas.easybatch.core.api.Record;
import io.github.benas.easybatch.core.api.RecordReader;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.EndDocument;
import javax.xml.stream.events.XMLEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* A record reader that reads xml records from an xml file.
*
* @author benas (md.benhassine@gmail.com)
*/
public class XmlRecordReader implements RecordReader {
private static final Logger LOGGER = Logger.getLogger(XmlRecordReader.class.getSimpleName());
/**
* The root element name.
*/
private String rootElementName;
/**
* The xml input file.
*/
private String xmlFile;
/**
* The xml reader.
*/
private XMLEventReader xmlEventReader;
/**
* The current record number.
*/
private long currentRecordNumber;
public XmlRecordReader(final String rootElementName, final String xmlFile) {
this.rootElementName = rootElementName;
this.xmlFile = xmlFile;
}
@Override
public void open() throws Exception {
currentRecordNumber = 0;
xmlEventReader = XMLInputFactory.newInstance().createXMLEventReader(new FileInputStream(new File(xmlFile)));
}
@Override
public boolean hasNextRecord() {
try {
while (!nextTagIsRootElementStart()) {
XMLEvent xmlEvent = xmlEventReader.nextEvent();
if (xmlEvent instanceof EndDocument) {
return false;
}
}
return true;
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "An exception occurred during checking the existence of next xml record", e);
return false;
}
}
@Override
public Record readNextRecord() {
StringBuilder stringBuilder = new StringBuilder("");
try {
while (!nextTagIsRootElementEnd()) {
stringBuilder.append(xmlEventReader.nextEvent().toString());
}
//append root element end tag
stringBuilder.append(xmlEventReader.nextEvent().toString());
return new XmlRecord(++currentRecordNumber, stringBuilder.toString());
} catch (Exception e) {
throw new RuntimeException("An exception occurred during reading next xml record", e);
}
}
@Override
public Long getTotalRecords() {
long totalRecords = 0;
try {
XMLEventReader totalRecordsXmlEventReader =
XMLInputFactory.newInstance().createXMLEventReader(new FileInputStream(new File(xmlFile)));
XMLEvent event;
while (totalRecordsXmlEventReader.hasNext()) {
event = totalRecordsXmlEventReader.nextEvent();
if (event.isStartElement() && event.asStartElement().getName().toString().equals(rootElementName)) {
totalRecords++;
}
}
totalRecordsXmlEventReader.close();
} catch (XMLStreamException e) {
throw new RuntimeException("Unable to read data from xml file " + xmlFile, e);
} catch (FileNotFoundException e) {
throw new RuntimeException("File not found " + xmlFile, e);
}
return totalRecords;
}
@Override
public String getDataSourceName() {
return xmlFile;
}
@Override
public void close() {
try {
xmlEventReader.close();
} catch (XMLStreamException e) {
throw new RuntimeException("An exception occurred during closing xml reader", e);
}
}
/**
* Utility method to check if the next tag matches a start tag of the root element.
* @return true if the next tag matches a start element of the root element, false else
* @throws Exception thrown if no able to peek the next xml element
*/
private boolean nextTagIsRootElementStart() throws Exception {
return xmlEventReader.peek().isStartElement() &&
xmlEventReader.peek().asStartElement().getName().toString().equalsIgnoreCase(rootElementName);
}
/**
* Utility method to check if the next tag matches an end tag of the root element.
* @return true if the next tag matches an end tag of the root element, false else
* @throws Exception thrown if no able to peek the next xml element
*/
private boolean nextTagIsRootElementEnd() throws Exception {
return xmlEventReader.peek().isEndElement() &&
xmlEventReader.peek().asEndElement().getName().toString().equalsIgnoreCase(rootElementName);
}
}
|
package org.elasticsearch.xpack.prelert;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.ActionRequest;
import org.elasticsearch.action.ActionResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.cluster.metadata.MetaData;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.ParseFieldMatcher;
import org.elasticsearch.common.ParseFieldMatcherSupplier;
import org.elasticsearch.common.component.LifecycleListener;
import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Setting.Property;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.env.Environment;
import org.elasticsearch.plugins.ActionPlugin;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.rest.RestHandler;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.search.SearchRequestParsers;
import org.elasticsearch.threadpool.ExecutorBuilder;
import org.elasticsearch.threadpool.FixedExecutorBuilder;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.watcher.ResourceWatcherService;
import org.elasticsearch.xpack.prelert.action.CloseJobAction;
import org.elasticsearch.xpack.prelert.action.DeleteJobAction;
import org.elasticsearch.xpack.prelert.action.DeleteListAction;
import org.elasticsearch.xpack.prelert.action.DeleteModelSnapshotAction;
import org.elasticsearch.xpack.prelert.action.DeleteSchedulerAction;
import org.elasticsearch.xpack.prelert.action.FlushJobAction;
import org.elasticsearch.xpack.prelert.action.GetBucketsAction;
import org.elasticsearch.xpack.prelert.action.GetCategoriesDefinitionAction;
import org.elasticsearch.xpack.prelert.action.GetInfluencersAction;
import org.elasticsearch.xpack.prelert.action.GetJobsAction;
import org.elasticsearch.xpack.prelert.action.GetListAction;
import org.elasticsearch.xpack.prelert.action.GetModelSnapshotsAction;
import org.elasticsearch.xpack.prelert.action.GetRecordsAction;
import org.elasticsearch.xpack.prelert.action.JobDataAction;
import org.elasticsearch.xpack.prelert.action.OpenJobAction;
import org.elasticsearch.xpack.prelert.action.PutJobAction;
import org.elasticsearch.xpack.prelert.action.PutListAction;
import org.elasticsearch.xpack.prelert.action.PutModelSnapshotDescriptionAction;
import org.elasticsearch.xpack.prelert.action.PutSchedulerAction;
import org.elasticsearch.xpack.prelert.action.RevertModelSnapshotAction;
import org.elasticsearch.xpack.prelert.action.StartSchedulerAction;
import org.elasticsearch.xpack.prelert.action.StopSchedulerAction;
import org.elasticsearch.xpack.prelert.action.UpdateJobStatusAction;
import org.elasticsearch.xpack.prelert.action.UpdateSchedulerStatusAction;
import org.elasticsearch.xpack.prelert.action.ValidateDetectorAction;
import org.elasticsearch.xpack.prelert.action.ValidateTransformAction;
import org.elasticsearch.xpack.prelert.action.ValidateTransformsAction;
import org.elasticsearch.xpack.prelert.job.data.DataProcessor;
import org.elasticsearch.xpack.prelert.job.manager.AutodetectProcessManager;
import org.elasticsearch.xpack.prelert.job.manager.JobManager;
import org.elasticsearch.xpack.prelert.job.metadata.JobAllocator;
import org.elasticsearch.xpack.prelert.job.metadata.JobLifeCycleService;
import org.elasticsearch.xpack.prelert.job.metadata.PrelertInitializationService;
import org.elasticsearch.xpack.prelert.job.metadata.PrelertMetadata;
import org.elasticsearch.xpack.prelert.job.persistence.JobDataCountsPersister;
import org.elasticsearch.xpack.prelert.job.persistence.JobDataDeleterFactory;
import org.elasticsearch.xpack.prelert.job.persistence.JobProvider;
import org.elasticsearch.xpack.prelert.job.persistence.JobRenormalizedResultsPersister;
import org.elasticsearch.xpack.prelert.job.persistence.JobResultsPersister;
import org.elasticsearch.xpack.prelert.job.process.NativeController;
import org.elasticsearch.xpack.prelert.job.process.ProcessCtrl;
import org.elasticsearch.xpack.prelert.job.process.autodetect.AutodetectProcessFactory;
import org.elasticsearch.xpack.prelert.job.process.autodetect.BlackHoleAutodetectProcess;
import org.elasticsearch.xpack.prelert.job.process.autodetect.NativeAutodetectProcessFactory;
import org.elasticsearch.xpack.prelert.job.process.autodetect.output.AutodetectResultsParser;
import org.elasticsearch.xpack.prelert.job.process.normalizer.NormalizerFactory;
import org.elasticsearch.xpack.prelert.scheduler.ScheduledJobRunner;
import org.elasticsearch.xpack.prelert.job.process.normalizer.NativeNormalizerProcessFactory;
import org.elasticsearch.xpack.prelert.job.process.normalizer.MultiplyingNormalizerProcess;
import org.elasticsearch.xpack.prelert.job.process.normalizer.NormalizerProcessFactory;
import org.elasticsearch.xpack.prelert.scheduler.http.HttpDataExtractorFactory;
import org.elasticsearch.xpack.prelert.job.status.StatusReporter;
import org.elasticsearch.xpack.prelert.job.usage.UsageReporter;
import org.elasticsearch.xpack.prelert.rest.job.RestCloseJobAction;
import org.elasticsearch.xpack.prelert.rest.job.RestDeleteJobAction;
import org.elasticsearch.xpack.prelert.rest.job.RestFlushJobAction;
import org.elasticsearch.xpack.prelert.rest.job.RestGetJobsAction;
import org.elasticsearch.xpack.prelert.rest.job.RestJobDataAction;
import org.elasticsearch.xpack.prelert.rest.job.RestOpenJobAction;
import org.elasticsearch.xpack.prelert.rest.job.RestPutJobAction;
import org.elasticsearch.xpack.prelert.rest.list.RestDeleteListAction;
import org.elasticsearch.xpack.prelert.rest.list.RestGetListAction;
import org.elasticsearch.xpack.prelert.rest.list.RestPutListAction;
import org.elasticsearch.xpack.prelert.rest.modelsnapshots.RestDeleteModelSnapshotAction;
import org.elasticsearch.xpack.prelert.rest.modelsnapshots.RestGetModelSnapshotsAction;
import org.elasticsearch.xpack.prelert.rest.modelsnapshots.RestPutModelSnapshotDescriptionAction;
import org.elasticsearch.xpack.prelert.rest.modelsnapshots.RestRevertModelSnapshotAction;
import org.elasticsearch.xpack.prelert.rest.results.RestGetBucketsAction;
import org.elasticsearch.xpack.prelert.rest.results.RestGetCategoriesAction;
import org.elasticsearch.xpack.prelert.rest.results.RestGetInfluencersAction;
import org.elasticsearch.xpack.prelert.rest.results.RestGetRecordsAction;
import org.elasticsearch.xpack.prelert.rest.schedulers.RestDeleteSchedulerAction;
import org.elasticsearch.xpack.prelert.rest.schedulers.RestPutSchedulerAction;
import org.elasticsearch.xpack.prelert.rest.schedulers.RestStartSchedulerAction;
import org.elasticsearch.xpack.prelert.rest.schedulers.RestStopSchedulerAction;
import org.elasticsearch.xpack.prelert.rest.validate.RestValidateDetectorAction;
import org.elasticsearch.xpack.prelert.rest.validate.RestValidateTransformAction;
import org.elasticsearch.xpack.prelert.rest.validate.RestValidateTransformsAction;
import org.elasticsearch.xpack.prelert.utils.NamedPipeHelper;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
public class PrelertPlugin extends Plugin implements ActionPlugin {
public static final String NAME = "prelert";
public static final String BASE_PATH = "/_xpack/prelert/";
public static final String THREAD_POOL_NAME = NAME;
public static final String SCHEDULER_THREAD_POOL_NAME = NAME + "_scheduler";
public static final String AUTODETECT_PROCESS_THREAD_POOL_NAME = NAME + "_autodetect_process";
// NORELEASE - temporary solution
static final Setting<Boolean> USE_NATIVE_PROCESS_OPTION = Setting.boolSetting("useNativeProcess", true, Property.NodeScope,
Property.Deprecated);
private final Settings settings;
private final Environment env;
private final ParseFieldMatcherSupplier parseFieldMatcherSupplier;
static {
MetaData.registerPrototype(PrelertMetadata.TYPE, PrelertMetadata.PROTO);
}
public PrelertPlugin(Settings settings) {
this.settings = settings;
this.env = new Environment(settings);
ParseFieldMatcher matcher = new ParseFieldMatcher(settings);
parseFieldMatcherSupplier = () -> matcher;
}
@Override
public List<Setting<?>> getSettings() {
return Collections.unmodifiableList(
Arrays.asList(USE_NATIVE_PROCESS_OPTION,
ProcessCtrl.DONT_PERSIST_MODEL_STATE_SETTING,
ProcessCtrl.MAX_ANOMALY_RECORDS_SETTING,
StatusReporter.ACCEPTABLE_PERCENTAGE_DATE_PARSE_ERRORS_SETTING,
StatusReporter.ACCEPTABLE_PERCENTAGE_OUT_OF_ORDER_ERRORS_SETTING,
UsageReporter.UPDATE_INTERVAL_SETTING,
AutodetectProcessManager.MAX_RUNNING_JOBS_PER_NODE));
}
@Override
public Collection<Object> createComponents(Client client, ClusterService clusterService, ThreadPool threadPool,
ResourceWatcherService resourceWatcherService, ScriptService scriptService,
SearchRequestParsers searchRequestParsers) {
JobResultsPersister jobResultsPersister = new JobResultsPersister(settings, client);
JobProvider jobProvider = new JobProvider(client, 0, parseFieldMatcherSupplier.getParseFieldMatcher());
JobRenormalizedResultsPersister jobRenormalizedResultsPersister = new JobRenormalizedResultsPersister(settings,
jobResultsPersister);
JobDataCountsPersister jobDataCountsPersister = new JobDataCountsPersister(settings, client);
JobManager jobManager = new JobManager(settings, jobProvider, jobResultsPersister, clusterService);
AutodetectProcessFactory autodetectProcessFactory;
NormalizerProcessFactory normalizerProcessFactory;
if (USE_NATIVE_PROCESS_OPTION.get(settings)) {
try {
NativeController nativeController = new NativeController(env, new NamedPipeHelper());
nativeController.tailLogsInThread();
autodetectProcessFactory = new NativeAutodetectProcessFactory(jobProvider, env, settings, nativeController);
normalizerProcessFactory = new NativeNormalizerProcessFactory(env, settings, nativeController);
} catch (IOException e) {
throw new ElasticsearchException("Failed to create native process factories", e);
}
} else {
autodetectProcessFactory = (jobDetails, ignoreDowntime, executorService) -> new BlackHoleAutodetectProcess();
// factor of 1.0 makes renormalization a no-op
normalizerProcessFactory = (jobId, quantilesState, bucketSpan, perPartitionNormalization,
executorService) -> new MultiplyingNormalizerProcess(settings, 1.0);
}
NormalizerFactory normalizerFactory = new NormalizerFactory(normalizerProcessFactory,
threadPool.executor(PrelertPlugin.THREAD_POOL_NAME));
AutodetectResultsParser autodetectResultsParser = new AutodetectResultsParser(settings, parseFieldMatcherSupplier);
DataProcessor dataProcessor = new AutodetectProcessManager(settings, client, threadPool, jobManager, jobProvider,
jobResultsPersister, jobRenormalizedResultsPersister, jobDataCountsPersister, autodetectResultsParser,
autodetectProcessFactory, normalizerFactory, clusterService.getClusterSettings());
ScheduledJobRunner scheduledJobRunner = new ScheduledJobRunner(threadPool, client, clusterService, jobProvider,
// norelease: we will no longer need to pass the client here after we switch to a client based data extractor
new HttpDataExtractorFactory(client),
System::currentTimeMillis);
JobLifeCycleService jobLifeCycleService =
new JobLifeCycleService(settings, client, clusterService, dataProcessor, threadPool.generic());
// we hop on the lifecycle service of ResourceWatcherService, because
// that one is stopped before discovery is.
// (when discovery is stopped it will send a leave request to elected master node, which will then be removed
// from the cluster state, which then triggers other events)
resourceWatcherService.addLifecycleListener(new LifecycleListener() {
@Override
public void beforeStop() {
jobLifeCycleService.stop();
}
});
return Arrays.asList(
jobProvider,
jobManager,
new JobAllocator(settings, clusterService, threadPool),
jobLifeCycleService,
new JobDataDeleterFactory(client), //NORELEASE: this should use Delete-by-query
dataProcessor,
new PrelertInitializationService(settings, threadPool, clusterService, jobProvider),
jobDataCountsPersister,
scheduledJobRunner
);
}
@Override
public List<Class<? extends RestHandler>> getRestHandlers() {
return Arrays.asList(
RestGetJobsAction.class,
RestPutJobAction.class,
RestDeleteJobAction.class,
RestOpenJobAction.class,
RestGetListAction.class,
RestPutListAction.class,
RestDeleteListAction.class,
RestGetInfluencersAction.class,
RestGetRecordsAction.class,
RestGetBucketsAction.class,
RestJobDataAction.class,
RestCloseJobAction.class,
RestFlushJobAction.class,
RestValidateDetectorAction.class,
RestValidateTransformAction.class,
RestValidateTransformsAction.class,
RestGetCategoriesAction.class,
RestGetModelSnapshotsAction.class,
RestRevertModelSnapshotAction.class,
RestPutModelSnapshotDescriptionAction.class,
RestPutSchedulerAction.class,
RestDeleteSchedulerAction.class,
RestStartSchedulerAction.class,
RestStopSchedulerAction.class,
RestDeleteModelSnapshotAction.class
);
}
@Override
public List<ActionHandler<? extends ActionRequest, ? extends ActionResponse>> getActions() {
return Arrays.asList(
new ActionHandler<>(GetJobsAction.INSTANCE, GetJobsAction.TransportAction.class),
new ActionHandler<>(PutJobAction.INSTANCE, PutJobAction.TransportAction.class),
new ActionHandler<>(DeleteJobAction.INSTANCE, DeleteJobAction.TransportAction.class),
new ActionHandler<>(OpenJobAction.INSTANCE, OpenJobAction.TransportAction.class),
new ActionHandler<>(UpdateJobStatusAction.INSTANCE, UpdateJobStatusAction.TransportAction.class),
new ActionHandler<>(UpdateSchedulerStatusAction.INSTANCE, UpdateSchedulerStatusAction.TransportAction.class),
new ActionHandler<>(GetListAction.INSTANCE, GetListAction.TransportAction.class),
new ActionHandler<>(PutListAction.INSTANCE, PutListAction.TransportAction.class),
new ActionHandler<>(DeleteListAction.INSTANCE, DeleteListAction.TransportAction.class),
new ActionHandler<>(GetBucketsAction.INSTANCE, GetBucketsAction.TransportAction.class),
new ActionHandler<>(GetInfluencersAction.INSTANCE, GetInfluencersAction.TransportAction.class),
new ActionHandler<>(GetRecordsAction.INSTANCE, GetRecordsAction.TransportAction.class),
new ActionHandler<>(JobDataAction.INSTANCE, JobDataAction.TransportAction.class),
new ActionHandler<>(CloseJobAction.INSTANCE, CloseJobAction.TransportAction.class),
new ActionHandler<>(FlushJobAction.INSTANCE, FlushJobAction.TransportAction.class),
new ActionHandler<>(ValidateDetectorAction.INSTANCE, ValidateDetectorAction.TransportAction.class),
new ActionHandler<>(ValidateTransformAction.INSTANCE, ValidateTransformAction.TransportAction.class),
new ActionHandler<>(ValidateTransformsAction.INSTANCE, ValidateTransformsAction.TransportAction.class),
new ActionHandler<>(GetCategoriesDefinitionAction.INSTANCE, GetCategoriesDefinitionAction.TransportAction.class),
new ActionHandler<>(GetModelSnapshotsAction.INSTANCE, GetModelSnapshotsAction.TransportAction.class),
new ActionHandler<>(RevertModelSnapshotAction.INSTANCE, RevertModelSnapshotAction.TransportAction.class),
new ActionHandler<>(PutModelSnapshotDescriptionAction.INSTANCE, PutModelSnapshotDescriptionAction.TransportAction.class),
new ActionHandler<>(PutSchedulerAction.INSTANCE, PutSchedulerAction.TransportAction.class),
new ActionHandler<>(DeleteSchedulerAction.INSTANCE, DeleteSchedulerAction.TransportAction.class),
new ActionHandler<>(StartSchedulerAction.INSTANCE, StartSchedulerAction.TransportAction.class),
new ActionHandler<>(StopSchedulerAction.INSTANCE, StopSchedulerAction.TransportAction.class),
new ActionHandler<>(DeleteModelSnapshotAction.INSTANCE, DeleteModelSnapshotAction.TransportAction.class)
);
}
public static Path resolveConfigFile(Environment env, String name) {
return env.configFile().resolve(NAME).resolve(name);
}
@Override
public List<ExecutorBuilder<?>> getExecutorBuilders(Settings settings) {
int maxNumberOfJobs = AutodetectProcessManager.MAX_RUNNING_JOBS_PER_NODE.get(settings);
FixedExecutorBuilder prelert = new FixedExecutorBuilder(settings, THREAD_POOL_NAME,
maxNumberOfJobs * 2, 1000, "xpack.prelert.thread_pool");
// fail quick to run autodetect process / scheduler, so no queues
// 4 threads: for c++ logging, result processing, state processing and restore state
FixedExecutorBuilder autoDetect = new FixedExecutorBuilder(settings, AUTODETECT_PROCESS_THREAD_POOL_NAME,
maxNumberOfJobs * 4, 4, "xpack.prelert.autodetect_process_thread_pool");
// TODO: if scheduled and non scheduled jobs are considered more equal and the scheduler and
// autodetect process are created at the same time then these two different TPs can merge.
FixedExecutorBuilder scheduler = new FixedExecutorBuilder(settings, SCHEDULER_THREAD_POOL_NAME,
maxNumberOfJobs, 1, "xpack.prelert.scheduler_thread_pool");
return Arrays.asList(prelert, autoDetect, scheduler);
}
}
|
package smartsockets.direct;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import smartsockets.util.NetworkUtils;
/**
* This class implements a multi-SocketAddress (any number of IP addresses
* and port numbers).
*
* It provides an immutable object used by IbisSockets for binding, connecting,
* or as returned values.
*
* @author Jason Maassen
* @version 1.0 Dec 19, 2005
* @since 1.0
*/
public class SocketAddressSet extends SocketAddress {
private static final long serialVersionUID = -2662260670251814982L;
private static final char IP_PORT_SEPERATOR = '-';
private static final char ADDRESS_SEPERATOR = '/';
private final IPAddressSet address;
private final InetSocketAddress [] sas;
private SocketAddressSet(IPAddressSet as, InetSocketAddress [] sas) {
this.address = as;
this.sas = sas;
}
/**
* Construct a new IbisSocketAddress, using InetAddress and a port number.
*
* a valid port value is between 0 and 65535. A port number of zero will
* let the system pick up an ephemeral port in a bind operation.
*
* A null address will assign the wildcard address.
*
* @param address The InetAddress.
* @param port The port number.
*/
public SocketAddressSet(InetAddress address, int port) {
this(IPAddressSet.getFromAddress(new InetAddress[] {address}), port);
}
/**
* Construct a new IbisSocketAddress, using InetSocketAddress
*
* @param address The InetSocketAddress.
*/
public SocketAddressSet(InetSocketAddress address) {
this(address.getAddress(), address.getPort());
}
/**
* Construct a new IbisSocketAddress, using an IbisInetAddress and a port
* number.
*
* a valid port value is between 0 and 65535. A port number of zero will
* let the system pick up an ephemeral port in a bind operation.
*
* A null address will assign the wildcard address.
*
* @param address The IbisInetAddress.
* @param port The port number.
*/
public SocketAddressSet(IPAddressSet address, int port) {
if (port < 0 || port > 65535) {
throw new IllegalArgumentException("Port out of range");
}
if (address == null) {
this.address = IPAddressSet.getLocalHost();
} else {
this.address = address;
}
int len = address.addresses.length;
sas = new InetSocketAddress[len];
for (int i=0;i<len;i++) {
sas[i] = new InetSocketAddress(address.addresses[i], port);
}
}
/**
* Construct a new IbisSocketAddress, using an IbisInetAddress and an array
* of ports.
*
* A valid port value is between 1 and 65535. A port number of zero is not
* allowed.
*
* A null address will assign the wildcard address.
*
* @param address The IbisInetAddress.
* @param port The port number.
*/
public SocketAddressSet(IPAddressSet address, int [] port) {
if (address == null) {
this.address = IPAddressSet.getLocalHost();
} else {
this.address = address;
}
if (port.length != address.addresses.length) {
throw new IllegalArgumentException("Number of ports does not match"
+ "number of addresses");
}
int len = address.addresses.length;
sas = new InetSocketAddress[len];
for (int i=0;i<len;i++) {
if (port[i] <= 0 || port[i] > 65535) {
throw new IllegalArgumentException("Port["+i+"] out of range");
}
sas[i] = new InetSocketAddress(address.addresses[i], port[i]);
}
}
/**
* Construct a new IbisSocketAddress from a String representation of an
* IbisInetAddress and a port number.
*
* A valid port value is between 0 and 65535. A port number of zero will let
* the system pick up an ephemeral port in a bind operation.
*
* @param address The String representation of an IbisInetAddress.
* @param port The port number.
* @throws UnknownHostException
*/
public SocketAddressSet(String address, int port)
throws UnknownHostException {
this(IPAddressSet.getFromString(address), port);
}
/**
* Construct a new IbisSocketAddress from a String representation of a
* IbisSocketAddress.
*
* This representation contains any number of InetAddresses seperated by
* ADDRESS_SEPARATOR characters (usually defined as '/'), followed by a
* IP_PORT_SEPERATOR (usually '-') and a port number.
*
* This sequence may be repeated any number of times, separated by slashes.
*
* The following examples are valid IPv4 string representations:
*
* 192.168.1.35-1234
* 192.168.1.35/10.0.0.1-1234
* 192.168.1.35/10.0.0.1-1234/192.31.231.65-5678
* 192.168.1.35/10.0.0.1-1234/192.31.231.65/130.37.24.4-5678
*
* We can also handle IPv6:
*
* fe80:0:0:0:2e0:18ff:fe2c:a31%2-1234
*
* Or a mix of the two:
*
* fe80:0:0:0:2e0:18ff:fe2c:a31%2/169.254.207.84-1234
*
* @param addressPort The String representation of a IbisSocketAddress.
* @throws UnknownHostException
*/
public SocketAddressSet(String addressPort) throws UnknownHostException {
int start = 0;
boolean done = false;
IPAddressSet addr = null;
int [] ports = new int[0];
while (!done) {
// We start by selecting a single address and port number from the
// string, starting where we ended the last time.
int colon = addressPort.indexOf(IP_PORT_SEPERATOR, start);
int slash = addressPort.indexOf(ADDRESS_SEPERATOR, colon+1);
// We now seperate the 'address' and 'port' parts. If there is a '/'
// behind the port there is an other address following it. If not,
// this is the last time we go through the loop.
String a = addressPort.substring(start, colon);
String p;
if (slash == -1) {
p = addressPort.substring(colon+1);
done = true;
} else {
p = addressPort.substring(colon+1, slash);
start = slash+1;
}
// Now convert the address and port strings to real values ...
IPAddressSet tA = IPAddressSet.getFromString(a);
int tP = Integer.parseInt(p);
// ... do a sanity check on the port value ...
if (tP <= 0 || tP > 65535) {
throw new IllegalArgumentException("Port out of range: " + tP);
}
// ... and merge the result into what was already there.
addr = IPAddressSet.merge(addr, tA);
ports = add(ports, tP, tA.addresses.length);
}
// Finally, store the result in the object fields.
address = addr;
int len = addr.addresses.length;
sas = new InetSocketAddress[len];
for (int i=0;i<len;i++) {
sas[i] = new InetSocketAddress(addr.addresses[i], ports[i]);
}
}
/**
* This method appends a value a specified number of times to an existing
* int array. A new array is returned.
*
* @param orig the original array
* @param value the value to append
* @param repeat the number of times the value should be appended.
* @return a new array
*/
private int [] add(int [] orig, int value, int repeat) {
int [] result = new int[orig.length+repeat];
System.arraycopy(orig, 0, result, 0, orig.length);
Arrays.fill(result, orig.length, result.length, value);
return result;
}
/**
* Gets the InetAddressSet.
*
* @return the InetAddressSet.
*/
public IPAddressSet getAddressSet() {
return address;
}
/**
* Gets the SocketAddresses.
*
* @return the ports.
*/
public InetSocketAddress [] getSocketAddresses() {
return sas;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
public int hashCode() {
// TODO: improve
return address.hashCode();
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
public boolean equals(Object other) {
// Check pointers
if (this == other) {
return true;
}
// Check type
if (!(other instanceof SocketAddressSet)) {
return false;
}
SocketAddressSet tmp = (SocketAddressSet) other;
// System.out.println("TcpSocketAdressSet.equals: ");
// System.out.println("arrays : " + Arrays.equals(sas, tmp.sas));
// System.out.println("address: " + address.equals(tmp.address));
// Finally, compare ports and addresses
// TODO: this is only correct if the addresses are exactly the same.
// So how do we handle partial addresses ?
for (int i=0;i<sas.length;i++) {
InetSocketAddress a = sas[i];
boolean found = false;
for (int j=0;j<tmp.sas.length;j++) {
if (a.equals(tmp.sas[j])) {
found = true;
break;
}
}
if (!found) {
return false;
}
}
return true;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
public String toString() {
StringBuffer b = new StringBuffer();
final int len = address.addresses.length;
for (int i=0;i<len;i++) {
b.append(NetworkUtils.ipToString(address.addresses[i]));
if (i < len-1) {
if (sas[i].getPort() != sas[i+1].getPort()) {
b.append(IP_PORT_SEPERATOR);
b.append(sas[i].getPort());
}
b.append(ADDRESS_SEPERATOR);
} else {
b.append(IP_PORT_SEPERATOR);
b.append(sas[i].getPort());
}
}
return b.toString();
}
/**
* Merges two IbisSocketAddresses.
*
* @param s1 the first IbisSocketAddress
* @param s2 the second IbisSocketAddress
* @return a new SmartSocketAddress
*/
public static SocketAddressSet merge(SocketAddressSet s1,
SocketAddressSet s2) {
IPAddressSet as = IPAddressSet.merge(s1.address, s2.address);
InetSocketAddress [] sa =
new InetSocketAddress[s1.sas.length + s2.sas.length];
System.arraycopy(s1.sas, 0, sa, 0, s1.sas.length);
System.arraycopy(s2.sas, 0, sa, s1.sas.length, s2.sas.length);
Arrays.sort(sa, IPAddressSet.SORTER);
return new SocketAddressSet(as, sa);
}
/**
* Converts an array of SocketAddressSets to a String array.
*
* @param s the array of {@link SocketAddressSet}
* @return a new String array containing the {@link String} representations
* of the {@link SocketAddressSet}s, or <code>null</code> if
* s was <code>null</code>
*/
public static String [] convertToStrings(SocketAddressSet [] s) {
if (s == null) {
return null;
}
String [] result = new String[s.length];
for (int i=0;i<s.length;i++) {
if (s[i] != null) {
result[i] = s[i].toString();
}
}
return result;
}
/**
* Converts an array of Strings into an array of SocketAddressSets.
*
* @param s the array of {@link String} to convert
* @param ignoreProblems indicates if conversion problems should be silently
* ignored.
* @return a new array containing the {@link SocketAddressSet}s
* or <code>null</code> if s was <code>null</code>
* @throws UnknownHostException when any of the Strings cannot be converted
* and ignoreProblems is false
*/
public static SocketAddressSet [] convertToSocketAddressSet(String [] s,
boolean ignoreProblems) throws UnknownHostException {
if (s == null) {
return null;
}
SocketAddressSet [] result = new SocketAddressSet[s.length];
for (int i=0;i<s.length;i++) {
if (s[i] != null) {
if (ignoreProblems) {
try {
result[i] = new SocketAddressSet(s[i]);
} catch (UnknownHostException e) {
// ignore
}
} else {
result[i] = new SocketAddressSet(s[i]);
}
}
}
return result;
}
/**
* Converts an array of Strings into an array of SocketAddressSets.
*
* @param s the array of {@link String} to convert
* @return a new array containing the {@link SocketAddressSet}s
* or <code>null</code> if s was <code>null</code>
* @throws UnknownHostException when any of the Strings cannot be converted
*/
public static SocketAddressSet [] convertToSocketAddressSet(String [] s)
throws UnknownHostException {
return convertToSocketAddressSet(s, false);
}
/**
* Returns if the other SocketAddressSet represents the same machine as
* this one.
*
* @param other the SocketAddressSet to compare to
* @return if both SocketAddressSets represent the same machine
*/
public boolean sameMachine(SocketAddressSet other) {
return address.equals(other.address);
}
/**
* Returns if the other SocketAddressSet represents the same process as
* this one.
*
* @param other the SocketAddressSet to compare to
* @return if both SocketAddressSets represent the same process
*/
public boolean sameProcess(SocketAddressSet other) {
return equals(other);
}
/**
* Returns if the two SocketAddressSets represent the same machine.
*
*/
public static boolean sameMachine(SocketAddressSet a, SocketAddressSet b) {
return a.sameMachine(b);
}
/**
* Returns if the two SocketAddressSets represent the same process.
*
*/
public static boolean sameProcess(SocketAddressSet a, SocketAddressSet b) {
return a.sameProcess(b);
}
}
|
package smp.clipboard;
import javafx.event.EventHandler;
import javafx.scene.control.Slider;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import smp.components.Values;
import smp.components.staff.Staff;
import smp.components.staff.sequences.StaffNoteLine;
import smp.fx.SMPFXController;
import smp.stateMachine.StateMachine;
/**
* Event Handler for rubber band which follows mouse movements. Mouse moves and
* the rubber band will adjust. Move to the edges of the pane and the pane will
* readjust position.
*
* @author j574y923
*/
public class RubberBandEventHandler implements EventHandler<MouseEvent> {
RubberBand rubberBand;
SMPFXController controller;
Pane rubberBandLayer;
DataClipboard theDataClipboard;
/* Get line with these */
private static double mouseX;
private static double mouseY;
private static boolean selVolAtNoteFlag;
public RubberBandEventHandler(SMPFXController ct, Pane basePane, DataClipboard clippy) {
controller = ct;
theDataClipboard = clippy;
rubberBandLayer = basePane;
rubberBand = new RubberBand();
// TEMPORARY, should probably be in a dataclipboardeventhandler
basePane.addEventHandler(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent event) {
if (event.isControlDown()) {
switch (event.getCode()) {
case A:
theDataClipboard.getFunctions().clearSelection();
theDataClipboard.getFunctions().select(0, 0,
(int) controller.getScrollbar().getMax() + Values.NOTELINES_IN_THE_WINDOW,
Values.NOTES_IN_A_LINE);
break;
case C:
//select code should not be with the copy code obviously
System.out.println("COPY");
// System.out.println("COPY POS: pb" + pb + " pe" + pe);
theDataClipboard.getFunctions().copy();
for ( StaffNoteLine line : theDataClipboard.getData().values() ) {
if(!line.isEmpty())
System.out.println(line);
}
break;
case V:
System.out.println("PASTE");
int currentLine = getLine(mouseX) + StateMachine.getMeasureLineNum();
System.out.println(currentLine);
theDataClipboard.getFunctions().paste(currentLine);
break;
case X:
theDataClipboard.getFunctions().cut();
break;
default:
break;
}
} else {
switch (event.getCode()) {
case DELETE:
theDataClipboard.getFunctions().delete();
break;
default:
break;
}
}
}
});
}
@Override
public void handle(MouseEvent mouseEvent) {
mouseX = mouseEvent.getX();
mouseY = mouseEvent.getY();
if(!StateMachine.isClipboardPressed()){
if (mouseEvent.getEventType() == MouseEvent.MOUSE_CLICKED)
theDataClipboard.getFunctions().clearSelection();
return;
}
//// rubberBand.toFront();
if (mouseEvent.getEventType() == MouseEvent.MOUSE_PRESSED) {
if(!mouseEvent.isControlDown()) {
// scrollPane.unhighlightAllNotes();
// scrollPane.unhighlightAllVols();
theDataClipboard.getFunctions().clearSelection();
} else {
}
rubberBandLayer.getChildren().add(rubberBand);
rubberBand.begin(mouseEvent.getX(), mouseEvent.getY());
System.out.print("begin GetLine:" + getLine(mouseEvent.getX()));
System.out.println(" GetPos:" + getPosition(mouseEvent.getY()));
} else if (mouseEvent.isPrimaryButtonDown()) {
rubberBand.resizeBand(mouseEvent.getX(), mouseEvent.getY());
} else if (mouseEvent.getEventType() == MouseEvent.MOUSE_RELEASED) {
rubberBand.end();
rubberBandLayer.getChildren().remove(rubberBand);
int lb = rubberBand.getLineBegin() + StateMachine.getMeasureLineNum();//getLine(rubberBand.getTranslateX()) + StateMachine.getMeasureLineNum();
int pb = rubberBand.getPositionBegin();//getPosition(rubberBand.getTranslateY() + rubberBand.getHeight());
int le = rubberBand.getLineEnd() + StateMachine.getMeasureLineNum();//getLine(rubberBand.getTranslateX() + rubberBand.getWidth()) + StateMachine.getMeasureLineNum();
int pe = rubberBand.getPositionEnd();//getPosition(rubberBand.getTranslateY());
theDataClipboard.getFunctions().select(lb, pb, le, pe);
System.out.print("end GetLine:" + getLine(mouseEvent.getX()));
System.out.println(" GetPos:" + getPosition(mouseEvent.getY()));
}
}
/**
*
*
*
* @relevant Values.NOTELINES_IN_THE_WINDOW,
* StateMachine.getMeasureLineNum()
*
* @param x
* mouse pos for entire scene
* @return -1 if out of bounds (x < 128 || x > 784), 0-9 otherwise
*/
private int getLine(double x) {
if (x < 128 || x > 784) {
return -1;
}
return (((int) x - 128) / 64);
}
/**
*
* temporary call this in RubberBand instead
*
* @relevant Values.NOTES_IN_A_LINE
*
* @param y
* mouse pos for entire scene
* @return note based on y coord
*/
private int getPosition(double y) {
// HARD CODED FOR NOW
if (y < 0 || y > 304) {
return -1;
}
return (Values.NOTES_IN_A_LINE - ((int) y - 0) / 16);
}
// public int getLineBegin() {
// //x, 32px is exactly at the line
// /* lineOffsetX is indices 0-31 of the row */
// int lineOffsetX = 0;
// if (this.getTranslateX() < 122 + 32) {//122 is arbitrary
// lineOffsetX = 0;
// } else if (this.getTranslateX() > Constants.WIDTH_DEFAULT - 48 + 32 - 64) {//48 is arbitrary
//// return -1;
// lineOffsetX = 32;
// } else {
// lineOffsetX = ((int)this.getTranslateX() - (122 + 32)) / Constants.LINE_SPACING + 1;
// /* lineOffsetY is row */
// int lineOffsetY = 0;
// if(!zby(this.getTranslateY())){
// lineOffsetY = (int)this.getTranslateY() / Constants.ROW_HEIGHT_TOTAL + 1;
// } else {
// lineOffsetY = (int)this.getTranslateY() / Constants.ROW_HEIGHT_TOTAL;
// System.out.println("BEG" + lineOffsetY * Constants.LINES_IN_A_ROW + " " + lineOffsetX);
// return lineOffsetY * Constants.LINES_IN_A_ROW + lineOffsetX;
//// return getLine(xOrigin, yOrigin);
//public int getLineEnd() {
// //x, 32px is exactly at the line
// /* lineOffsetX is indices 0-31 of the row */
// int lineOffsetX = 0;
// if ((this.getTranslateX() + this.getWidth()) < 122 + 32) {//122 is arbitrary
//// return -1;
// lineOffsetX = -1;
// } else if ((this.getTranslateX() + this.getWidth()) > Constants.WIDTH_DEFAULT - 48 + 32) {//48 is arbitrary
// lineOffsetX = 31;
// } else {
// lineOffsetX = ((int)(this.getTranslateX() + this.getWidth()) - (122 + 32 + 64)) / Constants.LINE_SPACING + 1;
// /* lineOffsetY is row */
// int lineOffsetY = 0;
// if(!zby(this.getTranslateY() + this.getHeight())){
// lineOffsetY = (int)(this.getTranslateY() + this.getHeight()) / Constants.ROW_HEIGHT_TOTAL;
// } else {
// lineOffsetY = (int)(this.getTranslateY() + this.getHeight()) / Constants.ROW_HEIGHT_TOTAL;
// System.out.println("END" + lineOffsetY * Constants.LINES_IN_A_ROW + " " + lineOffsetX);
// return lineOffsetY * Constants.LINES_IN_A_ROW + lineOffsetX;
//// return getLine(xOrigin + this.getWidth(), yOrigin + this.getHeight());
// /* If valid y */
// private boolean zby(double y) {
// return y % Constants.ROW_HEIGHT_TOTAL <= Constants.ROW_HEIGHT_NOTES;
// public void selectNotes() {
// Selection type = ((RibbonMenuMPO) Variables.stageInFocus.getRibbonMenu()).getSelectionToolbar().getSelectionType();
// if (type.equals(Selection.SELECTION_NOTES) || type.equals(Selection.SELECTION_NOTES_AND_VOL)) {
// //Note: overlapping rubberbands will highlight the same notes and this might have a big impact on performance and may need to be optimized later.
// for (RubberBand rb : rubberBands) {
// int lineBegin = rb.getLineBegin();
// List<MeasureLine> selection = DataClipboardFunctions.sel(scrollPane.getSong(),
// lineBegin,
// rb.getPositionBegin(),
// rb.getLineEnd(),
// rb.getPositionEnd());
// for (MeasureLine ml : selection) {
// if(ml != null) {
// for (Note n : ml) {
// scrollPane.highlightNote(n, true);
// public void selectVols() {
// Selection type = ((RibbonMenuMPO) Variables.stageInFocus.getRibbonMenu()).getSelectionToolbar().getSelectionType();
// if (type.equals(Selection.SELECTION_VOL) || type.equals(Selection.SELECTION_NOTES_AND_VOL)) {
// for (RubberBand rb : rubberBands) {
// int lineBeginVol = rb.getLineBeginVol();
// int lineEndVol = rb.getLineEndVol();
// System.out.println("SV_lBV:" + lineBeginVol);
// System.out.println("SV_lEV:" + lineEndVol);
// List<MeasureLine> selectionVol = DataClipboardFunctions.selVol(scrollPane.getSong(),
// lineBeginVol,
// lineEndVol);
// for (int i = 0; i < selectionVol.size(); i++) {
// if (selectionVol.get(i) != null) {
// scrollPane.highlightVol(selectionVol.get(i).getLineNumber(), true);
public RubberBand getRubberBand() {
return rubberBand;
}
/**
* REQUIRED. will define min x bound for rubberband
*
* @param x
* coord of left edge of the left-most line in the staff frame.
* Use absolute(window) coordinates
*/
public void initializeLineMinBound(double x) {
rubberBand.setLineMinBound(x);
}
/**
* REQUIRED. will define max x bound for rubberband
*
* @param x
* coord of right edge of the right-most line in the staff frame.
* Use absolute(window) coordinates
*/
public void initializeLineMaxBound(double x) {
rubberBand.setLineMaxBound(x);
}
/**
* REQUIRED. will define min y bound for rubberband
*
* @param y
* coord of top edge of the top-most position in the staff frame.
* Use absolute(window) coordinates
*/
public void initializePositionMinBound(double y) {
rubberBand.setPositionMinBound(y);
}
/**
* REQUIRED. will define max y bound for rubberband
*
* @param y
* coord of bottom edge of the bottom-most position in the staff
* frame. Use absolute(window) coordinates
*/
public void initializePositionMaxBound(double y) {
rubberBand.setPositionMaxBound(y);
}
/**
* REQUIRED. will define extra bound for selecting volume for rubberband.
* should be > positionMaxBound + marginVertical
*
* @param y
* coord of bottom edge of the bottom-most position in the staff
* frame. Use absolute(window) coordinates
*/
public void initializeVolumeYMaxCoord(double y) {
rubberBand.setVolumeYMaxCoord(y);
}
//calculate this with line width
@Deprecated
public void initializeVolumeSpacing(double x) {
}
/**
* REQUIRED. will be used to define width between lines
*
* @param dx
* delta x
*/
public void initializeLineSpacing(double dx) {
rubberBand.setLineSpacing(dx);
}
/**
* REQUIRED. will be used to define height between positions
*
* @param dy
* delta y
*/
public void initializePositionSpacing(double dy) {
rubberBand.setPositionSpacing(dy);
}
/**
* increase top and bottom margins around staff for drawing rubberband.
* default is 0.0.
*
* @param margin
*/
public void setMarginVertical(double m) {
rubberBand.setMarginVertical(m);
}
/**
* increase left and right margins around staff for drawing rubberband.
* default is 0.0.
*
* @param margin
*/
public void setMarginHorizontal(double m) {
rubberBand.setMarginHorizontal(m);
}
public void setScrollBarResizable(Slider slider) {
rubberBand.setScrollBarResizable(slider);
}
}
|
package com.spaceproject.screens;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.utils.Align;
import com.badlogic.gdx.utils.viewport.ScreenViewport;
import com.kotcrab.vis.ui.VisUI;
import com.kotcrab.vis.ui.util.dialog.Dialogs;
import com.kotcrab.vis.ui.util.dialog.OptionDialogAdapter;
import com.spaceproject.SpaceProject;
import com.spaceproject.generation.FontFactory;
import com.spaceproject.screens.animations.DelaunayAnim;
import com.spaceproject.screens.animations.NBodyGravityAnim;
import com.spaceproject.screens.animations.NoiseAnim;
import com.spaceproject.screens.animations.OrbitAnim;
import com.spaceproject.screens.animations.TitleAnimation;
import com.spaceproject.screens.animations.TreeAnim;
import com.spaceproject.ui.menu.TitleScreenMenu;
public class TitleScreen extends MyScreenAdapter {
private SpaceProject game;
private Stage stage;
private Table versionTable;
private Label titleLabel;
private int edgePad;
private Matrix4 projectionMatrix = new Matrix4();
private TitleAnimation foregroundAnimation, backgroundAnimation;
enum ForegroundAnimation {
tree, delaunay, orbit, crossNoise, nbody;/*, asteroid*/;
public static ForegroundAnimation random() {
return ForegroundAnimation.values()[MathUtils.random(ForegroundAnimation.values().length - 1)];
}
public static ForegroundAnimation next(ForegroundAnimation e) {
int index = e.ordinal();
int nextIndex = index + 1;
ForegroundAnimation[] cars = ForegroundAnimation.values();
nextIndex %= cars.length;
return cars[nextIndex];
}
}
public TitleScreen(SpaceProject spaceProject) {
this.game = spaceProject;
//init scene2d and VisUI
if (VisUI.isLoaded())
VisUI.dispose(true);
VisUI.load(VisUI.SkinScale.X2);
stage = new Stage(new ScreenViewport());
Gdx.input.setInputProcessor(stage);
//init fonts
String titleFont = "titleFontLarge";
initTitleFont(titleFont);
String menuFont = "menuFont";
initMenuFont(menuFont);
titleLabel = new Label(SpaceProject.TITLE, VisUI.getSkin(), titleFont, Color.WHITE);
titleLabel.setPosition(Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight(), Align.top);
stage.addActor(titleLabel);
//menu
Table menuTable = TitleScreenMenu.buildMenu(game, stage, false);
stage.addActor(menuTable);
menuTable.pack();
edgePad = SpaceProject.isMobile() ? 20 : 10;
menuTable.setPosition(edgePad, edgePad);
//version note
versionTable = new Table();
versionTable.add(new Label(SpaceProject.VERSION, VisUI.getSkin(), menuFont, Color.WHITE));
stage.addActor(versionTable);
versionTable.pack();
//init animations
backgroundAnimation = new NoiseAnim();
initForegroundAnim();
Gdx.graphics.setVSync(true);
}
public void render(float delta) {
super.render(delta);
Gdx.gl20.glClearColor(1, 1, 1, 1);
Gdx.gl20.glClear(GL20.GL_COLOR_BUFFER_BIT);
cam.position.set(Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() / 2, 0);
projectionMatrix.setToOrtho2D(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
shape.setProjectionMatrix(projectionMatrix);
batch.setProjectionMatrix(projectionMatrix);
backgroundAnimation.render(delta, shape);
//enable transparency
Gdx.gl.glEnable(GL20.GL_BLEND);
Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
foregroundAnimation.render(delta, shape);
Gdx.gl.glDisable(GL20.GL_BLEND);
stage.act(Math.min(Gdx.graphics.getDeltaTime(), 1 / 30f));
stage.draw();
if (Gdx.input.isKeyJustPressed(Input.Keys.F5)) {
initForegroundAnim();
}
if (Gdx.input.isKeyJustPressed(Input.Keys.F3)) {
Table table = TitleScreenMenu.buildMenu(game, stage, true);
table.pack();
table.setPosition(edgePad, edgePad);
stage.clear();
stage.addActor(table);
}
if (Gdx.input.isKeyJustPressed(Input.Keys.ESCAPE)) {
if (!exitPromptUp) {
exitPromptUp = true;
Dialogs.showOptionDialog(stage, "exit", "goodbye?", Dialogs.OptionDialogType.YES_NO, new OptionDialogAdapter() {
@Override
public void yes() {
Gdx.app.exit();
}
@Override
public void no () {
exitPromptUp = false;
}
@Override
public void cancel () {
exitPromptUp = false;
}
});
}
}
}
boolean exitPromptUp = false;
@Override
public void resize(int width, int height) {
super.resize(width, height);
stage.getViewport().update(width, height, true);
versionTable.setPosition(Gdx.graphics.getWidth() - versionTable.getWidth() - edgePad, edgePad);
titleLabel.setPosition(Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight(), Align.top);
foregroundAnimation.resize(width, height);
backgroundAnimation.resize(width, height);
}
private void initMenuFont(String menuFont) {
FreeTypeFontGenerator.FreeTypeFontParameter parameter = new FreeTypeFontGenerator.FreeTypeFontParameter();
parameter.size = 30;
parameter.borderColor = Color.DARK_GRAY;
parameter.borderWidth = 1;
BitmapFont fontComfortaaBold = FontFactory.createFont(FontFactory.fontComfortaaBold, parameter);
VisUI.getSkin().add(menuFont, fontComfortaaBold);
}
private void initTitleFont(String titleFont) {
FreeTypeFontGenerator.FreeTypeFontParameter parameter = new FreeTypeFontGenerator.FreeTypeFontParameter();
parameter.size = 90;
parameter.borderColor = Color.DARK_GRAY;
parameter.borderWidth = 1;
BitmapFont fontComfortaaBold = FontFactory.createFont(FontFactory.fontComfortaaBold, parameter);
VisUI.getSkin().add(titleFont, fontComfortaaBold);
}
ForegroundAnimation previousAnim;
private void initForegroundAnim() {
ForegroundAnimation anim = ForegroundAnimation.random();
//don't allow same anim on refresh
if (previousAnim != null && anim == previousAnim) {
anim = ForegroundAnimation.next(anim);
}
switch (anim) {
case delaunay:
this.foregroundAnimation = new DelaunayAnim();
break;
case tree:
this.foregroundAnimation = new TreeAnim();
break;
case orbit:
this.foregroundAnimation = new OrbitAnim();
break;
case crossNoise:
this.foregroundAnimation = new NoiseAnim(0, 0.01f, 3, 0.013f, true);
break;
case nbody:
this.foregroundAnimation = new NBodyGravityAnim();
break;
/*
case asteroid: /
this.foregroundAnimation = new AsteroidAnim();
break;*/
}
previousAnim = anim;
Gdx.app.debug(this.getClass().getSimpleName(), "Animation: " + anim);
}
public void dispose() {
batch.dispose();
shape.dispose();
VisUI.dispose(true);
stage.dispose();
}
}
|
package hudson.scm;
import hudson.model.AbstractBuild;
import hudson.model.User;
import hudson.scm.CVSChangeLogSet.CVSChangeLog;
import hudson.util.IOException2;
import org.apache.commons.digester.Digester;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Collection;
import java.util.AbstractList;
/**
* {@link ChangeLogSet} for CVS.
* @author Kohsuke Kawaguchi
*/
public final class CVSChangeLogSet extends ChangeLogSet<CVSChangeLog> {
private List<CVSChangeLog> logs;
public CVSChangeLogSet(AbstractBuild<?,?> build, List<CVSChangeLog> logs) {
super(build);
this.logs = Collections.unmodifiableList(logs);
for (CVSChangeLog log : logs)
log.setParent(this);
}
/**
* Returns the read-only list of changes.
*/
public List<CVSChangeLog> getLogs() {
return logs;
}
@Override
public boolean isEmptySet() {
return logs.isEmpty();
}
public Iterator<CVSChangeLog> iterator() {
return logs.iterator();
}
public static CVSChangeLogSet parse( AbstractBuild build, java.io.File f ) throws IOException, SAXException {
Digester digester = new Digester();
ArrayList<CVSChangeLog> r = new ArrayList<CVSChangeLog>();
digester.push(r);
digester.addObjectCreate("*/entry",CVSChangeLog.class);
digester.addBeanPropertySetter("*/entry/date");
digester.addBeanPropertySetter("*/entry/time");
digester.addBeanPropertySetter("*/entry/author","user");
digester.addBeanPropertySetter("*/entry/msg");
digester.addSetNext("*/entry","add");
digester.addObjectCreate("*/entry/file",File.class);
digester.addBeanPropertySetter("*/entry/file/name");
digester.addBeanPropertySetter("*/entry/file/revision");
digester.addBeanPropertySetter("*/entry/file/prevrevision");
digester.addCallMethod("*/entry/file/dead","setDead");
digester.addSetNext("*/entry/file","addFile");
try {
digester.parse(f);
} catch (IOException e) {
throw new IOException2("Failed to parse "+f,e);
} catch (SAXException e) {
throw new IOException2("Failed to parse "+f,e);
}
// merge duplicate entries. Ant task somehow seems to report duplicate entries.
for(int i=r.size()-1; i>=0; i
CVSChangeLog log = r.get(i);
boolean merged = false;
for(int j=0;j<i;j++) {
CVSChangeLog c = r.get(j);
if(c.canBeMergedWith(log)) {
c.merge(log);
merged = true;
break;
}
}
if(merged)
r.remove(log);
}
return new CVSChangeLogSet(build,r);
}
/**
* In-memory representation of CVS Changelog.
*/
public static class CVSChangeLog extends ChangeLogSet.Entry {
private String date;
private String time;
private User author;
private String msg;
private final List<File> files = new ArrayList<File>();
/**
* Checks if two {@link CVSChangeLog} entries can be merged.
* This is to work around the duplicate entry problems.
*/
public boolean canBeMergedWith(CVSChangeLog that) {
if(!this.date.equals(that.date))
return false;
if(!this.time.equals(that.time)) // TODO: perhaps check this loosely?
return false;
if(this.author==null || that.author==null || !this.author.equals(that.author))
return false;
if(!this.msg.equals(that.msg))
return false;
return true;
}
public void merge(CVSChangeLog that) {
this.files.addAll(that.files);
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public User getAuthor() {
return author;
}
public Collection<String> getAffectedPaths() {
return new AbstractList<String>() {
public String get(int index) {
return files.get(index).getName();
}
public int size() {
return files.size();
}
};
}
public void setUser(String author) {
this.author = User.get(author);
}
public String getUser() {// digester wants read/write property, even though it never reads. Duh.
return author.getDisplayName();
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public void addFile( File f ) {
f.parent = this;
files.add(f);
}
public List<File> getFiles() {
return files;
}
}
public static class File {
private String name;
private String revision;
private String prevrevision;
private boolean dead;
private CVSChangeLog parent;
/**
* Gets the full file name in the CVS repository, like
* "foo/bar/zot.c"
*
* <p>
* The path is relative to the workspace root.
*/
public String getName() {
return name;
}
/**
* Gets just the last component of the path, like "zot.c"
*/
public String getSimpleName() {
int idx = name.lastIndexOf('/');
if(idx>0) return name.substring(idx+1);
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRevision() {
return revision;
}
public void setRevision(String revision) {
this.revision = revision;
}
public String getPrevrevision() {
return prevrevision;
}
public void setPrevrevision(String prevrevision) {
this.prevrevision = prevrevision;
}
public boolean isDead() {
return dead;
}
public void setDead() {
this.dead = true;
}
public EditType getEditType() {
// see issue #73. Can't do much better right now
if(dead)
return EditType.DELETE;
if(revision.equals("1.1"))
return EditType.ADD;
return EditType.EDIT;
}
public CVSChangeLog getParent() {
return parent;
}
}
/**
* Represents CVS revision number like "1.5.3.2". Immutable.
*/
public static class Revision {
public final int[] numbers;
public Revision(int[] numbers) {
this.numbers = numbers;
assert numbers.length%2==0;
}
public Revision(String s) {
String[] tokens = s.split("\\.");
numbers = new int[tokens.length];
for( int i=0; i<tokens.length; i++ )
numbers[i] = Integer.parseInt(tokens[i]);
assert numbers.length%2==0;
}
/**
* Returns a new {@link Revision} that represents the previous revision.
*
* For example, "1.5"->"1.4", "1.5.2.13"->"1.5.2.12", "1.5.2.1"->"1.5"
*
* @return
* null if there's no previous version, meaning this is "1.1"
*/
public Revision getPrevious() {
if(numbers[numbers.length-1]==1) {
// x.y.z.1 => x.y
int[] p = new int[numbers.length-2];
System.arraycopy(numbers,0,p,0,p.length);
if(p.length==0) return null;
return new Revision(p);
}
int[] p = numbers.clone();
p[p.length-1]
return new Revision(p);
}
public String toString() {
StringBuilder buf = new StringBuilder();
for (int n : numbers) {
if(buf.length()>0) buf.append('.');
buf.append(n);
}
return buf.toString();
}
}
}
|
package org.javarosa.core.util;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Stack;
import java.util.Vector;
/**
* Directed A-cyclic (NOT ENFORCED) graph datatype.
*
* Genericized with three types: An unique index value (representing the node), a generic
* set of data to associate with that node, and a piece of data to associate with each
* edge
*
* @author ctsims
*/
public class DAG<I, N, E> {
//TODO: This is a really unsafe datatype. Needs an absurd amount of updating for representation
//invariance, synchronicity, cycle detection, etc.
private final Hashtable<I, N> nodes;
private final Hashtable<I, Vector<Edge<I, E>>> edges;
private final Hashtable<I, Vector<Edge<I, E>>> inverseEdges;
public DAG() {
nodes = new Hashtable<I, N>();
edges = new Hashtable<I, Vector<Edge<I, E>>>();
inverseEdges = new Hashtable<I, Vector<Edge<I, E>>>();
}
public void addNode(I i, N n) {
nodes.put(i, n);
}
public void removeNode(I i) {
nodes.remove(i);
}
/**
* Connect Source -> Destination
*/
public void setEdge(I source, I destination, E edgeData) {
addToEdges(edges, source, destination, edgeData);
addToEdges(inverseEdges, destination, source, edgeData);
}
private void addToEdges(Hashtable<I, Vector<Edge<I, E>>> edgeList, I source, I dest, E edgeData) {
Vector<Edge<I, E>> edge;
if (edgeList.containsKey(source)) {
edge = edgeList.get(source);
} else {
edge = new Vector<Edge<I, E>>();
}
edge.addElement(new Edge<I, E>(dest, edgeData));
edgeList.put(source, edge);
}
/**
* Removes the given edge from both edge lists
*/
public void removeEdge(I sourceIndex, I destinationIndex) {
removeEdge(edges, sourceIndex, destinationIndex);
removeEdge(inverseEdges, destinationIndex, sourceIndex);
}
/**
* If an edge from sourceIndex to destinationIndex exists in the given edge list, remove it
*/
private void removeEdge(Hashtable<I, Vector<Edge<I, E>>> edgeList, I sourceIndex, I destinationIndex) {
Vector<Edge<I, E>> edgesFromSource = edgeList.get(sourceIndex);
if (edgesFromSource != null) {
for (Edge<I, E> edge : edgesFromSource) {
if (edge.i.equals(destinationIndex)) {
// Remove the edge
edgesFromSource.remove(edge);
// If removing this edge has made it such that this source index no longer has
// any edges from it, remove that entire index from the edges hashtable
if (edgesFromSource.size() == 0) {
edgeList.remove(sourceIndex);
}
return;
}
}
}
}
public Vector<Edge<I, E>> getParents(I index) {
if (inverseEdges.containsKey(index)) {
return inverseEdges.get(index);
} else {
return new Vector<Edge<I, E>>();
}
}
public Vector<Edge<I, E>> getChildren(I index) {
if (!edges.containsKey(index)) {
return new Vector<Edge<I, E>>();
} else {
return edges.get(index);
}
}
public N getNode(I index) {
return nodes.get(index);
}
/**
* @return Indices for all nodes in the graph which are not the target of
* any edges in the graph
*/
public Stack<I> getSources() {
Stack<I> sources = new Stack<I>();
for (Enumeration en = nodes.keys(); en.hasMoreElements(); ) {
I i = (I)en.nextElement();
if (!inverseEdges.containsKey(i)) {
sources.addElement(i);
}
}
return sources;
}
/**
* @return Indices for all nodes that do not have any outgoing edges
*/
public Stack<I> getSinks() {
Stack<I> roots = new Stack<I>();
for (Enumeration en = nodes.keys(); en.hasMoreElements(); ) {
I i = (I)en.nextElement();
if (!edges.containsKey(i)) {
roots.addElement(i);
}
}
return roots;
}
public static class Edge<I, E> {
public final I i;
public final E e;
public Edge(I i, E e) {
this.i = i;
this.e = e;
}
}
public Enumeration getNodes() {
return nodes.elements();
}
public Enumeration getIndices() {
return nodes.keys();
}
public Hashtable<I, Vector<Edge<I, E>>> getEdges() {
return this.edges;
}
}
|
package android.view;
import io.leocad.webcachedimageview.BitmapWorkerTask;
import io.leocad.webcachedimageview.CacheManager;
import io.leocad.webcachedimageview.R;
import java.lang.ref.WeakReference;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.os.Build;
import android.util.AttributeSet;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.widget.ImageView;
public class WebCachedImageView extends ImageView {
private static final int[] ATTRS_DIMEN_ANDROID = {android.R.attr.layout_width, android.R.attr.layout_height};
public CacheManager mCacheMgr;
private WeakReference<BitmapWorkerTask> mBitmapWorkerRef;
private int mWidth;
private int mHeight;
private Animation mAppearAnimation;
public WebCachedImageView(Context context) {
super(context);
init(context, CacheManager.MODE_MEMORY | CacheManager.MODE_DISK, 12.5f, null);
}
public WebCachedImageView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray styledAttrs = context.obtainStyledAttributes(attrs, R.styleable.WebCachedImageView);
int mode = styledAttrs.getInt(R.styleable.WebCachedImageView_mode, CacheManager.MODE_MEMORY | CacheManager.MODE_DISK);
float memoryFractionToUse = styledAttrs.getFloat(R.styleable.WebCachedImageView_memoryPercentToUse, 12.5f);
styledAttrs.recycle();
init(context, mode, memoryFractionToUse, attrs);
}
private void init(Context context, int mode, float memoryPercentToUse, AttributeSet attrs) {
if (!isInEditMode()) {
// Get the image dimensions
if (attrs != null) {
TypedArray styledAttrs = context.obtainStyledAttributes(attrs, ATTRS_DIMEN_ANDROID);
try {
mWidth = styledAttrs.getDimensionPixelSize(0, ViewGroup.LayoutParams.MATCH_PARENT);
} catch (UnsupportedOperationException e) {
// This dimension is either "match_parent" or "wrap_content"
mWidth = -1;
}
try {
mHeight = styledAttrs.getDimensionPixelSize(1, ViewGroup.LayoutParams.MATCH_PARENT);
} catch (UnsupportedOperationException e) {
mHeight = -1;
}
styledAttrs.recycle();
// Use the screen dimensions if the imageview's dimensions aren't set.
// The image will never de bigger than the screen
if (mWidth <= 0 || mHeight <= 0) {
Point screenDimensions = getScreenDimensions(context);
mWidth = screenDimensions.x;
mHeight = screenDimensions.y;
}
}
mCacheMgr = CacheManager.getInstance(context, mode, memoryPercentToUse);
mAppearAnimation = new AlphaAnimation(0.f, 1.f);
mAppearAnimation.setDuration(300);
mAppearAnimation.setRepeatCount(0);
mAppearAnimation.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
setAlphaCompat(1.f);
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
}
});
} // TODO else show placeholder
}
public void setImageUrl(String url) {
setAlphaCompat(0.f); // TODO Add placeholder
if (cancelPotentialWork(url)) {
final BitmapWorkerTask bitmapWorkerTask = new BitmapWorkerTask(this);
mBitmapWorkerRef = new WeakReference<BitmapWorkerTask>(bitmapWorkerTask);
bitmapWorkerTask.execute(url, mCacheMgr, mWidth, mHeight);
}
}
@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
private static Point getScreenDimensions(Context context) {
Point size = new Point();
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
if (Build.VERSION.SDK_INT >= 13) {
display.getSize(size);
} else {
size.x = display.getWidth();
size.y = display.getHeight();
}
return size;
}
@SuppressLint("NewApi")
private void setAlphaCompat(float alpha) {
if (Build.VERSION.SDK_INT >= 11 && Build.VERSION.SDK_INT < 16) {
setAlpha(alpha);
} else if (Build.VERSION.SDK_INT >= 16) {
setImageAlpha((int) (alpha * 255));
} else {
if (alpha == 0.f) {
setVisibility(View.INVISIBLE);
} else {
setVisibility(View.VISIBLE);
}
}
}
private boolean cancelPotentialWork(String url) {
BitmapWorkerTask task = getBitmapWorkerTask();
if (task != null) {
if (url != task.url) {
// Cancel previous task
task.cancel(true);
} else {
// The same work is already in progress
return false;
}
}
// No task associated with the ImageView, or an existing task was cancelled
return true;
}
public BitmapWorkerTask getBitmapWorkerTask() {
return mBitmapWorkerRef == null? null: mBitmapWorkerRef.get();
}
@Override
public void setImageBitmap(Bitmap bm) {
super.setImageBitmap(bm);
startAnimation(mAppearAnimation);
}
}
|
package com.androidessence.lib;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.net.Uri;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.BackgroundColorSpan;
import android.text.style.BulletSpan;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.ImageSpan;
import android.text.style.StrikethroughSpan;
import android.text.style.StyleSpan;
import android.text.style.SubscriptSpan;
import android.text.style.SuperscriptSpan;
import android.text.style.URLSpan;
import android.text.style.UnderlineSpan;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import org.json.JSONObject;
import org.w3c.dom.Text;
import java.util.Calendar;
import java.util.EnumSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RichTextView extends TextView {
//-- Properties --//
/**
* The Context that this view is displayed in.
*/
private Context mContext;
/**
* The spannable string to display in this TextView.
*/
private SpannableString mSpannableString;
/**
* The number of spans applied to this SpannableString.
*/
private int mSpanCount;
//-- Constructors --//
public RichTextView(Context context) {
this(context, null);
}
public RichTextView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public RichTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs);
// Set variables.
this.mContext = context;
this.mSpanCount = 0;
initStyle(attrs, defStyleAttr);
}
//-- Initializations --//
private void initStyle(AttributeSet attrs, int defStyleAttr) {
TypedArray typedArray = mContext.obtainStyledAttributes(attrs, R.styleable.RichTextView, defStyleAttr, 0);
//TODO: Implement special attributes.
if (typedArray != null) typedArray.recycle();
}
//-- Overridden methods --//
@Override
public void setText(CharSequence text, BufferType type) {
// Set our spannable string.
mSpannableString = new SpannableString(text);
super.setText(mSpannableString, type);
}
public void formatNumberSpan(int startline,int endline) {
String[] splitter = mSpannableString.toString().split("\n");
int start = 0;
int index = 1;
for (int i = 0; i < splitter.length; i++) {
Log.d("Index : " + i, splitter[i]);
if (!splitter[i].equals("") && !splitter[i].equals("\n")) {
/* index starts at 0.*/
if(i>=(startline-1) && i<endline) {
mSpanCount++;
mSpannableString.setSpan(new NumberSpan(index++, 100, false, getTextSize()), start, (start + 1), 0);
start = start + splitter[i].length() + 1;
}else
{
start = start + splitter[i].length() + 1;
}
}
}
setText(mSpannableString);
}
public void formatImageSpan(int start, int end, Bitmap drawable) {
// If the start index is less than 0 or greater than/equal to the length of the string, it is invalid.
// If the end index is less than start or greater than the string length, it is invalid.
if (start < 0 || start >= mSpannableString.length()) {
throw new IllegalArgumentException("Invalid start index.");
} else if (end < start || end > mSpannableString.length()) {
throw new IllegalArgumentException("Invalid end index.");
}
// Add span
mSpanCount++;
mSpannableString.setSpan(new ImageSpan(getContext(), drawable), start, end, 0);
// Set text
setText(mSpannableString);
}
//-- Format methods --//
/**
* Formats a Span of text in the text view. This method was added as a convenience method
* so the user doesn't have to use EnumSet for one item.
*
* @param start The index of the first character to span.
* @param end The index of the last character to span.
* @param formatType The format to apply to this span.
*/
public void formatSpan(int start, int end, FormatType formatType) {
// Call the other method as if this were an EnumSet.
formatSpan(start, end, EnumSet.of(formatType));
}
/**
* Formats a Span of text in the text view.
*
* @param start The index of the first character to span.
* @param end The index of the last character to span.
* @param formatTypes The formats to apply to this span.
*/
public void formatSpan(int start, int end, EnumSet<FormatType> formatTypes) {
// If the start index is less than 0 or greater than/equal to the length of the string, it is invalid.
// If the end index is less than start or greater than the string length, it is invalid.
if (start < 0 || start >= mSpannableString.length()) {
throw new IllegalArgumentException("Invalid start index.");
} else if (end < start || end > mSpannableString.length()) {
throw new IllegalArgumentException("Invalid end index.");
}
// There is no need to consider a null FormatType. Since we have two method headers of (int, int, type)
// The compiler will claim that `formatSpan(int, int, null);` call is ambiguous.
mSpanCount += formatTypes.size();
// Create span to be applied - Default to normal.
for (FormatType type : formatTypes) {
mSpannableString.setSpan(type.getSpan(), start, end, 0);
}
setText(mSpannableString);
}
/**
* Colors a portion of the string.
*
* @param start The index of the first character to color.
* @param end The index of the last character to color..
* @param formatType The type of format to apply to this span.
* @param color The color to apply to this substring.
*/
public void colorSpan(int start, int end, ColorFormatType formatType, int color) {
// If the start index is less than 0 or greater than/equal to the length of the string, it is invalid.
// If the end index is less than start or greater than the string length, it is invalid.
if (start < 0 || start >= mSpannableString.length()) {
throw new IllegalArgumentException("Invalid start index.");
} else if (end < start || end > mSpannableString.length()) {
throw new IllegalArgumentException("Invalid end index.");
} else if (formatType == null) {
throw new IllegalArgumentException("Invalid FormatType.");
}
// Add span
mSpanCount++;
mSpannableString.setSpan(formatType.getSpan(color), start, end, 0);
// Set text
setText(mSpannableString);
}
/**
* Adds a hyperlink to a portion of the string.
*
* @param start The index of the first character of the link.
* @param end The index of the last character of the link.
* @param url The URL that the hyperlink points to.
*/
public void addHyperlinkToSpan(int start, int end, final String url) {
// If the start index is less than 0 or greater than/equal to the length of the string, it is invalid.
// If the end index is less than start or greater than the string length, it is invalid.
if (start < 0 || start >= mSpannableString.length()) {
throw new IllegalArgumentException("Invalid start index.");
} else if (end < start || end > mSpannableString.length()) {
throw new IllegalArgumentException("Invalid end index.");
}
// Add span
mSpanCount++;
this.setMovementMethod(LinkMovementMethod.getInstance());
URLSpan urlSpan = new URLSpan(url);
mSpannableString.setSpan(urlSpan, start, end, 0);
// Set text
setText(mSpannableString);
}
/**
* Clears all spans applied to our SpannableString.
*/
public void clearSpans() {
// Get spans
Object[] spans = mSpannableString.getSpans(0, mSpannableString.length(), Object.class);
// Loop through and remove each one.
for (Object span : spans) {
mSpannableString.removeSpan(span);
mSpanCount
}
// Set text again.
setText(mSpannableString);
}
//-- Accessors --//
/**
* Retrieves the number of spans applied to this SpannableString.
*
* @return The number of spans applied.
*/
public int getSpanCount() {
return mSpanCount;
}
/**
* Retrieves all spans applied to the string.
*
* @return An array of object representing the types of spans applied.
*/
public Object[] getSpans() {
return mSpannableString.getSpans(0, mSpanCount, Object.class);
}
//-- Inner classes --//
/**
* An enumeration of various ways to format the text.
*/
public enum FormatType {
NONE {
@Override
public Object getSpan() {
return new StyleSpan(Typeface.NORMAL);
}
},
BOLD {
@Override
public Object getSpan() {
return new StyleSpan(Typeface.BOLD);
}
},
ITALIC {
@Override
public Object getSpan() {
return new StyleSpan(Typeface.ITALIC);
}
},
UNDERLINE {
@Override
public Object getSpan() {
return new UnderlineSpan();
}
},
STRIKETHROUGH {
@Override
public Object getSpan() {
return new StrikethroughSpan();
}
},
SUPERSCRIPT {
@Override
public Object getSpan() {
return new SuperscriptSpan();
}
},
SUBSCRIPT {
@Override
public Object getSpan() {
return new SubscriptSpan();
}
};
/**
* @return The type of Span to apply for this FormatType.
*/
public abstract Object getSpan();
}
/**
* An enumeration of various ways to color the text.
*/
public enum ColorFormatType {
FOREGROUND {
@Override
public Object getSpan(int color) {
return new ForegroundColorSpan(color);
}
},
HIGHLIGHT {
@Override
public Object getSpan(int color) {
return new BackgroundColorSpan(color);
}
};
/**
* @param color The color to apply to this span.
* @return The type of Span to apply for this ColorformatType.
*/
public abstract Object getSpan(int color);
}
}
|
package eu.project.rapid.common;
/**
* Control Messages for client-server communication Message IDs up to 255 - one byte only, as they
* are sent over sockets using write()/read() - only one byte read/written.
*/
public class RapidMessages {
// Generic Messages
public static final int OK = 1;
public static final int ERROR = 0;
public static final int PING = 11;
public static final int PONG = 12;
// Communication Phone <-> VM
public static final int AC_REGISTER_AS = 13;
public static final int AS_APP_PRESENT_AC = 14;
public static final int AS_APP_REQ_AC = 15;
public static final int AC_OFFLOAD_REQ_AS = 16;
// Communication Phone <-> VM (for testing purposes)
public static final int SEND_INT = 17;
public static final int SEND_BYTES = 18;
public static final int RECEIVE_INT = 19;
public static final int RECEIVE_BYTES = 20;
// Communication Main VM <-> Helper VM
public static final int CLONE_ID_SEND = 21;
// Communication Phone/VM <-> DS/Manager
public static final int PHONE_CONNECTION = 30;
public static final int CLONE_CONNECTION = 31;
public static final int MANAGER_CONNECTION = 32;
public static final int PHONE_AUTHENTICATION = 33;
public static final int AC_REGISTER_NEW_DS = 34;
public static final int AC_REGISTER_PREV_DS = 35;
public static final int AC_REGISTER_SLAM = 36;
public static final int AS_RM_REGISTER_DS = 37;
public static final int AS_RM_REGISTER_VMM = 38;
public static final int AS_RM_NOTIFY_VMM = 39;
public static final int CLONE_AUTHENTICATION = 40;
public static final int MANAGER_AUTHENTICATION = 41;
public static final int GET_ASSOCIATED_CLONE_INFO = 42;
public static final int GET_NEW_CLONE_INFO = 43;
public static final int GET_PORT = 44;
public static final int GET_SSL_PORT = 45;
public static final int DOWNLOAD_FILE = 146;
public static final int UPLOAD_FILE = 147;
public static final int UPLOAD_FILE_RESULT = 48;
public static final int DATA_RATE_THROTTLE = 49;
public static final int DATA_RATE_UNTHROTTLE = 50;
public static final int FORWARD_REQ = 51;
public static final int FORWARD_START = 52;
public static final int FORWARD_END = 53;
public static final int PARALLEL_REQ = 54;
public static final int PARALLEL_START = 55;
public static final int PARALLEL_END = 56;
public static final int DS_MIGRATION_VM_AS = 57;
// Demo server registers with the DS so that the others can find its IP
public static final int DEMO_SERVER_REGISTER_DS = 80;
// Everyone to DS for asking for demo animation ip
public static final int GET_DEMO_SERVER_IP_DS = 81;
// Communication SLAM <-> VMM
public static final int SLAM_START_VM_VMM = 60;
public static final int VMM_REGISTER_SLAM = 61;
public static final int SLAM_GET_VMCPU_VMM = 62;
public static final int SLAM_GET_VMINFO_VMM = 63;
public static final int SLAM_CHANGE_VMFLV_VMM = 64;
public static final int SLAM_CONFIRM_VMFLV_VMM = 65;
public static final int SLAM_GET_VMMEM_VMM = 66;
public static final int SLAM_GET_VMDISK_VMM = 67;
// Communication DS <-> VMM
public static final int VMM_REGISTER_DS = 70;
public static final int VMM_NOTIFY_DS = 71;
public static final int VM_REGISTER_DS = 72;
public static final int VM_NOTIFY_DS = 73;
public static final int HELPER_NOTIFY_DS = 74;
public static final int DS_VM_DEREGISTER_VMM = 75;
// Communication DS <-> SLAM
public static final int SLAM_REGISTER_DS = 90;
// Communication Phone <-> Registration Manager
public static final int AC_HELLO_AC_RM = 1;
// Messages to send to the demo server, which will create the animation
// of the events happening on the system
public enum AnimationMsg {
PING,
// Scenario 1: DS, SLAM, VMM starting up
INITIAL_IMG_0,
DS_UP,
SLAM_UP,
SLAM_REGISTER_DS,
VMM_UP,
VMM_REGISTER_DS,
VMM_REGISTER_SLAM,
// Scenario 2:
AC_INITIAL_IMG,
AC_NEW_REGISTER_DS,
DS_NEW_FIND_MACHINES,
DS_NEW_IP_LIST_AC,
AC_NEW_REGISTER_SLAM,
SLAM_NEW_VM_VMM,
VMM_NEW_START_VM,
VMM_NEW_REGISTER_AS,
VMM_NEW_VM_REGISTER_DS,
VMM_NEW_VM_IP_SLAM,
SLAM_NEW_VM_IP_AC,
AC_NEW_REGISTER_VM,
AC_NEW_CONN_VM,
AC_NEW_APK_VM,
AC_NEW_RTT_VM,
AC_NEW_DL_RATE_VM,
AC_NEW_UL_RATE_VM,
AC_NEW_REGISTRATION_OK_VM,
// Scenario 3:
AC_PREV_REGISTRATION_OK_VM,
AC_PREV_UL_RATE_VM,
AC_PREV_DL_RATE_VM,
AC_PREV_RTT_VM,
AC_PREV_APK_VM,
AC_PREV_CONN_VM,
AC_PREV_REGISTER_VM,
AC_REGISTER_VM_ERROR,
SLAM_PREV_VM_IP_AC,
VMM_PREV_VM_IP_SLAM,
VMM_PREV_FIND_VM,
SLAM_PREV_VM_REQ_VMM,
AC_PREV_REGISTER_SLAM,
DS_PREV_IP_AC,
DS_PREV_FIND_MACHINE,
AC_PREV_VM_DS,
// AC_INITIAL_IMG
// Scenario 4: offload execution
AC_OFFLOADING_FINISHED,
AS_RESULT_AC,
AS_RUN_METHOD,
AC_DECISION_OFFLOAD_AS,
AC_PREPARE_DATA,
// AC_INITIAL_IMG,
// Scenario 5: local execution
AC_LOCAL_FINISHED,
AC_DECISION_LOCAL,
//AC_PREPARE_DATA,
//AC_INITIAL_IMG,
// Scenario 6: D2D 1
AC_OFFLOADING_FINISHED_D2D,
AS_RESULT_AC_D2D,
AS_RUN_METHOD_D2D,
AC_OFFLOAD_D2D,
AC_PREPARE_DATA_D2D,
//Scenario 7: D2D 2
AC_RECEIVED_D2D,
AC_NO_MORE_D2D,
AS_BROADCASTING_D2D,
AC_LISTENING_D2D,
D2D_INITIAL_IMG,
}
}
|
package com.afollestad.silk.caching;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Environment;
import android.os.Handler;
import java.io.*;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
class SilkCacheBase<Item extends SilkComparable<Item>> extends SilkCacheBaseLimiter<Item> {
public SilkCacheBase(Context context, String name) {
this(context, name, null);
}
public SilkCacheBase(Context context, String name, Handler handler) {
super(context, name);
if (handler == null) mHandler = new Handler();
else mHandler = handler;
}
private final static File CACHE_DIR = new File(Environment.getExternalStorageDirectory(), ".silk_cache");
private final Handler mHandler;
private List<Item> mBuffer;
private boolean isChanged;
public final boolean isChanged() {
return isChanged;
}
protected List<Item> getBuffer() {
return mBuffer;
}
protected Handler getHandler() {
return mHandler;
}
protected File getCacheFile() {
return new File(CACHE_DIR, getName() + ".cache");
}
protected void markChanged() {
isChanged = true;
}
protected void loadItems() {
try {
File cacheFile = getCacheFile();
if (hasExpiration()) {
long expiration = getExpiration();
long now = Calendar.getInstance().getTimeInMillis();
if (now >= expiration) {
// Cache is expired
cacheFile.delete();
log("Cache has expired, re-creating...");
setExpiration(-1);
}
}
mBuffer = new ArrayList<Item>();
if (cacheFile.exists()) {
FileInputStream fileInputStream = new FileInputStream(cacheFile);
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
while (true) {
try {
final Item item = (Item) objectInputStream.readObject();
if (item != null) mBuffer.add(item);
} catch (EOFException eof) {
break;
}
}
objectInputStream.close();
} else log("Cache file doesn't exist.");
log("Read " + mBuffer.size() + " items from the cache file");
} catch (Exception e) {
e.printStackTrace();
log("Error loading items -- " + e.getMessage());
}
}
public final long getExpiration() {
SharedPreferences prefs = getContext().getSharedPreferences("[silk-cache-expiration]", Context.MODE_PRIVATE);
return prefs.getLong(getName(), -1);
}
public final boolean hasExpiration() {
return getExpiration() > -1;
}
public final void setExpiration(long dateTime) {
SharedPreferences.Editor prefs = getContext().getSharedPreferences("[silk-cache-expiration]", Context.MODE_PRIVATE).edit();
if (dateTime < 0)
prefs.remove(getName());
else prefs.putLong(getName(), dateTime);
prefs.commit();
}
public final void setExpiration(int weeks, int days, int hours, int minutes) {
long now = Calendar.getInstance().getTimeInMillis();
now += (1000 * 60) * minutes; // 60 seconds in a minute
now += (1000 * 60 * 60) * hours; // 60 minutes in an hour
now += (1000 * 60 * 60 * 24) * days; // 24 hours in a day
now += (1000 * 60 * 60 * 24 * 7) * weeks; // 7 days in a week
setExpiration(now);
}
public final void setLimiter(SilkCacheLimiter limiter) {
if (limiter == null) {
getLimiterPrefs().edit().remove(getName()).commit();
} else {
getLimiterPrefs().edit().putString(getName(), limiter.toString()).commit();
// Perform limiting if necessary
if (atLimit(mBuffer)) {
mBuffer = performLimit(mBuffer);
}
}
}
public final void commit() throws Exception {
final File cacheFile = getCacheFile();
if (!isChanged) {
throw new IllegalStateException("The cache has not been modified since initialization or the last commit.");
} else if (mBuffer.size() == 0) {
if (cacheFile.exists()) {
log("Deleting: " + cacheFile.getName());
cacheFile.delete();
}
return;
}
// Perform limiting if necessary
if (atLimit(mBuffer)) {
mBuffer = performLimit(mBuffer);
}
CACHE_DIR.mkdirs();
FileOutputStream fileOutputStream = new FileOutputStream(cacheFile);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
for (Item item : mBuffer)
objectOutputStream.writeObject(item);
objectOutputStream.close();
log("Committed " + mBuffer.size() + " items.");
isChanged = false;
}
public final void commit(final SilkCache.SimpleCommitCallback callback) {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
commit();
mHandler.post(new Runnable() {
@Override
public void run() {
if (callback != null && callback instanceof SilkCache.CommitCallback)
((SilkCache.CommitCallback) callback).onCommitted();
}
});
} catch (final Exception e) {
log("Commit error: " + e.getMessage());
mHandler.post(new Runnable() {
@Override
public void run() {
if (callback != null) callback.onError(e);
}
});
}
}
});
t.setPriority(Thread.MAX_PRIORITY);
t.start();
}
}
|
package com.ironz.binaryprefs.util;
import java.util.HashSet;
import java.util.Set;
/**
* Converts bytes to primitives and backwards. For type detecting uses prefix flag which stores at start of byte arrays.
*/
public final class Bits {
/**
* Uses for detecting byte array type of {@link Set} of {@link String}
*/
static final byte FLAG_STRING_SET = -1;
/**
* Uses for detecting byte array type of {@link String}
*/
static final byte FLAG_STRING = -2;
/**
* Uses for detecting byte array primitive type of {@link Integer}
*/
static final byte FLAG_INT = -3;
/**
* Uses for detecting byte array primitive type of {@link Long}
*/
static final byte FLAG_LONG = -4;
/**
* Uses for detecting byte array primitive type of {@link Double}
*/
static final byte FLAG_DOUBLE = -5;
/**
* Uses for detecting byte array primitive type of {@link Float}
*/
static final byte FLAG_FLOAT = -6;
/**
* Uses for detecting byte array primitive type of {@link Boolean}
*/
static final byte FLAG_BOOLEAN = -7;
/**
* Uses for detecting byte primitive type of {@link Byte}
*/
static final byte FLAG_BYTE = -8;
/**
* Uses for detecting byte array primitive type of {@link Byte}
*/
static final byte FLAG_BYTE_ARRAY = -9;
/**
* Uses for detecting byte array primitive type of {@link Short}
*/
static final byte FLAG_SHORT = -10;
/**
* Uses for detecting byte array primitive type of {@link Character}
*/
static final byte FLAG_CHAR = -11;
private static final int INITIAL_INTEGER_LENGTH = 5;
private static final int NULL_STRING_SIZE = -1;
private Bits() {
}
/**
* Serialize {@code Set<String>} into byte array with following scheme:
* [{@link #FLAG_STRING_SET}] + (([string_size] + [string_byte_array]) * n).
*
* @param value target Set to serialize.
* @return specific byte array with scheme.
*/
public static byte[] stringSetToBytesWithFlag(Set<String> value) {
byte[][] bytes = new byte[value.size()][];
int i = 0;
int totalArraySize = 1;
for (String s : value) {
byte[] stringBytes = s == null ? new byte[0] : s.getBytes();
byte[] stringSizeBytes = s == null ? intToBytesWithFlag(NULL_STRING_SIZE) : intToBytesWithFlag(stringBytes.length);
byte[] merged = new byte[stringBytes.length + stringSizeBytes.length];
System.arraycopy(stringSizeBytes, 0, merged, 0, stringSizeBytes.length);
System.arraycopy(stringBytes, 0, merged, stringSizeBytes.length, stringBytes.length);
bytes[i] = merged;
totalArraySize += merged.length;
i++;
}
byte[] totalArray = new byte[totalArraySize];
totalArray[0] = FLAG_STRING_SET;
int offset = 1;
for (byte[] b : bytes) {
System.arraycopy(b, 0, totalArray, offset, b.length);
offset = offset + b.length;
}
return totalArray;
}
/**
* Deserialize byte by {@link #stringSetToBytesWithFlag(Set)} convention
*
* @param bytes target byte array for deserialization
* @return deserialized String Set
*/
public static Set<String> stringSetFromBytesWithFlag(byte[] bytes) {
byte flag = bytes[0];
if (flag == FLAG_STRING_SET) {
if (bytes.length == 1) {
return new HashSet<>(0);
}
Set<String> set = new HashSet<>();
int i = 1;
while (i < bytes.length) {
byte[] stringSizeBytes = {bytes[i], bytes[i + 1], bytes[i + 2], bytes[i + 3], bytes[i + 4]};
int stringSize = intFromBytesWithFlag(stringSizeBytes);
if (stringSize == NULL_STRING_SIZE) {
set.add(null);
i += INITIAL_INTEGER_LENGTH;
continue;
}
byte[] stringBytes = new byte[stringSize];
for (int k = 0; k < stringBytes.length; k++) {
int offset = i + k + INITIAL_INTEGER_LENGTH;
stringBytes[k] = bytes[offset];
}
set.add(new String(stringBytes));
i += INITIAL_INTEGER_LENGTH + stringSize;
}
return set;
}
throw new ClassCastException(String.format("Set<String> cannot be deserialized in '%s' flag type", flag));
}
/**
* Serialize {@code String} into byte array with following scheme:
* [{@link #FLAG_STRING}] + [string_byte_array].
*
* @param value target String to serialize.
* @return specific byte array with scheme.
*/
public static byte[] stringToBytesWithFlag(String value) {
byte[] stringBytes = value.getBytes();
int flagSize = 1;
byte[] b = new byte[stringBytes.length + flagSize];
b[0] = FLAG_STRING;
System.arraycopy(stringBytes, 0, b, flagSize, stringBytes.length);
return b;
}
/**
* Deserialize byte by {@link #stringToBytesWithFlag(String)} convention
*
* @param bytes target byte array for deserialization
* @return deserialized String
*/
public static String stringFromBytesWithFlag(byte[] bytes) {
byte flag = bytes[0];
if (flag != FLAG_STRING) {
throw new ClassCastException(String.format("String cannot be deserialized in '%s' flag type", flag));
}
int lengthWithoutFlag = bytes.length - 1;
return new String(bytes, 1, lengthWithoutFlag);
}
/**
* Serialize {@code int} into byte array with following scheme:
* [{@link #FLAG_INT}] + [int_bytes].
*
* @param value target int to serialize.
* @return specific byte array with scheme.
*/
public static byte[] intToBytesWithFlag(int value) {
return new byte[]{
FLAG_INT,
(byte) (value >>> 24),
(byte) (value >>> 16),
(byte) (value >>> 8),
(byte) value
};
}
/**
* Deserialize byte by {@link #intToBytesWithFlag(int)} convention
*
* @param bytes target byte array for deserialization
* @return deserialized int
*/
public static int intFromBytesWithFlag(byte[] bytes) {
int i = 0xFF;
byte flag = bytes[0];
if (flag != FLAG_INT) {
throw new ClassCastException(String.format("int cannot be deserialized in '%s' flag type", flag));
}
return ((bytes[4] & i)) +
((bytes[3] & i) << 8) +
((bytes[2] & i) << 16) +
((bytes[1]) << 24);
}
/**
* Serialize {@code long} into byte array with following scheme:
* [{@link #FLAG_LONG}] + [long_bytes].
*
* @param value target long to serialize.
* @return specific byte array with scheme.
*/
public static byte[] longToBytesWithFlag(long value) {
return new byte[]{
FLAG_LONG,
(byte) (value >>> 56),
(byte) (value >>> 48),
(byte) (value >>> 40),
(byte) (value >>> 32),
(byte) (value >>> 24),
(byte) (value >>> 16),
(byte) (value >>> 8),
(byte) (value)
};
}
/**
* Deserialize byte by {@link #longToBytesWithFlag(long)} convention
*
* @param bytes target byte array for deserialization
* @return deserialized long
*/
public static long longFromBytesWithFlag(byte[] bytes) {
long l = 0xFFL;
byte flag = bytes[0];
if (flag != FLAG_LONG) {
throw new ClassCastException(String.format("long cannot be deserialized in '%s' flag type", flag));
}
return ((bytes[8] & l)) +
((bytes[7] & l) << 8) +
((bytes[6] & l) << 16) +
((bytes[5] & l) << 24) +
((bytes[4] & l) << 32) +
((bytes[3] & l) << 40) +
((bytes[2] & l) << 48) +
(((long) bytes[1]) << 56);
}
/**
* Serialize {@code double} into byte array with following scheme:
* [{@link #FLAG_DOUBLE}] + [double_bytes].
*
* @param value target double to serialize.
* @return specific byte array with scheme.
*/
public static byte[] doubleToBytesWithFlag(double value) {
long l = Double.doubleToLongBits(value);
return new byte[]{
FLAG_DOUBLE,
(byte) (l >>> 56),
(byte) (l >>> 48),
(byte) (l >>> 40),
(byte) (l >>> 32),
(byte) (l >>> 24),
(byte) (l >>> 16),
(byte) (l >>> 8),
(byte) (value)
};
}
/**
* Deserialize byte by {@link #doubleToBytesWithFlag(double)} convention
*
* @param bytes target byte array for deserialization
* @return deserialized double
*/
public static double doubleFromBytesWithFlag(byte[] bytes) {
long l = 0xFFL;
byte flag = bytes[0];
if (flag != FLAG_DOUBLE) {
throw new ClassCastException(String.format("double cannot be deserialized in '%s' flag type", flag));
}
long value = ((bytes[8] & l)) +
((bytes[7] & l) << 8) +
((bytes[6] & l) << 16) +
((bytes[5] & l) << 24) +
((bytes[4] & l) << 32) +
((bytes[3] & l) << 40) +
((bytes[2] & l) << 48) +
(((long) bytes[1]) << 56);
return Double.longBitsToDouble(value);
}
/**
* Serialize {@code float} into byte array with following scheme:
* [{@link #FLAG_FLOAT}] + [float_bytes].
*
* @param value target float to serialize.
* @return specific byte array with scheme.
*/
public static byte[] floatToBytesWithFlag(float value) {
int i = Float.floatToIntBits(value);
return new byte[]{
FLAG_FLOAT,
(byte) (i >>> 24),
(byte) (i >>> 16),
(byte) (i >>> 8),
(byte) value
};
}
/**
* Deserialize byte by {@link #floatToBytesWithFlag(float)} convention
*
* @param bytes target byte array for deserialization
* @return deserialized float
*/
public static float floatFromBytesWithFlag(byte[] bytes) {
int i = 0xFF;
byte flag = bytes[0];
if (flag != FLAG_FLOAT) {
throw new ClassCastException(String.format("float cannot be deserialized in '%s' flag type", flag));
}
int value = ((bytes[4] & i)) +
((bytes[3] & i) << 8) +
((bytes[2] & i) << 16) +
(bytes[1] << 24);
return Float.intBitsToFloat(value);
}
/**
* Serialize {@code boolean} into byte array with following scheme:
* [{@link #FLAG_BOOLEAN}] + [boolean_bytes].
*
* @param value target boolean to serialize.
* @return specific byte array with scheme.
*/
public static byte[] booleanToBytesWithFlag(boolean value) {
return new byte[]{
FLAG_BOOLEAN,
(byte) (value ? 1 : 0)
};
}
/**
* Deserialize byte by {@link #booleanToBytesWithFlag(boolean)} convention
*
* @param bytes target byte array for deserialization
* @return deserialized boolean
*/
public static boolean booleanFromBytesWithFlag(byte[] bytes) {
byte flag = bytes[0];
if (flag != FLAG_BOOLEAN) {
throw new ClassCastException(String.format("boolean cannot be deserialized in '%s' flag type", flag));
}
return bytes[1] != 0;
}
/**
* Serialize {@code byte} into byte array with following scheme:
* [{@link #FLAG_BYTE}] + [byte].
*
* @param value target byte to serialize.
* @return specific byte array with scheme.
*/
public static byte[] byteToBytesWithFlag(byte value) {
return new byte[]{
FLAG_BYTE,
value
};
}
/**
* Serialize {@code byte array} into byte array with following scheme:
* [{@link #FLAG_BYTE}] + [byte_array].
*
* @param value target byte array to serialize.
* @return specific byte array with scheme.
*/
public static byte[] byteArrayToBytesWithFlag(byte[] value) {
int flagOffset = 1;
byte[] copy = new byte[value.length + flagOffset];
copy[0] = FLAG_BYTE_ARRAY;
System.arraycopy(value, 0, copy, flagOffset, value.length);
return copy;
}
/**
* Deserialize byte array by {@link #byteToBytesWithFlag(byte)} convention
*
* @param bytes target byte array for deserialization
* @return deserialized byte array
*/
public static byte[] byteArrayFromBytesWithFlag(byte[] bytes) {
byte flag = bytes[0];
if (flag != FLAG_BYTE_ARRAY) {
throw new ClassCastException(String.format("byte array cannot be deserialized in '%s' flag type", flag));
}
int flagOffset = 1;
byte[] copy = new byte[bytes.length - flagOffset];
System.arraycopy(bytes, flagOffset, copy, 0, copy.length);
return copy;
}
/**
* Deserialize byte by {@link #byteToBytesWithFlag(byte)} convention
*
* @param bytes target byte array for deserialization
* @return deserialized byte
*/
public static byte byteFromBytesWithFlag(byte[] bytes) {
byte flag = bytes[0];
if (flag != FLAG_BYTE) {
throw new ClassCastException(String.format("byte cannot be deserialized in '%s' flag type", flag));
}
return bytes[1];
}
/**
* Serialize {@code short} into byte array with following scheme:
* [{@link #FLAG_SHORT}] + [short_bytes].
*
* @param value target short to serialize.
* @return specific byte array with scheme.
*/
public static byte[] shortToBytesWithFlag(short value) {
return new byte[]{
FLAG_SHORT,
(byte) (value >>> 8),
((byte) value)
};
}
/**
* Deserialize short by {@link #shortToBytesWithFlag(short)} convention
*
* @param bytes target byte array for deserialization
* @return deserialized short
*/
public static short shortFromBytesWithFlag(byte[] bytes) {
byte flag = bytes[0];
if (flag != FLAG_SHORT) {
throw new ClassCastException(String.format("short cannot be deserialized in '%s' flag type", flag));
}
return (short) ((bytes[1] << 8) +
(bytes[2] & 0xFF));
}
/**
* Serialize {@code char} into byte array with following scheme:
* [{@link #FLAG_CHAR}] + [char_bytes].
*
* @param value target char to serialize.
* @return specific byte array with scheme.
*/
public static byte[] charToBytesWithFlag(char value) {
return new byte[]{
FLAG_CHAR,
(byte) (value >>> 8),
((byte) value)
};
}
/**
* Deserialize char by {@link #charToBytesWithFlag(char)} convention
*
* @param bytes target byte array for deserialization
* @return deserialized char
*/
public static char charFromBytesWithFlag(byte[] bytes) {
byte flag = bytes[0];
if (flag != FLAG_CHAR) {
throw new ClassCastException(String.format("char cannot be deserialized in '%s' flag type", flag));
}
return (char) ((bytes[1] << 8) +
(bytes[2] & 0xFF));
}
/**
* Tries to deserialize byte array by all flags and returns object if deserialized or throws exception if target flag is unexpected.
*
* @param bytes target byte array for deserialization
* @return deserialized object
*/
public static Object tryDeserializeByFlag(byte[] bytes) {
byte flag = bytes[0];
if (flag == FLAG_STRING_SET) {
return stringSetFromBytesWithFlag(bytes);
}
if (flag == FLAG_STRING) {
return stringFromBytesWithFlag(bytes);
}
if (flag == FLAG_INT) {
return intFromBytesWithFlag(bytes);
}
if (flag == FLAG_LONG) {
return longFromBytesWithFlag(bytes);
}
if (flag == FLAG_FLOAT) {
return floatFromBytesWithFlag(bytes);
}
if (flag == FLAG_BOOLEAN) {
return booleanFromBytesWithFlag(bytes);
}
throw new UnsupportedClassVersionError(String.format("Flag verification failed. Incorrect type '%s'", flag));
}
}
|
package tools.debugger.message;
import som.interpreter.actors.Actor;
import som.primitives.processes.ChannelPrimitives.ProcessThread;
import som.primitives.threading.ThreadPrimitives.SomThread;
import som.vm.NotYetImplementedException;
import tools.debugger.frontend.Suspension;
import tools.debugger.message.Message.OutgoingMessage;
@SuppressWarnings("unused")
public final class StoppedMessage extends OutgoingMessage {
private String reason;
private int activityId;
private String activityType;
private String text;
private boolean allThreadsStopped;
private StoppedMessage(final Reason reason, final int activityId,
final ActivityType type, final String text) {
this.reason = reason.value;
this.activityId = activityId;
this.activityType = type.value;
this.text = text;
this.allThreadsStopped = false;
}
private enum Reason {
step("step"),
breakpoint("breakpoint"),
exception("exception"),
pause("pause");
private final String value;
Reason(final String value) {
this.value = value;
}
}
private enum ActivityType {
Actor("Actor"),
Thread("Thread"),
Process("Process");
private final String value;
ActivityType(final String value) {
this.value = value;
}
}
public static StoppedMessage create(final Suspension suspension) {
Reason reason;
if (suspension.getEvent().getBreakpoints().isEmpty()) {
reason = Reason.step;
} else {
reason = Reason.breakpoint;
}
ActivityType type;
if (suspension.getActivity() instanceof Actor) {
type = ActivityType.Actor;
} else if (suspension.getActivity() instanceof SomThread) {
type = ActivityType.Thread;
} else if (suspension.getActivity() instanceof ProcessThread) {
type = ActivityType.Process;
} else {
// need to support this type of activity first
throw new NotYetImplementedException();
}
return new StoppedMessage(reason, suspension.activityId, type, ""); // TODO: look into additional details that can be provided as text
}
}
|
package hotchemi.android.rate;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import java.util.List;
final class UriHelper {
private static final String GOOGLE_PLAY = "https://play.google.com/store/apps/details?id=";
private UriHelper() {
}
static Uri getGooglePlay(String packageName) {
return packageName == null ? null : Uri.parse(GOOGLE_PLAY + packageName);
}
static boolean isPackageExists(Context context, String targetPackage) {
PackageManager pm = context.getPackageManager();
List<ApplicationInfo> packages = pm.getInstalledApplications(0);
for (ApplicationInfo packageInfo : packages) {
if (packageInfo.packageName.equals(targetPackage)) return true;
}
return false;
}
}
|
package minesweeper;
import java.util.Random;
/**
*
* @author veeti "walther" haapsamo
*/
class Board {
private final Square[][] board;
private final int mines;
Random rn = new Random();
private final int width;
private final int height;
public Board(int width, int height, int mines) {
this.width = width;
this.height = height;
this.mines = mines;
this.board = new Square[this.width][this.height];
clear();
addMines();
addNumbers();
addNumbers();
}
private void addNumbers() {
// Calculate number values for squares
for (int y = 0; y < this.height; y++) {
for (int x = 0; x < this.width; x++) {
countNearbyMines(y, x);
}
}
}
private void clear() {
for (int i = 0; i < this.height; i++) {
for (int j = 0; j < this.width; j++) {
this.board[i][j] = new Square();
System.out.println("DEBUG: added square at " + i + "," + j);
}
}
}
private void countNearbyMines(int i, int j) {
int nearbyMines = 0;
if (!this.board[i][j].isMine()) { // Count nearby mines only if not mine itself
for (int k = i - 1; k <= i + 1; k++) { // three wide
for (int l = j - 1; l <= j + 1; l++) { // three high
System.out.println("DEBUG: trying to see if " + l + "," + k + "has a mine");
try {
if (this.board[k][l].isMine()) {
System.out.println("DEBUG: Had a mine");
nearbyMines++;
}
} catch (ArrayIndexOutOfBoundsException exception) {
}
}
}
this.board[i][j].setValue(nearbyMines);
}
}
private void addMines() {
// Add mines
int addedMines = 0;
while (addedMines < this.mines) {
int randomX = rn.nextInt(this.width);
int randomY = rn.nextInt(this.height);
if (!this.board[randomX][randomY].isMine()) {
this.board[randomX][randomY].setMine();
System.out.println("DEBUG: added mine at " + randomX + "," + randomY);
addedMines++;
}
}
}
@Override
public String toString() {
String ret = "";
for (int i = 0; i < this.height; i++) {
for (int j = 0; j < this.width; j++) {
Square sq = this.board[i][j];
if (sq.isVisible()) {
ret += sq.toString();
} else {
ret += "?";
}
}
ret += "\n";
}
return ret;
}
// Step onto a square. Following things happen:
// - The square you stepped on is revealed
// - if it is a mine, return 1 - you lost
// - if you hit an empty square, areaFill other nearby empty squares + one row of numbers
// - if you opened the last non-mine square, return 2 - you won
int step(int stepY, int stepX) { // return 0 = normal click, 1 = stepped on mine, 2 = won the game
this.board[stepY][stepX].setVisible();
if (this.board[stepY][stepX].isMine()) {
return 1;
} else {
if (this.board[stepY][stepX].isEmpty()) { // If hit an empty square, fill outwards
for (int k = stepY - 1; k <= stepY + 1; k++) { // three wide
for (int l = stepX - 1; l <= stepX + 1; l++) { // three high
System.out.println("DEBUG: trying to see if " + l + "," + k + "is steppable");
try {
if (this.board[k][l].isEmpty() && !this.board[k][l].isVisible()) {
System.out.println("DEBUG: Was steppable, stepping");
this.step(k, l);
} else if (!this.board[k][l].isMine()) {
System.out.println("DEBUG: Hit a number instead, only revealing");
this.board[k][l].setVisible();
}
} catch (ArrayIndexOutOfBoundsException exception) {
}
}
}
}
if (invisibleCount() == this.mines) {
return 2;
}
return 0;
}
}
int invisibleCount() {
int count = 0;
for (int i = 0; i < this.width; i++) {
for (int j = 0; j < this.height; j++) {
if (!this.board[i][j].isVisible()) {
count++;
}
}
}
return count;
}
Square getSquare(int y, int x) {
return board[y][x];
}
}
|
package edu.umich.eac;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.CancellationException;
import java.util.Collections;
import java.util.Set;
import java.util.TreeSet;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
import android.util.Log;
import edu.umich.eac.FetchFuture;
import edu.umich.eac.CacheFetcher;
public class EnergyAdaptiveCache {
private static String TAG = EnergyAdaptiveCache.class.getName();
private ExecutorService executor;
// contains prefetches yet to be sent.
private BlockingQueue<FetchFuture<?> > prefetchQueue;
// contains prefetches that have been sent, potentially having results.
// XXX: might be unnecessary. Only the application needs references
// to these objects
private Set<FetchFuture<?> > prefetchCache;
/** Hints a future access and gets a Future for that access.
*
* TODO: figure out how app could pass ordering constraints,
* relative priority of prefetches
*
* @param fetcher Application-specific logic to fetch a data item
* and return an object representing it.
* @return A Future that can be used later to actually carry out
* the hinted access, via get().
*/
public <V> Future<V> prefetch(CacheFetcher<V> fetcher) {
try {
FetchFuture<V> fetchFuture = new FetchFuture<V>(fetcher, this);
prefetchQueue.put(fetchFuture);
return fetchFuture;
} catch (InterruptedException e) {
// the queue has no max size, so this won't happen.
assert false;
return null;
}
}
/** Hint a future access and start prefetching it immediately,
* bypassing any deferral decision.
*
* This is useful for testing.
*/
public <V> Future<V> prefetchNow(CacheFetcher<V> fetcher) {
return fetchNow(fetcher, false);
}
/** "Hint" an immediate access and start fetching it immediately.
*
* This is useful for demand fetches that weren't hinted in advance.
*/
public <V> Future<V> fetch(CacheFetcher<V> fetcher) {
return fetchNow(fetcher, true);
}
private <V> Future<V> fetchNow(CacheFetcher<V> fetcher, boolean demand) {
FetchFuture<V> fetchFuture = new FetchFuture<V>(fetcher, this);
prefetchCache.add(fetchFuture);
try {
fetchFuture.startAsync(demand);
} catch (CancellationException e) {
Log.e(TAG, "No-defer prefetch cancelled before it was sent");
fetchFuture = null;
}
return fetchFuture;
}
<V> Future<V> submit(Callable<V> fetcher) {
// TODO: record whatever necessary information
// TODO: make a method to do that, and call it from FetchFuture
return executor.submit(fetcher);
}
void remove(FetchFuture<?> fetchFuture) {
evaluatePrefetchDecision(fetchFuture);
prefetchCache.remove(fetchFuture);
}
private <V> void evaluatePrefetchDecision(FetchFuture<V> fetchFuture) {
// TODO: estimate whether I "made a mistake" with this fetch
// e.g. too early, too late
}
// Bound on the number of in-flight prefetches, similar to before.
// XXX: does this need to be configurable?
public static final int NUM_THREADS = 10;
public EnergyAdaptiveCache(PrefetchStrategyType strategyType) {
Log.d(TAG, "Created a new EnergyAdaptiveCache");
executor = Executors.newFixedThreadPool(NUM_THREADS);
prefetchQueue = new LinkedBlockingQueue<FetchFuture<?> >();
prefetchCache = Collections.synchronizedSet(
new TreeSet<FetchFuture<?> >()
);
strategy = PrefetchStrategy.create(strategyType);
prefetchThread = new PrefetchThread();
prefetchThread.start();
}
private PrefetchThread prefetchThread;
private PrefetchStrategy strategy;
private class PrefetchThread extends Thread {
public void run() {
/* TODO
* forever:
* Check whether I should invoke a prefetch
* If so, submit its callable to the ExecutorService
* Decide how long to wait before checking again,
* perhaps registering an intnw notification callback
* to be woken up at that point
*/
while (true) {
try {
FetchFuture<?> prefetch = prefetchQueue.take();
prefetchCache.add(prefetch);
strategy.handlePrefetch(prefetch);
// TODO: implement the real strategy
// I imagine this will take the form of a
// callback with a timeout.
// The callback may be triggered by an IntNW
// "enhanced thunk."
} catch (InterruptedException e) {
// if thrown by take(); ignore and try again.
} catch (CancellationException e) {
Log.e(TAG, "Prefetch cancelled before it was sent");
}
}
}
}
}
|
package mods.railcraft.api.tracks;
import mcp.MethodsReturnNonnullByDefault;
import mods.railcraft.api.core.INetworkedObject;
import net.minecraft.block.Block;
import net.minecraft.block.BlockRailBase;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.item.EntityMinecart;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import javax.annotation.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.util.ArrayList;
import java.util.List;
/**
* This interface defines a track.
*
* Basically all block and tile entity functions for Tracks are delegated to an
* ITrackInstance.
*
* Instead of implementing this interface directly, you should probably extend
* TrackInstanceBase. It will simplify your life.
*
* You must have a constructor that accepts a single TileEntity object.
*
* All packet manipulation is handled by Railcraft's code, you just need to
* implement the functions in INetworkedObject to pass data from the server to
* the client.
*
* @author CovertJaguar
* @see TrackKitInstance
*/
@MethodsReturnNonnullByDefault
@ParametersAreNonnullByDefault
public interface ITrackKitInstance extends INetworkedObject<DataInputStream, DataOutputStream> {
TileEntity getTile();
void setTile(TileEntity tileEntity);
TrackKit getTrackKit();
/**
* Return the render state. Ranges from 0 to 15.
* Used by the TrackKit blockstate JSON to determine which model/texture to display.
*/
default int getRenderState() {
return 0;
}
default List<ItemStack> getDrops(int fortune) {
List<ItemStack> drops = new ArrayList<ItemStack>();
drops.add(getTrackKit().getTrackKitItem());
return drops;
}
/**
* Return the rail's shape.
* Can be used to make the cart think the rail something other than it is,
* for example when making diamond junctions or switches.
*
* @param cart The cart asking for the metadata, null if it is not called by
* EntityMinecart.
* @return The metadata.
*/
BlockRailBase.EnumRailDirection getRailDirection(IBlockState state, @Nullable EntityMinecart cart);
/**
* This function is called by any minecart that passes over this rail. It is
* called once per update tick that the minecart is on the rail.
*
* @param cart The cart on the rail.
*/
default void onMinecartPass(EntityMinecart cart) {
}
default void writeToNBT(NBTTagCompound data) {
}
default void readFromNBT(NBTTagCompound data) {
}
default void update() {
}
boolean blockActivated(EntityPlayer player, EnumHand hand, @Nullable ItemStack heldItem);
default void onBlockRemoved() {
}
void onBlockPlacedBy(IBlockState state, @Nullable EntityLivingBase placer, ItemStack stack);
void onNeighborBlockChange(IBlockState state, @Nullable Block neighborBlock);
default BlockPos getPos() {
return getTile().getPos();
}
@Nullable
@Override
default World theWorld() {
return getTile().getWorld();
}
/**
* Returns the max speed of the rail.
*
* @param cart The cart on the rail, may be null.
* @return The max speed of the current rail.
*/
default float getRailMaxSpeed(World world, @Nullable EntityMinecart cart, BlockPos pos) {
return getTrackType().getEventHandler().getMaxSpeed(world, cart, pos);
}
/**
* Returning true here will make the track unbreakable.
*/
default boolean isProtected() {
return false;
}
/**
* Returns the track type of this track.
*/
default TrackType getTrackType() {
return ((IOutfittedTrackTile) getTile()).getTrackType();
}
/**
* Requests for saving the data of the track kit.
*/
default void markDirty() {
getTile().markDirty();
}
}
|
package jcdc.pluginfactory.betterexamples;
import org.bukkit.Effect;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.event.Listener;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.java.JavaPlugin;
import scala.Option;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Logger;
public class BetterJavaPlugin extends JavaPlugin {
public final Logger logger = Logger.getLogger("Minecraft");
public List<Listener> listeners = new ArrayList<Listener>();
public List<Cmd> commands = new ArrayList<Cmd>();
public void onDisable() {
info(getDescription().getName() + " is now disabled.");
}
public void onEnable() {
for (Listener l : listeners) { register(l); }
info(getDescription().getName() + " version " + getVersion() + " is now enabled.");
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
for(Cmd c: commands){
if(c.name.toLowerCase().equals(commandLabel.toLowerCase())){
c.body.run((Player)sender, args);
}
}
return true;
}
public void info(String message) {
logger.info(message);
}
public String getVersion() {
return getDescription().getVersion();
}
public void register(Listener listener) {
getServer().getPluginManager().registerEvents(listener, this);
}
public void erase(Block b){
b.getWorld().playEffect(b.getLocation(), Effect.SMOKE, 1);
b.setType(Material.AIR);
b.getWorld().dropItem(b.getLocation(), new ItemStack(b.getType(), 1, b.getData()));
}
public Block blockAbove(Block b){
return new Location(b.getWorld(), b.getX(), b.getY() + 1, b.getZ()).getBlock();
}
abstract class F0<A>{ abstract A run(); }
abstract class F1<A, B>{ abstract B run(A a); }
public class Cmd {
final String name;
final String description;
final CommandBody body;
public <T> Cmd(String name, String description, CommandBody<T> body){
this.name = name;
this.description = description;
this.body = body;
}
}
abstract public class CommandBody<T>{
private ArgParser<T> argParser;
public CommandBody(ArgParser<T> argParser){
this.argParser = argParser;
}
abstract public void run(Player p, T t);
}
abstract class ParseResult<T>{
abstract boolean isFailure();
abstract boolean isSuccess();
abstract T get();
abstract String error();
}
class Success<T> extends ParseResult<T> {
private final T t;
private final LinkedList<String> rest;
public Success(T t, LinkedList<String> rest){
this.t = t;
this.rest = rest;
}
boolean isFailure() { return false; }
boolean isSuccess() { return true; }
T get(){ return t; }
String error(){ throw new RuntimeException("cant get error message Success"); }
}
class Failure<T> extends ParseResult<T> {
private String message;
public Failure(String message){
this.message = message;
}
boolean isFailure() { return true; }
boolean isSuccess() { return false; }
T get(){ throw new RuntimeException("cant get from Failure"); }
String error(){ return message; }
}
abstract class ArgParser<T> {
abstract ParseResult<T> parse(LinkedList<String> args);
ArgParser<T> or(final ArgParser<T> p2){
final ArgParser<T> self = this;
return new ArgParser<T>() {
ParseResult<T> parse(LinkedList<String> args) {
ParseResult<T> pr1 = self.parse(args);
if(pr1.isSuccess()) return pr1;
else {
ParseResult<T> pr2 = p2.parse(args);
if(pr2.isSuccess()) return pr2;
else return new Failure<T>(pr1.error() + " or " + pr2.error());
}
}
};
}
<U> ArgParser<U> map(final F1<T, U> f1){
final ArgParser<T> self = this;
return new ArgParser<U>() {
ParseResult<U> parse(LinkedList<String> args) {
ParseResult<T> pr = self.parse(args);
if(pr.isSuccess()) {
LinkedList<String> ss = new LinkedList<String>(args);
ss.removeFirst();
return new Success<U>(f1.run(pr.get()), ss);
}
else return (Failure<U>)pr;
}
};
}
<U> ArgParser<U> outputting(final U u){
return map(new F1<T, U>() {
U run(T t) { return u; }
});
}
}
ArgParser<String> match(final String s){
return new ArgParser<String>(){
ParseResult<String> parse(LinkedList<String> args) {
if(args.size() > 0) {
if(args.getFirst().equalsIgnoreCase(s)){
LinkedList<String> ss = new LinkedList<String>(args);
return new Success<String>(ss.removeFirst(), ss);
}
else return new Failure<String>("expected: " + s + ", but got: " + args.getFirst());
}
else return new Failure<String>("expected: " + s + ", but got nothing");
}
};
}
ArgParser<String> anyString = new ArgParser<String>() {
@Override
ParseResult<String> parse(LinkedList<String> args) {
if(args.size() > 0) {
LinkedList<String> ss = new LinkedList<String>(args);
return new Success<String>(ss.removeFirst(), ss);
}
else return new Failure<String>("expected a string, but didn't get any");
}
};
public <T> ArgParser<Option<T>> opt(final ArgParser<T> p){
return new ArgParser<Option<T>>(){
@Override
ParseResult<Option<T>> parse(LinkedList<String> args) {
ParseResult<T> pr = p.parse(args);
if(pr.isFailure()) return new Success<Option<T>>(Option.<T>empty(), args);
else {
LinkedList<String> ss = new LinkedList<String>(args);
ss.removeFirst();
return new Success<Option<T>>(Option.apply(pr.get()), ss);
}
}
};
}
public <T> ArgParser<T> token(final String name, final F1<String, Option<T>> f){
return new ArgParser<T>() {
ParseResult<T> parse(LinkedList<String> args) {
if(args.isEmpty()) return new Failure<T>("expected " + name + ", got nothing");
else{
Option<T> ot = f.run(args.getFirst());
LinkedList<String> ss = new LinkedList<String>(args);
ss.removeFirst();
if(ot.isDefined()) return new Success<T>(ot.get(), ss);
else return new Failure<T>("invalid " + name + ": " + args.getFirst());
}
}
};
}
public ArgParser<Material> material = token("material", new F1<String, Option<Material>>() {
Option<Material> run(String s) {
Material m = Material.getMaterial(s);
if(m == null) m = Material.getMaterial(Integer.parseInt(s));
return Option.apply(m);
};
});
public ArgParser<EntityType> entity = token("entity", new F1<String, Option<EntityType>>() {
Option<EntityType> run(String s) {
EntityType e = EntityType.fromName(s.toUpperCase());
if(e == null) e = EntityType.valueOf(s.toUpperCase());
return Option.apply(e);
};
});
public ArgParser<Player> player = token("player", new F1<String, Option<Player>>() {
Option<Player> run(String s) {
return Option.apply(getServer().getPlayer(s));
};
});
public ArgParser<GameMode> gamemode =
match("c").or(match("creative")).or(match("1")).outputting(GameMode.CREATIVE).or(
match("s").or(match("survival")).or(match("0")).outputting(GameMode.SURVIVAL));
}
|
package org.fakekoji.jobmanager;
import org.fakekoji.Utils;
import org.fakekoji.model.BuildProvider;
import org.fakekoji.model.Platform;
import org.fakekoji.model.Product;
import org.fakekoji.model.Task;
import org.fakekoji.model.TaskVariant;
import org.fakekoji.model.TaskVariantValue;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.nio.file.Paths;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
public class JenkinsJobTemplateBuilder {
private static final String NEW_LINE = System.getProperty("line.separator");
public static final String XML_DECLARATION = "<?xml version=\"1.1\" encoding=\"UTF-8\" ?>\n";
private static final String JENKINS_TEMPLATES = "jenkins-templates";
static final String BUILD_PROVIDER_TOP_URL = "%{BUILD_PROVIDER_TOP_URL}";
static final String BUILD_PROVIDER_DOWNLOAD_URL = "%{BUILD_PROVIDER_DOWNLOAD_URL}";
static final String BUILD_PROVIDERS = "%{BUILD_PROVIDERS}";
static final String XML_RPC_API = "%{XML_RPC_API}";
static final String PACKAGE_NAME = "%{PACKAGE_NAME}";
static final String ARCH = "%{ARCH}";
static final String TAGS = "%{TAGS}";
static final String SUBPACKAGE_BLACKLIST = "%{SUBPACKAGE_BLACKLIST}";
static final String SUBPACKAGE_WHITELIST = "%{SUBPACKAGE_WHITELIST}";
static final String PROJECT_NAME = "%{PROJECT_NAME}";
static final String BUILD_VARIANTS = "%{BUILD_VARIANTS}";
static final String PLATFORM = "%{PLATFORM}";
static final String IS_BUILT = "%{IS_BUILT}";
static final String VM_POST_BUILD_TASK = "%{VM_POST_BUILD_TASK}";
static final String POST_BUILD_TASKS = "%{POST_BUILD_TASKS}";
static final String NODES = "%{NODES}";
static final String SHELL_SCRIPT = "%{SHELL_SCRIPT}";
static final String TASK_SCRIPT = "%{TASK_SCRIPT}";
static final String RUN_SCRIPT = "%{RUN_SCRIPT}";
static final String EXPORTED_VARIABLES = "%{EXPORTED_VARIABLES}";
static final String PLATFORM_NAME = "%{PLATFORM_NAME}";
static final String PULL_SCRIPT = "%{PULL_SCRIPT}";
static final String DESTROY_SCRIPT = "%{DESTROY_SCRIPT}";
static final String SCM_POLL_SCHEDULE = "%{SCM_POLL_SCHEDULE}";
static final String XML_NEW_LINE = "&
static final String XML_APOS = "'";
static final String LOCAL = "local";
static final String EXPORT = "export";
static final String O_TOOL = "otool";
static final String VAGRANT = "vagrant";
static final String PULL_SCRIPT_NAME = "pull.sh";
static final String RUN_SCRIPT_NAME = "run.sh";
static final String DESTROY_SCRIPT_NAME = "destroy.sh";
static final String BASH = "bash";
static final String SHEBANG = "#!/bin/sh";
static final String OTOOL_BASH_VAR_PREFIX = "OTOOL_";
static final String VM_NAME_OR_LOCAL_VAR = OTOOL_BASH_VAR_PREFIX + "VM_NAME_OR_LOCAL=";
static final String PROJECT_PATH_VAR = OTOOL_BASH_VAR_PREFIX + "PROJECT_PATH=";
static final String ARCH_VAR = OTOOL_BASH_VAR_PREFIX + "ARCH=";
static final String JDK_MAJOR_VAR = OTOOL_BASH_VAR_PREFIX + "JDK_MAJOR=";
static final String OJDK_VERSION_VAR = OTOOL_BASH_VAR_PREFIX + "OJDK_VERSION=";
static final String PLATFORM_PROVIDER_VAR = OTOOL_BASH_VAR_PREFIX + "PLATFORM_PROVIDER=";
static final String RELEASE_SUFFIX_VAR = OTOOL_BASH_VAR_PREFIX + "RELEASE_SUFFIX=";
static final String PROJECT_NAME_VAR = OTOOL_BASH_VAR_PREFIX + "PROJECT_NAME=";
static final String PACKAGE_NAME_VAR = OTOOL_BASH_VAR_PREFIX + "PACKAGE_NAME=";
static final String OS_VAR = OTOOL_BASH_VAR_PREFIX + "OS=";
private String template;
public JenkinsJobTemplateBuilder(String template) {
this.template = template;
}
public JenkinsJobTemplateBuilder buildPullScriptTemplate(
String projectName,
Product product,
String repositoriesRootPath,
File scriptsRoot
) {
final String pullScript = SHEBANG + XML_NEW_LINE +
EXPORT + " " + PROJECT_NAME_VAR + XML_APOS + projectName + XML_APOS + XML_NEW_LINE +
EXPORT + " " + PROJECT_PATH_VAR + XML_APOS + Paths.get(repositoriesRootPath, projectName) + XML_APOS + XML_NEW_LINE +
EXPORT + " " + OJDK_VERSION_VAR + XML_APOS + product.getVersion() + XML_APOS + XML_NEW_LINE +
EXPORT + " " + PACKAGE_NAME_VAR + XML_APOS + product.getPackageName() + XML_APOS + XML_NEW_LINE +
BASH + " '" + Paths.get(scriptsRoot.getAbsolutePath(), O_TOOL, PULL_SCRIPT_NAME) + "'";
template = template.replace(PULL_SCRIPT, pullScript);
return this;
}
public JenkinsJobTemplateBuilder buildBuildProvidersTemplate(Set<BuildProvider> buildProviders) throws IOException {
final String buildProviderTemplate = loadTemplate(JenkinsTemplate.BUILD_PROVIDER_TEMPLATE);
final String buildProviderTemplates = buildProviders.stream()
.map(buildProvider -> buildProviderTemplate
.replace(BUILD_PROVIDER_TOP_URL, buildProvider.getTopUrl())
.replace(BUILD_PROVIDER_DOWNLOAD_URL, buildProvider.getDownloadUrl()))
.collect(Collectors.joining(NEW_LINE));
template = template.replace(
BUILD_PROVIDERS,
loadTemplate(JenkinsTemplate.BUILD_PROVIDERS_TEMPLATE)
.replace(BUILD_PROVIDERS, buildProviderTemplates)
);
return this;
}
JenkinsJobTemplateBuilder buildKojiXmlRpcApiTemplate(
String packageName,
String arch,
List<String> tags,
String subpackageBlacklist,
String subpackageWhitelist
) throws IOException {
template = template
.replace(XML_RPC_API, loadTemplate(JenkinsTemplate.KOJI_XML_RPC_API_TEMPLATE))
.replace(PACKAGE_NAME, packageName)
.replace(ARCH, arch)
.replace(TAGS, '{' + String.join(",", tags) + '}')
.replace(SUBPACKAGE_BLACKLIST, subpackageBlacklist)
.replace(SUBPACKAGE_WHITELIST, subpackageWhitelist);
return this;
}
public JenkinsJobTemplateBuilder buildFakeKojiXmlRpcApiTemplate(
String projectName,
Map<TaskVariant, TaskVariantValue> buildVariants,
String platform,
boolean isBuilt
) throws IOException {
template = template
.replace(XML_RPC_API, loadTemplate(JenkinsTemplate.FAKEKOJI_XML_RPC_API_TEMPLATE))
.replace(PROJECT_NAME, projectName)
.replace(BUILD_VARIANTS, buildVariants.entrySet().stream()
.sorted(Comparator.comparing(entry -> entry.getKey().getId()))
.map(entry -> entry.getKey().getId() + '=' + entry.getValue().getId())
.collect(Collectors.joining(" ")))
.replace(PLATFORM, platform)
.replace(IS_BUILT, String.valueOf(isBuilt));
return this;
}
String fillExportedVariablesForBuildTask(
Platform platform,
String jdkVersion,
String jdkLabel,
String projectName,
String releaseSuffix
) {
return EXPORT + ' ' + JDK_MAJOR_VAR + jdkVersion + XML_NEW_LINE
+ EXPORT + ' ' + OJDK_VERSION_VAR + jdkLabel+ XML_NEW_LINE
+ EXPORT + ' ' + PROJECT_NAME_VAR + projectName + XML_NEW_LINE
+ EXPORT + ' ' + RELEASE_SUFFIX_VAR + releaseSuffix + XML_NEW_LINE
+ EXPORT + ' ' + ARCH_VAR + platform.getArchitecture() + XML_NEW_LINE
+ EXPORT + ' ' + OS_VAR + platform.getOs() + '.' + platform.getVersion() + XML_NEW_LINE;
}
String fillExportedVariables(
Map<TaskVariant, TaskVariantValue> variants,
String platformName,
String platformProvider
) {
return variants.entrySet().stream()
.sorted(Comparator.comparing(entry -> entry.getKey().getId()))
.map(entry -> EXPORT + ' ' + OTOOL_BASH_VAR_PREFIX + entry.getKey().getId() + '=' + entry.getValue().getId())
.collect(Collectors.joining(XML_NEW_LINE)) +
XML_NEW_LINE + EXPORT + ' ' + VM_NAME_OR_LOCAL_VAR + platformName +
XML_NEW_LINE + EXPORT + ' ' + PLATFORM_PROVIDER_VAR + platformProvider + XML_NEW_LINE;
}
public static String fillBuildPlatform(Platform platform, Task.FileRequirements fileRequirements) {
final List<String> platforms = new LinkedList<>();
if (fileRequirements.isSource()) {
platforms.add("src");
}
switch (fileRequirements.getBinary()) {
case BINARY:
platforms.add(platform.getString());
break;
case BINARIES:
return "";
case NONE:
break;
}
return String.join(" ", platforms);
}
public JenkinsJobTemplateBuilder buildScriptTemplate(
String projectName,
Product product,
Task task,
Platform platform,
Map<TaskVariant, TaskVariantValue> variants,
File scriptsRoot
) throws IOException {
final String vmName;
final List<String> nodes;
switch (task.getMachinePreference()) {
case HW:
if (platform.getHwNodes().isEmpty()) {
vmName = platform.getVmName();
nodes = platform.getVmNodes();
} else {
vmName = LOCAL;
nodes = platform.getHwNodes();
}
break;
case HW_ONLY:
vmName = LOCAL;
nodes = platform.getHwNodes();
break;
case VM:
if (platform.getVmNodes().isEmpty()) {
vmName = LOCAL;
nodes = platform.getHwNodes();
} else {
vmName = platform.getVmName();
nodes = platform.getVmNodes();
}
break;
case VM_ONLY:
vmName = platform.getVmName();
nodes = platform.getVmNodes();
break;
default:
throw new RuntimeException("Unknown machine preference");
}
final String exportedVariables = fillExportedVariables(
variants,
vmName,
platform.getProvider()
) + fillExportedVariablesForBuildTask(
platform,
product.getVersion(),
'o' + product.getId(),
projectName,
variants.entrySet()
.stream()
.filter(e -> e.getKey().getType() == Task.Type.BUILD)
.sorted(Comparator.comparing(Map.Entry::getKey))
.map(e -> e.getValue().getId())
.collect(Collectors.joining(".")) + '.' + platform.getString()
);
template = template
.replace(NODES, String.join(" ", nodes))
.replace(SCM_POLL_SCHEDULE, task.getScmPollSchedule())
.replace(SHELL_SCRIPT, loadTemplate(JenkinsTemplate.SHELL_SCRIPT_TEMPLATE))
.replace(TASK_SCRIPT, task.getScript())
.replace(RUN_SCRIPT, Paths.get(scriptsRoot.getAbsolutePath(), O_TOOL, RUN_SCRIPT_NAME).toString())
.replace(EXPORTED_VARIABLES, exportedVariables);
if (!vmName.equals(LOCAL)) {
return buildVmPostBuildTaskTemplate(vmName, scriptsRoot);
}
template = template.replace(VM_POST_BUILD_TASK, "");
return this;
}
JenkinsJobTemplateBuilder buildVmPostBuildTaskTemplate(String platformVmName, File scriptsRoot) throws IOException {
template = template
.replace(VM_POST_BUILD_TASK, loadTemplate(JenkinsTemplate.VM_POST_BUILD_TASK_TEMPLATE))
.replace(DESTROY_SCRIPT, Paths.get(scriptsRoot.getAbsolutePath(), VAGRANT, DESTROY_SCRIPT_NAME).toString())
.replace(PLATFORM_NAME, platformVmName);
return this;
}
public JenkinsJobTemplateBuilder buildPostBuildTasks(String postBuildTasksTemplate) {
template = template.replace(POST_BUILD_TASKS, postBuildTasksTemplate);
return this;
}
String getTemplate() {
return template;
}
public String prettyPrint() {
try {
final Transformer transformer = TransformerFactory.newInstance().newTransformer();
final Document document = DocumentBuilderFactory.newInstance()
.newDocumentBuilder()
.parse(new InputSource(new StringReader(template)));
final XPath xPath = XPathFactory.newInstance().newXPath();
final NodeList nodeList = (NodeList) xPath.evaluate(
"//text()[normalize-space()='']",
document,
XPathConstants.NODESET
);
for (int i = 0; i < nodeList.getLength(); i++) {
final Node node = nodeList.item(i);
node.getParentNode().removeChild(node);
}
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
final StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(document), new StreamResult(writer));
return writer.getBuffer().toString();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static String loadTemplate(JenkinsTemplate jenkinsTemplate) throws IOException {
return Utils.readResource(jenkinsTemplate.getValue());
}
public enum JenkinsTemplate {
KOJI_XML_RPC_API_TEMPLATE("koji-xml-rpc-api"),
SHELL_SCRIPT_TEMPLATE("shell-script"),
FAKEKOJI_XML_RPC_API_TEMPLATE("fakekoji-xml-rpc-api"),
BUILD_PROVIDER_TEMPLATE("provider"),
BUILD_PROVIDERS_TEMPLATE("/providers"),
TASK_JOB_TEMPLATE("task-job"),
PULL_JOB_TEMPLATE("pull-job"),
VM_POST_BUILD_TASK_TEMPLATE("vm-post-build-task");
private final String value;
JenkinsTemplate(final String template) {
this.value = Paths.get(JENKINS_TEMPLATES, template + ".xml").toString();
}
public String getValue() {
return value;
}
}
}
|
package org.flymine.dataconversion;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.Set;
import java.util.HashSet;
import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.io.File;
import java.io.FileReader;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import org.intermine.InterMineException;
import org.intermine.util.XmlUtil;
import org.intermine.xml.full.Attribute;
import org.intermine.xml.full.Item;
import org.intermine.xml.full.Reference;
import org.intermine.xml.full.ReferenceList;
import org.intermine.xml.full.ItemHelper;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.objectstore.ObjectStore;
import org.intermine.objectstore.ObjectStoreFactory;
import org.intermine.objectstore.ObjectStoreWriter;
import org.intermine.objectstore.ObjectStoreWriterFactory;
import org.intermine.dataconversion.ItemReader;
import org.intermine.dataconversion.ObjectStoreItemReader;
import org.intermine.dataconversion.ItemWriter;
import org.intermine.dataconversion.ObjectStoreItemWriter;
import org.intermine.dataconversion.ObjectStoreItemPathFollowingImpl;
import org.intermine.dataconversion.DataTranslator;
import org.intermine.dataconversion.ItemPrefetchDescriptor;
import org.intermine.dataconversion.ItemPrefetchConstraintDynamic;
import org.intermine.dataconversion.FieldNameAndValue;
import org.apache.log4j.Logger;
/**
* Convert MAGE data in fulldata Item format conforming to a source OWL definition
* to fulldata Item format conforming to InterMine OWL definition.
*
* @author Wenyan Ji
* @author Richard Smith
*/
public class MageDataTranslator extends DataTranslator
{
protected static final Logger LOG = Logger.getLogger(MageDataTranslator.class);
// flymine:ReporterLocation id -> flymine:Feature id
protected Map rlToFeature = new HashMap();
// mage:Feature id -> flymine:MicroArraySlideDesign id
protected Map featureToDesign = new HashMap();
// hold on to ReporterLocation items until end
protected Set reporterLocs = new HashSet();
protected Map gene2BioEntity = new HashMap();
//mage: Feature id -> flymine:MicroArrayExperimentResult id when processing BioAssayDatum
protected Map maer2Feature = new HashMap();
protected Map feature2Maer = new HashMap();
protected Set maerSet = new HashSet();
//flymine: BioEntity id -> mage:Feature id when processing Reporter
protected Map bioEntity2Feature = new HashMap();
protected Map bioEntity2IdentifierMap = new HashMap();
protected Set bioEntitySet = new HashSet();
protected Set geneSet = new HashSet();
protected Map synonymMap = new HashMap(); //key:itemId value:synonymItem
protected Map synonymAccessionMap = new HashMap();//key:accession value:synonymItem
protected Set synonymAccession = new HashSet();
// reporterSet:Flymine reporter. reporter:material -> bioEntity may probably merged when
//it has same identifier. need to reprocess reporterMaterial
protected Set reporterSet = new HashSet();
protected Map bioEntityRefMap = new HashMap();
protected Map identifier2BioEntity = new HashMap();
protected Map organismDbId2Gene = new HashMap();
protected Map treatment2BioSourceMap = new HashMap();
protected Set bioSource = new HashSet();
protected Map organismMap = new HashMap();
/**
* @see DataTranslator#DataTranslator
*/
public MageDataTranslator(ItemReader srcItemReader, OntModel model, String ns) {
super(srcItemReader, model, ns);
}
/**
* @see DataTranslator#translate
*/
public void translate(ItemWriter tgtItemWriter)
throws ObjectStoreException, InterMineException {
super.translate(tgtItemWriter);
Iterator i = processReporterLocs().iterator();
while (i.hasNext()) {
tgtItemWriter.store(ItemHelper.convert((Item) i.next()));
}
i = processBioEntity2MAEResult().iterator();
while (i.hasNext()) {
tgtItemWriter.store(ItemHelper.convert((Item) i.next()));
}
i = processGene2MAEResult().iterator();
while (i.hasNext()) {
tgtItemWriter.store(ItemHelper.convert((Item) i.next()));
}
i = processReporterMaterial().iterator();
while (i.hasNext()) {
tgtItemWriter.store(ItemHelper.convert((Item) i.next()));
}
i = processBioSourceTreatment().iterator();
while (i.hasNext()) {
tgtItemWriter.store(ItemHelper.convert((Item) i.next()));
}
}
/**
* @see DataTranslator#translateItem
*/
protected Collection translateItem(Item srcItem)
throws ObjectStoreException, InterMineException {
Collection result = new HashSet();
String normalised = null;
String srcNs = XmlUtil.getNamespaceFromURI(srcItem.getClassName());
String className = XmlUtil.getFragmentFromURI(srcItem.getClassName());
if (className.equals("BioAssayDatum")) {
normalised = srcItem.getAttribute("normalised").getValue();
srcItem = removeNormalisedAttribute(srcItem);
}
Collection translated = super.translateItem(srcItem);
Item gene = new Item();
Item organism = new Item();
if (translated != null) {
for (Iterator i = translated.iterator(); i.hasNext();) {
boolean storeTgtItem = true;
Item tgtItem = (Item) i.next();
// mage: BibliographicReference flymine:Publication
if (className.equals("BibliographicReference")) {
Set authors = createAuthors(srcItem);
List authorIds = new ArrayList();
Iterator j = authors.iterator();
while (j.hasNext()) {
Item author = (Item) j.next();
authorIds.add(author.getIdentifier());
result.add(author);
}
ReferenceList authorsRef = new ReferenceList("authors", authorIds);
tgtItem.addCollection(authorsRef);
} else if (className.equals("FeatureReporterMap")) {
setReporterLocationCoords(srcItem, tgtItem);
storeTgtItem = false;
} else if (className.equals("PhysicalArrayDesign")) {
createFeatureMap(srcItem);
translateMicroArraySlideDesign(srcItem, tgtItem);
} else if (className.equals("Experiment")) {
// collection bioassays includes MeasuredBioAssay, PhysicalBioAssay
// and DerivedBioAssay, only keep DerivedBioAssay
keepDBA(srcItem, tgtItem, srcNs);
translateMicroArrayExperiment(srcItem, tgtItem);
} else if (className.equals("DerivedBioAssay")) {
translateMicroArrayAssay(srcItem, tgtItem);
} else if (className.equals("BioAssayDatum")) {
translateMicroArrayExperimentalResult(srcItem, tgtItem, normalised);
} else if (className.equals("Reporter")) {
setBioEntityMap(srcItem, tgtItem);
storeTgtItem = false;
} else if (className.equals("BioSequence")) {
translateBioEntity(srcItem, tgtItem);
storeTgtItem = false;
} else if (className.equals("LabeledExtract")) {
translateLabeledExtract(srcItem, tgtItem);
} else if (className.equals("BioSource")) {
organism = translateSample(srcItem, tgtItem);
result.add(organism);
} else if (className.equals("Treatment")) {
translateTreatment(srcItem, tgtItem);
}
if (storeTgtItem) {
result.add(tgtItem);
}
}
}
return result;
}
/**
* @param srcItem = mage:BibliographicReference
* @return author set
*/
protected Set createAuthors(Item srcItem) {
Set result = new HashSet();
if (srcItem.hasAttribute("authors")) {
Attribute authorsAttr = srcItem.getAttribute("authors");
if (authorsAttr != null) {
String authorStr = authorsAttr.getValue();
StringTokenizer st = new StringTokenizer(authorStr, ";");
while (st.hasMoreTokens()) {
String name = st.nextToken().trim();
Item author = createItem(tgtNs + "Author", "");
author.addAttribute(new Attribute("name", name));
result.add(author);
}
}
}
return result;
}
/**
* @param srcItem = mage: FeatureReporterMap
* @param tgtItem = flymine: ReporterLocation
* @throws ObjectStoreException if problem occured during translating
*/
protected void setReporterLocationCoords(Item srcItem, Item tgtItem)
throws ObjectStoreException {
if (srcItem.hasCollection("featureInformationSources")) {
ReferenceList featureInfos = srcItem.getCollection("featureInformationSources");
if (!isSingleElementCollection(featureInfos)) {
LOG.error("FeatureReporterMap (" + srcItem.getIdentifier()
+ ") does not have single element collection"
+ featureInfos.getRefIds().toString());
// + srcItem.getIdentifier()
// + " has more than one featureInformationSource");
}
//FeatureInformationSources->FeatureInformation->Feature->FeatureLocation
// prefetch done
Item featureInfo = ItemHelper.convert(srcItemReader
.getItemById(getFirstId(featureInfos)));
if (featureInfo.hasReference("feature")) {
Item feature = ItemHelper.convert(srcItemReader
.getItemById(featureInfo.getReference("feature").getRefId()));
if (feature.hasReference("featureLocation")) {
Item featureLoc = ItemHelper.convert(srcItemReader
.getItemById(feature.getReference("featureLocation").getRefId()));
if (featureLoc != null) {
tgtItem.addAttribute(new Attribute("localX",
featureLoc.getAttribute("column").getValue()));
tgtItem.addAttribute(new Attribute("localY",
featureLoc.getAttribute("row").getValue()));
}
}
if (feature.hasReference("zone")) {
Item zone = ItemHelper.convert(srcItemReader
.getItemById(feature.getReference("zone").getRefId()));
if (zone != null) {
tgtItem.addAttribute(new Attribute("zoneX",
zone.getAttribute("column").getValue()));
tgtItem.addAttribute(new Attribute("zoneY",
zone.getAttribute("row").getValue()));
}
}
// to set MicroArraySlideDesign <-> ReporterLocation reference
// need to hold on to ReporterLocations and their feature ids
// until end of processing
reporterLocs.add(tgtItem);
rlToFeature.put(tgtItem.getIdentifier(), feature.getIdentifier());
}
} else {
LOG.error("FeatureReporterMap (" + srcItem.getIdentifier()
+ ") does not have featureInformationSource");
// + srcItem.getIdentifier()
// + " does not have featureInformationSource");
}
}
/**
* @param srcItem = mage:PhysicalArrayDesign
* @throws ObjectStoreException if problem occured during translating
*/
protected void createFeatureMap(Item srcItem)
throws ObjectStoreException {
if (srcItem.hasCollection("featureGroups")) {
ReferenceList featureGroups = srcItem.getCollection("featureGroups");
if (featureGroups == null || !isSingleElementCollection(featureGroups)) {
throw new IllegalArgumentException("PhysicalArrayDesign (" + srcItem.getIdentifier()
+ ") does not have exactly one featureGroup");
}
// prefetch done
Item featureGroup = ItemHelper.convert(srcItemReader
.getItemById(getFirstId(featureGroups)));
Iterator featureIter = featureGroup.getCollection("features").getRefIds().iterator();
while (featureIter.hasNext()) {
featureToDesign.put((String) featureIter.next(), srcItem.getIdentifier());
}
}
}
/**
* @param maer2FeatureMap and
* @param maerSet
* both created during translating BioAssayDatum to MicroArrayExperimentalResult
* iterator through maerSet to create feature2Maer
* @return feature2Maer map
*/
protected Map createFeature2MaerMap(Map maer2FeatureMap, Set maerSet) {
for (Iterator i = maerSet.iterator(); i.hasNext(); ) {
String maer = (String) i.next();
String feature = (String) maer2FeatureMap.get(maer);
if (feature2Maer.containsKey(feature)) {
String multiMaer = ((String) feature2Maer.get(feature)).concat(" " + maer);
feature2Maer.put(feature, multiMaer);
} else {
feature2Maer.put(feature, maer);
}
}
LOG.debug("feature2maer " + feature2Maer.toString());
return feature2Maer;
}
/**
* @param srcItem = mage:Reporter
* @param tgtItem = flymine:Reporter
* set BioEntity2FeatureMap when translating Reporter
* set BioEntity2IdentifierMap when translating Reporter
* @throws ObjectStoreException if errors occured during translating
*/
protected void setBioEntityMap(Item srcItem, Item tgtItem)
throws ObjectStoreException {
StringBuffer sb = new StringBuffer();
boolean controlFlg = false;
ReferenceList failTypes = new ReferenceList();
if (srcItem.hasCollection("failTypes")) {
failTypes = srcItem.getCollection("failTypes");
if (failTypes != null) {
for (Iterator l = srcItem.getCollection("failTypes").getRefIds().iterator();
l.hasNext();) {
Item ontoItem = ItemHelper.convert(srcItemReader.getItemById(
(String) l.next()));
sb.append(ontoItem.getAttribute("value").getValue() + " ");
}
tgtItem.addAttribute(new Attribute("failType", sb.toString()));
}
}
if (srcItem.hasReference("controlType")) {
Reference controlType = srcItem.getReference("controlType");
if (controlType != null) {
Item controlItem = ItemHelper.convert(srcItemReader.getItemById(
(String) srcItem.getReference("controlType").getRefId()));
if (controlItem.getAttribute("value").getValue().equals("control_buffer")) {
controlFlg = true;
}
}
}
ReferenceList featureReporterMaps = srcItem.getCollection("featureReporterMaps");
ReferenceList immobilizedChar = srcItem.getCollection("immobilizedCharacteristics");
sb = new StringBuffer();
String identifier = null;
if (immobilizedChar == null) {
if (failTypes != null) {
LOG.info("Reporter ("
+ srcItem.getIdentifier()
+ ") does not have immobilizedCharacteristics because it fails");
} else if (controlFlg) {
LOG.info("Reporter ("
+ srcItem.getIdentifier()
+ ") does not have immobilizedCharacteristics because"
+ " it is a control_buffer");
} else {
throw new IllegalArgumentException("Reporter ("
+ srcItem.getIdentifier()
+ ") does not have immobilizedCharacteristics");
}
} else if (!isSingleElementCollection(immobilizedChar)) {
throw new IllegalArgumentException("Reporter ("
+ srcItem.getIdentifier()
+ ") have more than one immobilizedCharacteristics");
} else {
//create bioEntity2IdentifierMap
//identifier = reporter: name for CDNAClone, Vector
//identifier = reporter: controlType;name;descriptions for genomic_dna
identifier = getFirstId(immobilizedChar);
String identifierAttribute = null;
Item bioSequence = ItemHelper.convert(srcItemReader.getItemById(identifier));
if (bioSequence.hasReference("type")) {
Item oeItem = ItemHelper.convert(srcItemReader.getItemById(
(String) bioSequence.getReference("type").getRefId()));
if (oeItem.getAttribute("value").getValue().equals("genomic_DNA")) {
sb = new StringBuffer();
if (srcItem.hasReference("controlType")) {
Item controlItem = ItemHelper.convert(srcItemReader.getItemById((String)
srcItem.getReference("controlType").getRefId()));
if (controlItem.hasAttribute("value")) {
sb.append(controlItem.getAttribute("value").getValue() + ";");
}
}
if (srcItem.hasAttribute("name")) {
sb.append(srcItem.getAttribute("name").getValue() + ";");
}
if (srcItem.hasCollection("descriptions")) {
for (Iterator k = srcItem.getCollection(
"descriptions").getRefIds().iterator(); k.hasNext();) {
Item description = ItemHelper.convert(srcItemReader.getItemById(
(String) k.next()));
if (description.hasAttribute("text")) {
sb.append(description.getAttribute("text").getValue() + ";");
}
}
}
if (sb.length() > 1) {
identifierAttribute = sb.substring(0, sb.length() - 1);
bioEntity2IdentifierMap.put(identifier, identifierAttribute);
}
} else {
sb = new StringBuffer();
if (srcItem.hasAttribute("name")) {
sb.append(srcItem.getAttribute("name").getValue());
identifierAttribute = sb.toString();
bioEntity2IdentifierMap.put(identifier, identifierAttribute);
}
}
}
//create bioEntity2FeatureMap
sb = new StringBuffer();
if (featureReporterMaps != null) {
for (Iterator i = featureReporterMaps.getRefIds().iterator(); i.hasNext(); ) {
//FeatureReporterMap //desc2
String s = (String) i.next();
Item frm = ItemHelper.convert(srcItemReader.getItemById(s));
if (frm.hasCollection("featureInformationSources")) {
Iterator j = frm.getCollection("featureInformationSources").
getRefIds().iterator();
// prefetch done
while (j.hasNext()) {
Item fis = ItemHelper.convert(srcItemReader.getItemById(
(String) j.next()));
if (fis.hasReference("feature")) {
sb.append(fis.getReference("feature").getRefId() + " ");
}
}
}
}
if (sb.length() > 1) {
bioEntity2Feature.put(identifier, sb.substring(0, sb.length() - 1));
}
LOG.debug("bioEntity2Feature" + bioEntity2Feature.toString());
//identifier = (String) immobilizedChar.getRefIds().get(0);
tgtItem.addReference(new Reference("material", identifier));
}
}
reporterSet.add(tgtItem);
}
/**
* @param srcItem = mage:PhysicalArrayDesign
* @param tgtItem = flymine:MicroArraySlideDesign
* @throws ObjectStoreException if problem occured during translating
*/
protected void translateMicroArraySlideDesign(Item srcItem, Item tgtItem)
throws ObjectStoreException {
// move descriptions reference list
if (srcItem.hasCollection("descriptions")) {
ReferenceList des = srcItem.getCollection("descriptions");
if (des != null) {
for (Iterator i = des.getRefIds().iterator(); i.hasNext(); ) {
Item anno = ItemHelper.convert(srcItemReader.getItemById((String) i.next()));
if (anno != null) {
promoteCollection(srcItem, "descriptions", "annotations",
tgtItem, "descriptions");
}
}
}
}
// change substrateType reference to attribute
if (srcItem.hasReference("surfaceType")) {
Item surfaceType = ItemHelper.convert(srcItemReader
.getItemById(srcItem.getReference("surfaceType").getRefId()));
if (surfaceType.hasAttribute("value")) {
tgtItem.addAttribute(new Attribute("surfaceType",
surfaceType.getAttribute("value").getValue()));
}
}
if (srcItem.hasAttribute("version")) {
tgtItem.addAttribute(new Attribute("version",
srcItem.getAttribute("version").getValue()));
}
if (srcItem.hasAttribute("name")) {
tgtItem.addAttribute(new Attribute("name",
srcItem.getAttribute("name").getValue()));
}
}
/**
* @param srcItem = mage:Experiment
* @param tgtItem = flymine: MicroArrayExperiment
* @param srcNs = mage: src namespace
* @throws ObjectStoreException if problem occured during translating
*/
protected void keepDBA(Item srcItem, Item tgtItem, String srcNs)
throws ObjectStoreException {
ReferenceList rl = srcItem.getCollection("bioAssays");
ReferenceList newRl = new ReferenceList();
newRl.setName("assays");
// prefetch done
if (rl != null) {
for (Iterator i = rl.getRefIds().iterator(); i.hasNext(); ) {
Item baItem = ItemHelper.convert(srcItemReader.getItemById((String) i.next()));
if (baItem.getClassName().equals(srcNs + "DerivedBioAssay")) {
newRl.addRefId(baItem.getIdentifier());
}
}
tgtItem.addCollection(newRl);
}
}
/**
* @param srcItem = mage:Experiment
* @param tgtItem = flymine: MicroArrayExperiment
* @throws ObjectStoreException if problem occured during translating
*/
protected void translateMicroArrayExperiment(Item srcItem, Item tgtItem)
throws ObjectStoreException {
if (srcItem.hasAttribute("name")) {
tgtItem.addAttribute(new Attribute("name", srcItem.getAttribute("name").getValue()));
}
// prefetch done
ReferenceList desRl = srcItem.getCollection("descriptions");
boolean desFlag = false;
boolean pubFlag = false;
for (Iterator i = desRl.getRefIds().iterator(); i.hasNext(); ) {
Item desItem = ItemHelper.convert(srcItemReader.getItemById((String) i.next()));
if (desItem != null) {
if (desItem.hasAttribute("text")) {
if (desFlag) {
LOG.error("Already set description for MicroArrayExperiment, "
+ " srcItem = " + srcItem.getIdentifier());
} else {
tgtItem.addAttribute(new Attribute("description",
desItem.getAttribute("text").getValue()));
desFlag = true;
}
}
ReferenceList publication = desItem.getCollection("bibliographicReferences");
if (publication != null) {
if (!isSingleElementCollection(publication)) {
throw new IllegalArgumentException("Experiment description collection ("
+ desItem.getIdentifier()
+ ") has more than one bibliographicReferences");
} else {
if (pubFlag) {
LOG.error("Already set publication for MicroArrayExperiment, "
+ " srcItem = " + srcItem.getIdentifier());
} else {
tgtItem.addReference(new Reference("publication",
getFirstId(publication)));
pubFlag = true;
}
}
}
}
}
}
/**
* @param srcItem = mage: DerivedBioAssay
* @param tgtItem = flymine:MicroArrayAssay
* @throws ObjectStoreException if problem occured during translating
*/
protected void translateMicroArrayAssay(Item srcItem, Item tgtItem)
throws ObjectStoreException {
ReferenceList dbad = srcItem.getCollection("derivedBioAssayData");
if (dbad != null) {
for (Iterator j = dbad.getRefIds().iterator(); j.hasNext(); ) {
// prefetch done
Item dbadItem = ItemHelper.convert(srcItemReader.getItemById((String) j.next()));
if (dbadItem.hasReference("bioDataValues")) {
Item bioDataTuples = ItemHelper.convert(srcItemReader.getItemById(
dbadItem.getReference("bioDataValues").getRefId()));
if (bioDataTuples.hasCollection("bioAssayTupleData")) {
ReferenceList rl = bioDataTuples.getCollection("bioAssayTupleData");
ReferenceList resultsRl = new ReferenceList();
resultsRl.setName("results");
for (Iterator i = rl.getRefIds().iterator(); i.hasNext(); ) {
resultsRl.addRefId((String) i.next());
}
tgtItem.addCollection(resultsRl);
}
}
}
}
}
/**
* @param srcItem = mage:BioAssayDatum
* @param tgtItem = flymine:MicroArrayExperimentalResult
* @param normalised is defined in translateItem
* @throws ObjectStoreException if problem occured during translating
*/
public void translateMicroArrayExperimentalResult(Item srcItem, Item tgtItem, String normalised)
throws ObjectStoreException {
tgtItem.addAttribute(new Attribute("normalised", normalised));
//create maer2Feature map, and maer set
if (srcItem.hasReference("designElement")) {
maer2Feature.put(tgtItem.getIdentifier(),
srcItem.getReference("designElement").getRefId());
maerSet.add(tgtItem.getIdentifier());
}
if (srcItem.hasReference("quantitationType")) {
Item qtItem = ItemHelper.convert(srcItemReader.getItemById(
srcItem.getReference("quantitationType").getRefId()));
if (qtItem.getClassName().endsWith("MeasuredSignal")
|| qtItem.getClassName().endsWith("Ratio")) {
if (qtItem.hasAttribute("name")) {
tgtItem.addAttribute(new Attribute("type",
qtItem.getAttribute("name").getValue()));
} else {
LOG.error("srcItem ( " + qtItem.getIdentifier()
+ " ) does not have name attribute");
}
if (qtItem.hasReference("scale")) {
Item oeItem = ItemHelper.convert(srcItemReader.getItemById(
qtItem.getReference("scale").getRefId()));
tgtItem.addAttribute(new Attribute("scale",
oeItem.getAttribute("value").getValue()));
} else {
LOG.error("srcItem (" + qtItem.getIdentifier()
+ "( does not have scale attribute ");
}
if (qtItem.hasAttribute("isBackground")) {
tgtItem.addAttribute(new Attribute("isBackground",
qtItem.getAttribute("isBackground").getValue()));
} else {
LOG.error("srcItem (" + qtItem.getIdentifier()
+ "( does not have scale reference ");
}
} else if (qtItem.getClassName().endsWith("Error")) {
if (qtItem.hasAttribute("name")) {
tgtItem.addAttribute(new Attribute("type",
qtItem.getAttribute("name").getValue()));
} else {
LOG.error("srcItem ( " + qtItem.getIdentifier()
+ " ) does not have name attribute");
}
if (qtItem.hasReference("targetQuantitationType")) {
Item msItem = ItemHelper.convert(srcItemReader.getItemById(
qtItem.getReference("targetQuantitationType").getRefId()));
if (msItem.hasReference("scale")) {
Item oeItem = ItemHelper.convert(srcItemReader.getItemById(
msItem.getReference("scale").getRefId()));
tgtItem.addAttribute(new Attribute("scale",
oeItem.getAttribute("value").getValue()));
} else {
LOG.error("srcItem (" + msItem.getIdentifier()
+ "( does not have scale attribute ");
}
if (msItem.hasAttribute("isBackground")) {
tgtItem.addAttribute(new Attribute("isBackground",
msItem.getAttribute("isBackground").getValue()));
} else {
LOG.error("srcItem (" + msItem.getIdentifier()
+ "( does not have scale reference ");
}
}
}
}
}
/**
* @param srcItem = mage:BioSequence
* @param tgtItem = flymine:BioEntity(genomic_DNA =>NuclearDNA cDNA_clone=>CDNAClone,
* vector=>Vector)
* extra will create for Gene(FBgn), Vector(FBmc) and Synonym(embl)
* synonymMap(itemid, item), synonymAccessionMap(accession, item) and
* synonymAccession (HashSet) created for flymine:Synonym,
* geneList include Gene and Vector to reprocess to add mAER collection
* bioEntityList include CDNAClone and NuclearDNA to add identifier attribute
* and mAER collection
* @throws ObjectStoreException if problem occured during translating
*/
protected void translateBioEntity(Item srcItem, Item tgtItem)
throws ObjectStoreException {
Item gene = new Item();
Item vector = new Item();
Item synonym = new Item();
String s = null;
String identifier = null;
if (srcItem.hasReference("type")) {
Item item = ItemHelper.convert(srcItemReader.getItemById(
srcItem.getReference("type").getRefId()));
if (item.hasAttribute("value")) {
s = item.getAttribute("value").getValue();
if (s.equals("genomic_DNA")) {
tgtItem.setClassName(tgtNs + "NuclearDNA");
} else if (s.equals("cDNA_clone")) {
tgtItem.setClassName(tgtNs + "CDNAClone");
} else if (s.equals("vector")) {
tgtItem.setClassName(tgtNs + "Vector");
} else {
tgtItem = null;
}
}
}
// prefetch done
if (srcItem.hasCollection("sequenceDatabases")) {
ReferenceList rl = srcItem.getCollection("sequenceDatabases");
identifier = null;
List geneList = new ArrayList();
List emblList = new ArrayList();
for (Iterator i = rl.getRefIds().iterator(); i.hasNext(); ) {
Item dbEntryItem = ItemHelper.convert(srcItemReader.
getItemById((String) i.next()));
if (dbEntryItem.hasReference("database")) {
Item dbItem = ItemHelper.convert(srcItemReader.getItemById(
(String) dbEntryItem.getReference("database").getRefId()));
String synonymSourceId = dbItem.getIdentifier();
if (dbItem.hasAttribute("name")) {
String dbName = dbItem.getAttribute("name").getValue();
String organismDbId = dbEntryItem.getAttribute("accession").getValue();
if (dbName.equals("flybase") && organismDbId.startsWith("FBgn")) {
gene = createGene(tgtNs + "Gene", "", dbEntryItem.getIdentifier(),
organismDbId);
geneList.add(dbItem.getIdentifier());
// } else if (dbName.equals("flybase")
// && organismDbId.startsWith("FBmc")) {
// tgtItem.addAttribute(new Attribute("organismDbId", organismDbId));
} else if (dbName.equals("embl") && dbEntryItem.hasAttribute("accession")) {
String accession = dbEntryItem.getAttribute("accession").getValue();
//make sure synonym only create once for same accession
if (!synonymAccession.contains(accession)) {
emblList.add(dbEntryItem.getIdentifier());
synonym = createSynonym(dbEntryItem, synonymSourceId,
srcItem.getIdentifier());
synonymAccession.add(accession); //Set
synonymMap.put(dbEntryItem.getIdentifier(), synonym);
synonymAccessionMap.put(accession, synonym);
}
// result.add(synonym);
} else {
//getDatabaseRef();
}
}
}
}
if (!geneList.isEmpty()) {
geneSet.add(gene);
gene2BioEntity.put(gene.getIdentifier(), srcItem.getIdentifier());
}
if (!emblList.isEmpty()) {
ReferenceList synonymEmblRl = new ReferenceList("synonyms", emblList);
tgtItem.addCollection(synonymEmblRl);
}
}
if (tgtItem != null) {
bioEntitySet.add(tgtItem);
}
}
/**
* @param srcItem = databaseEntry item refed in BioSequence
* @param sourceId = database id
* @param subjectId = bioEntity identifier will probably be changed
* when reprocessing bioEntitySet
* @return synonym item
*/
protected Item createSynonym(Item srcItem, String sourceId, String subjectId) {
Item synonym = new Item();
synonym.setClassName(tgtNs + "Synonym");
synonym.setIdentifier(srcItem.getIdentifier());
synonym.setImplementations("");
synonym.addAttribute(new Attribute("type", "accession"));
synonym.addReference(new Reference("source", sourceId));
synonym.addAttribute(new Attribute("value",
srcItem.getAttribute("accession").getValue()));
synonym.addReference(new Reference("subject", subjectId));
return synonym;
}
/**
* @param srcItem = mage:LabeledExtract
* @param tgtItem = flymine:LabeledExtract
* @throws ObjectStoreException if problem occured during translating
*/
public void translateLabeledExtract(Item srcItem, Item tgtItem)
throws ObjectStoreException {
if (srcItem.hasReference("materialType")) {
Item type = ItemHelper.convert(srcItemReader.getItemById(
(String) srcItem.getReference("materialType").getRefId()));
tgtItem.addAttribute(new Attribute("materialType",
type.getAttribute("value").getValue()));
}
ReferenceList labels = srcItem.getCollection("labels");
if (labels == null || !isSingleElementCollection(labels)) {
throw new IllegalArgumentException("LabeledExtract (" + srcItem.getIdentifier()
+ " does not have exactly one label");
}
// prefetch done
Item label = ItemHelper.convert(srcItemReader
.getItemById(getFirstId(labels)));
tgtItem.addAttribute(new Attribute("label", label.getAttribute("name").getValue()));
// prefetch done
ReferenceList treatments = srcItem.getCollection("treatments");
List treatmentList = new ArrayList();
ReferenceList tgtTreatments = new ReferenceList("treatments", treatmentList);
String sampleId = null;
StringBuffer sb = new StringBuffer();
if (treatments != null) {
for (Iterator i = treatments.getRefIds().iterator(); i.hasNext(); ) {
String refId = (String) i.next();
treatmentList.add(refId);
Item treatmentItem = ItemHelper.convert(srcItemReader.getItemById(refId));
if (treatmentItem.hasCollection("sourceBioMaterialMeasurements")) {
ReferenceList sourceRl = treatmentItem.getCollection(
"sourceBioMaterialMeasurements");
for (Iterator j = sourceRl.getRefIds().iterator(); j.hasNext(); ) {
//bioMaterialMeausrement
Item bioMMItem = ItemHelper.convert(srcItemReader.getItemById(
(String) j.next()));
if (bioMMItem.hasReference("bioMaterial")) {
Item bioSample = ItemHelper.convert(srcItemReader.getItemById(
(String) bioMMItem.getReference("bioMaterial").getRefId()));
if (bioSample.hasCollection("treatments")) {
ReferenceList bioSampleTreatments = bioSample.getCollection(
"treatments");
for (Iterator k = bioSampleTreatments.getRefIds().iterator();
k.hasNext();) {
refId = (String) k.next();
treatmentList.add(refId);
//create treatment2BioSourceMap
Item treatItem = ItemHelper.convert(srcItemReader.
getItemById(refId));
sampleId = createTreatment2BioSourceMap(treatItem);
sb.append(sampleId + " ");
}
}
}
}
}
}
tgtItem.addCollection(tgtTreatments);
StringTokenizer st = new StringTokenizer(sb.toString());
while (st.hasMoreTokens()) {
String s = st.nextToken();
if (!s.equals(sampleId)) {
throw new IllegalArgumentException ("LabeledExtract ("
+ srcItem.getIdentifier()
+ " does not have exactly one reference to sample");
}
}
tgtItem.addReference(new Reference("sample", sampleId));
}
}
/**
* @param srcItem = mage:BioSource
* @param tgtItem = flymine:Sample
* @return flymine:Organism
* @throws ObjectStoreException if problem occured during translating
*/
protected Item translateSample(Item srcItem, Item tgtItem)
throws ObjectStoreException {
ReferenceList characteristics = srcItem.getCollection("characteristics");
List list = new ArrayList();
Item organism = new Item();
String s = null;
if (characteristics != null) {
for (Iterator i = characteristics.getRefIds().iterator(); i.hasNext();) {
String id = (String) i.next();
// prefetch done
Item charItem = ItemHelper.convert(srcItemReader.getItemById(id));
s = charItem.getAttribute("category").getValue();
if (s.equalsIgnoreCase("organism") && charItem.hasAttribute("value")) {
String organismName = charItem.getAttribute("value").getValue();
organism = createOrganism(tgtNs + "Organism", "", organismName);
tgtItem.addReference(new Reference("organism", organism.getIdentifier()));
} else {
list.add(id);
}
}
ReferenceList tgtChar = new ReferenceList("characteristics", list);
tgtItem.addCollection(tgtChar);
}
if (srcItem.hasReference("materialType")) {
Item type = ItemHelper.convert(srcItemReader.getItemById(
(String) srcItem.getReference("materialType").getRefId()));
tgtItem.addAttribute(new Attribute("materialType",
type.getAttribute("value").getValue()));
}
if (srcItem.hasAttribute("name")) {
tgtItem.addAttribute(new Attribute("name", srcItem.getAttribute("name").getValue()));
}
bioSource.add(tgtItem);
return organism;
}
/**
* @param srcItem = mage:Treatment
* @param tgtItem = flymine:Treatment
* @throws ObjectStoreException if problem occured during translating
*/
public void translateTreatment(Item srcItem, Item tgtItem)
throws ObjectStoreException {
if (srcItem.hasReference("action")) {
Item action = ItemHelper.convert(srcItemReader.getItemById(
(String) srcItem.getReference("action").getRefId()));
if (action.hasAttribute("value")) {
tgtItem.addAttribute(new Attribute("action",
action.getAttribute("value").getValue()));
}
}
}
/**
* @param srcItem = mage:Treatment from BioSample<Extract>
* @return string of bioSourceId
* @throws ObjectStoreException if problem occured during translating
* method called when processing LabeledExtract
*/
protected String createTreatment2BioSourceMap(Item srcItem)
throws ObjectStoreException {
StringBuffer bioSourceId = new StringBuffer();
StringBuffer treatment = new StringBuffer();
String id = null;
if (srcItem.hasCollection("sourceBioMaterialMeasurements")) {
ReferenceList sourceRl1 = srcItem.getCollection("sourceBioMaterialMeasurements");
for (Iterator l = sourceRl1.getRefIds().iterator(); l.hasNext(); ) {
// bioSampleItem, type extract
// prefetch done (but limited)
Item bioSampleExItem = ItemHelper.convert(srcItemReader.getItemById(
(String) l.next()));
if (bioSampleExItem.hasReference("bioMaterial")) {
// bioSampleItem, type not-extract
Item bioSampleItem = ItemHelper.convert(srcItemReader.getItemById(
(String) bioSampleExItem.getReference("bioMaterial").getRefId()));
if (bioSampleItem.hasCollection("treatments")) {
ReferenceList bioSourceRl = bioSampleItem.getCollection("treatments");
for (Iterator m = bioSourceRl.getRefIds().iterator(); m.hasNext();) {
String treatmentList = (String) m.next();
treatment.append(treatmentList + " ");
Item bioSourceTreatmentItem = ItemHelper.convert(srcItemReader.
getItemById(treatmentList));
if (bioSourceTreatmentItem.hasCollection(
"sourceBioMaterialMeasurements")) {
ReferenceList sbmmRl = bioSourceTreatmentItem.getCollection(
"sourceBioMaterialMeasurements");
for (Iterator n = sbmmRl.getRefIds().iterator(); n.hasNext();) {
Item bmm = ItemHelper.convert(srcItemReader.getItemById(
(String) n.next()));
if (bmm.hasReference("bioMaterial")) {
id = (String) bmm.getReference("bioMaterial").
getRefId();
bioSourceId.append(id + " ");
}
}
}
}
}
}
}
}
StringTokenizer st = new StringTokenizer(bioSourceId.toString());
while (st.hasMoreTokens()) {
String s = st.nextToken();
if (!s.equals(id)) {
throw new IllegalArgumentException("LabeledExtract (" + srcItem.getIdentifier()
+ " does not have exactly one reference to sample");
}
}
treatment2BioSourceMap.put(id, treatment.toString());
return id;
}
/**
* bioSourceItem = flymine:Sample item without treatment collection
* treatment collection is from mage:BioSample<type: not-Extract> treatment collection
* treatment2BioSourceMap is created when tranlating LabeledExtract
* @return resultSet
*/
protected Set processBioSourceTreatment() {
Set results = new HashSet();
Iterator i = bioSource.iterator();
while (i.hasNext()) {
Item bioSourceItem = (Item) i.next();
List treatList = new ArrayList();
String s = (String) treatment2BioSourceMap.get((String) bioSourceItem.getIdentifier());
LOG.debug("treatmentList " + s + " for " + bioSourceItem.getIdentifier());
if (s != null) {
StringTokenizer st = new StringTokenizer(s);
while (st.hasMoreTokens()) {
treatList.add(st.nextToken());
}
}
ReferenceList treatments = new ReferenceList("treatments", treatList);
bioSourceItem.addCollection(treatments);
results.add(bioSourceItem);
}
return results;
}
/**
* set ReporterLocation.design reference, don't need to set
* MicroArraySlideDesign.locations explicitly
* @return results set
*/
protected Set processReporterLocs() {
Set results = new HashSet();
if (reporterLocs != null && featureToDesign != null && rlToFeature != null) {
for (Iterator i = reporterLocs.iterator(); i.hasNext();) {
Item rl = (Item) i.next();
String designId = (String) featureToDesign.get(rlToFeature.get(rl.getIdentifier()));
Reference designRef = new Reference();
if (designId != null) {
designRef.setName("design");
designRef.setRefId(designId);
rl.addReference(designRef);
results.add(rl);
}
}
}
return results;
}
/**
* BioAssayDatum mage:FeatureId -> flymine:MAEResultId (MicroArrayExperimentalResults)
* Reporter flymine: BioEntityId -> mage:FeatureId
* BioSequece BioEntityId -> BioEntity Item
* -> extra Gene Item
* @return add microExperimentalResults collection to BioEntity item
* and add identifier attribute to BioEntity
*/
protected Set processBioEntity2MAEResult() {
Set results = new HashSet();
Set entitySet = new HashSet();
feature2Maer = new HashMap();
feature2Maer = createFeature2MaerMap(maer2Feature, maerSet);
String s = null;
String itemId = null;
String identifierAttribute = null;
Set identifierSet = new HashSet();
for (Iterator i = bioEntitySet.iterator(); i.hasNext();) {
Item bioEntity = (Item) i.next();
// add collection microArrayExperimentalResult
List maerIds = new ArrayList();
s = (String) bioEntity2Feature.get((String) bioEntity.getIdentifier());
LOG.debug("featureId " + s + " bioEntityId " + bioEntity.getIdentifier());
if (s != null) {
StringTokenizer st = new StringTokenizer(s);
String multiMaer = null;
while (st.hasMoreTokens()) {
multiMaer = (String) feature2Maer.get(st.nextToken());
if (multiMaer != null) {
StringTokenizer token = new StringTokenizer(multiMaer);
while (token.hasMoreTokens()) {
maerIds.add(token.nextToken());
}
}
}
ReferenceList maerRl = new ReferenceList("microArrayExperimentalResults", maerIds);
bioEntity.addCollection(maerRl);
entitySet.add(bioEntity);
}
}
for (Iterator i = entitySet.iterator(); i.hasNext();) {
Item bioEntity = (Item) i.next();
//add attribute identifier for bioEntity
identifierAttribute = (String) bioEntity2IdentifierMap.get(
(String) bioEntity.getIdentifier());
if (identifier2BioEntity.containsKey(identifierAttribute)) {
Item anotherEntity = (Item) identifier2BioEntity.get(identifierAttribute);
List synonymList = new ArrayList();
if (anotherEntity.hasCollection("synonyms")) {
ReferenceList synonymList1 = anotherEntity.getCollection("synonyms");
for (Iterator k = synonymList1.getRefIds().iterator(); k.hasNext();) {
String refId = (String) k.next();
synonymList.add(refId);
}
}
if (bioEntity.hasCollection("synonyms")) {
ReferenceList synonymList2 = bioEntity.getCollection("synonyms");
String subject = anotherEntity.getIdentifier();
for (Iterator k = synonymList2.getRefIds().iterator(); k.hasNext();) {
String refId = (String) k.next();
if (!synonymList.contains(refId)) {
synonymList.add(refId);
}
//change subjectId for sysnonym when its bioentity is merged
Item synonym = (Item) synonymMap.get(refId);
String accession = synonym.getAttribute("value").getValue();
synonym.addReference(new Reference("subject", subject));
synonymAccessionMap.put(accession, synonym);
}
}
if (synonymList != null) {
anotherEntity.addCollection(new ReferenceList("synonyms", synonymList));
}
List maerList = new ArrayList();
if (anotherEntity.hasCollection("microArrayExperimentalResults")) {
ReferenceList maerList1 = anotherEntity.getCollection(
"microArrayExperimentalResults");
for (Iterator j = maerList1.getRefIds().iterator(); j.hasNext();) {
String refId = (String) j.next();
maerList.add(refId);
}
}
if (bioEntity.hasCollection("microArrayExperimentalResults")) {
ReferenceList maerList2 = bioEntity.getCollection(
"microArrayExperimentalResults");
for (Iterator j = maerList2.getRefIds().iterator(); j.hasNext();) {
String refId = (String) j.next();
if (!maerList.contains(refId)) {
maerList.add(refId);
}
}
}
if (maerList != null) {
anotherEntity.addCollection(new ReferenceList("microArrayExperimentalResults",
maerList));
}
identifier2BioEntity.put(identifierAttribute, anotherEntity);
bioEntityRefMap.put(bioEntity.getIdentifier(), anotherEntity.getIdentifier());
} else {
bioEntity.addAttribute(new Attribute("identifier", identifierAttribute));
identifier2BioEntity.put(identifierAttribute, bioEntity);
identifierSet.add(identifierAttribute);
}
}
for (Iterator i = identifierSet.iterator(); i.hasNext();) {
Item bioEntity = (Item) identifier2BioEntity.get((String) i.next());
results.add(bioEntity);
}
for (Iterator i = synonymAccession.iterator(); i.hasNext();) {
Item synonym = (Item) synonymAccessionMap.get((String) i.next());
results.add(synonym);
}
return results;
}
/**
* BioAssayDatum mage:FeatureId -> flymine:MAEResultId (MicroArrayExperimentalResult)
* Reporter flymine: BioEntityId -> mage:FeatureId
* BioSequece BioEntityId -> BioEntity Item
* -> extra Gene Item
* @return add microExperimentalResult collection to Gene item
*/
protected Set processGene2MAEResult() {
Set results = new HashSet();
Set destGene = new HashSet();
Set organismDbSet = new HashSet();
feature2Maer = new HashMap();
Map organismDbId2Gene = new HashMap();
feature2Maer = createFeature2MaerMap(maer2Feature, maerSet);
String organismDbId = null;
for (Iterator i = geneSet.iterator(); i.hasNext();) {
Item gene = (Item) i.next();
List maerIds = new ArrayList();
String geneId = (String) gene.getIdentifier();
String bioEntityId = (String) gene2BioEntity.get(geneId);
String s = (String) bioEntity2Feature.get(bioEntityId);
LOG.debug("featureId " + s + " bioEntityId " + bioEntityId + " geneId " + geneId);
if (s != null) {
StringTokenizer st = new StringTokenizer(s);
String multiMaer = null;
while (st.hasMoreTokens()) {
multiMaer = (String) feature2Maer.get(st.nextToken());
if (multiMaer != null) {
StringTokenizer token = new StringTokenizer(multiMaer);
while (token.hasMoreTokens()) {
maerIds.add(token.nextToken());
}
}
}
ReferenceList maerRl = new ReferenceList("microArrayExperimentalResults", maerIds);
gene.addCollection(maerRl);
destGene.add(gene);
}
}
for (Iterator i = destGene.iterator(); i.hasNext();) {
Item gene = (Item) i.next();
organismDbId = gene.getAttribute("organismDbId").getValue();
if (organismDbId2Gene.containsKey(organismDbId)) {
Item anotherGene = (Item) organismDbId2Gene.get(organismDbId);
List maerList = new ArrayList();
if (anotherGene.hasCollection("microArrayExperimentalResults")) {
ReferenceList maerList1 = anotherGene.getCollection(
"microArrayExperimentalResults");
for (Iterator j = maerList1.getRefIds().iterator(); j.hasNext();) {
String refId = (String) j.next();
maerList.add(refId);
}
}
if (gene.hasCollection("microArrayExperimentalResults")) {
ReferenceList maerList2 = gene.getCollection("microArrayExperimentalResults");
for (Iterator j = maerList2.getRefIds().iterator(); j.hasNext();) {
String refId = (String) j.next();
if (!maerList.contains(refId)) {
maerList.add(refId);
}
}
}
anotherGene.addCollection(new ReferenceList("microArrayExperimentalResults",
maerList));
organismDbId2Gene.put(organismDbId, anotherGene);
} else {
organismDbId2Gene.put(organismDbId, gene);
organismDbSet.add(organismDbId);
}
}
for (Iterator i = organismDbSet.iterator(); i.hasNext();) {
Item gene = (Item) organismDbId2Gene.get((String) i.next());
results.add(gene);
}
return results;
}
/**
* got reporterSet from setBioEntityMap()
* refererence material may be changed after processBioEntity2MAEResult()
* bioEntity is merged if it has the same identifierAttribute
* @return resutls with right material refid
*/
protected Set processReporterMaterial() {
Set results = new HashSet();
for (Iterator i = reporterSet.iterator(); i.hasNext();) {
Item reporter = (Item) i.next();
String bioEntityId = (String) reporter.getReference("material").getRefId();
if (bioEntityRefMap.containsKey("bioEntityId")) {
String newBioEntityId = (String) bioEntityRefMap.get("bioEntityId");
reporter.addReference(new Reference("material", newBioEntityId));
results.add(reporter);
} else {
results.add(reporter);
}
}
return results;
}
/**
* normalised attribute is added during MageConverter
* converting BioAssayDatum
* true for Derived BioAssayData
* false for Measured BioAssayData
* removed this attribute before translateItem
*/
private Item removeNormalisedAttribute(Item item) {
Item newItem = new Item();
newItem.setClassName(item.getClassName());
newItem.setIdentifier(item.getIdentifier());
newItem.setImplementations(item.getImplementations());
Iterator i = item.getAttributes().iterator();
while (i.hasNext()) {
Attribute attr = (Attribute) i.next();
if (!attr.getName().equals("normalised")) {
newItem.addAttribute(attr);
}
}
i = item.getReferences().iterator();
while (i.hasNext()) {
newItem.addReference((Reference) i.next());
}
i = item.getCollections().iterator();
while (i.hasNext()) {
newItem.addCollection((ReferenceList) i.next());
}
return newItem;
}
/**
* @param className = tgtClassName
* @param implementation = tgtClass implementation
* @param identifier = gene item identifier from database item identifier
* @param organismDbId = attribute for gene organismDbId
* @return gene item
*/
private Item createGene(String className, String implementation, String identifier,
String organismDbId) {
Item gene = new Item();
gene = createItem(className, implementation);
gene.setIdentifier(identifier);
gene.addAttribute(new Attribute("organismDbId", organismDbId));
return gene;
}
/**
* @param className = tgtClassName
* @param implementation = tgtClass implementation
* @param value = attribute for organism name
* @return organism item
*/
private Item createOrganism(String className, String implementation, String value) {
Item organism = new Item();
if (!organismMap.containsKey("value")) {
organism = createItem(className, implementation);
organism.addAttribute(new Attribute("name", value));
organismMap.put("value", organism);
} else {
organism = (Item) organismMap.get("value");
}
return organism;
}
/**
* main method
* @param args command line arguments
* @throws Exception if something goes wrong
*/
public static void main (String[] args) throws Exception {
String srcOsName = args[0];
String tgtOswName = args[1];
String modelName = args[2];
String format = args[3];
String namespace = args[4];
Map paths = new HashMap();
HashSet descSet = new HashSet();
ItemPrefetchDescriptor desc1 = new ItemPrefetchDescriptor(
"(FeatureGroup <- Feature.featureGroup)");
desc1.addConstraint(new ItemPrefetchConstraintDynamic(
ObjectStoreItemPathFollowingImpl.IDENTIFIER,
"featureGroup"));
desc1.addConstraint(new FieldNameAndValue(ObjectStoreItemPathFollowingImpl.CLASSNAME,
"http://www.flymine.org/model/mage#Feature", false));
paths.put("http://www.flymine.org/model/mage#FeatureGroup", Collections.singleton(desc1));
// BioAssayDatum.quantitationType.scale
desc1 = new ItemPrefetchDescriptor("BioAssayDatum.quantitationType");
desc1.addConstraint(new ItemPrefetchConstraintDynamic("quantitationType",
ObjectStoreItemPathFollowingImpl.IDENTIFIER));
ItemPrefetchDescriptor desc2 = new ItemPrefetchDescriptor(
"(BioAssayDatum.quantitationType).scale");
desc2.addConstraint(new ItemPrefetchConstraintDynamic("scale",
ObjectStoreItemPathFollowingImpl.IDENTIFIER));
desc1.addPath(desc2);
descSet.add(desc1);
// BioAssayDatum.quantitationType.targetQuantitationType.scale
ItemPrefetchDescriptor desc3 = new ItemPrefetchDescriptor(
"(BioAssayDatum.quantitationType).targetQuantitationType");
desc3.addConstraint(new ItemPrefetchConstraintDynamic(
"targetQuantitationType", ObjectStoreItemPathFollowingImpl.IDENTIFIER));
ItemPrefetchDescriptor desc4 = new ItemPrefetchDescriptor(
"(BioAssayDatum.quantitationType.targetQuantitationType).scale");
desc4.addConstraint(new ItemPrefetchConstraintDynamic("scale",
ObjectStoreItemPathFollowingImpl.IDENTIFIER));
desc3.addPath(desc4);
desc1.addPath(desc3);
descSet.add(desc1);
//paths.put("http://www.flymine.org/model/mage#BioAssayDatum",Collections.singleton(desc1));
paths.put("http://www.flymine.org/model/mage#BioAssayDatum", descSet);
// BioSequence...
descSet = new HashSet();
// BioSequence.type
desc1 = new ItemPrefetchDescriptor("BioSequence.type");
desc1.addConstraint(new ItemPrefetchConstraintDynamic("type",
ObjectStoreItemPathFollowingImpl.IDENTIFIER));
descSet.add(desc1);
// BioSequence.sequenceDatabases.database
desc1 = new ItemPrefetchDescriptor("BioSequence.sequenceDatabases");
desc1.addConstraint(new ItemPrefetchConstraintDynamic("sequenceDatabases",
ObjectStoreItemPathFollowingImpl.IDENTIFIER));
desc2 = new ItemPrefetchDescriptor("(BioSequence.sequenceDatabases).database");
desc2.addConstraint(new ItemPrefetchConstraintDynamic("database",
ObjectStoreItemPathFollowingImpl.IDENTIFIER));
desc1.addPath(desc2);
descSet.add(desc1);
paths.put("http://www.flymine.org/model/mage#BioSequence", descSet);
// LabeledExtract...
descSet = new HashSet();
// LabeledExtract.materialType
desc1 = new ItemPrefetchDescriptor("LabeledExtract.materialType");
desc1.addConstraint(new ItemPrefetchConstraintDynamic("materialType",
ObjectStoreItemPathFollowingImpl.IDENTIFIER));
descSet.add(desc1);
// LabeledExtract.labels
desc1 = new ItemPrefetchDescriptor("LabeledExtract.labels");
desc1.addConstraint(new ItemPrefetchConstraintDynamic("labels",
ObjectStoreItemPathFollowingImpl.IDENTIFIER));
descSet.add(desc1);
// code descends through treatments in a loop - prefetch can't handle
// that so need to define cutoff (??)
// LabeledExtract.treatments.sourceBioMaterialMeasurements.bioMaterial.treatments
// .sourceBioMaterialMeasurements.bioMaterial.treatments
desc1 = new ItemPrefetchDescriptor("LabeledExtract.treatments");
desc1.addConstraint(new ItemPrefetchConstraintDynamic("treatments",
ObjectStoreItemPathFollowingImpl.IDENTIFIER));
desc2 = new ItemPrefetchDescriptor(
"(LabeledExtract.treatments).sourceBioMaterialMeasurements");
desc2.addConstraint(new ItemPrefetchConstraintDynamic("bioMaterialMeasurements",
ObjectStoreItemPathFollowingImpl.IDENTIFIER));
desc3 = new ItemPrefetchDescriptor(
"((LabeledExtract.treatments).sourceBioMaterialMeasurements).bioMaterial");
desc3.addConstraint(new ItemPrefetchConstraintDynamic("bioMaterial",
ObjectStoreItemPathFollowingImpl.IDENTIFIER));
desc4 = new ItemPrefetchDescriptor(
"(((LabeledExtract.treatments).sourceBioMaterialMeasurements).bioMaterial).treatments");
desc4.addConstraint(new ItemPrefetchConstraintDynamic("treatments",
ObjectStoreItemPathFollowingImpl.IDENTIFIER));
ItemPrefetchDescriptor desc5 = new ItemPrefetchDescriptor(
"(...).sourceBioMaterialMeasurements");
desc5.addConstraint(new ItemPrefetchConstraintDynamic("sorceBioMaterialMeasurements",
ObjectStoreItemPathFollowingImpl.IDENTIFIER));
ItemPrefetchDescriptor desc6 = new ItemPrefetchDescriptor(
"((...).sourceBioMaterialMeasurements).bioMaterial");
desc6.addConstraint(new ItemPrefetchConstraintDynamic("bioMaterial",
ObjectStoreItemPathFollowingImpl.IDENTIFIER));
ItemPrefetchDescriptor desc7 = new ItemPrefetchDescriptor(
"(((...).sourceBioMaterialMeasurements).bioMaterial).treatments");
desc7.addConstraint(new ItemPrefetchConstraintDynamic("treatments",
ObjectStoreItemPathFollowingImpl.IDENTIFIER));
desc6.addPath(desc7);
desc5.addPath(desc6);
desc4.addPath(desc5);
desc3.addPath(desc4);
desc2.addPath(desc3);
desc1.addPath(desc2);
descSet.add(desc1);
paths.put("http://www.flymine.org/model/mage#LabeledExtract", descSet);
// BioSource...
descSet = new HashSet();
// BioSource.materialType
desc1 = new ItemPrefetchDescriptor("BioSource.materialType");
desc1.addConstraint(new ItemPrefetchConstraintDynamic("materialType",
ObjectStoreItemPathFollowingImpl.IDENTIFIER));
descSet.add(desc1);
// BioSource.characteristics
desc1 = new ItemPrefetchDescriptor("BioSource.characteristics");
desc1.addConstraint(new ItemPrefetchConstraintDynamic("characteristics",
ObjectStoreItemPathFollowingImpl.IDENTIFIER));
descSet.add(desc1);
paths.put("http://www.flymine.org/model/mage#BioSource", descSet);
// Treatment.action
desc1 = new ItemPrefetchDescriptor("Treatment.action");
desc1.addConstraint(new ItemPrefetchConstraintDynamic(
ObjectStoreItemPathFollowingImpl.IDENTIFIER, "action"));
paths.put("http://www.flymine.org/model/mage#Treatment",
Collections.singleton(desc1));
// new prefetch with collections
// FeatureReporterMap->featureInformationSources->feature->featureLocation
descSet = new HashSet();
desc1 = new ItemPrefetchDescriptor("FeatureReporterMap.featureInformaionSources");
desc1.addConstraint(new ItemPrefetchConstraintDynamic("featureInformationSources",
ObjectStoreItemPathFollowingImpl.IDENTIFIER));
desc2 = new ItemPrefetchDescriptor(
"(FeatureReporterMap.featureInformaionSources).feature");
desc2.addConstraint(new ItemPrefetchConstraintDynamic("feature",
ObjectStoreItemPathFollowingImpl.IDENTIFIER));
desc3 = new ItemPrefetchDescriptor(
"((FeatureReporterMap.featureInformaionSources).feature).featureLocation");
desc3.addConstraint(new ItemPrefetchConstraintDynamic("featureLocation",
ObjectStoreItemPathFollowingImpl.IDENTIFIER));
desc1.addPath(desc2);
desc2.addPath(desc3);
//descSet.add(desc1); required?
// FeatureReporterMap->featureInformationSources->feature->zone
desc4 = new ItemPrefetchDescriptor(
"((FeatureReporterMap.featureInformaionSources).feature).zone");
desc4.addConstraint(new ItemPrefetchConstraintDynamic("zone",
ObjectStoreItemPathFollowingImpl.IDENTIFIER));
desc2.addPath(desc4);
descSet.add(desc1);
paths.put("http://www.flymine.org/model/mage#FeatureReporterMap", descSet);
// PhysicalArrayDesign...
descSet = new HashSet();
// PhysicalArrayDesign->featureGroups
desc1 = new ItemPrefetchDescriptor("PhysicalArrayDesign.featureGroups");
desc1.addConstraint(new ItemPrefetchConstraintDynamic("featureGroups",
ObjectStoreItemPathFollowingImpl.IDENTIFIER));
descSet.add(desc1);
// PhysicalArrayDesign->surfaceType
desc1 = new ItemPrefetchDescriptor("PhysicalArrayDesign.surfaceType");
desc1.addConstraint(new ItemPrefetchConstraintDynamic("surfaceType",
ObjectStoreItemPathFollowingImpl.IDENTIFIER));
descSet.add(desc1);
// PhysicalArrayDesign->descriptions
desc1 = new ItemPrefetchDescriptor("PhysicalArrayDesign.descriptions");
desc1.addConstraint(new ItemPrefetchConstraintDynamic("descripions",
ObjectStoreItemPathFollowingImpl.IDENTIFIER));
descSet.add(desc1);
paths.put("http://www.flymine.org/model/mage#PhysicalArrayDesign", descSet);
// Reporter...
descSet = new HashSet();
// Reporter <- FeatureReporterMap.reporter
desc1 = new ItemPrefetchDescriptor("(Reporter <- FeatureReporterMap.reporter)");
desc1.addConstraint(new ItemPrefetchConstraintDynamic(
ObjectStoreItemPathFollowingImpl.IDENTIFIER, "reporter"));
desc1.addConstraint(new FieldNameAndValue(ObjectStoreItemPathFollowingImpl.CLASSNAME,
"http://www.flymine.org/model/mage#FeatureReporterMap", false));
descSet.add(desc1);
// Reporter->failTypes
desc1 = new ItemPrefetchDescriptor("Reporter.failTypes");
desc1.addConstraint(new ItemPrefetchConstraintDynamic("failTypes",
ObjectStoreItemPathFollowingImpl.IDENTIFIER));
descSet.add(desc1);
// Reporter->controlType
desc1 = new ItemPrefetchDescriptor("Reporter.controlType");
desc1.addConstraint(new ItemPrefetchConstraintDynamic("controlType",
ObjectStoreItemPathFollowingImpl.IDENTIFIER));
descSet.add(desc1);
// Reporter->immobilizedCharacteristics->type
desc1 = new ItemPrefetchDescriptor("Reporter.immobilizedCharacteristics");
desc1.addConstraint(new ItemPrefetchConstraintDynamic("immobilizedCharacteristics",
ObjectStoreItemPathFollowingImpl.IDENTIFIER));
desc2 = new ItemPrefetchDescriptor(
"(Reporter.immobilizedCharacteristics).type");
desc2.addConstraint(new ItemPrefetchConstraintDynamic("type",
ObjectStoreItemPathFollowingImpl.IDENTIFIER));
desc1.addPath(desc2);
descSet.add(desc1);
// Reporter->descriptions
desc1 = new ItemPrefetchDescriptor("Reporter.descriptions");
desc1.addConstraint(new ItemPrefetchConstraintDynamic("descriptions",
ObjectStoreItemPathFollowingImpl.IDENTIFIER));
descSet.add(desc1);
// Reporter->featureReporterMaps->featureInformationSources
desc1 = new ItemPrefetchDescriptor("Reporter.featureReporterMaps");
desc1.addConstraint(new ItemPrefetchConstraintDynamic("featureReporterMaps",
ObjectStoreItemPathFollowingImpl.IDENTIFIER));
desc2 = new ItemPrefetchDescriptor(
"(Reporter.featureReporterMaps).featureInformationSources");
desc2.addConstraint(new ItemPrefetchConstraintDynamic("featureInformationSources",
ObjectStoreItemPathFollowingImpl.IDENTIFIER));
desc1.addPath(desc2);
descSet.add(desc1);
paths.put("http://www.flymine.org/model/mage#Reporter", descSet);
// Experiment...
descSet = new HashSet();
// Experiment->bioAssays
desc1 = new ItemPrefetchDescriptor("Experiment.bioAssays");
desc1.addConstraint(new ItemPrefetchConstraintDynamic("bioAssays",
ObjectStoreItemPathFollowingImpl.IDENTIFIER));
descSet.add(desc1);
// Experiment.descriptions
desc1 = new ItemPrefetchDescriptor("Experiment.descriptions");
desc1.addConstraint(new ItemPrefetchConstraintDynamic("descriptions",
ObjectStoreItemPathFollowingImpl.IDENTIFIER));
descSet.add(desc1);
paths.put("http://www.flymine.org/model/mage#Experiment", descSet);
// DerivedBioAssay.derivedBioAssayData.bioDataValues.
desc1 = new ItemPrefetchDescriptor("DerivedBioAssay.derivedBioAssayData");
desc1.addConstraint(new ItemPrefetchConstraintDynamic("derivedBioAssayData",
ObjectStoreItemPathFollowingImpl.IDENTIFIER));
desc2 = new ItemPrefetchDescriptor(
"(DerivedBioAssay.derivedBioAssayData).bioDataValues");
desc2.addConstraint(new ItemPrefetchConstraintDynamic("bioDataValues",
ObjectStoreItemPathFollowingImpl.IDENTIFIER));
desc1.addPath(desc2);
descSet.add(desc1);
paths.put("http://www.flymine.org/model/mage#DerivedBioAssay",
Collections.singleton(desc1));
ObjectStore osSrc = ObjectStoreFactory.getObjectStore(srcOsName);
ItemReader srcItemReader = new ObjectStoreItemReader(osSrc, paths);
ObjectStoreWriter oswTgt = ObjectStoreWriterFactory.getObjectStoreWriter(tgtOswName);
ItemWriter tgtItemWriter = new ObjectStoreItemWriter(oswTgt);
OntModel model = ModelFactory.createOntologyModel();
model.read(new FileReader(new File(modelName)), null, format);
DataTranslator dt = new MageDataTranslator(srcItemReader, model, namespace);
model = null;
dt.translate(tgtItemWriter);
tgtItemWriter.close();
}
}
|
package benchmark.web;
import benchmark.model.Fortune;
import benchmark.model.World;
import benchmark.repository.DbRepository;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import static java.util.Comparator.comparing;
@Component
public class WebfluxHandler {
private final DbRepository dbRepository;
public WebfluxHandler(DbRepository dbRepository) {
this.dbRepository = dbRepository;
}
public Mono<ServerResponse> plaintext(ServerRequest request) {
return ServerResponse.ok()
.contentType(MediaType.TEXT_PLAIN)
.body(Mono.just("Hello, World!"), String.class);
}
public Mono<ServerResponse> json(ServerRequest request) {
return ServerResponse.ok()
.contentType(MediaType.APPLICATION_JSON)
.body(Mono.just(Map.of("message", "Hello, World!")), Map.class);
}
public Mono<ServerResponse> db(ServerRequest request) {
int id = randomWorldNumber();
Mono<World> world = dbRepository.getWorld(id)
.switchIfEmpty(Mono.error(new Exception("No World found with Id: " + id)));
return ServerResponse.ok()
.contentType(MediaType.APPLICATION_JSON)
.body(world, World.class);
}
public Mono<ServerResponse> queries(ServerRequest request) {
int queries = getQueries(request);
Mono<List<World>> worlds = Flux.range(0, queries)
.flatMap(i -> dbRepository.getWorld(randomWorldNumber()))
.collectList();
return ServerResponse.ok()
.contentType(MediaType.APPLICATION_JSON)
.body(worlds, new ParameterizedTypeReference<List<World>>() {
});
}
private static int parseQueryCount(Optional<String> maybeTextValue) {
if (!maybeTextValue.isPresent()) {
return 1;
}
int parsedValue;
try {
parsedValue = Integer.parseInt(maybeTextValue.get());
} catch (NumberFormatException e) {
return 1;
}
return Math.min(500, Math.max(1, parsedValue));
}
public Mono<ServerResponse> updates(ServerRequest request) {
int queries = getQueries(request);
Mono<List<World>> worlds = Flux.range(0, queries)
.flatMap(i -> dbRepository.findAndUpdateWorld(randomWorldNumber(), randomWorldNumber()))
.collectList();
return ServerResponse.ok()
.contentType(MediaType.APPLICATION_JSON)
.body(worlds, new ParameterizedTypeReference<List<World>>() {
});
}
public Mono<ServerResponse> fortunes(ServerRequest request) {
Mono<List<Fortune>> result = dbRepository.fortunes().collectList().flatMap(fortunes -> {
fortunes.add(new Fortune(0, "Additional fortune added at request time."));
fortunes.sort(comparing(fortune -> fortune.message));
return Mono.just(fortunes);
});
return ServerResponse.ok()
.render("fortunes", Collections.singletonMap("fortunes", result));
}
private static int getQueries(ServerRequest request) {
return parseQueryCount(request.queryParam("queries"));
}
private static int randomWorldNumber() {
return 1 + ThreadLocalRandom.current().nextInt(10000);
}
}
|
package org.voltdb.utils;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeMap;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import org.voltdb.VoltDB;
import org.voltdb.VoltTable;
import org.voltdb.VoltType;
import org.voltdb.catalog.Catalog;
import org.voltdb.catalog.CatalogMap;
import org.voltdb.catalog.CatalogType;
import org.voltdb.catalog.Cluster;
import org.voltdb.catalog.Column;
import org.voltdb.catalog.ColumnRef;
import org.voltdb.catalog.Constraint;
import org.voltdb.catalog.ConstraintRef;
import org.voltdb.catalog.Database;
import org.voltdb.catalog.Group;
import org.voltdb.catalog.GroupRef;
import org.voltdb.catalog.Index;
import org.voltdb.catalog.PlanFragment;
import org.voltdb.catalog.Table;
import org.voltdb.compiler.ClusterCompiler;
import org.voltdb.compiler.ClusterConfig;
import org.voltdb.compiler.deploymentfile.ClusterType;
import org.voltdb.compiler.deploymentfile.DeploymentType;
import org.voltdb.compiler.deploymentfile.UsersType;
import org.voltdb.logging.Level;
import org.voltdb.logging.VoltLogger;
import org.voltdb.types.ConstraintType;
import org.voltdb.types.IndexType;
import org.xml.sax.SAXException;
public abstract class CatalogUtil {
private static final VoltLogger hostLog = new VoltLogger("HOST");
public static final String CATALOG_FILENAME = "catalog.txt";
public static String loadCatalogFromJar(String pathToCatalog, VoltLogger log) {
assert(pathToCatalog != null);
String serializedCatalog = null;
try {
InMemoryJarfile jarfile = new InMemoryJarfile(pathToCatalog);
byte[] serializedCatalogBytes = jarfile.get(CATALOG_FILENAME);
serializedCatalog = new String(serializedCatalogBytes, "UTF-8");
} catch (Exception e) {
if (log != null)
log.l7dlog( Level.FATAL, LogKeys.host_VoltDB_CatalogReadFailure.name(), e);
return null;
}
return serializedCatalog;
}
/**
* Get a unique id for a plan fragment by munging the indices of it's parents
* and grandparents in the catalog.
*
* @param frag Catalog fragment to identify
* @return unique id for fragment
*/
public static long getUniqueIdForFragment(PlanFragment frag) {
long retval = 0;
CatalogType parent = frag.getParent();
retval = ((long) parent.getParent().getRelativeIndex()) << 32;
retval += ((long) parent.getRelativeIndex()) << 16;
retval += frag.getRelativeIndex();
return retval;
}
/**
*
* @param catalogTable
* @return An empty table with the same schema as a given catalog table.
*/
public static VoltTable getVoltTable(Table catalogTable) {
List<Column> catalogColumns = CatalogUtil.getSortedCatalogItems(catalogTable.getColumns(), "index");
VoltTable.ColumnInfo[] columns = new VoltTable.ColumnInfo[catalogColumns.size()];
int i = 0;
for (Column catCol : catalogColumns) {
columns[i++] = new VoltTable.ColumnInfo(catCol.getTypeName(), VoltType.get((byte)catCol.getType()));
}
return new VoltTable(columns);
}
/**
* Given a set of catalog items, return a sorted list of them, sorted by
* the value of a specified field. The field is specified by name. If the
* field doesn't exist, trip an assertion. This is primarily used to sort
* a table's columns or a procedure's parameters.
*
* @param <T> The type of item to sort.
* @param items The set of catalog items.
* @param sortFieldName The name of the field to sort on.
* @return A list of catalog items, sorted on the specified field.
*/
public static <T extends CatalogType> List<T> getSortedCatalogItems(CatalogMap<T> items, String sortFieldName) {
assert(items != null);
assert(sortFieldName != null);
// build a treemap based on the field value
TreeMap<Object, T> map = new TreeMap<Object, T>();
boolean hasField = false;
for (T item : items) {
// check the first time through for the field
if (hasField == false)
hasField = item.getFields().contains(sortFieldName);
assert(hasField == true);
map.put(item.getField(sortFieldName), item);
}
// create a sorted list from the map
ArrayList<T> retval = new ArrayList<T>();
for (T item : map.values()) {
retval.add(item);
}
return retval;
}
/**
* For a given Table catalog object, return the PrimaryKey Index catalog object
* @param catalogTable
* @return The index representing the primary key.
* @throws Exception if the table does not define a primary key
*/
public static Index getPrimaryKeyIndex(Table catalogTable) throws Exception {
// We first need to find the pkey constraint
Constraint catalog_constraint = null;
for (Constraint c : catalogTable.getConstraints()) {
if (c.getType() == ConstraintType.PRIMARY_KEY.getValue()) {
catalog_constraint = c;
break;
}
}
if (catalog_constraint == null) {
throw new Exception("ERROR: Table '" + catalogTable.getTypeName() + "' does not have a PRIMARY KEY constraint");
}
// And then grab the index that it is using
return (catalog_constraint.getIndex());
}
/**
* Return all the of the primary key columns for a particular table
* If the table does not have a primary key, then the returned list will be empty
* @param catalogTable
* @return An ordered list of the primary key columns
*/
public static Collection<Column> getPrimaryKeyColumns(Table catalogTable) {
Collection<Column> columns = new ArrayList<Column>();
Index catalog_idx = null;
try {
catalog_idx = CatalogUtil.getPrimaryKeyIndex(catalogTable);
} catch (Exception ex) {
// IGNORE
return (columns);
}
assert(catalog_idx != null);
for (ColumnRef catalog_col_ref : getSortedCatalogItems(catalog_idx.getColumns(), "index")) {
columns.add(catalog_col_ref.getColumn());
}
return (columns);
}
/**
* Convert a Table catalog object into the proper SQL DDL, including all indexes,
* constraints, and foreign key references.
* @param catalog_tbl
* @return SQL Schema text representing the table.
*/
public static String toSchema(Table catalog_tbl) {
assert(!catalog_tbl.getColumns().isEmpty());
final String spacer = " ";
Set<Index> skip_indexes = new HashSet<Index>();
Set<Constraint> skip_constraints = new HashSet<Constraint>();
String ret = "CREATE TABLE " + catalog_tbl.getTypeName() + " (";
// Columns
String add = "\n";
for (Column catalog_col : CatalogUtil.getSortedCatalogItems(catalog_tbl.getColumns(), "index")) {
VoltType col_type = VoltType.get((byte)catalog_col.getType());
// this next assert would be great if we dealt with default values well
//assert(! ((catalog_col.getDefaultvalue() == null) && (catalog_col.getNullable() == false) ) );
ret += add + spacer + catalog_col.getTypeName() + " " +
col_type.toSQLString() +
(col_type == VoltType.STRING && catalog_col.getSize() > 0 ? "(" + catalog_col.getSize() + ")" : "");
// Default value
String defaultvalue = catalog_col.getDefaultvalue();
//VoltType defaulttype = VoltType.get((byte)catalog_col.getDefaulttype());
boolean nullable = catalog_col.getNullable();
// TODO: Shouldn't have to check whether the string contains "null"
if (defaultvalue != null && defaultvalue.toLowerCase().equals("null") && nullable) {
defaultvalue = null;
}
else { // XXX: if (defaulttype != VoltType.VOLTFUNCTION) {
// TODO: Escape strings properly
defaultvalue = "'" + defaultvalue + "'";
}
ret += " DEFAULT " + (defaultvalue != null ? defaultvalue : "NULL") +
(!nullable ? " NOT NULL" : "");
// Single-column constraints
for (ConstraintRef catalog_const_ref : catalog_col.getConstraints()) {
Constraint catalog_const = catalog_const_ref.getConstraint();
ConstraintType const_type = ConstraintType.get(catalog_const.getType());
// Check if there is another column in our table with the same constraint
// If there is, then we need to add it to the end of the table definition
boolean found = false;
for (Column catalog_other_col : catalog_tbl.getColumns()) {
if (catalog_other_col.equals(catalog_col)) continue;
if (catalog_other_col.getConstraints().getIgnoreCase(catalog_const.getTypeName()) != null) {
found = true;
break;
}
}
if (!found) {
switch (const_type) {
case FOREIGN_KEY: {
Table catalog_fkey_tbl = catalog_const.getForeignkeytable();
Column catalog_fkey_col = null;
for (ColumnRef ref : catalog_const.getForeignkeycols()) {
catalog_fkey_col = ref.getColumn();
break; // Nasty hack to get first item
}
assert(catalog_fkey_col != null);
ret += " REFERENCES " + catalog_fkey_tbl.getTypeName() + " (" + catalog_fkey_col.getTypeName() + ")";
skip_constraints.add(catalog_const);
break;
}
default:
// Nothing for now
}
}
}
add = ",\n";
}
// Constraints
for (Constraint catalog_const : catalog_tbl.getConstraints()) {
if (skip_constraints.contains(catalog_const)) continue;
ConstraintType const_type = ConstraintType.get(catalog_const.getType());
// Primary Keys / Unique Constraints
if (const_type == ConstraintType.PRIMARY_KEY || const_type == ConstraintType.UNIQUE) {
Index catalog_idx = catalog_const.getIndex();
IndexType idx_type = IndexType.get(catalog_idx.getType());
String idx_suffix = idx_type.getSQLSuffix();
ret += add + spacer +
(!idx_suffix.isEmpty() ? "CONSTRAINT " + catalog_const.getTypeName() + " " : "") +
(const_type == ConstraintType.PRIMARY_KEY ? "PRIMARY KEY" : "UNIQUE") + " (";
String col_add = "";
for (ColumnRef catalog_colref : CatalogUtil.getSortedCatalogItems(catalog_idx.getColumns(), "index")) {
ret += col_add + catalog_colref.getColumn().getTypeName();
col_add = ", ";
} // FOR
ret += ")";
skip_indexes.add(catalog_idx);
// Foreign Key
} else if (const_type == ConstraintType.FOREIGN_KEY) {
Table catalog_fkey_tbl = catalog_const.getForeignkeytable();
String col_add = "";
String our_columns = "";
String fkey_columns = "";
for (ColumnRef catalog_colref : catalog_const.getForeignkeycols()) {
// The name of the ColumnRef is the column in our base table
Column our_column = catalog_tbl.getColumns().getIgnoreCase(catalog_colref.getTypeName());
assert(our_column != null);
our_columns += col_add + our_column.getTypeName();
Column fkey_column = catalog_colref.getColumn();
assert(fkey_column != null);
fkey_columns += col_add + fkey_column.getTypeName();
col_add = ", ";
}
ret += add + spacer + "CONSTRAINT " + catalog_const.getTypeName() + " " +
"FOREIGN KEY (" + our_columns + ") " +
"REFERENCES " + catalog_fkey_tbl.getTypeName() + " (" + fkey_columns + ")";
}
skip_constraints.add(catalog_const);
}
ret += "\n);\n";
// All other Indexes
for (Index catalog_idx : catalog_tbl.getIndexes()) {
if (skip_indexes.contains(catalog_idx)) continue;
ret += "CREATE INDEX " + catalog_idx.getTypeName() +
" ON " + catalog_tbl.getTypeName() + " (";
add = "";
for (ColumnRef catalog_colref : CatalogUtil.getSortedCatalogItems(catalog_idx.getColumns(), "index")) {
ret += add + catalog_colref.getColumn().getTypeName();
add = ", ";
}
ret += ");\n";
}
return ret;
}
/**
* Return true if a table is a streamed / export-only table
* This function is duplicated in CatalogUtil.h
* @param database
* @param table
* @return true if a table is export-only or false otherwise
*/
public static boolean isTableExportOnly(org.voltdb.catalog.Database database,
org.voltdb.catalog.Table table)
{
// no export, no export only tables
if (database.getConnectors().size() == 0) {
return false;
}
// there is one well-known-named connector
org.voltdb.catalog.Connector connector = database.getConnectors().get("0");
// iterate the connector tableinfo list looking for tableIndex
// tableInfo has a reference to a table - can compare the reference
// to the desired table by looking at the relative index. ick.
for (org.voltdb.catalog.ConnectorTableInfo tableInfo : connector.getTableinfo()) {
if (tableInfo.getTable().getRelativeIndex() == table.getRelativeIndex()) {
return tableInfo.getAppendonly();
}
}
return false;
}
/**
* Return true if a table is the source table for a materialized view.
*/
public static boolean isTableMaterializeViewSource(org.voltdb.catalog.Database database,
org.voltdb.catalog.Table table)
{
CatalogMap<Table> tables = database.getTables();
for (Table t : tables) {
Table matsrc = t.getMaterializer();
if ((matsrc != null) && (matsrc.getRelativeIndex() == table.getRelativeIndex())) {
return true;
}
}
return false;
}
/**
* Parse the deployment.xml file and add its data into the catalog.
* @param catalog Catalog to be updated.
* @param pathToDeployment Path to the deployment.xml file.
*/
public static boolean compileDeployment(Catalog catalog, String deploymentURL) {
DeploymentType deployment = parseDeployment(deploymentURL);
// wasn't a valid xml deployment file
if (deployment == null) {
hostLog.error("Not a valid XML deployment file at URL: " + deploymentURL);
return false;
}
if (!validateDeployment(catalog, deployment)) {
return false;
}
// set the cluster info
setClusterInfo(catalog, deployment.getCluster());
// set the users info
setUsersInfo(catalog, deployment.getUsers());
return true;
}
/**
* Parses the deployment XML file.
* @param deploymentURL Path to the deployment.xml file.
* @return a reference to the root <deployment> element.
*/
public static DeploymentType parseDeployment(String deploymentURL) {
// get the URL/path for the deployment and prep an InputStream
InputStream deployIS = null;
try {
URL deployURL = new URL(deploymentURL);
deployIS = deployURL.openStream();
} catch (MalformedURLException ex) {
// Invalid URL. Try as a file.
try {
deployIS = new FileInputStream(deploymentURL);
} catch (FileNotFoundException e) {
deployIS = null;
}
} catch (IOException ioex) {
deployIS = null;
}
// make sure the file exists
if (deployIS == null) {
hostLog.error("Could not locate deployment info at given URL: " + deploymentURL);
return null;
} else {
hostLog.info("URL of deployment info: " + deploymentURL);
}
// get deployment info from xml file
return getDeployment(deployIS);
}
/**
* Get a reference to the root <deployment> element from the deployment.xml file.
* @param pathToDeployment Path to the deployment.xml file.
* @return Returns a reference to the root <deployment> element.
*/
@SuppressWarnings("unchecked")
private static DeploymentType getDeployment(InputStream deployIS) {
try {
JAXBContext jc = JAXBContext.newInstance("org.voltdb.compiler.deploymentfile");
// This schema shot the sheriff.
SchemaFactory sf = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
// This is ugly, but I couldn't get CatalogUtil.class.getResource("../compiler/DeploymentFileSchema.xsd")
// to work and gave up.
Schema schema = sf.newSchema(VoltDB.class.getResource("compiler/DeploymentFileSchema.xsd"));
Unmarshaller unmarshaller = jc.createUnmarshaller();
// But did not shoot unmarshaller!
unmarshaller.setSchema(schema);
JAXBElement<DeploymentType> result =
(JAXBElement<DeploymentType>) unmarshaller.unmarshal(deployIS);
DeploymentType deployment = result.getValue();
return deployment;
} catch (JAXBException e) {
// Convert some linked exceptions to more friendly errors.
if (e.getLinkedException() instanceof java.io.FileNotFoundException) {
hostLog.error(e.getLinkedException().getMessage());
return null;
} else if (e.getLinkedException() instanceof org.xml.sax.SAXParseException) {
hostLog.error("Error schema validating deployment.xml file. " + e.getLinkedException().getMessage());
return null;
} else {
throw new RuntimeException(e);
}
} catch (SAXException e) {
hostLog.error("Error schema validating deployment.xml file. " + e.getMessage());
return null;
}
}
/**
* Validate the contents of the deployment.xml file. This is for things like making sure users aren't being added to
* non-existent groups, not for validating XML syntax.
* @param catalog Catalog to be validated against.
* @param deployment Reference to root <deployment> element of deployment file to be validated.
* @return Returns true if the deployment file is valid.
*/
private static boolean validateDeployment(Catalog catalog, DeploymentType deployment) {
if (deployment.getUsers() == null) {
return true;
}
Cluster cluster = catalog.getClusters().get("cluster");
Database database = cluster.getDatabases().get("database");
Set<String> validGroups = new HashSet<String>();
for (Group group : database.getGroups()) {
validGroups.add(group.getTypeName());
}
for (UsersType.User user : deployment.getUsers().getUser()) {
if (user.getGroups() == null)
continue;
for (String group : user.getGroups().split(",")) {
group = group.trim();
if (!validGroups.contains(group)) {
hostLog.error("Cannot assign user \"" + user.getName() + "\" to non-existent group \"" + group +
"\"");
return false;
}
}
}
return true;
}
/**
* Set cluster info in the catalog.
* @param catalog The catalog to be updated.
* @param cluster A reference to the <cluster> element of the deployment.xml file.
*/
private static void setClusterInfo(Catalog catalog, ClusterType cluster) {
int hostCount = cluster.getHostcount();
int sitesPerHost = cluster.getSitesperhost();
String leader = cluster.getLeader();
int kFactor = cluster.getKfactor();
ClusterConfig config = new ClusterConfig(hostCount, sitesPerHost, kFactor, leader);
hostLog.l7dlog(Level.INFO, LogKeys.compiler_VoltCompiler_LeaderAndHostCountAndSitesPerHost.name(),
new Object[] {config.getLeaderAddress(), config.getHostCount(), config.getSitesPerHost()}, null);
if (!config.validate()) {
hostLog.error(config.getErrorMsg());
} else {
ClusterCompiler.compile(catalog, config);
}
}
/**
* Set user info in the catalog.
* @param catalog The catalog to be updated.
* @param users A reference to the <users> element of the deployment.xml file.
*/
private static void setUsersInfo(Catalog catalog, UsersType users) {
if (users == null) {
return;
}
// TODO: The database name is not available in deployment.xml (it is defined in project.xml). However, it must
// always be named "database", so I've temporarily hardcoded it here until a more robust solution is available.
Database db = catalog.getClusters().get("cluster").getDatabases().get("database");
for (UsersType.User user : users.getUser()) {
org.voltdb.catalog.User catUser = db.getUsers().add(user.getName());
byte passwordHash[] = extractPassword(user.getPassword());
catUser.setShadowpassword(Encoder.hexEncode(passwordHash));
// process the @groups comma separated list
if (user.getGroups() != null) {
String grouplist[] = user.getGroups().split(",");
for (final String group : grouplist) {
final GroupRef groupRef = catUser.getGroups().add(group);
final Group catalogGroup = db.getGroups().get(group);
if (catalogGroup != null) {
groupRef.setGroup(catalogGroup);
}
}
}
}
}
/** Read a hashed password from password. */
private static byte[] extractPassword(String password) {
MessageDigest md = null;
try {
md = MessageDigest.getInstance("SHA-1");
} catch (final NoSuchAlgorithmException e) {
hostLog.l7dlog(Level.FATAL, LogKeys.compiler_VoltCompiler_NoSuchAlgorithm.name(), e);
System.exit(-1);
}
final byte passwordHash[] = md.digest(md.digest(password.getBytes()));
return passwordHash;
}
}
|
package tcking.github.com.giraffeplayer;
import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.media.AudioManager;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.OrientationEventListener;
import android.view.Surface;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import tv.danmaku.ijk.media.player.IMediaPlayer;
import tv.danmaku.ijk.media.player.IjkMediaPlayer;
public class GiraffePlayer {
/**
* ,,view
*/
public static final String SCALETYPE_FITPARENT="fitParent";
/**
* ,View,View
*/
public static final String SCALETYPE_FILLPARENT="fillParent";
/**
* view,view
*/
public static final String SCALETYPE_WRAPCONTENT="wrapContent";
/**
* ,View
*/
public static final String SCALETYPE_FITXY="fitXY";
/**
* ,16:9,View
*/
public static final String SCALETYPE_16_9="16:9";
/**
* ,4:3,View
*/
public static final String SCALETYPE_4_3="4:3";
private static final int MESSAGE_SHOW_PROGRESS = 1;
private static final int MESSAGE_FADE_OUT = 2;
private static final int MESSAGE_SEEK_NEW_POSITION = 3;
private static final int MESSAGE_HIDE_CENTER_BOX = 4;
private static final int MESSAGE_RESTART_PLAY = 5;
private final Activity activity;
private final IjkVideoView videoView;
private final SeekBar seekBar;
private final AudioManager audioManager;
private final int mMaxVolume;
private boolean playerSupport;
private String url;
private Query $;
private int STATUS_ERROR=-1;
private int STATUS_IDLE=0;
private int STATUS_LOADING=1;
private int STATUS_PLAYING=2;
private int STATUS_PAUSE=3;
private int STATUS_COMPLETED=4;
private long pauseTime;
private int status=STATUS_IDLE;
private boolean isLive = false;
private OrientationEventListener orientationEventListener;
final private int initHeight;
private int defaultTimeout=3000;
private int screenWidthPixels;
private final View.OnClickListener onClickListener=new View.OnClickListener() {
@Override
public void onClick(View v) {
if (v.getId() == R.id.app_video_fullscreen) {
toggleFullScreen();
} else if (v.getId() == R.id.app_video_play) {
doPauseResume();
show(defaultTimeout);
}else if (v.getId() == R.id.app_video_replay_icon) {
videoView.seekTo(0);
videoView.start();
doPauseResume();
} else if (v.getId() == R.id.app_video_finish) {
if (!fullScreenOnly && !portrait) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
} else {
activity.finish();
}
}
}
};
private boolean isShowing;
private boolean portrait;
private float brightness=-1;
private int volume=-1;
private long newPosition = -1;
private long defaultRetryTime=5000;
private OnErrorListener onErrorListener=new OnErrorListener() {
@Override
public void onError(int what, int extra) {
}
};
private Runnable oncomplete =new Runnable() {
@Override
public void run() {
}
};
private OnInfoListener onInfoListener=new OnInfoListener(){
@Override
public void onInfo(int what, int extra) {
}
};
private OnControlPanelVisibilityChangeListener onControlPanelVisibilityChangeListener=new OnControlPanelVisibilityChangeListener() {
@Override
public void change(boolean isShowing) {
}
};
/**
* try to play when error(only for live video)
* @param defaultRetryTime millisecond,0 will stop retry,default is 5000 millisecond
*/
public void setDefaultRetryTime(long defaultRetryTime) {
this.defaultRetryTime = defaultRetryTime;
}
private int currentPosition;
private boolean fullScreenOnly;
public void setTitle(CharSequence title) {
$.id(R.id.app_video_title).text(title);
}
private void doPauseResume() {
if (status==STATUS_COMPLETED) {
$.id(R.id.app_video_replay).gone();
videoView.seekTo(0);
videoView.start();
} else if (videoView.isPlaying()) {
statusChange(STATUS_PAUSE);
videoView.pause();
} else {
videoView.start();
}
updatePausePlay();
}
private void updatePausePlay() {
if (videoView.isPlaying()) {
$.id(R.id.app_video_play).image(R.drawable.ic_stop_white_24dp);
} else {
$.id(R.id.app_video_play).image(R.drawable.ic_play_arrow_white_24dp);
}
}
/**
* @param timeout
*/
public void show(int timeout) {
if (!isShowing) {
$.id(R.id.app_video_top_box).visible();
if (!isLive) {
showBottomControl(true);
}
if (!fullScreenOnly) {
$.id(R.id.app_video_fullscreen).visible();
}
isShowing = true;
onControlPanelVisibilityChangeListener.change(true);
}
updatePausePlay();
handler.sendEmptyMessage(MESSAGE_SHOW_PROGRESS);
handler.removeMessages(MESSAGE_FADE_OUT);
if (timeout != 0) {
handler.sendMessageDelayed(handler.obtainMessage(MESSAGE_FADE_OUT), timeout);
}
}
private void showBottomControl(boolean show) {
$.id(R.id.app_video_play).visibility(show ? View.VISIBLE : View.GONE);
$.id(R.id.app_video_currentTime).visibility(show ? View.VISIBLE : View.GONE);
$.id(R.id.app_video_endTime).visibility(show ? View.VISIBLE : View.GONE);
$.id(R.id.app_video_seekBar).visibility(show ? View.VISIBLE : View.GONE);
}
private long duration;
private boolean instantSeeking;
private boolean isDragging;
private final SeekBar.OnSeekBarChangeListener mSeekListener = new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (!fromUser)
return;
$.id(R.id.app_video_status).gone();//image
int newPosition = (int) ((duration * progress*1.0) / 1000);
String time = generateTime(newPosition);
if (instantSeeking){
videoView.seekTo(newPosition);
}
$.id(R.id.app_video_currentTime).text(time);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
isDragging = true;
show(3600000);
handler.removeMessages(MESSAGE_SHOW_PROGRESS);
if (instantSeeking){
audioManager.setStreamMute(AudioManager.STREAM_MUSIC, true);
}
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
if (!instantSeeking){
videoView.seekTo((int) ((duration * seekBar.getProgress()*1.0) / 1000));
}
show(defaultTimeout);
handler.removeMessages(MESSAGE_SHOW_PROGRESS);
audioManager.setStreamMute(AudioManager.STREAM_MUSIC, false);
isDragging = false;
handler.sendEmptyMessageDelayed(MESSAGE_SHOW_PROGRESS, 1000);
}
};
@SuppressWarnings("HandlerLeak")
private Handler handler=new Handler(Looper.getMainLooper()){
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_FADE_OUT:
hide(false);
break;
case MESSAGE_HIDE_CENTER_BOX:
$.id(R.id.app_video_volume_box).gone();
$.id(R.id.app_video_brightness_box).gone();
$.id(R.id.app_video_fastForward_box).gone();
break;
case MESSAGE_SEEK_NEW_POSITION:
if (!isLive && newPosition >= 0) {
videoView.seekTo((int) newPosition);
newPosition = -1;
}
break;
case MESSAGE_SHOW_PROGRESS:
setProgress();
if (!isDragging && isShowing) {
msg = obtainMessage(MESSAGE_SHOW_PROGRESS);
sendMessageDelayed(msg, 1000);
updatePausePlay();
}
break;
case MESSAGE_RESTART_PLAY:
play(url);
break;
}
}
};
public GiraffePlayer(final Activity activity) {
try {
IjkMediaPlayer.loadLibrariesOnce(null);
IjkMediaPlayer.native_profileBegin("libijkplayer.so");
playerSupport=true;
} catch (Throwable e) {
Log.e("GiraffePlayer", "loadLibraries error", e);
}
this.activity=activity;
screenWidthPixels = activity.getResources().getDisplayMetrics().widthPixels;
$=new Query(activity);
videoView = (IjkVideoView) activity.findViewById(R.id.video_view);
videoView.setOnCompletionListener(new IMediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(IMediaPlayer mp) {
statusChange(STATUS_COMPLETED);
oncomplete.run();
}
});
videoView.setOnErrorListener(new IMediaPlayer.OnErrorListener() {
@Override
public boolean onError(IMediaPlayer mp, int what, int extra) {
statusChange(STATUS_ERROR);
onErrorListener.onError(what,extra);
return true;
}
});
videoView.setOnInfoListener(new IMediaPlayer.OnInfoListener() {
@Override
public boolean onInfo(IMediaPlayer mp, int what, int extra) {
switch (what) {
case IMediaPlayer.MEDIA_INFO_BUFFERING_START:
statusChange(STATUS_LOADING);
break;
case IMediaPlayer.MEDIA_INFO_BUFFERING_END:
statusChange(STATUS_PLAYING);
break;
case IMediaPlayer.MEDIA_INFO_NETWORK_BANDWIDTH:
// Toaster.show("download rate:" + extra);
break;
case IMediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START:
statusChange(STATUS_PLAYING);
break;
}
onInfoListener.onInfo(what,extra);
return false;
}
});
seekBar = (SeekBar) activity.findViewById(R.id.app_video_seekBar);
seekBar.setMax(1000);
seekBar.setOnSeekBarChangeListener(mSeekListener);
$.id(R.id.app_video_play).clicked(onClickListener);
$.id(R.id.app_video_fullscreen).clicked(onClickListener);
$.id(R.id.app_video_finish).clicked(onClickListener);
$.id(R.id.app_video_replay_icon).clicked(onClickListener);
audioManager = (AudioManager) activity.getSystemService(Context.AUDIO_SERVICE);
mMaxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
final GestureDetector gestureDetector = new GestureDetector(activity, new PlayerGestureListener());
View liveBox = activity.findViewById(R.id.app_video_box);
liveBox.setClickable(true);
liveBox.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (gestureDetector.onTouchEvent(motionEvent))
return true;
switch (motionEvent.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_UP:
endGesture();
break;
}
return false;
}
});
orientationEventListener = new OrientationEventListener(activity) {
@Override
public void onOrientationChanged(int orientation) {
if (orientation >= 0 && orientation <= 30 || orientation >= 330 || (orientation >= 150 && orientation <= 210)) {
if (portrait) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
orientationEventListener.disable();
}
} else if ((orientation >= 90 && orientation <= 120) || (orientation >= 240 && orientation <= 300)) {
if (!portrait) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
orientationEventListener.disable();
}
}
}
};
if (fullScreenOnly) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
portrait=getScreenOrientation()==ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
initHeight=activity.findViewById(R.id.app_video_box).getLayoutParams().height;
hideAll();
if (!playerSupport) {
showStatus(activity.getResources().getString(R.string.not_support));
}
}
private void endGesture() {
volume = -1;
brightness = -1f;
if (newPosition >= 0) {
handler.removeMessages(MESSAGE_SEEK_NEW_POSITION);
handler.sendEmptyMessage(MESSAGE_SEEK_NEW_POSITION);
}
handler.removeMessages(MESSAGE_HIDE_CENTER_BOX);
handler.sendEmptyMessageDelayed(MESSAGE_HIDE_CENTER_BOX, 500);
}
private void statusChange(int newStatus) {
status=newStatus;
if (!isLive && newStatus==STATUS_COMPLETED) {
handler.removeMessages(MESSAGE_SHOW_PROGRESS);
hideAll();
$.id(R.id.app_video_replay).visible();
}else if (newStatus == STATUS_ERROR) {
handler.removeMessages(MESSAGE_SHOW_PROGRESS);
hideAll();
if (isLive) {
showStatus(activity.getResources().getString(R.string.small_problem));
if (defaultRetryTime>0) {
handler.sendEmptyMessageDelayed(MESSAGE_RESTART_PLAY, defaultRetryTime);
}
} else {
showStatus(activity.getResources().getString(R.string.small_problem));
}
} else if(newStatus==STATUS_LOADING){
hideAll();
$.id(R.id.app_video_loading).visible();
} else if (newStatus == STATUS_PLAYING) {
hideAll();
}
}
private void hideAll() {
$.id(R.id.app_video_replay).gone();
$.id(R.id.app_video_top_box).gone();
$.id(R.id.app_video_loading).gone();
$.id(R.id.app_video_fullscreen).invisible();
$.id(R.id.app_video_status).gone();
showBottomControl(false);
onControlPanelVisibilityChangeListener.change(false);
}
public void onPause() {
pauseTime=System.currentTimeMillis();
show(0);
if (status==STATUS_PLAYING) {
videoView.pause();
if (!isLive) {
currentPosition = videoView.getCurrentPosition();
}
}
}
public void onResume() {
pauseTime=0;
if (status==STATUS_PLAYING) {
if (isLive) {
videoView.seekTo(0);
} else {
if (currentPosition>0) {
videoView.seekTo(currentPosition);
}
}
videoView.start();
}
}
public void onConfigurationChanged(final Configuration newConfig) {
portrait = newConfig.orientation == Configuration.ORIENTATION_PORTRAIT;
doOnConfigurationChanged(portrait);
}
private void doOnConfigurationChanged(final boolean portrait) {
if (videoView != null && !fullScreenOnly) {
handler.post(new Runnable() {
@Override
public void run() {
tryFullScreen(!portrait);
if (portrait) {
$.id(R.id.app_video_box).height(initHeight, false);
} else {
int heightPixels = activity.getResources().getDisplayMetrics().heightPixels;
int widthPixels = activity.getResources().getDisplayMetrics().widthPixels;
$.id(R.id.app_video_box).height(Math.min(heightPixels,widthPixels), false);
}
updateFullScreenButton();
}
});
orientationEventListener.enable();
}
}
private void tryFullScreen(boolean fullScreen) {
if (activity instanceof AppCompatActivity) {
ActionBar supportActionBar = ((AppCompatActivity) activity).getSupportActionBar();
if (supportActionBar != null) {
if (fullScreen) {
supportActionBar.hide();
} else {
supportActionBar.show();
}
}
}
setFullScreen(fullScreen);
}
private void setFullScreen(boolean fullScreen) {
if (activity != null) {
WindowManager.LayoutParams attrs = activity.getWindow().getAttributes();
if (fullScreen) {
attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
activity.getWindow().setAttributes(attrs);
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
} else {
attrs.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
activity.getWindow().setAttributes(attrs);
activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
}
}
}
public void onDestroy() {
orientationEventListener.disable();
handler.removeCallbacksAndMessages(null);
videoView.stopPlayback();
}
private void showStatus(String statusText) {
$.id(R.id.app_video_status).visible();
$.id(R.id.app_video_status_text).text(statusText);
}
public void play(String url) {
this.url = url;
if (playerSupport) {
$.id(R.id.app_video_loading).visible();
videoView.setVideoPath(url);
videoView.start();
}
}
private String generateTime(long time) {
int totalSeconds = (int) (time / 1000);
int seconds = totalSeconds % 60;
int minutes = (totalSeconds / 60) % 60;
int hours = totalSeconds / 3600;
return hours > 0 ? String.format("%02d:%02d:%02d", hours, minutes, seconds) : String.format("%02d:%02d", minutes, seconds);
}
private int getScreenOrientation() {
int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
DisplayMetrics dm = new DisplayMetrics();
activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
int height = dm.heightPixels;
int orientation;
// if the device's natural orientation is portrait:
if ((rotation == Surface.ROTATION_0
|| rotation == Surface.ROTATION_180) && height > width ||
(rotation == Surface.ROTATION_90
|| rotation == Surface.ROTATION_270) && width > height) {
switch (rotation) {
case Surface.ROTATION_0:
orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
break;
case Surface.ROTATION_90:
orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
break;
case Surface.ROTATION_180:
orientation =
ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
break;
case Surface.ROTATION_270:
orientation =
ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
break;
default:
orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
break;
}
}
// if the device's natural orientation is landscape or if the device
// is square:
else {
switch (rotation) {
case Surface.ROTATION_0:
orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
break;
case Surface.ROTATION_90:
orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
break;
case Surface.ROTATION_180:
orientation =
ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
break;
case Surface.ROTATION_270:
orientation =
ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
break;
default:
orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
break;
}
}
return orientation;
}
/**
*
*
* @param percent
*/
private void onVolumeSlide(float percent) {
if (volume == -1) {
volume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
if (volume < 0)
volume = 0;
}
hide(true);
int index = (int) (percent * mMaxVolume) + volume;
if (index > mMaxVolume)
index = mMaxVolume;
else if (index < 0)
index = 0;
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, index, 0);
int i = (int) (index * 1.0 / mMaxVolume * 100);
String s = i + "%";
if (i == 0) {
s = "off";
}
$.id(R.id.app_video_volume_icon).image(i==0?R.drawable.ic_volume_off_white_36dp:R.drawable.ic_volume_up_white_36dp);
$.id(R.id.app_video_brightness_box).gone();
$.id(R.id.app_video_volume_box).visible();
$.id(R.id.app_video_volume_box).visible();
$.id(R.id.app_video_volume).text(s).visible();
}
private void onProgressSlide(float percent) {
long position = videoView.getCurrentPosition();
long duration = videoView.getDuration();
long deltaMax = Math.min(100 * 1000, duration - position);
long delta = (long) (deltaMax * percent);
newPosition = delta + position;
if (newPosition > duration) {
newPosition = duration;
} else if (newPosition <= 0) {
newPosition=0;
delta=-position;
}
int showDelta = (int) delta / 1000;
if (showDelta != 0) {
$.id(R.id.app_video_fastForward_box).visible();
String text = showDelta > 0 ? ("+" + showDelta) : "" + showDelta;
$.id(R.id.app_video_fastForward).text(text + "s");
$.id(R.id.app_video_fastForward_target).text(generateTime(newPosition)+"/");
$.id(R.id.app_video_fastForward_all).text(generateTime(duration));
}
}
/**
*
*
* @param percent
*/
private void onBrightnessSlide(float percent) {
if (brightness < 0) {
brightness = activity.getWindow().getAttributes().screenBrightness;
if (brightness <= 0.00f){
brightness = 0.50f;
}else if (brightness < 0.01f){
brightness = 0.01f;
}
}
Log.d(this.getClass().getSimpleName(),"brightness:"+brightness+",percent:"+ percent);
$.id(R.id.app_video_brightness_box).visible();
WindowManager.LayoutParams lpa = activity.getWindow().getAttributes();
lpa.screenBrightness = brightness + percent;
if (lpa.screenBrightness > 1.0f){
lpa.screenBrightness = 1.0f;
}else if (lpa.screenBrightness < 0.01f){
lpa.screenBrightness = 0.01f;
}
$.id(R.id.app_video_brightness).text(((int) (lpa.screenBrightness * 100))+"%");
activity.getWindow().setAttributes(lpa);
}
private long setProgress() {
if (isDragging){
return 0;
}
long position = videoView.getCurrentPosition();
long duration = videoView.getDuration();
if (seekBar != null) {
if (duration > 0) {
long pos = 1000L * position / duration;
seekBar.setProgress((int) pos);
}
int percent = videoView.getBufferPercentage();
seekBar.setSecondaryProgress(percent * 10);
}
this.duration = duration;
$.id(R.id.app_video_currentTime).text(generateTime(position));
$.id(R.id.app_video_endTime).text(generateTime(this.duration));
return position;
}
public void hide(boolean force) {
if (force || isShowing) {
handler.removeMessages(MESSAGE_SHOW_PROGRESS);
showBottomControl(false);
$.id(R.id.app_video_top_box).gone();
$.id(R.id.app_video_fullscreen).invisible();
isShowing = false;
onControlPanelVisibilityChangeListener.change(false);
}
}
private void updateFullScreenButton() {
if (getScreenOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
$.id(R.id.app_video_fullscreen).image(R.drawable.ic_fullscreen_exit_white_36dp);
} else {
$.id(R.id.app_video_fullscreen).image(R.drawable.ic_fullscreen_white_24dp);
}
}
public void setFullScreenOnly(boolean fullScreenOnly) {
this.fullScreenOnly = fullScreenOnly;
tryFullScreen(fullScreenOnly);
if (fullScreenOnly) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
} else {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
}
}
/**
* <pre>
* fitParent:,,view
* fillParent:,View,View
* wrapContent:view,view
* fitXY:,View
* 16:9:,16:9,View
* 4:3:,4:3,View
* </pre>
* @param scaleType
*/
public void setScaleType(String scaleType) {
if (SCALETYPE_FITPARENT.equals(scaleType)) {
videoView.setAspectRatio(IRenderView.AR_ASPECT_FIT_PARENT);
}else if (SCALETYPE_FILLPARENT.equals(scaleType)) {
videoView.setAspectRatio(IRenderView.AR_ASPECT_FILL_PARENT);
}else if (SCALETYPE_WRAPCONTENT.equals(scaleType)) {
videoView.setAspectRatio(IRenderView.AR_ASPECT_WRAP_CONTENT);
}else if (SCALETYPE_FITXY.equals(scaleType)) {
videoView.setAspectRatio(IRenderView.AR_MATCH_PARENT);
}else if (SCALETYPE_16_9.equals(scaleType)) {
videoView.setAspectRatio(IRenderView.AR_16_9_FIT_PARENT);
}else if (SCALETYPE_4_3.equals(scaleType)) {
videoView.setAspectRatio(IRenderView.AR_4_3_FIT_PARENT);
}
}
/**
* (actionbar or appToolbar)
* @param show
*/
public void setShowNavIcon(boolean show) {
$.id(R.id.app_video_finish).visibility(show ? View.VISIBLE : View.GONE);
}
public void start() {
videoView.start();
}
public void pause() {
videoView.pause();
}
public boolean onBackPressed() {
if (!fullScreenOnly && getScreenOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
return true;
}
return false;
}
class Query {
private final Activity activity;
private View view;
public Query(Activity activity) {
this.activity=activity;
}
public Query id(int id) {
view = activity.findViewById(id);
return this;
}
public Query image(int resId) {
if (view instanceof ImageView) {
((ImageView) view).setImageResource(resId);
}
return this;
}
public Query visible() {
if (view != null) {
view.setVisibility(View.VISIBLE);
}
return this;
}
public Query gone() {
if (view != null) {
view.setVisibility(View.GONE);
}
return this;
}
public Query invisible() {
if (view != null) {
view.setVisibility(View.INVISIBLE);
}
return this;
}
public Query clicked(View.OnClickListener handler) {
if (view != null) {
view.setOnClickListener(handler);
}
return this;
}
public Query text(CharSequence text) {
if (view!=null && view instanceof TextView) {
((TextView) view).setText(text);
}
return this;
}
public Query visibility(int visible) {
if (view != null) {
view.setVisibility(visible);
}
return this;
}
private void size(boolean width, int n, boolean dip){
if(view != null){
ViewGroup.LayoutParams lp = view.getLayoutParams();
if(n > 0 && dip){
n = dip2pixel(activity, n);
}
if(width){
lp.width = n;
}else{
lp.height = n;
}
view.setLayoutParams(lp);
}
}
public void height(int height, boolean dip) {
size(false,height,dip);
}
public int dip2pixel(Context context, float n){
int value = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, n, context.getResources().getDisplayMetrics());
return value;
}
public float pixel2dip(Context context, float n){
Resources resources = context.getResources();
DisplayMetrics metrics = resources.getDisplayMetrics();
float dp = n / (metrics.densityDpi / 160f);
return dp;
}
}
public class PlayerGestureListener extends GestureDetector.SimpleOnGestureListener {
private boolean firstTouch;
private boolean volumeControl;
private boolean toSeek;
@Override
public boolean onDoubleTap(MotionEvent e) {
videoView.toggleAspectRatio();
return true;
}
@Override
public boolean onDown(MotionEvent e) {
firstTouch = true;
return super.onDown(e);
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
float mOldX = e1.getX(), mOldY = e1.getY();
float deltaY = mOldY - e2.getY();
float deltaX = mOldX - e2.getX();
if (firstTouch) {
toSeek = Math.abs(distanceX) >= Math.abs(distanceY);
volumeControl=mOldX > screenWidthPixels * 0.5f;
firstTouch = false;
}
if (toSeek) {
if (!isLive) {
onProgressSlide(-deltaX / videoView.getWidth());
}
} else {
float percent = deltaY / videoView.getHeight();
if (volumeControl) {
onVolumeSlide(percent);
} else {
onBrightnessSlide(percent);
}
}
return super.onScroll(e1, e2, distanceX, distanceY);
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
if (isShowing) {
hide(false);
} else {
show(defaultTimeout);
}
return true;
}
}
/**
* is player support this device
* @return
*/
public boolean isPlayerSupport() {
return playerSupport;
}
/**
*
* @return
*/
public boolean isPlaying() {
return videoView!=null?videoView.isPlaying():false;
}
public void stop(){
videoView.stopPlayback();
}
/**
* seekTo position
* @param msec millisecond
*/
public GiraffePlayer seekTo(int msec, boolean showControlPanle){
videoView.seekTo(msec);
if (showControlPanle) {
show(defaultTimeout);
}
return this;
}
public GiraffePlayer forward(float percent) {
if (isLive || percent>1 || percent<-1) {
return this;
}
onProgressSlide(percent);
showBottomControl(true);
handler.sendEmptyMessage(MESSAGE_SHOW_PROGRESS);
endGesture();
return this;
}
public int getCurrentPosition(){
return videoView.getCurrentPosition();
}
/**
* get video duration
* @return
*/
public int getDuration(){
return videoView.getDuration();
}
public GiraffePlayer playInFullScreen(boolean fullScreen){
if (fullScreen) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
updateFullScreenButton();
}
return this;
}
public void toggleFullScreen(){
if (getScreenOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
} else {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
updateFullScreenButton();
}
public interface OnErrorListener{
void onError(int what, int extra);
}
public interface OnControlPanelVisibilityChangeListener{
void change(boolean isShowing);
}
public interface OnInfoListener{
void onInfo(int what, int extra);
}
public GiraffePlayer onError(OnErrorListener onErrorListener) {
this.onErrorListener = onErrorListener;
return this;
}
public GiraffePlayer onComplete(Runnable complete) {
this.oncomplete = complete;
return this;
}
public GiraffePlayer onInfo(OnInfoListener onInfoListener) {
this.onInfoListener = onInfoListener;
return this;
}
public GiraffePlayer onControlPanelVisibilityChang(OnControlPanelVisibilityChangeListener listener){
this.onControlPanelVisibilityChangeListener = listener;
return this;
}
/**
* set is live (can't seek forward)
* @param isLive
* @return
*/
public GiraffePlayer live(boolean isLive) {
this.isLive = isLive;
return this;
}
public GiraffePlayer toggleAspectRatio(){
if (videoView != null) {
videoView.toggleAspectRatio();
}
return this;
}
public GiraffePlayer onControlPanelVisibilityChange(OnControlPanelVisibilityChangeListener listener){
this.onControlPanelVisibilityChangeListener = listener;
return this;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.