answer stringlengths 17 10.2M |
|---|
/* Huomautukset:
Lissin COMMENTED, LINE_BY_LINE ja ANIMATED kentt.
Poistin parametrin speed menuSetRunningOptions() ja menuSetCompilingOptions() -metodeista
Lissin metodin public void waitForContinueTask()
Lissin metodin public void continueTaskWithoutPauses()
Lissin kentn noPauses
Lissin kentn File openedFile
*/
package fi.hu.cs.titokone;
import java.util.Locale;
import java.io.File;
import java.util.Hashtable;
import java.util.Iterator;
import java.io.IOException;
import java.util.logging.Logger;
import fi.hu.cs.ttk91.TTK91NoStdInData;
import fi.hu.cs.ttk91.TTK91AddressOutOfBounds;
import fi.hu.cs.ttk91.TTK91CompileException;
import fi.hu.cs.ttk91.TTK91RuntimeException;
import fi.hu.cs.ttk91.TTK91NoKbdData;
import java.text.ParseException;
import java.util.LinkedList;
import java.net.URI;
/** This class contains the intellect the GUI class needs to provide
services to the Control class. It also hides the GUI and Control from
each other, serving as the middle-man for all their communication. It
prepares all the data from CompileInfo, LoadInfo and RunInfo objects
to GUI, so that it doesn't have to be aware of what's happening behind
GUIBrain. Moreover, this class for its part doesn't take any position on
how to show the data provided here on the screen. It may, however, tell
GUI to disable or enable some elements or objects, such as buttons,
menuitems or inputfields.
*/
public class GUIBrain {
/** This field contains the languages available, with the long,
English names like "Finnish" or "English (GB)" as keys and
the locales corresponding to the languages as values.
*/
private Hashtable availableLanguages;
private Control control;
/** This field namely stores the current settings and everytime a setting
is changed, this is informed about it. When a GUIBrain object is created,
it asks for Control to get settings from settings file (which is as well
stored in this class, to settingsFile field) and GUIBrain saves
those settings (if there's any) in this field.
*/
private Settings currentSettings;
private GUI gui;
private String programPath = "fi/hu/cs/titokone/";
private File settingsFile;
private File currentlyOpenedFile;
public static final int COMMENTED = 1;
public static final int LINE_BY_LINE = 2;
public static final int PAUSED = 2;
public static final int ANIMATED = 4;
/** This field is set when menuInterrupt is called, and all continuous
loops which do many things and wait for input in between should
check if this is sent before continuing to their next step. An
interrupt sent means they should stop doing whatever they were doing
as soon as is reasonable. (Usually when it would be the time to
wait for input from the user.
*/
private boolean interruptSent;
/** This field is set true, when continueTaskWithoutPauses is launched.
Methods menuRun() and menuCompile() check this to see if they want
to override the setting in currentSettings.
*/
private boolean noPauses;
/** Keeps track of the state of this program. It can be NONE, B91_NOT_RUNNING,
B91_RUNNING, B91_PAUSED, B91_WAIT_FOR_KBD, K91_NOT_COMPILING, K91_COMPILING
or K91_PAUSED.
*/
private short currentState;
/** These fields are used to set the current state of program. It's stored into
currentState field.
*/
private static final short NONE = 0;
private static final short B91_NOT_RUNNING = 1;
private static final short B91_RUNNING = 2;
private static final short B91_PAUSED = 3;
private static final short B91_WAIT_FOR_KBD = 4;
private static final short K91_NOT_COMPILING = 5;
private static final short K91_COMPILING = 6;
private static final short K91_PAUSED = 7;
private static final short INTERRUPTED_WITHOUT_PAUSE = 10;
private static final short INTERRUPTED_WITH_PAUSE = 11;
public static String DEFAULT_STDIN_FILENAME = "stdin";
public static String DEFAULT_STDOUT_FILENAME = "stdout";
/** This constructor sets up the GUIBrain instance. It calls private
initialization functions, including findAvailableLanguages().
*/
public GUIBrain(GUI gui) {
this.gui = gui;
File defStdinFile = new File(System.getProperty("user.dir") + DEFAULT_STDIN_FILENAME);
File defStdoutFile = new File(System.getProperty("user.dir") + DEFAULT_STDOUT_FILENAME);
try {
defStdinFile.createNewFile();
defStdoutFile.createNewFile();
}
catch (IOException e) {
System.out.println(e.getMessage());
}
control = new Control(defStdinFile, defStdoutFile);
try {
getCurrentSettings();
}
catch (IOException e) {
System.out.println("Settings file cannot be accessed. ...exiting.");
System.exit(0);
}
String filemode = currentSettings.getStrValue(Settings.STDIN_PATH);
String path = currentSettings.getStrValue(Settings.DEFAULT_STDIN);
if (path != null && !path.equals("")) {
if (filemode.equals("absolute")) {
defStdinFile = new File(path);
}
else if (filemode.equals("relative")) {
defStdinFile = new File(System.getProperty("user.dir") + path);
}
}
try {
control.setDefaultStdIn(defStdinFile);
}
catch (Exception e) {
System.out.println(e.getMessage());
}
filemode = currentSettings.getStrValue(Settings.STDOUT_PATH);
path = currentSettings.getStrValue(Settings.DEFAULT_STDOUT);
if (path != null && !path.equals("")) {
if (filemode.equals("absolute")) {
defStdoutFile = new File(path);
}
else if (filemode.equals("relative")) {
defStdoutFile = new File(System.getProperty("user.dir") + path);
}
}
try {
control.setDefaultStdOut(defStdoutFile);
}
catch (Exception e) {
System.out.println(e.getMessage());
}
int runmode = currentSettings.getIntValue(Settings.RUN_MODE);
gui.setSelected(GUI.OPTION_RUNNING_COMMENTED, (runmode & COMMENTED) != 0);
gui.setSelected(GUI.OPTION_RUNNING_PAUSED, (runmode & PAUSED) != 0);
gui.setSelected(GUI.OPTION_RUNNING_ANIMATED, (runmode & ANIMATED) != 0);
int compilemode = currentSettings.getIntValue(Settings.COMPILE_MODE);
gui.setSelected(GUI.OPTION_COMPILING_COMMENTED, (compilemode & COMMENTED) != 0);
gui.setSelected(GUI.OPTION_COMPILING_PAUSED, (compilemode & PAUSED) != 0);
int memorysize = currentSettings.getIntValue(Settings.MEMORY_SIZE);
if (memorysize != Control.DEFAULT_MEMORY_SIZE) {
try {
control.changeMemorySize(memorysize);
}
catch (IllegalArgumentException wrongsize) {
control.changeMemorySize(Control.DEFAULT_MEMORY_SIZE);
}
}
availableLanguages = new Hashtable();
findAvailableLanguages();
String language = currentSettings.getStrValue(Settings.UI_LANGUAGE);
if ( availableLanguages.containsKey(language) ) {
Translator.setLocale((Locale)availableLanguages.get(language));
//gui.updateAllTexts();
}
noPauses = false;
interruptSent = false;
saveSettings();
currentState = NONE;
}
/** This method corresponds to the menu option File -> Open... It
calls either openBinaryFile or openSourceFile correspondingly.
*/
public void menuOpenFile(File openedFile) {
/* Opening a file is a command that interrupts all other tasks. */
interruptCurrentTasks(true);
String suffix = getExtension(openedFile);
gui.resetAll();
if (suffix.equals("b91")) {
try {
control.openBinary(openedFile);
}
catch (Exception e) {
gui.showError(e.getMessage());
return;
}
loadAndUpdateGUI();
}
else if (suffix.equals("k91")) {
gui.resetAll();
String k91Source = "";
try {
k91Source = control.openSource(openedFile);
}
catch (IOException e) {
gui.showError(e.getMessage());
return;
}
currentlyOpenedFile = openedFile;
String[] src = k91Source.split("\n|\r|\r\n");
gui.insertToCodeTable(src);
gui.updateStatusBar("Opened a new k91 source file");
gui.setGUIView(2);
currentState = K91_NOT_COMPILING;
setGUICommandsForCurrentState();
}
else { // if file extension isn't either b91 or k91
gui.showError(new Message("File extension must be k91 or b91").toString());
}
}
public static final int MIN_KBD_VALUE = -32766;
public static final int MAX_KBD_VALUE = 32767;
public boolean enterInput(String input) {
int inputValue;
String[] minAndMaxValues = {""+MIN_KBD_VALUE, ""+MAX_KBD_VALUE};
try {
inputValue = Integer.parseInt(input);
}
catch (NumberFormatException e) {
gui.changeTextInEnterNumberLabel(new Message("Illegal input").toString());
gui.updateStatusBar(new Message("Illegal input. You must insert a number between {0}...{1}", minAndMaxValues).toString());
return false;
}
if (inputValue > MAX_KBD_VALUE || inputValue < MIN_KBD_VALUE) {
gui.changeTextInEnterNumberLabel(new Message("Illegal input").toString());
gui.updateStatusBar(new Message("Illegal input. You must insert a number between {0}...{1}", minAndMaxValues).toString());
return false;
}
gui.changeTextInEnterNumberLabel("");
gui.updateStatusBar("");
control.keyboardInput(inputValue);
return true;
}
/** This method corresponds to the menu option File -> Run. It does
its work by calling runInstruction().
*/
public void menuRun() {
interruptSent = false;
noPauses = false;
/* If stdout file is set to be overwritten, then it must be emptied first.
It's done here by deleting it first and then creating it again.
*/
File stdoutFile = getCurrentDefaultStdoutFile();
if (currentSettings.getStrValue(Settings.STDOUT_USE).equals("overwrite")) {
try {
stdoutFile.delete();
stdoutFile.createNewFile();
}
catch (IOException e) {
String[] filename = { stdoutFile.getName() };
gui.showError(new Message("Error while emptying {0}", filename).toString());
System.out.println(e.getMessage());
return;
}
}
RunInfo runinfo;
int runmode = currentSettings.getIntValue(Settings.RUN_MODE);
currentState = B91_RUNNING;
setGUICommandsForCurrentState();
do {
currentState = B91_RUNNING;
setGUICommandsForCurrentState();
runmode = currentSettings.getIntValue(Settings.RUN_MODE);
try {
runinfo = control.runLine();
if (runinfo == null) {
break;
}
}
catch (TTK91NoKbdData needMoreData) {
gui.addComment(new Message("Enter a number in the text field above.").toString());
currentState = B91_WAIT_FOR_KBD;
setGUICommandsForCurrentState();
gui.enable(GUI.INPUT_FIELD);
/* Wait until continueTask() is run. In this case it's done by pressing
enter-button below the text field where user enter kbd-data.
*/
waitForContinueTask();
gui.disable(GUI.INPUT_FIELD);
continue; // And then go to beginning of the do-while-loop.
}
catch (TTK91RuntimeException e) {
gui.addComment(e.getMessage());
break;
}
System.out.println(runinfo.getComments());
System.out.println(runinfo.whatDevice());
if ((runmode & COMMENTED) != 0) {
if (runinfo.getComments() != null)
gui.addComment(runinfo.getLineNumber() + ": " + runinfo.getComments());
}
gui.selectLine(runinfo.getLineNumber(), GUI.INSTRUCTIONS_AND_DATA_TABLE);
if (runinfo.whatDevice() != null && runinfo.whatDevice().equals("Display")) {
if(runinfo.whatOUT() != null) {
gui.addOutputData( runinfo.whatOUT()[1] );
}
}
int[] newRegisterValues = runinfo.getRegisters();
gui.updateReg(GUI.R0, newRegisterValues[0]);
gui.updateReg(GUI.R1, newRegisterValues[1]);
gui.updateReg(GUI.R2, newRegisterValues[2]);
gui.updateReg(GUI.R3, newRegisterValues[3]);
gui.updateReg(GUI.R4, newRegisterValues[4]);
gui.updateReg(GUI.R5, newRegisterValues[5]);
gui.updateReg(GUI.R6, newRegisterValues[6]);
gui.updateReg(GUI.R7, newRegisterValues[7]);
//gui.updateReg(GUI.PC, newRegisterValues[8]);
LinkedList changedMemoryLines = runinfo.getChangedMemoryLines();
Iterator changedMemoryLinesListIterator = changedMemoryLines.iterator();
while (changedMemoryLinesListIterator.hasNext()) {
Object[] listItem = (Object[])changedMemoryLinesListIterator.next();
int line = ((Integer)listItem[0]).intValue();
MemoryLine contents = (MemoryLine)listItem[1];
gui.updateInstructionsAndDataTableLine(line, contents.getBinary(), contents.getSymbolic());
//changedMemoryLines.removeFirst();
}
//gui.invalidate();
gui.repaint();
if ((runmode & LINE_BY_LINE) != 0 && noPauses == false) {
currentState = B91_PAUSED;
setGUICommandsForCurrentState();
waitForContinueTask();
}
else {
synchronized(this) {
try {
wait(70);
}
catch(InterruptedException e) {
System.out.println("InterruptedException in menuRun()");
}
}
}
} while (interruptSent == false); // End of do-while -loop
if (currentState == INTERRUPTED_WITH_PAUSE) {
setGUICommandsForCurrentState();
waitForContinueTask();
}
load();
currentState = B91_NOT_RUNNING;
setGUICommandsForCurrentState();
gui.unselectAll();
}
/** This method corresponds to the menu option File -> Compile. It
does its work by calling compileLine().
*/
public void menuCompile() {
interruptSent = false;
noPauses = false;
currentState = K91_COMPILING;
setGUICommandsForCurrentState();
CompileInfo compileinfo;
int compilemode;
int phase;
/* This will be set to true once the compilation succeeds. The value
of this variable will be used in case of an interrupted compilation
or if an error occurs, when menuCompile() has to decide whether to
change back to pre-compilation-started state or not.
*/
boolean compilingCompleted = false;
do {
currentState = K91_COMPILING;
setGUICommandsForCurrentState();
try {
compileinfo = control.compileLine();
}
catch (TTK91CompileException e) {
gui.addComment(e.getMessage());
currentState = K91_PAUSED;
setGUICommandsForCurrentState();
waitForContinueTask();
break;
}
if (compileinfo == null) {
compilingCompleted = true;
break;
}
else {
String comments = compileinfo.getComments();
if (comments == null)
comments = "";
if (!comments.equals(""))
gui.addComment(compileinfo.getLineNumber() + ": " + comments);
compilemode = currentSettings.getIntValue(Settings.COMPILE_MODE);
phase = compileinfo.getPhase();
if (phase == CompileInfo.FIRST_ROUND) {
System.out.println(compileinfo.getSymbolFound());
System.out.println(compileinfo.getLabelFound());
if (compileinfo.getSymbolFound()) {
String symbolName = compileinfo.getSymbolName();
Integer symbolValue = null;
if (compileinfo.getSymbolDefined()) {
symbolValue = new Integer(compileinfo.getSymbolValue());
}
gui.updateRowInSymbolTable(symbolName, symbolValue);
}
if (compileinfo.getLabelFound()) {
String symbolName = compileinfo.getLabelName();
Integer symbolValue = new Integer(compileinfo.getLabelValue());
gui.updateRowInSymbolTable(symbolName, symbolValue);
}
System.out.println(compileinfo.getLineContents());
System.out.println(compileinfo.getLineNumber() + ": " + comments);
System.out.println("");
gui.selectLine(compileinfo.getLineNumber(), GUI.CODE_TABLE);
}
else if (phase == CompileInfo.FINALIZING_FIRST_ROUND) {
String[][] symbolTable = compileinfo.getSymbolTable();
if (symbolTable != null) {
for (int i=0 ; i<symbolTable.length ; i++) {
String symbolName = symbolTable[i][0];
Integer symbolValue = null;
try {
symbolValue = new Integer(symbolTable[i][1]);
}
catch (NumberFormatException e) {
}
gui.updateRowInSymbolTable(symbolName, symbolValue);
}
}
String[] newInstructionsContents = compileinfo.getInstructions();
String[] newDataContents = compileinfo.getData();
gui.insertToInstructionsTable(newInstructionsContents);
gui.insertToDataTable(newDataContents);
gui.setGUIView(3);
}
else if (phase == CompileInfo.SECOND_ROUND) {
int line = compileinfo.getLineNumber();
int binary = compileinfo.getLineBinary();
gui.updateInstructionsAndDataTableLine(line, binary);
gui.selectLine(compileinfo.getLineNumber(), GUI.INSTRUCTIONS_AND_DATA_TABLE);
}
/*else if (phase == CompileInfo.FINALIZING) {
if (compileinfo.getFinalPhase() == true) {
compilingCompleted = true;
break;
}
}*/
gui.repaint();
if ( ((compilemode & PAUSED) != 0) && !comments.equals("") && noPauses == false) {
currentState = K91_PAUSED;
setGUICommandsForCurrentState();
waitForContinueTask();
}
else {
synchronized(this) {
try {
wait(700); // TODO: Muista muuttaa pienemmksi lopulliseen versioon.
}
catch(InterruptedException e) {
System.out.println("InterruptedException in menuRun()");
}
}
}
}
} while ( interruptSent == false ); // End of do-loop
if (currentState == INTERRUPTED_WITH_PAUSE) {
setGUICommandsForCurrentState();
waitForContinueTask();
}
if (compilingCompleted == true) {
try {
control.saveBinary();
}
catch (IOException e) {
System.out.println(e);
}
gui.resetAll();
loadAndUpdateGUI();
}
else {
/* Reload the source so that the compiling starts again from the beginning. */
try {
control.openSource(currentlyOpenedFile);
}
catch (IOException e) {
gui.showError(e.getMessage());
currentState = NONE;
setGUICommandsForCurrentState();
return;
}
currentState = K91_NOT_COMPILING;
setGUICommandsForCurrentState();
gui.setGUIView(2);
gui.resetAll();
}
}
/** This method corresponds to the menu option File -> Erase memory.
*/
public void menuEraseMemory() {
interruptCurrentTasks(true);
control.eraseMemory();
gui.setGUIView(1);
currentState = NONE;
setGUICommandsForCurrentState();
}
/** This method corresponds to the menu option File -> Exit.
*/
public void menuExit() {
interruptCurrentTasks(true);
}
/** This method corresponds to the menu option Option -> Set language.
If the chosen language is one in the list, then this version is called.
@param language Name of the language. This should be one of those get
from getAvailableLanguages() method.
*/
public void menuSetLanguage(String language) {
if (availableLanguages.containsKey(language)) {
Translator.setLocale((Locale)availableLanguages.get(language));
currentSettings.setValue(Settings.UI_LANGUAGE, language);
saveSettings();
gui.updateAllTexts();
}
}
/** This method correspods as well to the menu option Option -> Set language.
This version is called, if user has chosen an external language file.
@param languageFile The language file. This must be class-file that
extends ListResourceBundle.
*/
public void menuSetLanguage(File languageFile) {
if (languageFile.exists()) {
try {
Translator.setLocale(Locale.CHINESE, control.loadLanguageFile(languageFile));
}
catch (ResourceLoadFailedException e) {
gui.showError(new Message("Not a language file").toString());
System.out.println(e.getMessage());
return;
}
//currentSettings.setValue(Settings.UI_LANGUAGE, language);
//control.saveSettings(currentSettings.toString(), settingsFile);
gui.updateAllTexts();
}
}
/** This method corresponds to the menu option Option -> Set Default Stdin File.
It informs Control about the new default stdin file and saves it to
settingsFile.
*/
public void menuSetStdin(File stdinFile) {
try {
control.setDefaultStdIn(stdinFile);
}
catch (Exception e) {
gui.showError(e.getMessage());
return;
}
String[] filename = { stdinFile.getPath() };
currentSettings.setValue(Settings.DEFAULT_STDIN, filename[0]);
currentSettings.setValue(Settings.STDIN_PATH, "absolute");
saveSettings();
gui.addComment(new Message("Default stdin file set to {0}", filename).toString());
}
/** This method corresponds to the menu option Option -> Set Default Stdout File.
It informs Control about the new default stdout file and saves it to
settingsFile.
*/
public void menuSetStdout(File stdoutFile, boolean append) {
if (append == true) {
currentSettings.setValue(Settings.STDOUT_USE, "append");
}
else {
currentSettings.setValue(Settings.STDOUT_USE, "overwrite");
}
try {
control.setDefaultStdOut(stdoutFile);
}
catch (Exception e) {
gui.showError(e.getMessage());
return;
}
String[] filename = { stdoutFile.getPath() };
currentSettings.setValue(Settings.DEFAULT_STDOUT, filename[0]);
currentSettings.setValue(Settings.STDOUT_PATH, "absolute");
saveSettings();
gui.addComment(new Message("Default stdout file set to {0}", filename).toString());
}
/** This method corresponds to the menu option Option -> Set Memory Size.
*/
public void menuSetMemorySize(int newSize) {
try {
control.changeMemorySize(newSize);
}
catch (IllegalArgumentException e) {
return;
}
currentSettings.setValue(Settings.MEMORY_SIZE, newSize);
saveSettings();
gui.setGUIView(1);
}
/** This methods refreshes GUI so that it shows running options as they
are declared currently.
*/
public void refreshRunningOptions() {
int runmode = currentSettings.getIntValue(Settings.RUN_MODE);
gui.setSelected(GUI.OPTION_RUNNING_PAUSED, (runmode & PAUSED) != 0);
gui.setSelected(GUI.OPTION_RUNNING_COMMENTED, (runmode & COMMENTED) != 0);
gui.setSelected(GUI.OPTION_RUNNING_ANIMATED, (runmode & ANIMATED) != 0);
}
public void menuSetRunningOption(int option,boolean b) {
int runmode = currentSettings.getIntValue(Settings.RUN_MODE);
if (((runmode & option) != 0) == b) {
// do nothing
}
else if ((runmode & option) != 0) {
runmode -= option;
}
else if ((runmode & option) == 0) {
runmode += option;
}
saveSettings();
currentSettings.setValue(Settings.RUN_MODE, runmode);
switch (option) {
case LINE_BY_LINE: // Synonym for case PAUSED:
gui.setSelected(GUI.OPTION_RUNNING_PAUSED, b);
break;
case COMMENTED:
gui.setSelected(GUI.OPTION_RUNNING_COMMENTED, b);
break;
case ANIMATED:
gui.setSelected(GUI.OPTION_RUNNING_ANIMATED, b);
break;
}
}
/** This methods refreshes GUI so that it shows compiling options as they
are declared currently.
*/
public void refreshCompilingOptions() {
int compilemode = currentSettings.getIntValue(Settings.COMPILE_MODE);
gui.setSelected(GUI.OPTION_COMPILING_PAUSED, (compilemode & PAUSED) != 0);
gui.setSelected(GUI.OPTION_COMPILING_COMMENTED, (compilemode & COMMENTED) != 0);
}
/** This method
*/
public void menuSetCompilingOption(int option,boolean b) {
int compilemode = currentSettings.getIntValue(Settings.COMPILE_MODE);
if (((compilemode & option) != 0) == b) {
// do nothing
}
else if ((compilemode & option) != 0) {
compilemode -= option;
}
else if ((compilemode & option) == 0) {
compilemode += option;
}
saveSettings();
currentSettings.setValue(Settings.COMPILE_MODE, compilemode);
switch (option) {
case PAUSED:
gui.setSelected(GUI.OPTION_COMPILING_PAUSED, b);
break;
case COMMENTED:
gui.setSelected(GUI.OPTION_COMPILING_COMMENTED, b);
break;
}
}
public void menuAbout() {}
public void menuManual() {}
/** This method corresponds to a request to interrupt whatever we
were doing once it becomes possible.
@param immediate If this is true, then continueTask is being waited before
the previous job ends.
If this is false, then it stops immediately and next job
can start right after calling this.
*/
public void menuInterrupt(boolean immediate) {
interruptCurrentTasks(immediate);
}
/** Notifies all currents tasks to be interrupted once they are able to read the
new value of interruptSent. Immediate interruption means that all tasks should
end without any further activities, while non-immediate interruption means
that some tasks may pause to wait for continueTask() to notify them before
ending completely.
@param immediate If this is true, then continueTask is being waited before
the previous job ends.
If this is false, then it stops immediately and next job
can start right after calling this.
*/
private void interruptCurrentTasks(boolean immediate) {
if (immediate == true)
currentState = INTERRUPTED_WITHOUT_PAUSE;
else
currentState = INTERRUPTED_WITH_PAUSE;
interruptSent = true;
synchronized(this) {
notifyAll();
}
}
/** Notifies all methods,that have called waitForContinueTask() to continue
their operation.
*/
public void continueTask() {
synchronized(this) {
notify();
}
return;
}
/** Notifies all methods, that have called waitForContinueTask() to continue
their operation plus informs them that waitForContinueTask() should no
longer be called during current operation.
*/
public void continueTaskWithoutPauses() {
noPauses = true;
synchronized(this) {
notify();
}
return;
}
/** A method can call this, if it wants enter into pause mode and wait for someone
to call continueTask() or continueTaskWithoutPauses() methods. This method cannot
however be used, unless the method which is calling this hasn't been set to run
in a thread of its own. eg. by calling new GUIThreader()
*/
public void waitForContinueTask() {
synchronized(this) {
try {
wait();
}
catch (InterruptedException e) {
System.out.println("InterruptedException");
}
}
return;
}
/** Returns all available languages. These (and only these) can be used as parameter
for setLanguge(String) method.
*/
public String[] getAvailableLanguages() {
Object[] keys = availableLanguages.keySet().toArray();
String[] str = new String[keys.length];
for (int i=0 ; i<keys.length ; i++) {
str[i] = (String)keys[i];
}
return str;
}
/** Makes sure that currentSettings contains at least the default values for each
key, if they cannot be obtained from settingsFile.
*/
private void getCurrentSettings() throws IOException {
System.out.println(System.getProperty("user.dir"));
String defaultStdinFile = System.getProperty("user.dir") + "/stdin";
String defaultStdinPath = "absolute";
String defaultStdoutFile = System.getProperty("user.dir") + "/stdout";
String defaultStdoutPath = "absolute";
String defaultStdoutUse = "overwrite";
int defaultMemorySize = Control.DEFAULT_MEMORY_SIZE;
String defaultUILanguage = "English";
int defaultRunningMode = 0;
int defaultCompilingMode = 0;
URI fileURI;
try {
fileURI = new URI( getClass().getClassLoader().getResource(programPath).toString() + "etc/settings.cfg" );
settingsFile = new File(fileURI);
}
catch (Exception e) {
System.out.println(new Message("Main path not found! (Trying to locate " +
"etc/settings.cfg.) " +
"...exiting.").toString());
System.exit(0);
}
if (settingsFile.exists() == false) {
settingsFile.createNewFile(); // throws IOException
}
String settingsFileContents;
try {
settingsFileContents = control.loadSettingsFileContents(settingsFile);
}
catch (IOException e) {
System.out.println(new Message("I/O error while reading settings "+
"file: {0}", e.getMessage()).toString());
throw e;
}
try {
//System.out.println( control.loadSettingsFileContents(settingsFile) );
currentSettings = new Settings( control.loadSettingsFileContents(settingsFile) );
}
catch (ParseException e) {
System.out.println(new Message("Parse error in settings file: {0}",
e.getMessage()).toString());
currentSettings = new Settings();
}
try {
if (currentSettings.getStrValue(Settings.STDIN_PATH) == null)
currentSettings.setValue(Settings.STDIN_PATH, defaultStdinPath);
}
catch (Exception e) {
currentSettings.setValue(Settings.STDIN_PATH, defaultStdinPath);
}
try {
if (currentSettings.getStrValue(Settings.DEFAULT_STDIN) == null)
currentSettings.setValue(Settings.DEFAULT_STDIN, defaultStdinFile);
}
catch (Exception e) {
currentSettings.setValue(Settings.DEFAULT_STDIN, defaultStdinFile);
}
try {
if (currentSettings.getStrValue(Settings.STDOUT_PATH) == null)
currentSettings.setValue(Settings.STDOUT_PATH, defaultStdoutPath);
}
catch (Exception e) {
currentSettings.setValue(Settings.STDOUT_PATH, defaultStdoutPath);
}
try {
if (currentSettings.getStrValue(Settings.DEFAULT_STDOUT) == null)
currentSettings.setValue(Settings.DEFAULT_STDOUT, defaultStdoutFile);
}
catch (Exception e) {
currentSettings.setValue(Settings.DEFAULT_STDOUT, defaultStdoutFile);
}
try {
if (currentSettings.getStrValue(Settings.STDOUT_USE) == null)
currentSettings.setValue(Settings.STDOUT_USE, defaultStdoutUse);
}
catch (Exception e) {
currentSettings.setValue(Settings.STDOUT_USE, defaultStdoutUse);
}
try {
currentSettings.getIntValue(Settings.MEMORY_SIZE);
}
catch (Exception e) {
currentSettings.setValue(Settings.MEMORY_SIZE, defaultMemorySize);
}
try {
if (currentSettings.getStrValue(Settings.UI_LANGUAGE) == null)
currentSettings.setValue(Settings.UI_LANGUAGE, defaultUILanguage);
}
catch (Exception e) {
currentSettings.setValue(Settings.UI_LANGUAGE, defaultUILanguage);
}
try {
currentSettings.getIntValue(Settings.RUN_MODE);
}
catch (Exception e) {
currentSettings.setValue(Settings.RUN_MODE, defaultRunningMode);
}
try {
currentSettings.getIntValue(Settings.COMPILE_MODE);
}
catch (Exception e) {
currentSettings.setValue(Settings.COMPILE_MODE, defaultCompilingMode);
}
}
/** This just loads the opened b91-program into Titokone's memory without updating
GUI anyway. However, GUI is told to show an error message, if the loaded program
is too large and thus Titokone is out of memory.
@returns LoadInfo object, which contains information about the loading process.
*/
private LoadInfo load() {
LoadInfo loadinfo;
try {
loadinfo = control.load();
}
catch (TTK91AddressOutOfBounds e) {
gui.showError(new Message("Titokone out of memory: {0}",
e.getMessage()).toString());
return null;
}
catch (TTK91NoStdInData e) {
File[] appDefs = control.getApplicationDefinitions();
String[] stdinFilePath = { getCurrentDefaultStdinFile().getPath() };
if ( appDefs[Control.DEF_STDIN_POS] != null ) {
stdinFilePath[0] = appDefs[Control.DEF_STDIN_POS].getPath();
}
gui.showError(e.getMessage());
return null;
}
return loadinfo;
}
/** Load the program into Titokone's memory and update's GUI to show the new memory contents
and register values and such.
*/
private void loadAndUpdateGUI() {
LoadInfo loadinfo = load();
if (loadinfo != null) {
gui.updateStatusBar(loadinfo.getStatusMessage());
gui.updateReg(GUI.SP, loadinfo.getSP());
gui.updateReg(GUI.FP, loadinfo.getFP());
String[][] symbolsAndValues = loadinfo.getSymbolTable();
gui.insertSymbolTable(symbolsAndValues);
int binaryCommands[] = loadinfo.getBinaryCommands();
String symbolicCommands[] = loadinfo.getSymbolicCommands();
int data[] = loadinfo.getData();
gui.insertToInstructionsTable(binaryCommands, symbolicCommands);
gui.insertToDataTable(data);
gui.addComment(loadinfo.getComments());
currentState = B91_NOT_RUNNING;
setGUICommandsForCurrentState();
gui.setGUIView(3);
}
}
/** Saves currentSettings to settingsFile.
*/
private void saveSettings() {
try {
control.saveSettings(currentSettings.toString(), settingsFile);
}
catch (IOException e) {
String[] errorParameters = { settingsFile.getName(), e.getMessage() };
gui.showError(new Message("{0} is inaccessible: {1}",
errorParameters).toString());
}
}
/** This method returns the default stdout file, which is the one declared in currentSettings.
*/
private File getCurrentDefaultStdoutFile() {
File currentStdoutFile = new File(System.getProperty("user.dir") + DEFAULT_STDOUT_FILENAME);
String filemode = currentSettings.getStrValue(Settings.STDOUT_PATH);
String path = currentSettings.getStrValue(Settings.DEFAULT_STDOUT);
if (path != null && !path.equals("")) {
if (filemode.equals("absolute")) {
currentStdoutFile = new File(path);
}
else if (filemode.equals("relative")) {
currentStdoutFile = new File(System.getProperty("user.dir") + path);
}
}
return currentStdoutFile;
}
/** This method returns the default stdin file, which is the one declared in currentSettings.
*/
private File getCurrentDefaultStdinFile() {
File currentStdinFile = new File(System.getProperty("user.dir") + DEFAULT_STDIN_FILENAME);
String filemode = currentSettings.getStrValue(Settings.STDIN_PATH);
String path = currentSettings.getStrValue(Settings.DEFAULT_STDIN);
if (path != null && !path.equals("")) {
if (filemode.equals("absolute")) {
currentStdinFile = new File(path);
}
else if (filemode.equals("relative")) {
currentStdinFile = new File(System.getProperty("user.dir") + path);
}
}
return currentStdinFile;
}
/** This method determines the available languages. It reads them from
a setup file languages.cfg, which contains lineseparator-delimited
sets of language-name, language-id, (country), eg.
"Finnish, fi", or "English (GB), en, GB".
*/
private void findAvailableLanguages() {
Logger logger;
URI fileURI;
File languageFile = null;
try {
fileURI = new URI( getClass().getClassLoader().getResource(programPath).toString() + "etc/languages.cfg" );
languageFile = new File(fileURI);
}
catch (Exception e) {
System.out.println(new Message("Main path not found! (Trying to locate " +
"etc/settings.cfg.) " +
"...exiting.").toString());
System.exit(0);
}
String languageName, language, country, variant;
if (languageFile.exists()) {
String languageFileContents;
try {
languageFileContents = control.loadSettingsFileContents(languageFile);
}
catch (IOException e) {
System.out.println(new Message("I/O error while reading settings " +
"file: {0}", e.getMessage()).toString());
return;
}
String[] languageFileRow = languageFileContents.split("\n|\r|\r\n");
System.out.println(languageFileContents);
/* Split each row of language.cfg into separate strings and
tokenize these strings by a colon. If there are two or three
tokens on each row, then everything goes well. Otherwise
the language.cfg is not a proper language file for this program.
*/
// TODO: This should just use a new Settings(String) and .getKeys().
for (int i=0 ; i<languageFileRow.length ; i++) {
String[] token = languageFileRow[i].split("=");
if (token.length != 2) {
System.out.println("Parse error in language file");
return;
}
languageName = token[0].trim();
token = token[1].split("\\.");
if (token.length == 1) {
language = token[0].trim();
availableLanguages.put(languageName, new Locale(language));
}
else if (token.length == 2) {
language = token[0].trim();
country = token[1].trim();
availableLanguages.put(languageName, new Locale(language, country));
}
else if (token.length == 3) {
language = token[0].trim();
country = token[1].trim();
variant = token[2].trim();
availableLanguages.put(languageName, new Locale(language, country, variant));
}
else {
//logger = Logger.getLogger(this.getClass().getPackage().toString());
//logger.fine(new Message("Parse error in language file").toString());
System.out.println("Parse error in language file");
}
}
}
}
public static String getExtension(File f) {
String ext = null;
String s = f.getName();
int i = s.lastIndexOf('.');
if (i > 0 && i < s.length() - 1) {
ext = s.substring(i+1).toLowerCase();
}
return ext;
}
/** Sets GUI to correspond the current state of program, which means that some
buttons should be enables while others not.
*/
private void setGUICommandsForCurrentState() {
switch (currentState) {
case NONE:
gui.disable(GUI.COMPILE_COMMAND);
gui.disable(GUI.RUN_COMMAND);
gui.disable(GUI.CONTINUE_COMMAND);
gui.disable(GUI.CONTINUE_WITHOUT_PAUSES_COMMAND);
gui.disable(GUI.STOP_COMMAND);
break;
case B91_NOT_RUNNING:
gui.disable(GUI.COMPILE_COMMAND);
gui.enable(GUI.RUN_COMMAND);
gui.disable(GUI.CONTINUE_COMMAND);
gui.disable(GUI.CONTINUE_WITHOUT_PAUSES_COMMAND);
gui.disable(GUI.STOP_COMMAND);
break;
case B91_RUNNING:
gui.disable(GUI.COMPILE_COMMAND);
gui.disable(GUI.RUN_COMMAND);
gui.disable(GUI.CONTINUE_COMMAND);
gui.disable(GUI.CONTINUE_WITHOUT_PAUSES_COMMAND);
gui.enable(GUI.STOP_COMMAND);
break;
case B91_PAUSED:
gui.disable(GUI.COMPILE_COMMAND);
gui.disable(GUI.RUN_COMMAND);
gui.enable(GUI.CONTINUE_COMMAND);
gui.enable(GUI.CONTINUE_WITHOUT_PAUSES_COMMAND);
gui.enable(GUI.STOP_COMMAND);
break;
case B91_WAIT_FOR_KBD:
gui.disable(GUI.COMPILE_COMMAND);
gui.disable(GUI.RUN_COMMAND);
gui.disable(GUI.CONTINUE_COMMAND);
gui.disable(GUI.CONTINUE_WITHOUT_PAUSES_COMMAND);
gui.enable(GUI.STOP_COMMAND);
break;
case K91_NOT_COMPILING:
gui.enable(GUI.COMPILE_COMMAND);
gui.disable(GUI.RUN_COMMAND);
gui.disable(GUI.CONTINUE_COMMAND);
gui.disable(GUI.CONTINUE_WITHOUT_PAUSES_COMMAND);
gui.disable(GUI.STOP_COMMAND);
gui.enable(GUI.CODE_TABLE_EDITING);
break;
case K91_COMPILING:
gui.disable(GUI.COMPILE_COMMAND);
gui.disable(GUI.RUN_COMMAND);
gui.disable(GUI.CONTINUE_COMMAND);
gui.disable(GUI.CONTINUE_WITHOUT_PAUSES_COMMAND);
gui.enable(GUI.STOP_COMMAND);
gui.disable(GUI.CODE_TABLE_EDITING);
break;
case K91_PAUSED:
gui.disable(GUI.COMPILE_COMMAND);
gui.disable(GUI.RUN_COMMAND);
gui.enable(GUI.CONTINUE_COMMAND);
gui.enable(GUI.CONTINUE_WITHOUT_PAUSES_COMMAND);
gui.enable(GUI.STOP_COMMAND);
gui.disable(GUI.CODE_TABLE_EDITING);
break;
case INTERRUPTED_WITH_PAUSE:
gui.disable(GUI.COMPILE_COMMAND);
gui.disable(GUI.RUN_COMMAND);
gui.enable(GUI.CONTINUE_COMMAND);
gui.enable(GUI.CONTINUE_WITHOUT_PAUSES_COMMAND);
gui.disable(GUI.STOP_COMMAND);
break;
}
}
} |
package info.justaway.util;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.Log;
import org.opencv.android.Utils;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.MatOfPoint;
import org.opencv.core.MatOfRect;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.core.RotatedRect;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.imgproc.Imgproc;
import org.opencv.imgproc.Moments;
import org.opencv.objdetect.CascadeClassifier;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import info.justaway.R;
import info.justaway.settings.BasicSettings;
public class FaceCrop {
private static final String TAG = FaceCrop.class.getSimpleName();
private boolean mIsFirst = true;
private boolean mIsSuccess;
private int mMaxHeight;
private float mWidth;
private float mHeight;
private Rect mRect;
private List<Rect> mRects = new ArrayList<>();
private int mColor = Color.MAGENTA;
private boolean mIsFace = false;
private static CascadeClassifier sFaceDetector = null;
private static CascadeClassifier sFaceDetector2 = null;
private static CascadeClassifier sFaceDetector_Cat = null;
private static Map<String, FaceCrop> sFaceInfoMap = new LinkedHashMap<String, FaceCrop>(100, 0.75f, true) {
private static final int MAX_ENTRIES = 100;
@Override
protected boolean removeEldestEntry(Map.Entry<String, FaceCrop> eldest) {
return size() > MAX_ENTRIES;
}
};
public static void initFaceDetector(Context context) {
if (sFaceDetector == null) {
sFaceDetector = setupFaceDetector(context, "lbpcascade_animeface.xml", R.raw.lbpcascade_animeface);
}
if (sFaceDetector2 == null) {
sFaceDetector2 = setupFaceDetector(context, "lbpcascade_frontalface_improved.xml", R.raw.lbpcascade_frontalface_improved);
}
if (sFaceDetector_Cat == null) {
sFaceDetector_Cat = setupFaceDetector(context, "lbpcascade_cat.xml", R.raw.lbpcascade_cat);
}
}
private static File setupCascadeFile(Context context, String fileName, int xml) {
File cascadeDir = context.getFilesDir();
File cascadeFile = null;
InputStream is = null;
FileOutputStream os = null;
try {
cascadeFile = new File(cascadeDir, fileName);
if (!cascadeFile.exists()) {
is = context.getResources().openRawResource(xml);
os = new FileOutputStream(cascadeFile);
byte[] buffer = new byte[4096];
int readLen = 0;
while ((readLen = is.read(buffer)) != -1) {
os.write(buffer, 0, readLen);
}
}
} catch (IOException e) {
return null;
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
// NOP
}
}
if (os != null) {
try {
os.close();
} catch (IOException e) {
// NOP
}
}
}
return cascadeFile;
}
private static CascadeClassifier setupFaceDetector(Context context, String fileName, int xml) {
File cascadeFile = setupCascadeFile(context, fileName, xml);
if (cascadeFile == null) {
return null;
}
CascadeClassifier detector = new CascadeClassifier(cascadeFile.getAbsolutePath());
detector.load(cascadeFile.getAbsolutePath());
if (detector.empty()) {
return null;
}
return detector;
}
public FaceCrop(int maxHeight, float w, float h) {
this.mMaxHeight = maxHeight;
this.mWidth = w;
this.mHeight = h;
}
private static Bitmap drawFaceRegion(Rect rect, Bitmap image, int color) {
try {
Bitmap result = image.copy(Bitmap.Config.ARGB_8888, true);
Paint paint = new Paint();
paint.setColor(color);
paint.setStrokeWidth(4);
paint.setStyle(Paint.Style.STROKE);
Canvas canvas = new Canvas(result);
if (rect != null) {
canvas.drawRect(rect.x, rect.y, rect.x + rect.width, rect.y + rect.height, paint);
}
return result;
} catch (Exception e) {
e.printStackTrace();
return image;
}
}
private static Bitmap drawFaceRegions(List<Rect> rects, Bitmap image, int color) {
try {
Bitmap result = image.copy(Bitmap.Config.ARGB_8888, true);
Paint paint = new Paint();
paint.setColor(color);
paint.setStrokeWidth(4);
paint.setStyle(Paint.Style.STROKE);
Canvas canvas = new Canvas(result);
for (Rect rect : rects) {
canvas.drawRect(rect.x, rect.y, rect.x + rect.width, rect.y + rect.height, paint);
}
return result;
} catch (Exception e) {
e.printStackTrace();
return image;
}
}
public Bitmap drawRegion(Bitmap bitmap) {
if (mIsSuccess) {
if (BasicSettings.isDebug()) {
// bitmap = drawFaceRegion(mRect, bitmap, Color.GREEN);
bitmap = drawFaceRegions(mRects, bitmap, mColor);
return bitmap;
}
}
return null;
}
private class DetectorConf {
public DetectorConf(CascadeClassifier detector, double angle, double scale, int neighbor, Size size, int color) {
this.detector = detector;
this.angle = angle;
this.scale = scale;
this.neighbor = neighbor;
this.size = size;
this.color = color;
}
public CascadeClassifier detector;
public double angle;
public double scale;
public int neighbor;
public Size size;
public int color;
}
public Rect getFaceRect(Bitmap bitmap) {
if (!mIsFirst) {
if (mColor == Color.MAGENTA || mColor == Color.GREEN) {
mColor = Color.GREEN;
} else {
mColor = Color.CYAN;
}
return mRect;
}
if (sFaceDetector == null) {
return mRect;
}
mIsFirst = false;
DetectorConf[] confs = new DetectorConf[] {
new DetectorConf(sFaceDetector, 0, 1.09f, 3, new Size(40, 40), Color.MAGENTA),
new DetectorConf(sFaceDetector, 10, 1.09f, 3, new Size(40, 40), Color.MAGENTA),
new DetectorConf(sFaceDetector, -10, 1.09f, 3, new Size(40, 40),Color.MAGENTA),
new DetectorConf(sFaceDetector2, 0, 1.09f, 3, new Size(40, 40),Color.BLUE),
new DetectorConf(sFaceDetector_Cat, 0, 1.09f, 3, new Size(40, 40), Color.BLUE)
};
try {
Mat imageMat = new Mat((int) mHeight, (int) mWidth, CvType.CV_8U, new Scalar(4));
Utils.bitmapToMat(bitmap, imageMat);
Imgproc.cvtColor(imageMat, imageMat, Imgproc.COLOR_RGB2GRAY);
Imgproc.equalizeHist(imageMat, imageMat);
double scale = mWidth * mHeight > 500 * 500 ? 0.5f : 1.0f;
if (scale < 1.0f) {
Imgproc.resize(imageMat, imageMat, new Size(mWidth * scale, mHeight * scale));
}
for (DetectorConf conf : confs) {
mColor = conf.color;
Rect ret = getFaceRectImpl(imageMat, conf, scale);
if (ret != null) {
return ret;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public Rect getFaceRectImpl(Mat imageMat, DetectorConf conf, double scale) {
if (conf.detector == null) {
return null;
}
try {
MatOfRect faces = new MatOfRect();
Mat rotMat = new Mat((int) mHeight, (int) mWidth, CvType.CV_8U, new Scalar(4));
if (conf.angle != 0) {
Mat rot = Imgproc.getRotationMatrix2D(new Point(mWidth / 2, mHeight / 2), conf.angle, 1.0f);
Imgproc.warpAffine(imageMat, rotMat, rot, imageMat.size());
} else {
rotMat = imageMat.clone();
}
conf.detector.detectMultiScale(rotMat, faces, conf.scale, conf.neighbor, 0, conf.size, new Size());
Rect[] facesArray = faces.toArray();
if (conf.angle != 0 || scale != 1.0f) {
for (Rect r : facesArray) {
if (conf.angle != 0) {
Point inPoint = r.tl();
Point outPoint = rotatePoint(inPoint, new Point(mWidth / 2, mHeight / 2), conf.angle);
r.x = (int) outPoint.x;
r.y = (int) outPoint.y;
}
if (scale != 1.0f) {
r.x /= scale;
r.y /= scale;
r.width /= scale;
r.height /= scale;
}
}
}
if (facesArray.length > 0) {
Rect r = getLargestFace(facesArray);
Log.d(TAG, String.format("image: (%s, %s)", mWidth, mHeight));
Log.d(TAG, String.format("face area: (%d, %d, %d, %d) : angle %s", r.x, r.y, r.width, r.height, conf.angle));
mRect = r;
mRects.clear();
Collections.addAll(mRects, facesArray);
mIsFace = true;
mIsSuccess = true;
if (conf.angle != 0) {
mColor = Color.YELLOW;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return mRect;
}
private Point rotatePoint(Point point, Point center, double angle) {
double rad = angle * Math.PI / 180.0;
Point inPoint = new Point(point.x - center.x, point.y - center.y);
Point outPoint = new Point();
outPoint.x = Math.cos(rad) * inPoint.x - Math.sin(rad) * inPoint.y + center.x;
outPoint.y = Math.sin(rad) * inPoint.x + Math.cos(rad) * inPoint.y + center.y;
return outPoint;
}
private Rect getGravityCenter(Bitmap bitmap) {
MatOfRect faces = new MatOfRect();
Mat imageMat = new Mat((int) mHeight, (int) mWidth, CvType.CV_8U, new Scalar(4));
Mat mask = new Mat((int) mHeight, (int) mWidth, CvType.CV_8U, new Scalar(4));
Mat hadairo = Mat.zeros((int) mHeight, (int) mWidth, CvType.CV_8U);
Utils.bitmapToMat(bitmap, imageMat);
Imgproc.cvtColor(imageMat, imageMat, Imgproc.COLOR_RGB2HSV);
Imgproc.medianBlur(imageMat, imageMat, 3);
Bitmap dst = Bitmap.createBitmap(imageMat.width(), imageMat.height(), Bitmap.Config.ARGB_8888);
Core.inRange(imageMat, new Scalar(0, 20, 88), new Scalar(25, 80, 255), mask);
// Utils.matToBitmap(mask, dst);
Utils.bitmapToMat(bitmap, imageMat);
Imgproc.cvtColor(hadairo, hadairo, Imgproc.COLOR_RGB2GRAY);
// Utils.matToBitmap(hadairo, dst);
Moments mu = Imgproc.moments(hadairo, false);
Rect r = new Rect();
r.x = (int) (mu.m10 / mu.m00);
r.y = (int) (mu.m01 / mu.m00);
r.x -= 50;
r.width = 100;
r.y -= 50;
r.height = 100;
mRect = r;
mRects.clear();
mRects.add(r);
mIsSuccess = true;
mColor = Color.BLUE;
return mRect;
}
private Rect getFeatureArea(Bitmap bitmap) {
MatOfRect faces = new MatOfRect();
Mat srcMat = new Mat((int) mHeight, (int) mWidth, CvType.CV_8U, new Scalar(4));
Utils.bitmapToMat(bitmap, srcMat);
Mat imageMat = new Mat((int) mHeight, (int) mWidth, CvType.CV_8U, new Scalar(4));
Imgproc.cvtColor(srcMat, imageMat, Imgproc.COLOR_RGB2HSV);
Imgproc.medianBlur(imageMat, imageMat, 3);
Bitmap dst = Bitmap.createBitmap(imageMat.width(), imageMat.height(), Bitmap.Config.ARGB_8888);
Mat tmp = new Mat((int) mHeight, (int) mWidth, CvType.CV_8U, new Scalar(4));
Mat bw = new Mat((int) mHeight, (int) mWidth, CvType.CV_8U, new Scalar(4));
Core.inRange(imageMat, new Scalar(0, 20, 88), new Scalar(25, 80, 255), bw);
Utils.matToBitmap(bw, dst);
Imgproc.threshold(bw, bw, 0, 255, Imgproc.THRESH_BINARY | Imgproc.THRESH_OTSU);
Utils.matToBitmap(bw, dst);
// ( and )
Mat kernel = Mat.ones(3, 3, CvType.CV_8U);
Imgproc.morphologyEx(bw, bw, Imgproc.MORPH_OPEN, kernel, new Point(-1, -1), 2);
// bw.convertTo(tmp, CvType.CV_8U);
Imgproc.cvtColor(bw, tmp, Imgproc.COLOR_GRAY2RGB, 4);
Utils.matToBitmap(tmp, dst);
Mat sureBg = new Mat((int) mHeight, (int) mWidth, CvType.CV_8U, new Scalar(4));
Imgproc.dilate(bw, sureBg, kernel, new Point(-1, -1), 3);
// sureBg.convertTo(tmp, CvType.CV_8U);
Imgproc.cvtColor(sureBg, tmp, Imgproc.COLOR_GRAY2RGB, 4);
Utils.matToBitmap(tmp, dst);
Mat sureFg = new Mat((int) mHeight, (int) mWidth, CvType.CV_8U, new Scalar(4));
Imgproc.distanceTransform(bw, sureFg, Imgproc.DIST_L2, 3); // 3.5 or 0 CV_8C1 -> CV_32FC1
sureFg.convertTo(tmp, CvType.CV_8U);
Imgproc.equalizeHist(tmp, tmp);
Utils.matToBitmap(tmp, dst);
Core.normalize(sureFg, sureFg, 0.0f, 255.0f, Core.NORM_MINMAX);
sureFg.convertTo(tmp, CvType.CV_8U);
Imgproc.equalizeHist(tmp, tmp);
Utils.matToBitmap(tmp, dst);
Imgproc.threshold(sureFg, sureFg, 40, 255, Imgproc.THRESH_BINARY);
Imgproc.dilate(sureFg, sureFg, kernel, new Point(-1, -1), 3); // CV_32FC1 -> CV_32FC1
sureFg.convertTo(tmp, CvType.CV_8U);
Imgproc.equalizeHist(tmp, tmp);
Utils.matToBitmap(tmp, dst);
Mat sureFgUC1 = sureFg.clone();
sureFg.convertTo(sureFgUC1, CvType.CV_8UC1);
Mat unknown = sureFg.clone();
Core.subtract(sureBg, sureFgUC1, unknown);
unknown.convertTo(tmp, CvType.CV_8U);
Imgproc.equalizeHist(tmp, tmp);
Utils.matToBitmap(tmp, dst);
Mat markers = Mat.zeros(sureFg.size(), CvType.CV_32SC1);
sureFg.convertTo(sureFg, CvType.CV_8U);
int nLabels = Imgproc.connectedComponents(sureFg, markers, 8, CvType.CV_32SC1);
if (nLabels < 2) {
return mRect;
}
Core.add(markers, new Scalar(1), markers);
for (int i=0; i<markers.rows(); i++) {
for (int j=0; j<markers.cols(); j++) {
double[] data = unknown.get(i, j);
if (data[0] == 255) {
int[] val = new int[] { 255 };
markers.put(i, j, val);
}
}
}
Imgproc.cvtColor(srcMat, srcMat, Imgproc.COLOR_RGBA2RGB);
Imgproc.watershed(srcMat, markers);
markers.convertTo(tmp, CvType.CV_8U);
Imgproc.equalizeHist(tmp, tmp);
Utils.matToBitmap(tmp, dst);
mRect = null;
mRects.clear();
return mRect;
}
private Rect getContourRect(Bitmap bitmap) {
if (bitmap == null) {
return mRect;
}
MatOfRect faces = new MatOfRect();
Mat imageMat = new Mat((int) mHeight, (int) mWidth, CvType.CV_8U, new Scalar(4));
Utils.bitmapToMat(bitmap, imageMat);
Imgproc.cvtColor(imageMat, imageMat, Imgproc.COLOR_RGB2HSV);
Imgproc.medianBlur(imageMat, imageMat, 5);
// Bitmap dst = Bitmap.createBitmap(imageMat.width(), imageMat.height(), Bitmap.Config.ARGB_8888);
Mat bw = new Mat((int) mHeight, (int) mWidth, CvType.CV_8U, new Scalar(4));
Core.inRange(imageMat, new Scalar(0, 20, 88), new Scalar(25, 80, 255), bw);
// Imgproc.threshold(bw, bw, 0, 255, Imgproc.THRESH_BINARY | Imgproc.THRESH_OTSU);
// ( and )
Mat kernel = Mat.ones(3, 3, CvType.CV_8U);
Imgproc.morphologyEx(bw, bw, Imgproc.MORPH_CLOSE, kernel, new Point(-1, -1), 2);
Imgproc.distanceTransform(bw, bw, Imgproc.DIST_L2, 3); // 3.5 or 0 CV_8C1 -> CV_32FC1
Core.normalize(bw, bw, 0.0f, 255.0f, Core.NORM_MINMAX);
Imgproc.threshold(bw, bw, 30, 255, Imgproc.THRESH_BINARY);
Imgproc.dilate(bw, bw, kernel, new Point(-1, -1), 3); // CV_32FC1 -> CV_32FC1
bw.convertTo(bw, CvType.CV_8U); // CV_32FC1 -> CV_8UC1
List<MatOfPoint> contours = new ArrayList<MatOfPoint>();
Mat hierarchy = Mat.zeros(new Size(5,5), CvType.CV_8UC1);
Imgproc.findContours(bw, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_TC89_L1);
mRect = null;
mRects.clear();
double maxArea = 0;
for (MatOfPoint contour : contours) {
Rect r = Imgproc.boundingRect(contour);
mRects.add(r);
double area = Imgproc.contourArea(contour);
if (maxArea < area) {
maxArea = area;
mRect = r;
}
}
if (contours.size() > 0) {
mColor = Color.BLUE;
mIsSuccess = true;
}
return mRect;
}
public Bitmap cropFace(Bitmap bitmap, float aspect) {
if (!mIsSuccess) {
return bitmap;
}
float w = bitmap.getWidth();
float h = bitmap.getHeight();
float bitmapAspect = h / w;
if (BasicSettings.isDebug()) {
// bitmap = drawFaceRegion(mRect, bitmap, mColor);
bitmap = drawFaceRegions(mRects, bitmap, mColor);
}
Rect r = new Rect(mRect.x, mRect.y, mRect.width, mRect.height);
if (bitmapAspect > aspect) {
r = addVPadding(r, bitmap, (int) (w * aspect));
Bitmap resized = Bitmap.createBitmap(bitmap, 0, r.y, (int)w, r.height);
return resized;
} else {
r = addHPadding(r, bitmap, (int) (h / aspect));
Bitmap resized = Bitmap.createBitmap(bitmap, r.x, 0, r.width, (int)h);
return resized;
}
}
public Bitmap invoke(Bitmap bitmap) {
mColor = mIsFirst ? Color.MAGENTA : Color.GREEN;
if (mIsFirst) {
mIsFirst = false;
if (sFaceDetector != null) {
MatOfRect faces = new MatOfRect();
Mat imageMat = new Mat((int) mHeight, (int) mWidth, CvType.CV_8U, new Scalar(4));
Utils.bitmapToMat(bitmap, imageMat);
Imgproc.cvtColor(imageMat, imageMat, Imgproc.COLOR_RGB2GRAY);
Imgproc.equalizeHist(imageMat, imageMat);
sFaceDetector.detectMultiScale(imageMat, faces, 1.1f, 3, 0, new Size(300 / 5, 300 / 5), new Size());
Rect[] facesArray = faces.toArray();
if (facesArray.length > 0) {
Rect r = getLargestFace(facesArray);
Log.d(TAG, String.format("image: (%s, %s)", mWidth, mHeight));
Log.d(TAG, String.format("face area: (%d, %d, %d, %d)", r.x, r.y, r.width, r.height));
mRect = r;
mRects.clear();
Collections.addAll(mRects, facesArray);
mIsSuccess = true;
}
}
}
if (mIsSuccess) {
if (BasicSettings.isDebug()) {
bitmap = drawFaceRegion(mRect, bitmap, mColor);
}
Rect r = new Rect(mRect.x, mRect.y, mRect.width, mRect.height);
r = addVPadding(r, bitmap, mMaxHeight);
Bitmap resized = Bitmap.createBitmap(bitmap, 0, r.y, (int) mWidth, r.height);
return resized;
} else {
return null;
}
}
static private Rect addVPadding(Rect r, Bitmap bitmap, int maxHeight) {
int padding = r.height < maxHeight ? maxHeight - r.height : (int)(r.height * 0.2f);
r.y -= padding / 2;
r.height += padding;
if (r.y < 0) {
r.y = 0;
}
int bottomExcess =r.y + r.height - bitmap.getHeight();
if (bottomExcess > 0) {
r.y -= bottomExcess;
if (r.y < 0) {
r.y = 0;
}
r.height = bitmap.getHeight() - r.y;
}
return r;
}
static private Rect addHPadding(Rect r, Bitmap bitmap, int maxWidth) {
int padding = r.width < maxWidth ? maxWidth - r.width : (int)(r.width * 0.2f);
r.x -= padding / 2;
r.width += padding;
if (r.x < 0) {
r.x = 0;
}
int rightExcess =r.x + r.width - bitmap.getWidth();
if (rightExcess > 0) {
r.x -= rightExcess;
if (r.x < 0) {
r.x = 0;
}
r.width = bitmap.getWidth() - r.x;
}
return r;
}
private Rect getLargestFace(Rect[] facesArray) {
Rect ret = null;
int maxSize = -1;
for (Rect r : facesArray) {
int size = r.width * r.height;
if (size > maxSize) {
ret = r;
maxSize = size;
}
}
return ret;
}
public static FaceCrop get(String imageUri, int maxHeight, float w, float h) {
FaceCrop faceCrop = sFaceInfoMap.get(imageUri);
if (faceCrop == null) {
faceCrop = new FaceCrop(maxHeight, w, h);
sFaceInfoMap.put(imageUri, faceCrop);
}
return faceCrop;
}
public boolean isSuccess() {
return mIsSuccess;
}
} |
package org.cinchapi.concourse.util;
import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.StandardCharsets;
import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;
/**
* Additional utility methods for ByteBuffers that are not found in the
* {@link ByteBuffer} class.
*
* @author jnelson
*/
public abstract class ByteBuffers {
/**
* Return a ByteBuffer that is a new read-only buffer that shares the
* content of {@code source} and has the same byte order, but maintains a
* distinct position, mark and limit.
*
* @param source
* @return the new, read-only byte buffer
*/
public static ByteBuffer asReadOnlyBuffer(ByteBuffer source) {
int position = source.position();
source.rewind();
ByteBuffer duplicate = source.asReadOnlyBuffer();
duplicate.order(source.order()); // byte order is not natively preserved
// when making duplicates:
source.position(position);
return duplicate;
}
/**
* Return a clone of {@code buffer} that has a copy of <em>all</em> its
* content and the same position and limit. Unlike the
* {@link ByteBuffer#slice()} method, the returned clone
* <strong>does not</strong> share its content with {@code buffer}, so
* subsequent operations to {@code buffer} or its clone will be
* completely independent and won't affect the other.
*
* @param buffer
* @return a clone of {@code buffer}
*/
public static ByteBuffer clone(ByteBuffer buffer) {
ByteBuffer clone = ByteBuffer.allocate(buffer.capacity());
int position = buffer.position();
int limit = buffer.limit();
buffer.rewind();
clone.put(buffer);
buffer.position(position);
clone.position(position);
buffer.limit(limit);
clone.limit(limit);
return clone;
}
/**
* Encode the remaining bytes in as {@link ByteBuffer} as a hex string and
* maintain the current position.
*
* @param buffer
* @return the hex string
*/
public static String encodeAsHexString(ByteBuffer buffer) {
StringBuilder sb = new StringBuilder();
buffer.mark();
while (buffer.hasRemaining()) {
sb.append(String.format("%02x", buffer.get()));
}
buffer.reset();
return sb.toString();
}
/**
* Relative <em>get</em> method. Reads the byte at the current position in
* {@code buffer} as a boolean, and then increments the position.
*
* @param buffer
* @return the boolean value at the current position
* @see {@link ByteBufferOutputStream#write(boolean)}
*/
public static boolean getBoolean(ByteBuffer buffer) {
return buffer.get() > 0 ? true : false;
}
/**
* Return a ByteBuffer that has a copy of {@code length} bytes from
* {@code buffer} starting from the current position. This method will
* advance the position of the source buffer.
*
* @param buffer
* @param bytes
* @return a ByteBuffer that has {@code length} bytes from {@code buffer}
*/
public static ByteBuffer get(ByteBuffer buffer, int length) {
Preconditions
.checkArgument(buffer.remaining() >= length,
"The number of bytes remaining in the buffer cannot be less than length");
byte[] backingArray = new byte[length];
buffer.get(backingArray);
return ByteBuffer.wrap(backingArray);
}
/**
* Relative <em>get</em> method. Reads the enum at the current position in
* {@code buffer} and then increments the position by four.
*
* @param buffer
* @param clazz
* @return the enum value at the current position
* @see {@link ByteBufferOutputStream#write(Enum)}
*/
public static <T extends Enum<?>> T getEnum(ByteBuffer buffer,
Class<T> clazz) {
return clazz.getEnumConstants()[buffer.getInt()];
}
/**
* Relative <em>get</em> method. Reads the UTF-8 encoded string at
* the current position in {@code buffer}.
*
* @param buffer
* @param charset
* @return the string value at the current position
* @see {@link ByteBufferOutputStream#write(String)}
*/
public static String getString(ByteBuffer buffer) {
return getString(buffer, StandardCharsets.UTF_8);
}
/**
* Relative <em>get</em> method. Reads the {@code charset} encoded string at
* the current position in {@code buffer}.
*
* @param buffer
* @param charset
* @return the string value at the current position
* @see {@link ByteBufferOutputStream#write(String, Charset)}
*/
public static String getString(ByteBuffer buffer, Charset charset) {
try {
CharsetDecoder decoder = charset.newDecoder();
decoder.onMalformedInput(CodingErrorAction.IGNORE);
return decoder.decode(buffer).toString().trim();
// necessary
// trim
// here
// because
// the
// decoding
// picks
// trailing
// whitespace
// sometimes
}
catch (CharacterCodingException e) {
throw Throwables.propagate(e);
}
}
/**
* Return a new ByteBuffer whose content is a shared subsequence of the
* content in {@code buffer} starting at the current position to
* current position + {@code length} (non-inclusive). Invoking this method
* has the same affect as doing the following:
*
* <pre>
* buffer.mark();
* int oldLimit = buffer.limit();
* buffer.limit(buffer.position() + length);
*
* ByteBuffer slice = buffer.slice();
*
* buffer.reset();
* buffer.limit(oldLimit);
* </pre>
*
* @param buffer
* @param length
* @return the new ByteBuffer slice
* @see {@link ByteBuffer#slice()}
*/
public static ByteBuffer slice(ByteBuffer buffer, int length) {
return slice(buffer, buffer.position(), length);
}
/**
* Return a new ByteBuffer whose content is a shared subsequence of the
* content in {@code buffer} starting at {@code position} to
* {@code position} + {@code length} (non-inclusive). Invoking this method
* has the same affect as doing the following:
*
* <pre>
* buffer.mark();
* int oldLimit = buffer.limit();
* buffer.position(position);
* buffer.limit(position + length);
*
* ByteBuffer slice = buffer.slice();
*
* buffer.reset();
* buffer.limit(oldLimit);
* </pre>
*
* @param buffer
* @param position
* @param length
* @return the new ByteBuffer slice
* @see {@link ByteBuffer#slice()}
*/
public static ByteBuffer slice(ByteBuffer buffer, int position, int length) {
int oldPosition = buffer.position();
int oldLimit = buffer.limit();
buffer.position(position);
buffer.limit(position + length);
ByteBuffer slice = buffer.slice();
buffer.limit(oldLimit);
buffer.position(oldPosition);
return slice;
}
/**
* Return a byte array with the content of {@code buffer}. This method
* returns the byte array that backs {@code buffer} if one exists, otherwise
* it creates a new byte array with the content between the current position
* of {@code buffer} and its limit.
*
* @param buffer
* @return the byte array with the content of {@code buffer}
*/
public static byte[] toByteArray(ByteBuffer buffer) {
if(buffer.hasArray()) {
return buffer.array();
}
else {
buffer.mark();
byte[] array = new byte[buffer.remaining()];
buffer.get(array);
buffer.reset();
return array;
}
}
} |
package Radioactivity_Sim;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import javax.swing.*;
public class RadioactivitySimTerminal extends JFrame {
//The program interface and console
/* Variable and Function Nomenclature prescripts:
* pv = private
* pr = protected
* pu = public
* pvs = private static
* prs = protected static
* pus = public static
* pvsf = private static final
* prsf = protected static final
* pusf = public static final
*/
private JTextPane pvTextPane;
private JTextField pvTextField;
private OutputScribe pvScrivener = new OutputScribe();
private NucleiSamplePredictiveSim pvPredictiveSample = new NucleiSamplePredictiveSim();
private NucleiSampleBruteForceSim pvBruteForceSample = new NucleiSampleBruteForceSim();
private String pvInputDir = "/home/user/git/Radioactivity_Sim/input/";
private String[] pvCommandLog;
private int pvCommandIndex = 0;
public RadioactivitySimTerminal() {
super("Radioactivity_Sim Terminal");
//creates a simple console
pvTextPane = new JTextPane();
pvTextPane.setCaretPosition(0);
pvTextPane.setMargin(new Insets(8,8,8,8));
JScrollPane scrollPane = new JScrollPane(pvTextPane);
scrollPane.setPreferredSize(new Dimension(800, 400));
pvTextPane.setEditable(false);
pvTextField = new JTextField();
pvTextField.setMargin(new Insets(8,8,8,8));
pvTextField.setEditable(true);
getContentPane().add(scrollPane, BorderLayout.CENTER);
getContentPane().add(pvTextField, BorderLayout.PAGE_START);
String initString = "Welcome to Radioactivity_Sim Terminal" + System.getProperty("line.separator") + "Enter help for command list" +System.getProperty("line.separator");
pvTextPane.setText(initString);
pvTextPane.setCaretPosition(0);
pvTextField.addKeyListener(new prTerminalKeyListener());;
}
private class prTerminalKeyListener
implements KeyListener {
public void keyTyped(KeyEvent e){
if(e.getKeyChar() == KeyEvent.VK_ENTER) {
//check for and execute commands
pvEnterCommand();
}
}
public void keyPressed(KeyEvent e){
//scroll back through old commands when up or down keys are pressed
//up = key code 38
//down = key code 40
if(e.getKeyCode()==38){
if(pvCommandIndex>0){
pvCommandIndex
}
pvTextField.setText(pvCommandLog[pvCommandIndex]);
} else if(e.getKeyCode()==40){
if(pvCommandIndex<(pvCommandLog.length-1)){
pvCommandIndex++;
}
pvTextField.setText(pvCommandLog[pvCommandIndex]);
}
}
public void keyReleased(KeyEvent e){
//no action
}
}
private void pvEnterCommand(){
//read text in from pvTextField
String commandString = pvTextField.getText();
pvLogCommand(commandString);
pvTextField.setText("");
StringBuilder currentText = new StringBuilder();
currentText.append(pvTextPane.getText() + System.getProperty("line.separator"));
currentText.append(">: " + commandString + System.getProperty("line.separator"));
pvTextPane.setText(currentText.toString());
//interpret command and print response or error
if(commandString.contains("help")){
currentText.append(System.getProperty("line.separator"));
currentText.append("The program commands are: " + System.getProperty("line.separator"));
currentText.append(">: clear" + System.getProperty("line.separator"));
currentText.append("This command clears the console." + System.getProperty("line.separator"));
currentText.append(System.getProperty("line.separator"));
currentText.append(">: add BFSample <numberOfNuclei> <inputFileName>" + System.getProperty("line.separator"));
currentText.append("This command adds nuclei to the brute force calculated nuclei sample, overwriting the current one." + System.getProperty("line.separator"));
currentText.append(System.getProperty("line.separator"));
currentText.append(">: add PSample <numberOfNuclei> <inputFileName>" + System.getProperty("line.separator"));
currentText.append("This command adds nuclei to the predictive calculated nuclei sample, overwriting the current one." + System.getProperty("line.separator"));
currentText.append(System.getProperty("line.separator"));
currentText.append(">: get PSample" + System.getProperty("line.separator"));
currentText.append("This command returns some statistics about the current NucleiSamplePredictiveSim" + System.getProperty("line.separator"));
currentText.append(System.getProperty("line.separator"));
currentText.append(">: get PSample energy all" + System.getProperty("line.separator"));
currentText.append("This command returns the sum of all event energies contained within the NucleiSamplePredictiveSim" + System.getProperty("line.separator"));
currentText.append(System.getProperty("line.separator"));
currentText.append(">: get PSample energy <startTime> <endTime>" + System.getProperty("line.separator"));
currentText.append("This command returns the sum of event energies contained within the NucleiSamplePredictiveSim which occur between <startTime> and <endTime>" + System.getProperty("line.separator"));
currentText.append(System.getProperty("line.separator"));
currentText.append(">: get BFSample" + System.getProperty("line.separator"));
currentText.append("This command returns some statistics about the current NucleiSampleBruteForceSim" + System.getProperty("line.separator"));
currentText.append(System.getProperty("line.separator"));
currentText.append(">: get inputDir" + System.getProperty("line.separator"));
currentText.append("This command returns the current dirctory from which the program is reading input files, and the contents thereof." + System.getProperty("line.separator"));
currentText.append(System.getProperty("line.separator"));
currentText.append(">: new NucleiSampleBruteForceSim <numberOfNuclei> <inputFileName> <startTime> <endTime>" + System.getProperty("line.separator"));
currentText.append("This command creates a new brute force calculated nuclei sample, overwriting the current one." + System.getProperty("line.separator"));
currentText.append(System.getProperty("line.separator"));
currentText.append(">: new NucleiSamplePredictiveSim <numberOfNuclei> <inputFileName> <startTime> <endTime> <resolution>" + System.getProperty("line.separator"));
currentText.append("This command creates a new predictive calculated nuclei sample, overwriting the current one." + System.getProperty("line.separator"));
currentText.append(System.getProperty("line.separator"));
currentText.append(">: set inputDir <Directory>" + System.getProperty("line.separator"));
currentText.append("This command sets the directory from which the program will read future input files." + System.getProperty("line.separator"));
currentText.append(System.getProperty("line.separator"));
currentText.append(">: verification1 <outfile>" + System.getProperty("line.separator"));
currentText.append("This command runs the verification1 test script and outputs it to <file>." + System.getProperty("line.separator"));
currentText.append(System.getProperty("line.separator"));
currentText.append(">: verification2 <outfile>" + System.getProperty("line.separator"));
currentText.append("This command runs the verification2 test script and outputs it to <file>." + System.getProperty("line.separator"));
currentText.append(System.getProperty("line.separator"));
currentText.append(">: verification3 <outfile>" + System.getProperty("line.separator"));
currentText.append("This command runs the verification3 test script and outputs it to <file>." + System.getProperty("line.separator"));
currentText.append(System.getProperty("line.separator"));
currentText.append(">: verification4 <outfile>" + System.getProperty("line.separator"));
currentText.append("This command runs the verification4 test script and outputs it to <file>." + System.getProperty("line.separator"));
pvTextPane.setText(currentText.toString());
}
String[] splits = commandString.split(" ");
if(splits[0].length()>=3) {
if(splits[0].compareTo("add")==0){
try {
if(splits.length==4){
if(splits[1].compareTo("PSample")==0){
try {
Double num = Double.valueOf(splits[2]);
String file = splits[3];
if(num > 0){
if(file.contains(pvInputDir)){
pvPredictiveSample.puAddSpecies(num,file);
currentText.append("Species added to NucleiSamplePredictiveSim!" + System.getProperty("line.separator"));
} else {
file = pvInputDir+file;
pvPredictiveSample.puAddSpecies(num,file);
currentText.append("Species added to NucleiSamplePredictiveSim!" + System.getProperty("line.separator"));
}
} else {
currentText.append("add NucleisamplePredictiveSim Failed! The <numberOfNuclei> must be greater than zero!" + System.getProperty("line.separator"));
currentText.append("Correct Syntax = add PSample <numberOfNuclei> <inputFileName>" + System.getProperty("line.separator"));
}
} catch (Exception e){
currentText.append(e.getClass() + " Occurred!" + System.getProperty("line.separator"));
currentText.append(e.getCause() + System.getProperty("line.separator"));
}
pvTextPane.setText(currentText.toString());
}
if(splits[1].compareTo("BFSample")==0){
try {
long num = Long.valueOf(splits[2]);
String file = splits[3];
if(num > 0){
if(file.contains(pvInputDir)){
pvBruteForceSample.puAddSpecies(num,file);
currentText.append("NucleiSampleBruteForceSim created!" + System.getProperty("line.separator"));
} else {
file = pvInputDir+file;
pvBruteForceSample.puAddSpecies(num,file);
currentText.append("NucleiSampleBruteForceSim created!" + System.getProperty("line.separator"));
}
} else {
currentText.append("add NucleisampleBruteForceSim Failed! The <numberOfNuclei> must be greater than zero!" + System.getProperty("line.separator"));
currentText.append("Correct Syntax = add BFSample <numberOfNuclei> <inputFileName>" + System.getProperty("line.separator"));
}
} catch (Exception e) {
currentText.append(e.getClass() + " Occurred!" + System.getProperty("line.separator"));
currentText.append(e.getCause() + System.getProperty("line.separator"));
}
pvTextPane.setText(currentText.toString());
}
}
} catch (Exception e) {
currentText.append("Error! add function has failed! Try typing help to find the correct format!" + System.getProperty("line.separator"));
pvTextPane.setText(currentText.toString());
}
}
if(splits[0].compareTo("get")==0){
try {
if(splits.length==2){
if(splits[1].compareTo("inputDir")==0){
currentText.append(System.getProperty("line.separator"));
currentText.append("The current input file directory is = " + pvInputDir + System.getProperty("line.separator"));
currentText.append("It contains the following files: " + System.getProperty("line.separator"));
File input = new File(pvInputDir);
File[] Files = input.listFiles();
for( int x = 0; x < Files.length; x++){
try {
currentText.append(Files[x].getCanonicalPath() + System.getProperty("line.separator"));
} catch (IOException e) {
currentText.append("Error! The program failed to print the file name!"+System.getProperty("line.separator"));
}
}
pvTextPane.setText(currentText.toString());
}
if(splits[1].compareTo("PSample")==0){
currentText.append(System.getProperty("line.separator"));
currentText.append("The current NucleiSamplePredictiveSim has the following properties: " + System.getProperty("line.separator"));
currentText.append("Sample start time = " + pvPredictiveSample.puGetStartTime() + System.getProperty("line.separator"));
currentText.append("Sample end time = " + pvPredictiveSample.puGetEndTime() + System.getProperty("line.separator"));
currentText.append("Sample resolution = " + pvPredictiveSample.puGetResolution() + System.getProperty("line.separator"));
currentText.append("Sample contains the following number of event sets = " + pvPredictiveSample.puGetNumDecayEventSets() + System.getProperty("line.separator"));
pvTextPane.setText(currentText.toString());
}
if(splits[1].compareTo("BFSample")==0){
currentText.append(System.getProperty("line.separator"));
currentText.append("The current NucleiSampleBruteForceSim has the following properties: " + System.getProperty("line.separator"));
currentText.append("Sample start time = " + pvBruteForceSample.puGetStartTime() + System.getProperty("line.separator"));
currentText.append("Sample end time = " + pvBruteForceSample.puGetEndTime() + System.getProperty("line.separator"));
currentText.append("Sample contains the following number of events = " + pvBruteForceSample.puGetNumDecayEvents() + System.getProperty("line.separator"));
pvTextPane.setText(currentText.toString());
}
}
if(splits.length==4){
if(splits[1].compareTo("PSample")==0){
if(splits[2].compareTo("energy")==0){
if(splits[3].compareTo("all")==0){
currentText.append(System.getProperty("line.separator"));
currentText.append("PSample Total Energy = " + pvPredictiveSample.puGetEnergySumOverTimeRange(pvPredictiveSample.puGetStartTime(),pvPredictiveSample.puGetEndTime()) + " [MeV]" + System.getProperty("line.separator"));
currentText.append(System.getProperty("line.separator"));
} else {
currentText.append("Command unknown! Please type help for a list of commands." + System.getProperty("line.separator"));
}
}
pvTextPane.setText(currentText.toString());
}
}
if(splits.length==5){
if(splits[1].compareTo("PSample")==0){
if(splits[2].compareTo("energy")==0){
try{
double start = Double.valueOf(splits[3]);
double end = Double.valueOf(splits[4]);
if(start >= 0){
if(end >= 0 & end > start){
currentText.append(System.getProperty("line.separator"));
currentText.append("PSample Energy = " + pvPredictiveSample.puGetEnergySumOverTimeRange(start,end) + " [MeV], between t_start = " + start + " and t_end = " + end + System.getProperty("line.separator"));
currentText.append(System.getProperty("line.separator"));
} else {
currentText.append("get PSample energy failed! The <endTime> must be greater than or equal to zero and greater than the <startTime>." + System.getProperty("line.separator"));
currentText.append("Correct Syntax = get PSample energy <startTime> <endTime>" + System.getProperty("line.separator"));
}
} else {
currentText.append("get PSample energy failed! The <startTime> must be greater than or equal to zero." + System.getProperty("line.separator"));
currentText.append("Correct Syntax = get PSample energy <startTime> <endTime>" + System.getProperty("line.separator"));
}
} catch (Exception e) {
currentText.append(e.getClass() + " Occurred!" + System.getProperty("line.separator"));
currentText.append(e.getCause() + System.getProperty("line.separator"));
}
}
pvTextPane.setText(currentText.toString());
}
}
} catch (Exception e) {
currentText.append("Error! get function has failed! Try typing help to find the correct format!" + System.getProperty("line.separator"));
pvTextPane.setText(currentText.toString());
}
}
if(splits[0].compareTo("new")==0){
try {
if(splits.length==7){
if(splits[1].compareTo("PSample")==0){
try {
Double num = Double.valueOf(splits[2]);
String file = splits[3];
Double start = Double.valueOf(splits[4]);
Double end = Double.valueOf(splits[5]);
int resolution = Integer.valueOf(splits[6]);
if(num > 0){
if(start >= 0){
if(end >= 0 & end > start){
if(resolution > 0){
if(file.contains(pvInputDir)){
pvPredictiveSample = new NucleiSamplePredictiveSim(num,file,start,end,resolution);
currentText.append("NucleiSamplePredictiveSim created!" + System.getProperty("line.separator"));
} else {
file = pvInputDir+file;
pvPredictiveSample = new NucleiSamplePredictiveSim(num,file,start,end,resolution);
currentText.append("NucleiSamplePredictiveSim created!" + System.getProperty("line.separator"));
}
} else {
currentText.append("new PSample Failed! The <resolution> must be greater than zero!" + System.getProperty("line.separator"));
currentText.append("Correct Syntax = new PSample <numberOfNuclei> <inputFileName> <startTime> <endTime> <resolution>" + System.getProperty("line.separator"));
}
} else {
currentText.append("new PSample Failed! The <endTime> must be greater than or equal to zero and greater than <startTime>!" + System.getProperty("line.separator"));
currentText.append("Correct Syntax = new PSample <numberOfNuclei> <inputFileName> <startTime> <endTime> <resolution>" + System.getProperty("line.separator"));
}
} else {
currentText.append("new PSample Failed! The <startTime> must be greater than or equal to zero!" + System.getProperty("line.separator"));
currentText.append("Correct Syntax = new PSample <numberOfNuclei> <inputFileName> <startTime> <endTime> <resolution>" + System.getProperty("line.separator"));
}
} else {
currentText.append("new PSample Failed! The <numberOfNuclei> must be greater than zero!" + System.getProperty("line.separator"));
currentText.append("Correct Syntax = new PSample <numberOfNuclei> <inputFileName> <startTime> <endTime> <resolution>" + System.getProperty("line.separator"));
}
} catch (Exception e) {
currentText.append(e.getClass() + " Occurred!" + System.getProperty("line.separator"));
currentText.append(e.getCause() + System.getProperty("line.separator"));
}
pvTextPane.setText(currentText.toString());
}
}
if(splits.length==6){
if(splits[1].compareTo("BFSample")==0){
try {
long num = Long.valueOf(splits[2]);
String file = splits[3];
double start = Double.valueOf(splits[4]);
double end = Double.valueOf(splits[5]);
if(num > 0){
if(start >= 0){
if(end >= 0 & end > start){
if(file.contains(pvInputDir)){
pvBruteForceSample = new NucleiSampleBruteForceSim(num,file,start,end);
currentText.append("NucleiSampleBruteForceSim created!" + System.getProperty("line.separator"));
} else {
file = pvInputDir+file;
pvBruteForceSample = new NucleiSampleBruteForceSim(num,file,start,end);
currentText.append("NucleiSampleBruteForceSim created!" + System.getProperty("line.separator"));
}
} else {
currentText.append("new BFSample Failed! The <endTime> must be greater than or equal to zero and greater than <startTime>!" + System.getProperty("line.separator"));
currentText.append("Correct Syntax = new BFSample <numberOfNuclei> <inputFileName> <startTime> <endTime>" + System.getProperty("line.separator"));
}
} else {
currentText.append("new BFSample Failed! The <startTime> must be greater than or equal to zero!" + System.getProperty("line.separator"));
currentText.append("Correct Syntax = new BFSample <numberOfNuclei> <inputFileName> <startTime> <endTime>" + System.getProperty("line.separator"));
}
} else {
currentText.append("new BFSample Failed! The <numberOfNuclei> must be greater than zero!" + System.getProperty("line.separator"));
currentText.append("Correct Syntax = new BFSample <numberOfNuclei> <inputFileName> <startTime> <endTime>" + System.getProperty("line.separator"));
}
} catch (Exception e) {
currentText.append(e.getClass() + " Occurred!" + System.getProperty("line.separator"));
currentText.append(e.getCause() + System.getProperty("line.separator"));
}
pvTextPane.setText(currentText.toString());
}
}
} catch (Exception e) {
currentText.append("Error! new function has failed! Try typing help to find the correct format!" + System.getProperty("line.separator"));
pvTextPane.setText(currentText.toString());
}
}
if(splits[0].compareTo("set")==0){
try {
if(splits.length==3){
if(splits[1].compareTo("inputDir")==0){
try {
pvInputDir = splits[2];
File inputDir = new File(pvInputDir);
if(inputDir.isDirectory()){
File[] Files = inputDir.listFiles();
currentText.append(System.getProperty("line.separator"));
currentText.append("The program has detected the following files in that directory: " + System.getProperty("line.separator"));
for(int x = 0; x<Files.length ;x++){
try {
currentText.append(Files[x].getCanonicalPath() + System.getProperty("line.separator"));
} catch (IOException e) {
currentText.append("An error occurred while reading the path name!" + System.getProperty("line.separator"));
}
}
} else {
currentText.append("Error! The supplied path = " + pvInputDir + " is not a Directory!" + System.getProperty("line.separator"));
}
} catch (Exception e) {
currentText.append(e.getClass() + " Occurred!" + System.getProperty("line.separator"));
currentText.append(e.getCause() + System.getProperty("line.separator"));
}
pvTextPane.setText(currentText.toString());
}
}
} catch (Exception e) {
currentText.append("Error! set function has failed! Try typing help to find the correct format!" + System.getProperty("line.separator"));
pvTextPane.setText(currentText.toString());
}
}
}
if(splits[0].length()>=13){
if(splits[0].compareTo("verification1")==0){
String file = splits[splits.length-1];
file = file.substring(0,file.length());
try{
pvVerification1(file);
} catch(Exception e) {
currentText.append(e.getClass() + " Occurred!" + System.getProperty("line.separator"));
currentText.append(e.getCause() + System.getProperty("line.separator"));
pvTextPane.setText(currentText.toString());
}
}
if(splits[0].compareTo("verification2")==0){
String file = splits[splits.length-1];
file = file.substring(0,file.length());
try{
pvVerification2(file);
} catch(Exception e) {
currentText.append(e.getClass() + " Occurred!" + System.getProperty("line.separator"));
currentText.append(e.getCause() + System.getProperty("line.separator"));
pvTextPane.setText(currentText.toString());
}
}
if(splits[0].compareTo("verification3")==0){
String file = splits[splits.length-1];
file = file.substring(0,file.length());
try{
pvVerification3(file);
} catch(Exception e) {
currentText.append(e.getClass() + " Occurred!" + System.getProperty("line.separator"));
currentText.append(e.getCause() + System.getProperty("line.separator"));
pvTextPane.setText(currentText.toString());
}
}
if(splits[0].compareTo("verification4 ")==0){
String file = splits[splits.length-1];
file = file.substring(0,file.length());
try{
pvVerification4(file);
} catch(Exception e) {
currentText.append(e.getClass() + " Occurred!" + System.getProperty("line.separator"));
currentText.append(e.getCause() + System.getProperty("line.separator"));
pvTextPane.setText(currentText.toString());
}
}
}
if(splits[0].length()>=5){
if(splits[0].compareTo("clear")==0){
currentText = new StringBuilder();
currentText.append(">:" + System.getProperty("line.separator"));
pvTextPane.setText(currentText.toString());
}
}
}
private static void prsShowGUI() {
//Create and set up the window.
final RadioactivitySimTerminal frame = new RadioactivitySimTerminal();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
prsShowGUI();
}
});
}
private void pvLogCommand(String command){
//adds a (command) to the (pvCommandLog)
try {
String[] log = new String[pvCommandLog.length+1];
for (int x = 0; x < pvCommandLog.length; x++) {
log[x] = pvCommandLog[x];
}
log[pvCommandLog.length] = command;
pvCommandLog = log;
pvCommandIndex = pvCommandLog.length - 1;
} catch (NullPointerException e) {
String[] log = new String[1];
log[0] = command;
pvCommandLog = log;
pvCommandIndex = 0;
}
}
private void pvVerification1(String file){
//Runs the verification1 test script and outputs it to (file)
double numRA224 = 0, numRN220 = 0, startTime = 0, endTime = 0;
int fileNum = 0;
//initialize time tracking
Calendar cal = Calendar.getInstance();
Date date = cal.getTime();
long now = date.getTime();
//read text in from pvTextField
String commandString = pvTextField.getText();
pvTextField.setText("");
//print command in pvTextPane
String currentText = pvTextPane.getText();
currentText = currentText + "\n" + commandString;
pvTextPane.setText(currentText);
int resolution = 1;
numRA224 = Math.pow(10, 5);
numRN220 = 17.58;
startTime = 0;
endTime = 100;
pvPredictiveSample = new NucleiSamplePredictiveSim(numRA224,"/home/user/git/Radioactivity_Sim/input/RA224test",startTime,endTime,resolution);
pvPredictiveSample.puAddSpecies(numRN220, "/home/user/git/Radioactivity_Sim/input/RN220test");
StringBuilder data = new StringBuilder();
data.append("verification1 for NucleiSamplePredictiveSim.java calculations: " + System.getProperty("line.separator"));
data.append("Secular Equilibrium occurs between RA224 and RN220 because the decay constant, lambda" + System.getProperty("line.separator"));
data.append("of RN220 is much greater than that of RA224. The decay constants are defined as: " + System.getProperty("line.separator"));
data.append(System.getProperty("line.separator"));
data.append(" lambda_RA224 = ln(2) / HALFLIFE_RA224 & lambda_RN220 = ln(2) / HALFLIFE_RN220 " + System.getProperty("line.separator"));
data.append(System.getProperty("line.separator"));
data.append("For these nuclei: lambda_RA224 = 2.19195E-6 & lambda_RN220 = 1.24667E-2 " + System.getProperty("line.separator"));
data.append("In the case of secular equilibrium, the number of child nuclei (in this case RN220) " + System.getProperty("line.separator"));
data.append("remains at a fixed ratio to the number of parent nuclei. This relationship is " + System.getProperty("line.separator"));
data.append("governed by the equation: N_RN220 = N_RA224 x lambda_RA224/lambda_RN220 " + System.getProperty("line.separator"));
data.append("where N is the total number of nuclei of each type. In order for this relationship " + System.getProperty("line.separator"));
data.append("to remain true, the number of decay events of the parent nuclei must equal the number" + System.getProperty("line.separator"));
data.append("of decay events of the child nuclei such that: NDECAYS_RA224 = NDECAYS_RN220 " + System.getProperty("line.separator"));
data.append("To prove this program's agreement with these theories we select a starting quantity " + System.getProperty("line.separator"));
data.append("of RA224 nuclei: " + System.getProperty("line.separator"));
data.append("N_RA224 = " + numRA224 + System.getProperty("line.separator"));
data.append("Then from theory, N_RN220 = " + numRA224 + "x(2.19195E-6/1.24667E-2) = " + (numRA224*2.19195*Math.pow(10, -6)/0.0124667) + System.getProperty("line.separator"));
data.append("Next, a sufficiently small time period is selected such that N_RA224 doesn't decrease" + System.getProperty("line.separator"));
data.append("by much. Let us choose a time period of 100 seconds. " + System.getProperty("line.separator"));
data.append("The number of decays of RA224 which occur in 100 seconds from a sample of 1E5 is " + System.getProperty("line.separator"));
data.append("given by: NDECAYS_RA224 = "+numRA224+" x(1 - e^(-100*lambda_RA224) = 21.92 " + System.getProperty("line.separator"));
data.append("Of course, in reality the number of decay events has to be a whole number, but for " + System.getProperty("line.separator"));
data.append("theory, it is acceptable to use the fraction, because it is an average amount that " + System.getProperty("line.separator"));
data.append("would occur during this time period. Since NDECAY_RA224 = NDECAY_RN220, the number " + System.getProperty("line.separator"));
data.append("of RN220 events is also 21.92. The energy released by each RA224 decay is 5.789 MeV " + System.getProperty("line.separator"));
data.append("and the energy released by each RN220 decay is 6.404 MeV. Therefore the total energy" + System.getProperty("line.separator"));
data.append("released is: NDECAY_RA224 x 5.789 + NDECAY_RN220 x 6.404 = 267.27 MeV " + System.getProperty("line.separator"));
data.append("and the average radiated power is: Energy/time = 267.27/100 = 2.6727 MeV/s " + System.getProperty("line.separator"));
data.append("Now let us see if the program can produce the same values: " + System.getProperty("line.separator"));
data.append(System.getProperty("line.separator"));
data.append("For a standard resolution of 10 we will get: " + System.getProperty("line.separator"));
data.append("Radiated Power = " + pvPredictiveSample.puGetRadiatedPowerOverTimeRange(startTime, endTime)+ " MeV/s" + System.getProperty("line.separator"));
data.append("Total Energy = " + pvPredictiveSample.puGetEnergySumOverTimeRange(startTime, endTime) + " MeV" + System.getProperty("line.separator"));
data.append(System.getProperty("line.separator"));
data.append(pvPredictiveSample.puGetAllEndTimeNucleiCounts());
data.append(System.getProperty("line.separator"));
data.append(pvPredictiveSample.puGetAllEventCountsOverTimeRangeByNuclei(startTime, endTime));
data.append(System.getProperty("line.separator"));
data.append("Next we see how the program is distributing the event energies into smaller groups as defined by the (resolution)" + System.getProperty("line.separator"));
double sum = 0;
for(int x = 1; x <= 1000 ;x = x*10) {
sum = 0;
data.append("For resolution set to " + x + " we get:" + System.getProperty("line.separator"));
pvPredictiveSample = new NucleiSamplePredictiveSim(numRA224,"/home/user/git/Radioactivity_Sim/input/RA224test",startTime,endTime,x);
pvPredictiveSample.puAddSpecies(17.58, "/home/user/git/Radioactivity_Sim/input/RN220test");
for(int y = 0; y < x; y++) {
data.append("Energy (t = "+(startTime+(y+1)*(endTime-startTime)/x)+") = " + pvPredictiveSample.puGetEnergySumOverTimeRange(startTime+y*(endTime-startTime)/x, startTime+(y+1)*(endTime-startTime)/x)+ " MeV" + System.getProperty("line.separator"));
sum += pvPredictiveSample.puGetEnergySumOverTimeRange(startTime+y*(endTime-startTime)/x, startTime+(y+1)*(endTime-startTime)/x);
}
data.append("Which all adds up to: " + sum + " MeV" + System.getProperty("line.separator"));
data.append(System.getProperty("line.separator"));
}
//retrieve the calculation time
data.append("Calculation Time = " + (Calendar.getInstance().getTime().getTime() - now) + System.getProperty("line.separator"));
data.append(">: " + System.getProperty("line.separator"));
pvScrivener.puOpenNewFile(file);
fileNum = pvScrivener.puGetNumFiles();
pvScrivener.puAppendStringToFile(fileNum-1, data.toString());
pvScrivener.puCloseFile(fileNum-1);
//write the output to pvTextPane
currentText = currentText + "\n" + data.toString();
pvTextPane.setText(currentText);
}
private void pvVerification2(String file){
//Runs the verification2 test script and outputs it to (file)
double numU238 = Math.pow(10, 26);
double numTH234 = 1.4776*Math.pow(10, 14);
double numPA234 = 1.7116*Math.pow(10, 12);
double startTime = 0, endTime = Math.pow(10,13);
int fileNum = 0;
//initialize time tracking
Calendar cal = Calendar.getInstance();
Date date = cal.getTime();
long now = date.getTime();
//read text in from pvTextField
String commandString = pvTextField.getText();
pvTextField.setText("");
//print command in pvTextPane
String currentText = pvTextPane.getText();
currentText = currentText + "\n" + commandString;
pvTextPane.setText(currentText);
int resolution = 10;
pvPredictiveSample = new NucleiSamplePredictiveSim(numU238,"/home/user/git/Radioactivity_Sim/input/U238test",startTime,endTime,resolution);
pvPredictiveSample.puAddSpecies(numTH234, "/home/user/git/Radioactivity_Sim/input/TH234test");
pvPredictiveSample.puAddSpecies(numPA234, "/home/user/git/Radioactivity_Sim/input/PA234test");
StringBuilder data = new StringBuilder();
data.append("verification2 for NucleiSamplePredictiveSim.java calculations: " + System.getProperty("line.separator"));
data.append("This verification is intended to show that the Radioactive_Sim program does not " + System.getProperty("line.separator"));
data.append("create or propagate error in decay products that are further down a chain. " + System.getProperty("line.separator"));
data.append("Secular Equilibrium occurs between U238 and the next two products on its decay chain " + System.getProperty("line.separator"));
data.append("TH234 and PA234 decay constant, lambda of PA234 is much greater than that of TH234 " + System.getProperty("line.separator"));
data.append("and the decay constant of TH234 is much greater than that of U238. " + System.getProperty("line.separator"));
data.append("The decay constants for these elements are defined as: " + System.getProperty("line.separator"));
data.append(System.getProperty("line.separator"));
data.append("lambda_RA224 = ln(2) / HALFLIFE_RA224 = 4.919 x 10^-19 " + System.getProperty("line.separator"));
data.append("lambda_RN220 = ln(2) / HALFLIFE_RN220 = 3.329 x 10^-7 " + System.getProperty("line.separator"));
data.append("lambda_PA234 = ln(2) / HALFLIFE_PA234 = 2.874 x 10^-5 " + System.getProperty("line.separator"));
data.append(System.getProperty("line.separator"));
data.append("In the case of secular equilibrium, the number of child nuclei (TH234 & PA234) " + System.getProperty("line.separator"));
data.append("remains at a fixed ratio to the number of parent nuclei. This relationship is " + System.getProperty("line.separator"));
data.append("governed by the equations: " + System.getProperty("line.separator"));
data.append("N_TH234 = N_U238 x lambda_U238/lambda_TH234 " + System.getProperty("line.separator"));
data.append("N_PA234 = N_TH234 x lambda_TH234/lambda_PA234 " + System.getProperty("line.separator"));
data.append("where N is the total number of nuclei of each type. In order for this relationship " + System.getProperty("line.separator"));
data.append("to remain true, the number of decay events of the parent nuclei must equal the number" + System.getProperty("line.separator"));
data.append("of decay events of the child nuclei such that: ND_U238 = ND_TH234 = ND_PA234 " + System.getProperty("line.separator"));
data.append("To prove this program's agreement with these theories we select a starting quantity " + System.getProperty("line.separator"));
data.append("of U238 nuclei: " + System.getProperty("line.separator"));
data.append("N_U238 = " + numU238 + System.getProperty("line.separator"));
data.append("Then: N_TH234 = " + numU238 + "x(4.919E-19/3.329E-7) = 1.4776 x 10^14 " + System.getProperty("line.separator"));
data.append("And: N_PA234 = " + numU238 + "x(4.919E-19/2.874E-5) = 1.7116 x 10^12 " + System.getProperty("line.separator"));
data.append("Next, a sufficiently small time period is selected such that N_U238 doesn't decrease " + System.getProperty("line.separator"));
data.append("by much. Let us choose a time period of 10^13 seconds (317,100 years). " + System.getProperty("line.separator"));
data.append("The number of decays of U238 which occur in 10^13 seconds from a sample of 1E26 is " + System.getProperty("line.separator"));
data.append("given by: ND_U238 = "+numU238+" x(1 - e^(-10^-13*lambda_U238) = 4.919 x 10^20 " + System.getProperty("line.separator"));
data.append("Since ND_U238 = ND_TH234 = ND_PA234, the number of the other events is also 4.919E20." + System.getProperty("line.separator"));
data.append("The energy released by each U238 decay is 4.2697 MeV, TH234 decays release 0.273 MeV " + System.getProperty("line.separator"));
data.append("and the energy released by each PA234 decay is 2.195 MeV. Therefore the total energy" + System.getProperty("line.separator"));
data.append("released is: ND_U238 x (4.2697 + 0.273 + 2.195) = 3.314 x 10^21 MeV " + System.getProperty("line.separator"));
data.append("and the average radiated power is: Energy/time = 3.314E21/1E13 = 3.3143E8 MeV/s " + System.getProperty("line.separator"));
data.append("Now let us see if this program can produce the same values: " + System.getProperty("line.separator"));
data.append(System.getProperty("line.separator"));
data.append("For a standard resolution of 10 we will get: " + System.getProperty("line.separator"));
data.append("Radiated Power = " + pvPredictiveSample.puGetRadiatedPowerOverTimeRange(startTime, endTime)+ " MeV/s" + System.getProperty("line.separator"));
data.append("Total Energy = " + pvPredictiveSample.puGetEnergySumOverTimeRange(startTime, endTime) + " MeV" + System.getProperty("line.separator"));
data.append(System.getProperty("line.separator"));
data.append(pvPredictiveSample.puGetAllEndTimeNucleiCounts());
data.append(System.getProperty("line.separator"));
data.append(pvPredictiveSample.puGetAllEventCountsOverTimeRangeByNuclei(startTime, endTime));
data.append(System.getProperty("line.separator"));
data.append("Next we see how the program is distributing the event energies into smaller groups as defined by the (resolution)" + System.getProperty("line.separator"));
double sum = 0;
for(int x = 1; x <= 1000;x = 10*x) {
sum = 0;
data.append("For resolution set to " + x + " we get:" + System.getProperty("line.separator"));
pvPredictiveSample = new NucleiSamplePredictiveSim(numU238,"/home/user/git/Radioactivity_Sim/input/U238test",startTime,endTime,x);
pvPredictiveSample.puAddSpecies(numTH234, "/home/user/git/Radioactivity_Sim/input/TH234test");
pvPredictiveSample.puAddSpecies(numPA234, "/home/user/git/Radioactivity_Sim/input/PA234test");
for(int y = 0; y < x; y++) {
data.append("Energy (t = "+(startTime+(y+1)*(endTime-startTime)/x)+") = " + pvPredictiveSample.puGetEnergySumOverTimeRange(startTime+y*(endTime-startTime)/x, startTime+(y+1)*(endTime-startTime)/x)+ " MeV" + System.getProperty("line.separator"));
sum += pvPredictiveSample.puGetEnergySumOverTimeRange(startTime+y*(endTime-startTime)/x, startTime+(y+1)*(endTime-startTime)/x);
}
data.append("Which all adds up to: " + sum + " MeV" + System.getProperty("line.separator"));
data.append(System.getProperty("line.separator"));
}
//retrieve the calculation time
data.append("Calculation Time = " + (Calendar.getInstance().getTime().getTime() - now) + System.getProperty("line.separator"));
data.append(">: " + System.getProperty("line.separator"));
pvScrivener.puOpenNewFile(file);
fileNum = pvScrivener.puGetNumFiles();
pvScrivener.puAppendStringToFile(fileNum-1, data.toString());
pvScrivener.puCloseFile(fileNum-1);
//write the output to pvTextPane
currentText = currentText + "\n" + data.toString();
pvTextPane.setText(currentText);
}
private void pvVerification3(String file){
//Runs the verification3 test script and outputs it to (file)
double startTime = 0, endTime = 0;
int fileNum = 0;
//initialize time tracking
Calendar cal = Calendar.getInstance();
Date date = cal.getTime();
long now = date.getTime();
//read text in from pvTextField
String commandString = pvTextField.getText();
pvTextField.setText("");
//print command in pvTextPane
String currentText = pvTextPane.getText();
currentText = currentText + "\n" + commandString;
pvTextPane.setText(currentText);
int resolution = 10;
startTime = 0; endTime = 100;
pvBruteForceSample = new NucleiSampleBruteForceSim(100000,"/home/user/git/Radioactivity_Sim/input/RA224test",startTime,endTime);
pvBruteForceSample.puAddSpecies(18, "/home/user/git/Radioactivity_Sim/input/RN220test");
StringBuilder data = new StringBuilder();
data.append("verification3 for NucleiSampleBruteForceSim.java calculations: " + System.getProperty("line.separator"));
data.append("Secular Equilibrium occurs between RA224 and RN220 because the decay constant, lambda" + System.getProperty("line.separator"));
data.append("of RN220 is much greater than that of RA224. The decay constants are defined as: " + System.getProperty("line.separator"));
data.append(System.getProperty("line.separator"));
data.append(" lambda_RA224 = ln(2) / HALFLIFE_RA224 & lambda_RN220 = ln(2) / HALFLIFE_RN220 " + System.getProperty("line.separator"));
data.append(System.getProperty("line.separator"));
data.append("For these nuclei: lambda_RA224 = 2.19195E-6 & lambda_RN220 = 1.24667E-2 " + System.getProperty("line.separator"));
data.append("In the case of secular equilibrium, the number of child nuclei (in this case RN220) " + System.getProperty("line.separator"));
data.append("remains at a fixed ratio to the number of parent nuclei. This relationship is " + System.getProperty("line.separator"));
data.append("governed by the equation: N_RN220 = N_RA224 x lambda_RA224/lambda_RN220 " + System.getProperty("line.separator"));
data.append("where N is the total number of nuclei of each type. In order for this relationship " + System.getProperty("line.separator"));
data.append("to remain true, the number of decay events of the parent nuclei must equal the number" + System.getProperty("line.separator"));
data.append("of decay events of the child nuclei such that: NDECAYS_RA224 = NDECAYS_RN220 " + System.getProperty("line.separator"));
data.append("To prove this program's agreement with these theories we select a starting quantity " + System.getProperty("line.separator"));
data.append("of RA224 nuclei: " + System.getProperty("line.separator"));
data.append("N_RA224 = " + 100000 + System.getProperty("line.separator"));
data.append("Then from theory, N_RN220 = " + 100000 + "x(2.19195E-6/1.24667E-2) = " + (100000*2.19195*Math.pow(10, -6)/0.0124667) + System.getProperty("line.separator"));
data.append("Next, a sufficiently small time period is selected such that N_RA224 doesn't decrease" + System.getProperty("line.separator"));
data.append("by much. Let us choose a time period of 100 seconds. " + System.getProperty("line.separator"));
data.append("The number of decays of RA224 which occur in 100 seconds from a sample of 1E5 is " + System.getProperty("line.separator"));
data.append("given by: NDECAYS_RA224 = "+100000+" x(1 - e^(-100*lambda_RA224) = 21.92 " + System.getProperty("line.separator"));
data.append("Of course, in reality the number of decay events has to be a whole number, but for " + System.getProperty("line.separator"));
data.append("theory, it is acceptable to use the fraction, because it is an average amount that " + System.getProperty("line.separator"));
data.append("would occur during this time period. Since NDECAY_RA224 = NDECAY_RN220, the number " + System.getProperty("line.separator"));
data.append("of RN220 events is also 21.92. The energy released by each RA224 decay is 5.789 MeV " + System.getProperty("line.separator"));
data.append("and the energy released by each RN220 decay is 6.404 MeV. Therefore the total energy" + System.getProperty("line.separator"));
data.append("released is: NDECAY_RA224 x 5.789 + NDECAY_RN220 x 6.404 = 267.27 MeV " + System.getProperty("line.separator"));
data.append("and the average radiated power is: Energy/time = 267.27/100 = 2.6727 MeV/s " + System.getProperty("line.separator"));
data.append("Now let us see if the program can produce the same values: " + System.getProperty("line.separator"));
data.append(System.getProperty("line.separator"));
pvScrivener.puOpenNewFile(file);
fileNum = pvScrivener.puGetNumFiles();
data.append("From the program we will get: " + System.getProperty("line.separator"));
double sumEnergy8 = 0;
double sumPower8 = 0;
for (int x = 0; x < 20; x++){
pvBruteForceSample = new NucleiSampleBruteForceSim(100000,"/home/user/git/Radioactivity_Sim/input/RA224test",startTime,endTime);
pvBruteForceSample.puAddSpecies(18, "/home/user/git/Radioactivity_Sim/input/RN220test");
data.append("Attempt No. " + (x+1) + System.getProperty("line.separator"));
data.append("Radiated Power = " + pvBruteForceSample.puGetRadiatedPowerOverTimeRange(startTime, endTime) + " MeV/s" + System.getProperty("line.separator"));
data.append("Total Energy = " + pvBruteForceSample.puGetEnergySumOverTimeRange(startTime, endTime) + " MeV" + System.getProperty("line.separator"));
data.append(System.getProperty("line.separator"));
sumEnergy8 += pvBruteForceSample.puGetEnergySumOverTimeRange(startTime, endTime);
sumPower8 += pvBruteForceSample.puGetRadiatedPowerOverTimeRange(startTime, endTime);
}
data.append("Average:" + System.getProperty("line.separator"));
data.append("Ave. Radiated Power = " + (sumPower8/20.0) + " MeV/s" + System.getProperty("line.separator"));
data.append("Ave. Total Energy = " + (sumEnergy8/20.0) + " MeV" + System.getProperty("line.separator"));
data.append(System.getProperty("line.separator"));
//retrieve the calculation time
data.append("Calculation Time = " + (Calendar.getInstance().getTime().getTime() - now) + System.getProperty("line.separator"));
data.append(">: " + System.getProperty("line.separator"));
pvScrivener.puOpenNewFile(file);
fileNum = pvScrivener.puGetNumFiles();
pvScrivener.puAppendStringToFile(fileNum-1, data.toString());
pvScrivener.puCloseFile(fileNum-1);
//write the output to pvTextPane
currentText = currentText + "\n" + data.toString();
pvTextPane.setText(currentText);
}
private void pvVerification4(String file){
//Runs the verification4 test script and outputs it to (file)
double startTime = 0, endTime = 0;
int fileNum = 0;
//initialize time tracking
Calendar cal = Calendar.getInstance();
Date date = cal.getTime();
long now = date.getTime();
//read text in from pvTextField
String commandString = pvTextField.getText();
pvTextField.setText("");
//print command in pvTextPane
String currentText = pvTextPane.getText();
currentText = currentText + "\n" + commandString;
pvTextPane.setText(currentText);
int resolution = 10;
startTime = 3*1.409*Math.pow(10,18)-Math.pow(10,13); endTime = 3*1.409*Math.pow(10,18);
pvPredictiveSample = new NucleiSamplePredictiveSim(Math.pow(10, 26),"/home/user/git/Radioactivity_Sim/input/U238",startTime,endTime,1);
StringBuilder data = new StringBuilder();
data.append("verification4 for NucleiSamplePredictiveSim.java calculations: " + System.getProperty("line.separator"));
data.append(System.getProperty("line.separator"));
data.append("In this verification a single pure sample of 10^26 U238 nuclei are allowed to decay " + System.getProperty("line.separator"));
data.append("for three half-lives and the decays which occur between t =" + startTime + " and " + endTime + System.getProperty("line.separator"));
data.append("are examined and verified for accuracy with the following hand calcs:" + System.getProperty("line.separator"));
data.append(System.getProperty("line.separator"));
data.append("Nuclei Parent ParentDecays EndTimeCount StartTimeCount PredictedDecays " + System.getProperty("line.separator"));
data.append("U238 N/A N/A 1.250000002E25 1.250006151E25 6.149298E19 " + System.getProperty("line.separator"));
data.append("TH234 U238 6.149298E19 1.847267569E13 1.847276656E13 6.149298E19 " + System.getProperty("line.separator"));
data.append("PA234 TH234 6.149298E19 2.139815476E11 2.139826002E11 6.149298E19 " + System.getProperty("line.separator"));
data.append("U234 PA234 6.149298E19 6.868472812E19 6.868506601E19 6.149331E19 " + System.getProperty("line.separator"));
data.append("TH230 U234 6.149331E19 2.108957662E19 2.108968037E19 6.149342E19 " + System.getProperty("line.separator"));
data.append("RA226 TH230 6.149342E19 1.250000002E25 1.250006151E25 6.149342E19 " + System.getProperty("line.separator"));
data.append("RN222 RA226 6.149342E19 1.250000002E25 1.250006151E25 6.149342E19 " + System.getProperty("line.separator"));
data.append("PO218 RN222 6.149342E19 1.250000002E25 1.250006151E25 6.149342E19 " + System.getProperty("line.separator"));
data.append("PB214 PO218 6.149342E19 1.250000002E25 1.250006151E25 6.149342E19 " + System.getProperty("line.separator"));
data.append("BI214 PB214 6.149342E19 1.250000002E25 1.250006151E25 6.149342E19 " + System.getProperty("line.separator"));
data.append("TI210 BI214 1.291362E16 1.250000002E25 1.250006151E25 1.291362E16 " + System.getProperty("line.separator"));
data.append("PB210 PO214,TI210 6.148051E19 1.250000002E25 1.250006151E25 6.149342E19 " + System.getProperty("line.separator"));
data.append("PO214 BI214 6.148051E19 1.250000002E25 1.250006151E25 6.148051E19 " + System.getProperty("line.separator"));
data.append("PB209 TI210 1.162226E12 1.250000002E25 1.250006151E25 1.162226E12 " + System.getProperty("line.separator"));
data.append("BI209 PB209 1.162226E12 1.250000002E25 1.250006151E25 1.213845E12 " + System.getProperty("line.separator"));
data.append("BI210 PB210 6.148530E19 1.250000002E25 1.250006151E25 6.148530E19 " + System.getProperty("line.separator"));
data.append("TI206 BI210 8.116060E15 1.250000002E25 1.250006151E25 8.116060E15 " + System.getProperty("line.separator"));
data.append("PO210 BI210 6.147718E19 1.250000002E25 1.250006151E25 6.147718E19 " + System.getProperty("line.separator"));
data.append(System.getProperty("line.separator"));
data.append("Energy of BI214 decays is 6.149342E19x(0.99979x3.27[MeV]+0.00021x5.6213[MeV]) = " + (6.149342*Math.pow(10, 19)*(0.99979*3.27+0.00021*5.6213)) + " [MeV]" + System.getProperty("line.separator"));
data.append("and the energy of PO214 decays is 6148051E19x7.83346[MeV] = " + (6.148051*Math.pow(10,19)*7.83346) + " [MeV]" + System.getProperty("line.separator"));
data.append("Which adds up to: " + ((6.148051*Math.pow(10,19)*7.83346)+(6.149342*Math.pow(10, 19)*(0.99979*3.27+0.00021*5.6213))) + " [MeV]" + System.getProperty("line.separator"));
data.append("Now let's see what the program comes up with: " + System.getProperty("line.separator"));
data.append(System.getProperty("line.separator"));
data.append("From the program we will get: " + System.getProperty("line.separator"));
data.append("Radiated Power (for BI214 and PO214) = " + (pvPredictiveSample.puGetRadiatedPowerForStartNucleusOverTimeRange(startTime, endTime,"BI214")+pvPredictiveSample.puGetRadiatedPowerForStartNucleusOverTimeRange(startTime, endTime, "PO214"))+ " MeV/s" + System.getProperty("line.separator"));
data.append("Total Energy (for BI214 and PO214) = " + (pvPredictiveSample.puGetEnergySumForStartingNucleusOverTimeRange(startTime, endTime, "BI214")+pvPredictiveSample.puGetEnergySumForStartingNucleusOverTimeRange(startTime, endTime, "PO214")) + " MeV" + System.getProperty("line.separator"));
data.append(System.getProperty("line.separator"));
data.append(pvPredictiveSample.puGetAllStartTimeNucleiCounts());
data.append(System.getProperty("line.separator"));
data.append(pvPredictiveSample.puGetAllEndTimeNucleiCounts());
data.append(System.getProperty("line.separator"));
data.append(pvPredictiveSample.puGetAllEventCountsOverTimeRangeByNuclei(startTime, endTime));
data.append(System.getProperty("line.separator"));
double sum = 0;
for(int x = 1; x <= 1000;x = 10*x) {
sum = 0;
data.append("For resolution set to " + x + " we get:" + System.getProperty("line.separator"));
pvPredictiveSample = new NucleiSamplePredictiveSim(Math.pow(10, 26),"/home/user/git/Radioactivity_Sim/input/U238",startTime,endTime,x);
for(double y = 0; y < x; y++) {
data.append("Energy (BI214 & PO214)(t = "+(startTime+(y+1)*(endTime-startTime)/x)+") = " + (pvPredictiveSample.puGetEnergySumForStartingNucleusOverTimeRange(startTime+y*(endTime-startTime)/x, startTime+(y+1)*(endTime-startTime)/x,"BI214")+pvPredictiveSample.puGetEnergySumForStartingNucleusOverTimeRange(startTime+y*(endTime-startTime)/x, startTime+(y+1)*(endTime-startTime)/x, "PO214")) + " MeV" + System.getProperty("line.separator"));
sum += (pvPredictiveSample.puGetEnergySumForStartingNucleusOverTimeRange(startTime+y*(endTime-startTime)/x, startTime+(y+1)*(endTime-startTime)/x,"BI214")+pvPredictiveSample.puGetEnergySumForStartingNucleusOverTimeRange(startTime+y*(endTime-startTime)/x, startTime+(y+1)*(endTime-startTime)/x, "PO214"));
}
data.append("Which all adds up to: " + sum + " MeV" + System.getProperty("line.separator"));
data.append(System.getProperty("line.separator"));
}
//retrieve the calculation time
data.append("Calculation Time = " + (Calendar.getInstance().getTime().getTime() - now) + System.getProperty("line.separator"));
data.append(">: " + System.getProperty("line.separator"));
pvScrivener.puOpenNewFile(file);
fileNum = pvScrivener.puGetNumFiles();
pvScrivener.puAppendStringToFile(fileNum-1, data.toString());
pvScrivener.puCloseFile(fileNum-1);
//write the output to pvTextPane
currentText = currentText + "\n" + data.toString();
pvTextPane.setText(currentText);
}
}
//private void prWriteAllEventData(String file) {
////Writes all event data (Warning! limited by maximum size of java String's!)
//String data = pvPredictiveSample.puGetAllEventData();
//scrivener.puOpenNewFile(file);
//fileNum = scrivener.puGetNumFiles();
//scrivener.puAppendStringToFile(fileNum-1, data);
//scrivener.puCloseFile(fileNum-1);
//Writes the average per minute energy for the first year (Warning! This is only useful if (startTime)<365*24*60*60!)
// String file2 = "/home/user/git/Radioactivity_Sim/output/FirstYear";
// String data2 = test.puGetPerSecondAveEnergyForOneYear(0);
// scrivener.puOpenNewFile(file2);
// fileNum = scrivener.puGetNumFiles();
// scrivener.puAppendStringToFile(fileNum-1, data2);
// scrivener.puCloseFile(fileNum-1);
//Writes the average per second energy for a year starting at (startTime)
// String file3 = "/home/user/git/Radioactivity_Sim/output/Output";
// String data3 = test.puGetPerSecondAveEnergyForOneYear(startTime);
// scrivener.puOpenNewFile(file3);
// fileNum = scrivener.puGetNumFiles();
// scrivener.puAppendStringToFile(fileNum-1, data3);
// scrivener.puCloseFile(fileNum-1);
//Writes the parsed (RuleBranches) to a file
// String file4 = "/home/user/git/Radioactivity_Sim/output/RuleBranches";
// DecayChainRuleSet rules4 = test.puGetDecayChainRuleSet(0);
// int numRuleSets4 = rules4.puGetNumBranches();
// StringBuilder data4 = new StringBuilder();
// for (int x = 0; x<numRuleSets4; x++){
// data4.append("Branch No: " + x + System.getProperty("line.separator"));
// data4.append(rules4.puOutputDecayRuleBranch(x) + System.getProperty("line.separator"));
// scrivener.puOpenNewFile(file4);
// fileNum = scrivener.puGetNumFiles();
// scrivener.puAppendStringToFile(fileNum-1, data4.toString());
// scrivener.puCloseFile(fileNum-1);
//Writes the first parsed (RuleSet) for the (NucleiSamplePredictiveSim) to file
// String file5 = "/home/user/git/Radioactivity_Sim/output/RuleSet";
// DecayChainRuleSet rules5 = test.puGetDecayChainRuleSet(0);
// scrivener.puOpenNewFile(file5);
// fileNum = scrivener.puGetNumFiles();
// scrivener.puAppendStringToFile(fileNum-1, rules5.puOutputDecayChainRuleSet());
// scrivener.puCloseFile(fileNum-1);
// //Verify if the calculations agree with theory:
// num = Math.pow(10, 5);
// startTime = 0; endTime = 100; resolution = 1;
// NucleiSamplePredictiveSim test6 = new NucleiSamplePredictiveSim(num,"/home/user/git/Radioactivity_Sim/input/RA224test",startTime,endTime,resolution);
// test6.puAddSpecies(17.58, "/home/user/git/Radioactivity_Sim/input/RN220test", startTime, endTime);
// String file6 = "/home/user/git/Radioactivity_Sim/proofs/verification1";
// StringBuilder data6 = new StringBuilder();
// data6.append("verification1 for NucleiSamplePredictiveSim.java calculations: " + System.getProperty("line.separator"));
// data6.append("Secular Equilibrium occurs between RA224 and RN220 because the decay constant, lambda" + System.getProperty("line.separator"));
// data6.append("of RN220 is much greater than that of RA224. The decay constants are defined as: " + System.getProperty("line.separator"));
// data6.append(System.getProperty("line.separator"));
// data6.append(" lambda_RA224 = ln(2) / HALFLIFE_RA224 & lambda_RN220 = ln(2) / HALFLIFE_RN220 " + System.getProperty("line.separator"));
// data6.append(System.getProperty("line.separator"));
// data6.append("For these nuclei: lambda_RA224 = 2.19195E-6 & lambda_RN220 = 1.24667E-2 " + System.getProperty("line.separator"));
// data6.append("In the case of secular equilibrium, the number of child nuclei (in this case RN220) " + System.getProperty("line.separator"));
// data6.append("remains at a fixed ratio to the number of parent nuclei. This relationship is " + System.getProperty("line.separator"));
// data6.append("governed by the equation: N_RN220 = N_RA224 x lambda_RA224/lambda_RN220 " + System.getProperty("line.separator"));
// data6.append("where N is the total number of nuclei of each type. In order for this relationship " + System.getProperty("line.separator"));
// data6.append("to remain true, the number of decay events of the parent nuclei must equal the number" + System.getProperty("line.separator"));
// data6.append("of decay events of the child nuclei such that: NDECAYS_RA224 = NDECAYS_RN220 " + System.getProperty("line.separator"));
// data6.append("To prove this program's agreement with these theories we select a starting quantity " + System.getProperty("line.separator"));
// data6.append("of RA224 nuclei: " + System.getProperty("line.separator"));
// data6.append("N_RA224 = " + num + System.getProperty("line.separator"));
// data6.append("Then from theory, N_RN220 = " + num + "x(2.19195E-6/1.24667E-2) = " + (num*2.19195*Math.pow(10, -6)/0.0124667) + System.getProperty("line.separator"));
// data6.append("Next, a sufficiently small time period is selected such that N_RA224 doesn't decrease" + System.getProperty("line.separator"));
// data6.append("by much. Let us choose a time period of 100 seconds. " + System.getProperty("line.separator"));
// data6.append("The number of decays of RA224 which occur in 100 seconds from a sample of 1E5 is " + System.getProperty("line.separator"));
// data6.append("given by: NDECAYS_RA224 = "+num+" x(1 - e^(-100*lambda_RA224) = 21.92 " + System.getProperty("line.separator"));
// data6.append("Of course, in reality the number of decay events has to be a whole number, but for " + System.getProperty("line.separator"));
// data6.append("theory, it is acceptable to use the fraction, because it is an average amount that " + System.getProperty("line.separator"));
// data6.append("would occur during this time period. Since NDECAY_RA224 = NDECAY_RN220, the number " + System.getProperty("line.separator"));
// data6.append("of RN220 events is also 21.92. The energy released by each RA224 decay is 5.789 MeV " + System.getProperty("line.separator"));
// data6.append("and the energy released by each RN220 decay is 6.404 MeV. Therefore the total energy" + System.getProperty("line.separator"));
// data6.append("released is: NDECAY_RA224 x 5.789 + NDECAY_RN220 x 6.404 = 267.27 MeV " + System.getProperty("line.separator"));
// data6.append("and the average radiated power is: Energy/time = 267.27/100 = 2.6727 MeV/s " + System.getProperty("line.separator"));
// data6.append("Now let us see if the program can produce the same values: " + System.getProperty("line.separator"));
// data6.append(System.getProperty("line.separator"));
// scrivener.puOpenNewFile(file6);
// fileNum = scrivener.puGetNumFiles();
// data6.append("For a standard resolution of 10 we will get: " + System.getProperty("line.separator"));
// data6.append("Radiated Power = " + test6.puGetRadiatedPowerOverTimeRange(startTime, endTime)+ " MeV/s" + System.getProperty("line.separator"));
// data6.append("Total Energy = " + test6.puGetEnergySumOverTimeRange(startTime, endTime) + " MeV" + System.getProperty("line.separator"));
// data6.append(System.getProperty("line.separator"));
// data6.append(test6.puGetAllEndTimeNucleiCounts());
// data6.append(System.getProperty("line.separator"));
// data6.append(test6.puGetAllEventCountsOverTimeRangeByNuclei(startTime, endTime));
// data6.append(System.getProperty("line.separator"));
// data6.append("Next we see how the program is distributing the event energies into smaller groups as defined by the (resolution)" + System.getProperty("line.separator"));
// double sum6 = 0;
// for(int x = 1; x <= 1000 ;x = x*10) {
// sum6 = 0;
// data6.append("For resolution set to " + x + " we get:" + System.getProperty("line.separator"));
// test6 = new NucleiSamplePredictiveSim(num,"/home/user/git/Radioactivity_Sim/input/RA224test",startTime,endTime,x);
// test6.puAddSpecies(17.58, "/home/user/git/Radioactivity_Sim/input/RN220test", startTime, endTime);
// for(int y = 0; y < x; y++) {
// data6.append("Energy (t = "+(startTime+(y+1)*(endTime-startTime)/x)+") = " + test6.puGetEnergySumOverTimeRange(startTime+y*(endTime-startTime)/x, startTime+(y+1)*(endTime-startTime)/x)+ " MeV" + System.getProperty("line.separator"));
// sum6 += test6.puGetEnergySumOverTimeRange(startTime+y*(endTime-startTime)/x, startTime+(y+1)*(endTime-startTime)/x);
// data6.append("Which all adds up to: " + sum6 + " MeV" + System.getProperty("line.separator"));
// data6.append(System.getProperty("line.separator"));
// scrivener.puAppendStringToFile(fileNum-1, data6.toString());
// scrivener.puCloseFile(fileNum-1);
// //Verify if the calculations agree with theory:
// double numU238 = Math.pow(10, 26);
// double numTH234 = 1.4776*Math.pow(10, 14);
// double numPA234 = 1.7116*Math.pow(10, 12);
// startTime = 0; endTime = Math.pow(10,13); resolution = 10;
// NucleiSamplePredictiveSim test7 = new NucleiSamplePredictiveSim(numU238,"/home/user/git/Radioactivity_Sim/input/U238test",startTime,endTime,resolution);
// test7.puAddSpecies(numTH234, "/home/user/git/Radioactivity_Sim/input/TH234test", startTime, endTime);
// test7.puAddSpecies(numPA234, "/home/user/git/Radioactivity_Sim/input/PA234test", startTime, endTime);
// String file7 = "/home/user/git/Radioactivity_Sim/proofs/verification2";
// StringBuilder data7 = new StringBuilder();
// data7.append("verification2 for NucleiSamplePredictiveSim.java calculations: " + System.getProperty("line.separator"));
// data7.append("This verification is intended to show that the Radioactive_Sim program does not " + System.getProperty("line.separator"));
// data7.append("create or propagate error in decay products that are further down a chain. " + System.getProperty("line.separator"));
// data7.append("Secular Equilibrium occurs between U238 and the next two products on its decay chain " + System.getProperty("line.separator"));
// data7.append("TH234 and PA234 decay constant, lambda of PA234 is much greater than that of TH234 " + System.getProperty("line.separator"));
// data7.append("and the decay constant of TH234 is much greater than that of U238. " + System.getProperty("line.separator"));
// data7.append("The decay constants for these elements are defined as: " + System.getProperty("line.separator"));
// data7.append(System.getProperty("line.separator"));
// data7.append("lambda_RA224 = ln(2) / HALFLIFE_RA224 = 4.919 x 10^-19 " + System.getProperty("line.separator"));
// data7.append("lambda_RN220 = ln(2) / HALFLIFE_RN220 = 3.329 x 10^-7 " + System.getProperty("line.separator"));
// data7.append("lambda_PA234 = ln(2) / HALFLIFE_PA234 = 2.874 x 10^-5 " + System.getProperty("line.separator"));
// data7.append(System.getProperty("line.separator"));
// data7.append("In the case of secular equilibrium, the number of child nuclei (TH234 & PA234) " + System.getProperty("line.separator"));
// data7.append("remains at a fixed ratio to the number of parent nuclei. This relationship is " + System.getProperty("line.separator"));
// data7.append("governed by the equations: " + System.getProperty("line.separator"));
// data7.append("N_TH234 = N_U238 x lambda_U238/lambda_TH234 " + System.getProperty("line.separator"));
// data7.append("N_PA234 = N_TH234 x lambda_TH234/lambda_PA234 " + System.getProperty("line.separator"));
// data7.append("where N is the total number of nuclei of each type. In order for this relationship " + System.getProperty("line.separator"));
// data7.append("to remain true, the number of decay events of the parent nuclei must equal the number" + System.getProperty("line.separator"));
// data7.append("of decay events of the child nuclei such that: ND_U238 = ND_TH234 = ND_PA234 " + System.getProperty("line.separator"));
// data7.append("To prove this program's agreement with these theories we select a starting quantity " + System.getProperty("line.separator"));
// data7.append("of U238 nuclei: " + System.getProperty("line.separator"));
// data7.append("N_U238 = " + numU238 + System.getProperty("line.separator"));
// data7.append("Then: N_TH234 = " + numU238 + "x(4.919E-19/3.329E-7) = 1.4776 x 10^14 " + System.getProperty("line.separator"));
// data7.append("And: N_PA234 = " + numU238 + "x(4.919E-19/2.874E-5) = 1.7116 x 10^12 " + System.getProperty("line.separator"));
// data7.append("Next, a sufficiently small time period is selected such that N_U238 doesn't decrease " + System.getProperty("line.separator"));
// data7.append("by much. Let us choose a time period of 10^13 seconds (317,100 years). " + System.getProperty("line.separator"));
// data7.append("The number of decays of U238 which occur in 10^13 seconds from a sample of 1E26 is " + System.getProperty("line.separator"));
// data7.append("given by: ND_U238 = "+numU238+" x(1 - e^(-10^-13*lambda_U238) = 4.919 x 10^20 " + System.getProperty("line.separator"));
// data7.append("Since ND_U238 = ND_TH234 = ND_PA234, the number of the other events is also 4.919E20." + System.getProperty("line.separator"));
// data7.append("The energy released by each U238 decay is 4.2697 MeV, TH234 decays release 0.273 MeV " + System.getProperty("line.separator"));
// data7.append("and the energy released by each PA234 decay is 2.195 MeV. Therefore the total energy" + System.getProperty("line.separator"));
// data7.append("released is: ND_U238 x (4.2697 + 0.273 + 2.195) = 3.314 x 10^21 MeV " + System.getProperty("line.separator"));
// data7.append("and the average radiated power is: Energy/time = 3.314E21/1E13 = 3.3143E8 MeV/s " + System.getProperty("line.separator"));
// data7.append("Now let us see if this program can produce the same values: " + System.getProperty("line.separator"));
// data7.append(System.getProperty("line.separator"));
// scrivener.puOpenNewFile(file7);
// fileNum = scrivener.puGetNumFiles();
// data7.append("For a standard resolution of 10 we will get: " + System.getProperty("line.separator"));
// data7.append("Radiated Power = " + test7.puGetRadiatedPowerOverTimeRange(startTime, endTime)+ " MeV/s" + System.getProperty("line.separator"));
// data7.append("Total Energy = " + test7.puGetEnergySumOverTimeRange(startTime, endTime) + " MeV" + System.getProperty("line.separator"));
// data7.append(System.getProperty("line.separator"));
// data7.append(test7.puGetAllEndTimeNucleiCounts());
// data7.append(System.getProperty("line.separator"));
// data7.append(test7.puGetAllEventCountsOverTimeRangeByNuclei(startTime, endTime));
// data7.append(System.getProperty("line.separator"));
// data7.append("Next we see how the program is distributing the event energies into smaller groups as defined by the (resolution)" + System.getProperty("line.separator"));
// double sum7 = 0;
// for(int x = 1; x <= 1000;x = 10*x) {
// sum7 = 0;
// data7.append("For resolution set to " + x + " we get:" + System.getProperty("line.separator"));
// test7 = new NucleiSamplePredictiveSim(numU238,"/home/user/git/Radioactivity_Sim/input/U238test",startTime,endTime,x);
// test7.puAddSpecies(numTH234, "/home/user/git/Radioactivity_Sim/input/TH234test", startTime, endTime);
// test7.puAddSpecies(numPA234, "/home/user/git/Radioactivity_Sim/input/PA234test", startTime, endTime);
// for(int y = 0; y < x; y++) {
// data7.append("Energy (t = "+(startTime+(y+1)*(endTime-startTime)/x)+") = " + test7.puGetEnergySumOverTimeRange(startTime+y*(endTime-startTime)/x, startTime+(y+1)*(endTime-startTime)/x)+ " MeV" + System.getProperty("line.separator"));
// sum7 += test7.puGetEnergySumOverTimeRange(startTime+y*(endTime-startTime)/x, startTime+(y+1)*(endTime-startTime)/x);
// data7.append("Which all adds up to: " + sum7 + " MeV" + System.getProperty("line.separator"));
// data7.append(System.getProperty("line.separator"));
// scrivener.puAppendStringToFile(fileNum-1, data7.toString());
// scrivener.puCloseFile(fileNum-1);
// //Verify if the calculations agree with theory:
// startTime = 0; endTime = 100;
// NucleiSampleBruteForceSim test8 = new NucleiSampleBruteForceSim(100000,"/home/user/git/Radioactivity_Sim/input/RA224test",startTime,endTime);
// test8.puAddSpecies(18, "/home/user/git/Radioactivity_Sim/input/RN220test", startTime, endTime);
// String file8 = "/home/user/git/Radioactivity_Sim/proofs/verification3";
// StringBuilder data8 = new StringBuilder();
// data8.append("verification3 for NucleiSampleBruteForceSim.java calculations: " + System.getProperty("line.separator"));
// data8.append("Secular Equilibrium occurs between RA224 and RN220 because the decay constant, lambda" + System.getProperty("line.separator"));
// data8.append("of RN220 is much greater than that of RA224. The decay constants are defined as: " + System.getProperty("line.separator"));
// data8.append(System.getProperty("line.separator"));
// data8.append(" lambda_RA224 = ln(2) / HALFLIFE_RA224 & lambda_RN220 = ln(2) / HALFLIFE_RN220 " + System.getProperty("line.separator"));
// data8.append(System.getProperty("line.separator"));
// data8.append("For these nuclei: lambda_RA224 = 2.19195E-6 & lambda_RN220 = 1.24667E-2 " + System.getProperty("line.separator"));
// data8.append("In the case of secular equilibrium, the number of child nuclei (in this case RN220) " + System.getProperty("line.separator"));
// data8.append("remains at a fixed ratio to the number of parent nuclei. This relationship is " + System.getProperty("line.separator"));
// data8.append("governed by the equation: N_RN220 = N_RA224 x lambda_RA224/lambda_RN220 " + System.getProperty("line.separator"));
// data8.append("where N is the total number of nuclei of each type. In order for this relationship " + System.getProperty("line.separator"));
// data8.append("to remain true, the number of decay events of the parent nuclei must equal the number" + System.getProperty("line.separator"));
// data8.append("of decay events of the child nuclei such that: NDECAYS_RA224 = NDECAYS_RN220 " + System.getProperty("line.separator"));
// data8.append("To prove this program's agreement with these theories we select a starting quantity " + System.getProperty("line.separator"));
// data8.append("of RA224 nuclei: " + System.getProperty("line.separator"));
// data8.append("N_RA224 = " + 100000 + System.getProperty("line.separator"));
// data8.append("Then from theory, N_RN220 = " + 100000 + "x(2.19195E-6/1.24667E-2) = " + (100000*2.19195*Math.pow(10, -6)/0.0124667) + System.getProperty("line.separator"));
// data8.append("Next, a sufficiently small time period is selected such that N_RA224 doesn't decrease" + System.getProperty("line.separator"));
// data8.append("by much. Let us choose a time period of 100 seconds. " + System.getProperty("line.separator"));
// data8.append("The number of decays of RA224 which occur in 100 seconds from a sample of 1E5 is " + System.getProperty("line.separator"));
// data8.append("given by: NDECAYS_RA224 = "+100000+" x(1 - e^(-100*lambda_RA224) = 21.92 " + System.getProperty("line.separator"));
// data8.append("Of course, in reality the number of decay events has to be a whole number, but for " + System.getProperty("line.separator"));
// data8.append("theory, it is acceptable to use the fraction, because it is an average amount that " + System.getProperty("line.separator"));
// data8.append("would occur during this time period. Since NDECAY_RA224 = NDECAY_RN220, the number " + System.getProperty("line.separator"));
// data8.append("of RN220 events is also 21.92. The energy released by each RA224 decay is 5.789 MeV " + System.getProperty("line.separator"));
// data8.append("and the energy released by each RN220 decay is 6.404 MeV. Therefore the total energy" + System.getProperty("line.separator"));
// data8.append("released is: NDECAY_RA224 x 5.789 + NDECAY_RN220 x 6.404 = 267.27 MeV " + System.getProperty("line.separator"));
// data8.append("and the average radiated power is: Energy/time = 267.27/100 = 2.6727 MeV/s " + System.getProperty("line.separator"));
// data8.append("Now let us see if the program can produce the same values: " + System.getProperty("line.separator"));
// data8.append(System.getProperty("line.separator"));
// scrivener.puOpenNewFile(file8);
// fileNum = scrivener.puGetNumFiles();
// data8.append("From the program we will get: " + System.getProperty("line.separator"));
// double sumEnergy8 = 0;
// double sumPower8 = 0;
// for (int x = 0; x < 20; x++){
// test8 = new NucleiSampleBruteForceSim(100000,"/home/user/git/Radioactivity_Sim/input/RA224test",startTime,endTime);
// test8.puAddSpecies(18, "/home/user/git/Radioactivity_Sim/input/RN220test", startTime, endTime);
// data8.append("Attempt No. " + (x+1) + System.getProperty("line.separator"));
// data8.append("Radiated Power = " + test8.puGetRadiatedPowerOverTimeRange(startTime, endTime) + " MeV/s" + System.getProperty("line.separator"));
// data8.append("Total Energy = " + test8.puGetEnergySumOverTimeRange(startTime, endTime) + " MeV" + System.getProperty("line.separator"));
// data8.append(System.getProperty("line.separator"));
// sumEnergy8 += test8.puGetEnergySumOverTimeRange(startTime, endTime);
// sumPower8 += test8.puGetRadiatedPowerOverTimeRange(startTime, endTime);
// data8.append("Average:" + System.getProperty("line.separator"));
// data8.append("Ave. Radiated Power = " + (sumPower8/20.0) + " MeV/s" + System.getProperty("line.separator"));
// data8.append("Ave. Total Energy = " + (sumEnergy8/20.0) + " MeV" + System.getProperty("line.separator"));
// data8.append(System.getProperty("line.separator"));
// scrivener.puAppendStringToFile(fileNum-1, data8.toString());
// scrivener.puCloseFile(fileNum-1);
//// //Writes a new set of Detailed Sieve code for the (DecayEvent) Class to increase the accuracy of the (NucleiSampleBruteForceSim) calculations
//// //Using if statements rather than a loop improves the speed of the calculations
//// int count9 = 0;
//// int test = 0;
//// String file9 = "/home/user/git/Radioactivity_Sim/output/newSieve";
//// StringBuilder data9 = new StringBuilder();
//// for(int x = 0; x < 600;x++){
//// test = Integer.valueOf(Long.toString(Math.round(1000000.0*(1-Math.exp(-(x+1)*Math.log(2.0)/600.0)))));
//// count9++;
//// if(x == 0){
//// data9.append("if (testDetailedLife <= "+ test + ") {" + System.getProperty("line.separator"));
//// } else {
//// data9.append("} else if (testDetailedLife <= "+ test + ") {" + System.getProperty("line.separator"));
//// data9.append(" t = (x+("+x+"+seed3)/1000.0)*prHalfLife;" + System.getProperty("line.separator"));
//// data9.append("}" + System.getProperty("line.separator"));
//// data9.append(count9);
//// scrivener.puOpenNewFile(file9);
//// fileNum = scrivener.puGetNumFiles();
//// scrivener.puAppendStringToFile(fileNum-1, data9.toString());
//// scrivener.puCloseFile(fileNum-1);
// //Verify if the calculations agree with theory:
// startTime = 3*1.409*Math.pow(10,18)-Math.pow(10,13); endTime = 3*1.409*Math.pow(10,18);
// NucleiSamplePredictiveSim test10 = new NucleiSamplePredictiveSim(Math.pow(10, 26),"/home/user/git/Radioactivity_Sim/input/U238",startTime,endTime,1);
// String file10 = "/home/user/git/Radioactivity_Sim/proofs/verification4";
// StringBuilder data10 = new StringBuilder();
// data10.append("verification4 for NucleiSamplePredictiveSim.java calculations: " + System.getProperty("line.separator"));
// data10.append(System.getProperty("line.separator"));
// data10.append("In this verification a single pure sample of 10^26 U238 nuclei are allowed to decay " + System.getProperty("line.separator"));
// data10.append("for three half-lives and the decays which occur between t =" + startTime + " and " + endTime + System.getProperty("line.separator"));
// data10.append("are examined and verified for accuracy with the following hand calcs:" + System.getProperty("line.separator"));
// data10.append(System.getProperty("line.separator"));
// data10.append("Nuclei Parent ParentDecays EndTimeCount StartTimeCount PredictedDecays " + System.getProperty("line.separator"));
// data10.append("U238 N/A N/A 1.250000002E25 1.250006151E25 6.149298E19 " + System.getProperty("line.separator"));
// data10.append("TH234 U238 6.149298E19 1.847267569E13 1.847276656E13 6.149298E19 " + System.getProperty("line.separator"));
// data10.append("PA234 TH234 6.149298E19 2.139815476E11 2.139826002E11 6.149298E19 " + System.getProperty("line.separator"));
// data10.append("U234 PA234 6.149298E19 6.868472812E19 6.868506601E19 6.149331E19 " + System.getProperty("line.separator"));
// data10.append("TH230 U234 6.149331E19 2.108957662E19 2.108968037E19 6.149342E19 " + System.getProperty("line.separator"));
// data10.append("RA226 TH230 6.149342E19 1.250000002E25 1.250006151E25 6.149342E19 " + System.getProperty("line.separator"));
// data10.append("RN222 RA226 6.149342E19 1.250000002E25 1.250006151E25 6.149342E19 " + System.getProperty("line.separator"));
// data10.append("PO218 RN222 6.149342E19 1.250000002E25 1.250006151E25 6.149342E19 " + System.getProperty("line.separator"));
// data10.append("PB214 PO218 6.149342E19 1.250000002E25 1.250006151E25 6.149342E19 " + System.getProperty("line.separator"));
// data10.append("BI214 PB214 6.149342E19 1.250000002E25 1.250006151E25 6.149342E19 " + System.getProperty("line.separator"));
// data10.append("TI210 BI214 1.291362E16 1.250000002E25 1.250006151E25 1.291362E16 " + System.getProperty("line.separator"));
// data10.append("PB210 PO214,TI210 6.148051E19 1.250000002E25 1.250006151E25 6.149342E19 " + System.getProperty("line.separator"));
// data10.append("PO214 BI214 6.148051E19 1.250000002E25 1.250006151E25 6.148051E19 " + System.getProperty("line.separator"));
// data10.append("PB209 TI210 1.162226E12 1.250000002E25 1.250006151E25 1.162226E12 " + System.getProperty("line.separator"));
// data10.append("BI209 PB209 1.162226E12 1.250000002E25 1.250006151E25 1.213845E12 " + System.getProperty("line.separator"));
// data10.append("BI210 PB210 6.148530E19 1.250000002E25 1.250006151E25 6.148530E19 " + System.getProperty("line.separator"));
// data10.append("TI206 BI210 8.116060E15 1.250000002E25 1.250006151E25 8.116060E15 " + System.getProperty("line.separator"));
// data10.append("PO210 BI210 6.147718E19 1.250000002E25 1.250006151E25 6.147718E19 " + System.getProperty("line.separator"));
// data10.append(System.getProperty("line.separator"));
// data10.append("Energy of BI214 decays is 6.149342E19x(0.99979x3.27[MeV]+0.00021x5.6213[MeV]) = " + (6.149342*Math.pow(10, 19)*(0.99979*3.27+0.00021*5.6213)) + " [MeV]" + System.getProperty("line.separator"));
// data10.append("and the energy of PO214 decays is 6148051E19x7.83346[MeV] = " + (6.148051*Math.pow(10,19)*7.83346) + " [MeV]" + System.getProperty("line.separator"));
// data10.append("Which adds up to: " + ((6.148051*Math.pow(10,19)*7.83346)+(6.149342*Math.pow(10, 19)*(0.99979*3.27+0.00021*5.6213))) + " [MeV]" + System.getProperty("line.separator"));
// data10.append("Now let's see what the program comes up with: " + System.getProperty("line.separator"));
// data10.append(System.getProperty("line.separator"));
// scrivener.puOpenNewFile(file10);
// fileNum = scrivener.puGetNumFiles();
// data10.append("From the program we will get: " + System.getProperty("line.separator"));
// data10.append("Radiated Power (for BI214 and PO214) = " + (test10.puGetRadiatedPowerForStartNucleusOverTimeRange(startTime, endTime,"BI214")+test10.puGetRadiatedPowerForStartNucleusOverTimeRange(startTime, endTime, "PO214"))+ " MeV/s" + System.getProperty("line.separator"));
// data10.append("Total Energy (for BI214 and PO214) = " + (test10.puGetEnergySumForStartingNucleusOverTimeRange(startTime, endTime, "BI214")+test10.puGetEnergySumForStartingNucleusOverTimeRange(startTime, endTime, "PO214")) + " MeV" + System.getProperty("line.separator"));
// data10.append(System.getProperty("line.separator"));
// data10.append(test10.puGetAllStartTimeNucleiCounts());
// data10.append(System.getProperty("line.separator"));
// data10.append(test10.puGetAllEndTimeNucleiCounts());
// data10.append(System.getProperty("line.separator"));
// data10.append(test10.puGetAllEventCountsOverTimeRangeByNuclei(startTime, endTime));
// data10.append(System.getProperty("line.separator"));
// double sum10 = 0;
// for(int x = 1; x <= 1000;x = 10*x) {
// sum10 = 0;
// data10.append("For resolution set to " + x + " we get:" + System.getProperty("line.separator"));
// test10 = new NucleiSamplePredictiveSim(Math.pow(10, 26),"/home/user/git/Radioactivity_Sim/input/U238",startTime,endTime,x);
// for(double y = 0; y < x; y++) {
// data10.append("Energy (BI214 & PO214)(t = "+(startTime+(y+1)*(endTime-startTime)/x)+") = " + (test10.puGetEnergySumForStartingNucleusOverTimeRange(startTime+y*(endTime-startTime)/x, startTime+(y+1)*(endTime-startTime)/x,"BI214")+test10.puGetEnergySumForStartingNucleusOverTimeRange(startTime+y*(endTime-startTime)/x, startTime+(y+1)*(endTime-startTime)/x, "PO214")) + " MeV" + System.getProperty("line.separator"));
// sum10 += (test10.puGetEnergySumForStartingNucleusOverTimeRange(startTime+y*(endTime-startTime)/x, startTime+(y+1)*(endTime-startTime)/x,"BI214")+test10.puGetEnergySumForStartingNucleusOverTimeRange(startTime+y*(endTime-startTime)/x, startTime+(y+1)*(endTime-startTime)/x, "PO214"));
// data10.append("Which all adds up to: " + sum10 + " MeV" + System.getProperty("line.separator"));
// data10.append(System.getProperty("line.separator"));
// scrivener.puAppendStringToFile(fileNum-1, data10.toString());
// scrivener.puCloseFile(fileNum-1);
// //Prints the program runtime to the console in milliseconds
// System.out.println(Calendar.getInstance().getTime().getTime() - now); |
package com.timeanddate.services;
/**
*
* @author Cato Auestad {@literal <cato@timeanddate.com>}
*
*/
final class Constants {
static final int DefaultVersion = 3;
static final String DefaultLanguage = "en";
static final String DefaultReturnFormat = "xml";
static final int DefaultVerboseTimeValue = 0;
static final String EntryPoint = "http://api.xmltime.com/";
} |
package mines;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.Scanner;
import java.util.Stack;
import javax.swing.ButtonGroup;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.Timer;
public class MineFrame
{
//Declare GUI objects
private static JFrame frame;
private static JPanel gamePanel;
private static JLabel statusbar;
//Generic int[] stacks
public static Stack<int[]> undoStack = new Stack<int[]>();
public static Stack<int[]> redoStack = new Stack<int[]>();
//Declare static integers so that they can be accessed from static getters and setters.
private static int noOfMines = 40;
private static int noOfRows = 24;
private static int noOfCols = 24;
//Declare a Timer object
private static Timer timer;
//Declare and set the delay on the timer
private final static int DELAY = 20;
//Static boolean to be accessed across all classes
public static boolean playingGame;
//Static long which will contain the time a game has started in milliseconds
private static long startTime;
//Default width and height for the frame
private static int height = 440;
private static int width = 377;
//Declare the menu bar and its items (GUI elements)
private JMenuBar menuBar = new JMenuBar();
private JMenu fileMenu, editMenu, viewMenu, helpMenu, highscore;
private static JMenuItem pauseItem;
private JMenuItem saveItem, loadItem, exitItem, newGameItem, resolveItem,
undoItem, redoItem;
private JRadioButtonMenuItem beginnerItem, intermediateItem, expertItem,
customItem;
//Constructor of the MineFrame
public MineFrame()
{
frame = new JFrame();//Create the frame for the GUI
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//Have the application exit when closed
frame.setPreferredSize(new Dimension(width, height));//Set the preferred frame size
frame.setLocationRelativeTo(null);//Centre the frame
frame.setTitle("Minesweeper");//Title of the frame
statusbar = new JLabel("");//Set the passed-in status bar
gamePanel = new JPanel(new BorderLayout());//New panel that contains the board
frame.setJMenuBar(buildMenuBar());//Build the menu bar and set it as the JMenuBar
frame.add(gamePanel);//Add gamePanel to the frame
startNewGame();
frame.setBackground(new Color(0xB3B3B3));//Set Background colour
frame.pack();//Resize the frame to occupy the smallest amount of space
frame.setLocationRelativeTo(null);//Centres the frame
frame.setResizable(true);//Have the frame re-sizable useful for custom games
frame.setVisible(true);//Show all components on the window
}
//Method to start/restart the game when a game has been lost, restarted or loaded
public static void startNewGame()
{
gamePanel.removeAll();
gamePanel.add(statusbar, BorderLayout.SOUTH);
playingGame = true;//Set to true so the user may make actions
timer = new Timer(DELAY, new TimerListener());//Initialise a timer object
timer.start();//Start the timer
startTime = System.currentTimeMillis(); //save the time the game started
gamePanel.add(new Board(statusbar, getNoOfMines(), getNoOfRows(), getNoOfCols()));
new SaveToDisk();//Save the generated board to disk
Arrays.fill(Board.field, 0);//Set all entries in the field to 0 to prove that LoadFromDisk does work
new LoadFromDisk();//Load the board from disk
frame.setPreferredSize(new Dimension(width, height));
frame.validate();
frame.repaint();
frame.pack();
}
//Method to create the MenuBar, its properties and associate ActionListners
public JMenuBar buildMenuBar()
{
//Create the fileMenu and it's items
fileMenu = new JMenu("File");
fileMenu.setMnemonic('F');
saveItem = new JMenuItem("Save");
saveItem.setMnemonic('S');
saveItem.addActionListener(new SaveListener());
loadItem = new JMenuItem("Load");
loadItem.setMnemonic('L');
loadItem.addActionListener(new LoadListener());
exitItem = new JMenuItem("Exit");
exitItem.setMnemonic('X');
exitItem.addActionListener(new ExitListener());
//Add file items to the fileMenu
fileMenu.add(saveItem);
fileMenu.add(loadItem);
fileMenu.add(exitItem);
//Create the editMenu and it's items
editMenu = new JMenu("Edit");
editMenu.setMnemonic('d');
undoItem = new JMenuItem("Undo");
undoItem.setMnemonic('Z');
undoItem.addActionListener(new UndoListener());
redoItem = new JMenuItem("Redo");
redoItem.setMnemonic('Y');
redoItem.addActionListener(new RedoListener());
//Add edit items to the editMenu
editMenu.add(undoItem);
editMenu.add(redoItem);
//Create the viewMenu and it's items
viewMenu = new JMenu("Game");
viewMenu.setMnemonic('G');
pauseItem = new JCheckBoxMenuItem("Pause");
pauseItem.setMnemonic('P');
pauseItem.addActionListener(new TimerListener());
newGameItem = new JMenuItem("New Game");
newGameItem.setMnemonic('N');
newGameItem.addActionListener(new newGameListener());
//Create difficulty radio buttons
beginnerItem = new JRadioButtonMenuItem("Beginner");
beginnerItem.setMnemonic('B');
beginnerItem.addActionListener(new DifficultyListener());
intermediateItem = new JRadioButtonMenuItem("Intermediate", true);
intermediateItem.setMnemonic('I');
intermediateItem.addActionListener(new DifficultyListener());
expertItem = new JRadioButtonMenuItem("Expert");
expertItem.setMnemonic('E');
expertItem.addActionListener(new DifficultyListener());
customItem = new JRadioButtonMenuItem("Custom...");
customItem.setMnemonic('C');
customItem.addActionListener(new CustomGameListener());
//Create a button group and add the difficulty items to it
ButtonGroup difficultyGroup = new ButtonGroup();
difficultyGroup.add(beginnerItem);
difficultyGroup.add(intermediateItem);
difficultyGroup.add(expertItem);
difficultyGroup.add(customItem);
//Add difficulty and view items to viewMenu
viewMenu.add(newGameItem);
viewMenu.add(pauseItem);
viewMenu.add(beginnerItem);
viewMenu.add(intermediateItem);
viewMenu.add(expertItem);
viewMenu.add(customItem);
//Create the helpMenu and it's item
helpMenu = new JMenu("Help");
helpMenu.setMnemonic('H');
resolveItem = new JMenuItem("Solve");
resolveItem.setMnemonic('c');
resolveItem.addActionListener(new ResolveListener());
//Add help item to helpMenu
helpMenu.add(resolveItem);
highscore = new JMenu("Highscore");
highscore.setMnemonic('H');
highscore.addMenuListener(new HighscoreListener());
//Add File, View and Help Menus to the JMenuBar
menuBar.add(fileMenu);
menuBar.add(editMenu);
menuBar.add(viewMenu);
menuBar.add(highscore);
menuBar.add(helpMenu);
// return the menuBar
return menuBar;
}
//Accessors and mutators
//Accessor for the number of mines
public static int getNoOfMines()
{
return noOfMines;
}
//Mutator for the number of mines
public static void setNoOfMines(int noOfMines)
{
MineFrame.noOfMines = noOfMines;
}
//Accessor for the number of columns
public static int getNoOfCols()
{
return noOfCols;
}
//Mutator for the number of columns
public static void setNoOfCols(int noOfCols)
{
MineFrame.noOfCols = noOfCols;
}
//Accessor for the number of rows
public static int getNoOfRows()
{
return noOfRows;
}
//Mutator for the number of rows
public static void setNoOfRows(int noOfRows)
{
MineFrame.noOfRows = noOfRows;
}
//Method that returns the time elapsed from the time a game was started
public static double getCurrentTime()
{
long endTime = System.currentTimeMillis();
long tDelta = endTime - startTime;
return tDelta / 1000.0;
}
//Class to handle the game difficulty changes
private class DifficultyListener implements ActionListener
{
@Override
//Beginner Difficulty
public void actionPerformed(ActionEvent e)
{
if (beginnerItem.isSelected())
{
Board.difficulty = 0;
setNoOfMines(20);
setNoOfRows(15);
setNoOfCols(15);
width = 250;
height = 300;
startNewGame();
}
//Intermediate Difficulty
else if (intermediateItem.isSelected())
{
Board.difficulty = 1;
setNoOfMines(80);
setNoOfRows(24);
setNoOfCols(24);
height = 440;
width = 377;
startNewGame();
}
//Expert Difficulty
else if (expertItem.isSelected())
{
Board.difficulty = 2;
setNoOfMines(200);
setNoOfRows(30);
setNoOfCols(30);
height = 529;
width = 466;
startNewGame();
}
}
}
//Method to rotate through all field cells to solve the board
private class ResolveListener implements ActionListener
{
@Override
public void actionPerformed(ActionEvent arg0)
{
for (int cCol = 0; cCol < MineFrame.getNoOfCols(); cCol++)
{
for (int cRow = 0; cRow < MineFrame.getNoOfRows(); cRow++)
{
//Checks that the square hasn't already been uncovered by the user
if (Board.getField()[(cRow * MineFrame.getNoOfCols()) + cCol] >= 10 && Board.getField()[(cRow * MineFrame.getNoOfCols()) + cCol] != 20)
{
Board.getField()[(cRow * MineFrame.getNoOfCols()) + cCol] -= Board.COVER_FOR_CELL;//Remove the covers for all cells
if (Board.getField()[(cRow * MineFrame.getNoOfCols()) + cCol] == 9)//Check if a cell is a mine
{
Board.getField()[(cRow * MineFrame.getNoOfCols()) + cCol] += 11;//Turn mine cells into a marked mine cell
}
}
}
}
Board.solved = true;
Board.inGame = false;
frame.repaint();//Repaint the frame to show the resolved board
}
}
private class RedoListener implements ActionListener
{
@Override
//Method that pushes the current redo to the undoStack and pops the redoStack to the (mine-) field
public void actionPerformed(ActionEvent e)
{
if (!redoStack.empty())//Check if the undoStack is empty
{
undoStack.push(redoStack.peek());//Return the item to the undo stack
Board.field = redoStack.pop();//Make the field equal to the item and remove it from the stack
gamePanel.repaint();//Repaint the frame
}
}
}
private class UndoListener implements ActionListener
{
@Override
//Method that pushes the current undo to the redoStack and pops the undoStack to the (mine-) field
public void actionPerformed(ActionEvent e)
{
if (!undoStack.empty())//Check if the undoStack is empty
{
redoStack.push(undoStack.peek());//Push the first element of undoStack to redoStack
Board.field = undoStack.pop();//Make the board equal to the first element in undoStack
gamePanel.repaint();//Repaint the frame
}
}
}
public class LoadListener implements ActionListener
{
//Initialise fileChooser
private JFileChooser fileChooser = new JFileChooser();
@Override
//Open a FileChooser, read the selected file into an array, override the (mine-) field with the array and repaint
public void actionPerformed(ActionEvent e)
{
//Initialise new Panel for the File chooser
class FileChooserPanel extends JPanel
{
public FileChooserPanel()
{
}
}
FileChooserPanel fileChooserPanel = new FileChooserPanel();//Create a new FileChooserPanel
int returnVal = fileChooser.showOpenDialog(fileChooserPanel);//Handle open button action
if (returnVal == JFileChooser.APPROVE_OPTION)//Run the following code if the user opens a file
{
File file = fileChooser.getSelectedFile();//Set the file to the one selected by the user
//Initialise scanner
Scanner scan = null;
try
{
scan = new Scanner(file);
}
catch (FileNotFoundException ex)//Handle file not found exception
{
ex.printStackTrace();
}
int n = 0;//Initialise n
while (scan.hasNext())
{
n += 1;//Get the length of the array/file
scan.next();
}
scan.close();//Close scanner
try
{
scan = new Scanner(file);//Reopen Scanner
}
catch (FileNotFoundException ex)//Handle file not found exception
{
ex.printStackTrace();
}
int[] arr = new int[n];//Initialise array
try
{
//Fill the array with the data from the file
for (int i = 0; i < arr.length; i++)
{
arr[i] = scan.nextInt();
}
}
catch (InputMismatchException ex)//Exception handling
{
JOptionPane.showMessageDialog(null, "This file is not supported!");//Give user notification of exception
}
scan.close();//Close Scanner
scan = null;//Garbage collection
Board.field = arr;//Set arr to field
frame.repaint();//Repaint
}
}
}
//Method to handle pausing the game and the timer
public static class TimerListener implements ActionListener
{
@Override
public void actionPerformed(ActionEvent e)
{
if (!pauseItem.isSelected())
{
playingGame = false;//Stop the user making actions
timer.stop();//Stop the timer
}
if (pauseItem.isSelected())
{
playingGame = true;//Allow the user to continue the game
timer.start();//Start the timer counting again
}
}
}
} |
package common;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* <p>A special immutable collection where each element maps one-to-one with an integer. Used as a
* backing for BackedSets, which identify their elements as indices in a BigInteger; such an index
* is the integer corresponding to the element in that BackedSet's Universe.</p>
* @author fiveham
* @param <E> the type of the elements of this universe and the parameter-type of BackedSets built
* on this Universe
* @see java.util.EnumSet
*/
public class Universe<E> {
private final List<E> ie;
private final Map<E,Integer> ei;
/**
* <p>Constructs a Universe containing exactly the elements of {@code c}.</p>
* @param c a set whose elements will become this Universe
*/
public Universe(Collection<? extends E> c){
this.ie = new ArrayList<E>(c);
this.ei = new HashMap<>();
for(int i=0; i<ie.size(); ++i){
ei.put(ie.get(i), i);
}
}
/**
* <p>Constructs a Universe containing exactly the unique elements of {@code s}.</p>
* @param s a stream whose contents will become this Universe
*/
public Universe(Stream<? extends E> s){
this.ie = s.collect(Collectors.toList());
this.ei = new HashMap<>();
for(int i=0; i<ie.size(); ++i){
ei.put(ie.get(i), i);
}
}
/**
* <p>Returns true if {@code o} is in this Universe, false otherwise.</p>
* @param o the object to be tested for its presence in this Universe
* @return true if {@code o} is in this Universe, false otherwise
*/
public boolean contains(Object o){
return ei.containsKey(o);
}
/**
* <p>Returns the number of elements that are a part of this Universe.</p>
* @return the number of elements in this Universe
*/
public int size(){
return ie.size();
}
/**
* <p>Returns the object having index {@code i} in this Universe.</p>
* @param i the index of the element of this Universe to be returned
* @return the object having index {@code i} in this Universe
* @throws IndexOutOfBoundsException if {@code i} is less than 0 or greater than or equal to the
* size of the Universe
*/
public E get(int i){
return ie.get(i);
}
public int index(E e){
return ei.get(e);
}
public BackedSet<E> set(Collection<? extends E> c){
return new BackedSet<E>(this,c);
}
@Override
public int hashCode(){
if(hash==null){
hash = ie.hashCode();
}
return hash;
}
private Integer hash = null;
@Override
public boolean equals(Object o){
if(o instanceof Universe<?>){
Universe<?> u = (Universe<?>) o;
return ie.equals(u.ie) && ei.equals(u.ei);
}
return false;
}
/**
* <p>A convenience method returning an empty BackedSet backed by this Universe.</p>
* @return an empty BackedSet backed by this Universe
*/
public BackedSet<E> back(){
return new BackedSet<>(this);
}
/**
* <p>A convenience method returning a BackedSet backed by this Universe and containing the
* contents of {@code c}.</p>
* @return a BackedSet backed by this Universe and containing the contents of {@code c}
* @throws OutOfUniverseException if any element of {@code c} is not in this Universe
*/
public BackedSet<E> back(Collection<? extends E> c){
return new BackedSet<>(this, c);
}
} |
package br.ifsp.pizzaria.repository;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import br.ifsp.pizzaria.entities.Pedido;
import br.ifsp.pizzaria.entities.Pizza;
import br.ifsp.pizzaria.entities.Usuario;
import br.ifsp.pizzaria.filtros.SessionUtils;
public class PedidoRepository {
public PedidoRepository(EntityManager manager) {
this.manager = manager;
}
private EntityManager manager;
public void adiciona(Pedido pedido){
System.out.println("Pizza para persistir: " + pedido.getPizzas().get(0).getSabor());
this.manager.persist(pedido);
}
public Pedido busca(int id) {
return this.manager.find(Pedido.class, id);
}
@SuppressWarnings("unchecked")
public List<Pedido> pedidosUsuario(int id) {
Query query = manager.createQuery(" FROM Pedido WHERE usuario_id = :id");
query.setParameter("id", id);
return query.getResultList();
}
@SuppressWarnings("unchecked")
public List<Pedido> buscaTodos() {
Query query = this.manager.createQuery(" FROM Pedido ");
return query.getResultList();
}
@SuppressWarnings("unchecked")
public List<Pedido> buscaTodosAberto() {
Query query = this.manager.createQuery(" FROM Pedido WHERE status = 'aberto'");
return query.getResultList();
}
@SuppressWarnings("unchecked")
public List<Pedido> buscaTodosDoUsuario() {
Usuario usu = SessionUtils.getUser();
Query query = this.manager.createQuery(" FROM Pedido WHERE usuario_id = :id");
query.setParameter("id", usu.getId());
return query.getResultList();
}
} |
package org.yuanheng.cookcc;
import java.io.IOException;
/**
* This interface is not used for anything. It is only a reminder of what
* functions are required in a Parser generated by the CookCC without Lexer.
* <p>
* These functions do not need to be public. They can protected or package
* access.
*
* @author Heng Yuan
* @version $Id$
* @since 0.4
*/
public interface ParserInterface
{
/**
* This function is used by the parser get the input from the lexer.
*
* @return a status value.
* @throws IOException
* in case of I/O error.
*/
int yyLex ();
/**
* Return the object associated with the token.
*
* @return the object associated with the token.
*/
Object yyValue ();
} |
package org.jetbrains.jetCheck;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.stream.Collectors;
/**
* @author peter
*/
interface IntCustomizer {
int suggestInt(IntData data, IntDistribution currentDistribution);
static int checkValidInt(IntData data, IntDistribution currentDistribution) {
int value = data.value;
if (!currentDistribution.isValidValue(value)) throw new CannotRestoreValue();
return value;
}
}
class CombinatorialIntCustomizer implements IntCustomizer {
private final LinkedHashMap<NodeId, Set<Integer>> valuesToTry;
private final Map<NodeId, Integer> currentCombination;
private final Map<NodeId, IntDistribution> changedDistributions = new HashMap<>();
CombinatorialIntCustomizer() {
this(new LinkedHashMap<>(), new HashMap<>());
}
private CombinatorialIntCustomizer(LinkedHashMap<NodeId, Set<Integer>> valuesToTry, Map<NodeId, Integer> currentCombination) {
this.valuesToTry = valuesToTry;
this.currentCombination = currentCombination;
}
public int suggestInt(IntData data, IntDistribution currentDistribution) {
if (data.distribution instanceof BoundedIntDistribution &&
currentDistribution instanceof BoundedIntDistribution &&
registerDifferentRange(data, (BoundedIntDistribution)currentDistribution, (BoundedIntDistribution)data.distribution)) {
return suggestCombinatorialVariant(data, currentDistribution);
}
return IntCustomizer.checkValidInt(data, currentDistribution);
}
private int suggestCombinatorialVariant(IntData data, IntDistribution currentDistribution) {
int value = currentCombination.computeIfAbsent(data.id, __ -> valuesToTry.get(data.id).iterator().next());
if (currentDistribution.isValidValue(value)) {
return value;
}
throw new CannotRestoreValue();
}
private boolean registerDifferentRange(IntData data, BoundedIntDistribution current, BoundedIntDistribution original) {
if (currentCombination.containsKey(data.id)) {
changedDistributions.put(data.id, current);
return true;
}
if (original.getMax() != current.getMax() || original.getMin() != current.getMin()) {
LinkedHashSet<Integer> possibleValues = getPossibleValues(data, current, original);
if (!possibleValues.isEmpty()) {
assert !valuesToTry.containsKey(data.id);
valuesToTry.put(data.id, possibleValues);
changedDistributions.put(data.id, current);
return true;
}
}
return false;
}
private LinkedHashSet<Integer> getPossibleValues(IntData data, BoundedIntDistribution current, BoundedIntDistribution original) {
List<Integer> possibleValues = new ArrayList<>();
int fromStart = data.value - original.getMin();
int fromEnd = original.getMax() - data.value;
int sameDistanceFromStart = current.getMin() + fromStart;
int sameDistanceFromEnd = current.getMax() - fromEnd;
if (!tooManyCombinations()) {
if (fromStart < fromEnd) {
possibleValues.add(sameDistanceFromStart);
possibleValues.add(sameDistanceFromEnd);
} else {
possibleValues.add(sameDistanceFromEnd);
possibleValues.add(sameDistanceFromStart);
}
}
possibleValues.add(data.value);
return possibleValues.stream()
.map(value -> Math.min(Math.max(value, current.getMin()), current.getMax()))
.filter(current::isValidValue)
.collect(Collectors.toCollection(LinkedHashSet::new));
}
private boolean tooManyCombinations() {
return valuesToTry.values().stream().filter(s -> s.size() > 1).count() > 3;
}
@Nullable
CombinatorialIntCustomizer nextAttempt() {
Map<NodeId, Integer> nextCombination = new HashMap<>(currentCombination);
for (Map.Entry<NodeId, Set<Integer>> entry : valuesToTry.entrySet()) {
List<Integer> possibleValues = new ArrayList<>(entry.getValue());
Integer usedValue = currentCombination.get(entry.getKey());
int index = possibleValues.indexOf(usedValue);
if (index < possibleValues.size() - 1) {
// found a position which can be incremented by 1
nextCombination.put(entry.getKey(), possibleValues.get(index + 1));
return new CombinatorialIntCustomizer(valuesToTry, nextCombination);
}
// digit overflow in this position, so zero it and try incrementing the next one
nextCombination.put(entry.getKey(), possibleValues.get(0));
}
return null;
}
StructureNode writeChanges(StructureNode node) {
StructureNode result = node;
for (Map.Entry<NodeId, IntDistribution> entry : changedDistributions.entrySet()) {
NodeId id = entry.getKey();
result = result.replace(id, new IntData(id, currentCombination.get(id), entry.getValue()));
}
return result;
}
int countVariants() {
return valuesToTry.values().stream().mapToInt(Set::size).reduce(1, (a, b) -> a*b);
}
} |
package jolie.runtime.embedding;
import jolie.runtime.JavaService;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import jolie.net.CommChannel;
import jolie.net.CommMessage;
import jolie.runtime.InvalidIdException;
/**
* @author Fabrizio Montesi
*/
public class JavaCommChannel extends CommChannel
{
final private JavaService javaService;
final private List< CommMessage > messages = new LinkedList< CommMessage >();
public JavaCommChannel( JavaService javaService )
{
this.javaService = javaService;
}
protected void sendImpl( CommMessage message )
throws IOException
{
try {
CommMessage response = javaService.callOperation( message );
if ( response != null ) {
response = new CommMessage(
message.id(),
message.operationName(),
message.resourcePath(),
response.value(),
response.fault()
);
synchronized( messages ) {
messages.add( response );
messages.notifyAll();
}
}
} catch( IllegalAccessException e ) {
throw new IOException( e );
} catch( InvalidIdException e ) {
throw new IOException( e );
}
}
protected CommMessage recvImpl()
throws IOException
{
CommMessage ret = null;
synchronized( messages ) {
while( messages.isEmpty() ) {
try {
messages.wait();
} catch( InterruptedException e ) {}
}
ret = messages.remove( 0 );
}
if ( ret == null ) {
throw new IOException( "Unknown exception occurred during communications with a Java Service" );
}
return ret;
}
protected void closeImpl()
{}
} |
package jsettlers.ai.army;
/**
* The army general can command the troops of the computer player.
* The idea behind different army generals is, that easy, middle and strong players
* can be constructed by different difficult economies with different army generals.
*
* @author codingberlin
*/
public interface ArmyGeneral {
void commandTroops();
} |
package com.intuit.karate;
import com.intuit.karate.cli.CliExecutionHook;
import com.intuit.karate.debug.DapServer;
import com.intuit.karate.exception.KarateException;
import com.intuit.karate.formats.postman.PostmanConverter;
import com.intuit.karate.job.JobExecutor;
import com.intuit.karate.netty.FeatureServer;
import com.intuit.karate.netty.FileChangedWatcher;
import net.masterthought.cucumber.Configuration;
import net.masterthought.cucumber.ReportBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import picocli.CommandLine;
import picocli.CommandLine.Option;
import picocli.CommandLine.Parameters;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.stream.Collectors;
/**
*
* @author pthomas3
*/
public class Main implements Callable<Void> {
private static final String DEFAULT_OUTPUT_DIR = "target";
private static final String LOGBACK_CONFIG = "logback.configurationFile";
private static Logger logger;
@Option(names = {"-h", "--help"}, usageHelp = true, description = "display this help message")
boolean help;
@Option(names = {"-m", "--mock"}, description = "mock server file")
File mock;
@Option(names = {"-p", "--port"}, description = "mock server port (required for --mock)")
Integer port;
@Option(names = {"-w", "--watch"}, description = "watch (and hot-reload) mock server file for changes")
boolean watch;
@Option(names = {"-s", "--ssl"}, description = "use ssl / https, will use '"
+ FeatureServer.DEFAULT_CERT_NAME + "' and '" + FeatureServer.DEFAULT_KEY_NAME
+ "' if they exist in the working directory, or generate them")
boolean ssl;
@Option(names = {"-c", "--cert"}, description = "ssl certificate (default: " + FeatureServer.DEFAULT_CERT_NAME + ")")
File cert;
@Option(names = {"-k", "--key"}, description = "ssl private key (default: " + FeatureServer.DEFAULT_KEY_NAME + ")")
File key;
@Option(names = {"-t", "--tags"}, description = "cucumber tags - e.g. '@smoke,~@ignore'")
List<String> tags;
@Option(names = {"-T", "--threads"}, description = "number of threads when running tests")
int threads = 1;
@Option(names = {"-o", "--output"}, description = "directory where logs and reports are output (default 'target')")
String output = DEFAULT_OUTPUT_DIR;
@Parameters(description = "one or more tests (features) or search-paths to run")
List<String> tests;
@Option(names = {"-n", "--name"}, description = "scenario name")
String name;
@Option(names = {"-e", "--env"}, description = "value of 'karate.env'")
String env;
@Option(names = {"-C", "--clean"}, description = "clean output directory")
boolean clean;
@Option(names = {"-d", "--debug"}, arity = "0..1", defaultValue = "-1", fallbackValue = "0",
description = "debug mode (optional port else dynamically chosen)")
int debugPort;
@Option(names = {"-j", "--jobserver"}, description = "job server url")
String jobServerUrl;
@Option(names = {"-i", "--import"}, description = "import and convert a file")
String importFile;
public static void main(String[] args) {
boolean isOutputArg = false;
String outputDir = DEFAULT_OUTPUT_DIR;
// hack to manually extract the output dir arg to redirect karate.log if needed
for (String s : args) {
if (isOutputArg) {
outputDir = s;
isOutputArg = false;
}
if (s.startsWith("-o") || s.startsWith("--output")) {
int pos = s.indexOf('=');
if (pos != -1) {
outputDir = s.substring(pos + 1);
} else {
isOutputArg = true;
}
}
}
System.setProperty("karate.output.dir", outputDir);
// ensure we init logback before anything else
String logbackConfig = System.getProperty(LOGBACK_CONFIG);
if (StringUtils.isBlank(logbackConfig)) {
System.setProperty(LOGBACK_CONFIG, "logback-netty.xml");
}
logger = LoggerFactory.getLogger(Main.class);
logger.info("Karate version: {}", FileUtils.getKarateVersion());
CommandLine cmd = new CommandLine(new Main());
int returnCode = cmd.execute(args);
System.exit(returnCode);
}
@Override
public Void call() throws Exception {
if (clean) {
org.apache.commons.io.FileUtils.deleteDirectory(new File(output));
logger.info("deleted directory: {}", output);
}
if (jobServerUrl != null) {
JobExecutor.run(jobServerUrl);
return null;
}
if (debugPort != -1) {
DapServer server = new DapServer(debugPort);
server.waitSync();
return null;
}
if (tests != null) {
if (env != null) {
System.setProperty(ScriptBindings.KARATE_ENV, env);
}
String configDir = System.getProperty(ScriptBindings.KARATE_CONFIG_DIR);
configDir = StringUtils.trimToNull(configDir);
if (configDir == null) {
System.setProperty(ScriptBindings.KARATE_CONFIG_DIR, new File("").getAbsolutePath());
}
List<String> fixed = tests.stream().map(f -> new File(f).getAbsolutePath()).collect(Collectors.toList());
String jsonOutputDir = output + File.separator + ScriptBindings.SUREFIRE_REPORTS;
CliExecutionHook hook = new CliExecutionHook(false, jsonOutputDir, false);
Results results = Runner
.path(fixed).tags(tags).scenarioName(name)
.reportDir(jsonOutputDir).hook(hook).parallel(threads);
Collection<File> jsonFiles = org.apache.commons.io.FileUtils.listFiles(new File(jsonOutputDir), new String[]{"json"}, true);
List<String> jsonPaths = new ArrayList(jsonFiles.size());
jsonFiles.forEach(file -> jsonPaths.add(file.getAbsolutePath()));
Configuration config = new Configuration(new File(output), new Date() + "");
ReportBuilder reportBuilder = new ReportBuilder(jsonPaths, config);
reportBuilder.generateReports();
if (results.getFailCount() > 0) {
Exception ke = new KarateException("there are test failures !");
StackTraceElement[] newTrace = new StackTraceElement[]{
new StackTraceElement(".", ".", ".", -1)
};
ke.setStackTrace(newTrace);
throw ke;
}
return null;
}
if (importFile != null) {
new PostmanConverter().convert(importFile, output);
return null;
}
if (clean) {
return null;
}
if (mock == null) {
CommandLine.usage(this, System.err);
return null;
}
if (port == null) {
System.err.println("--port required for --mock option");
CommandLine.usage(this, System.err);
return null;
}
// these files will not be created, unless ssl or ssl proxying happens
// and then they will be lazy-initialized
if (cert == null || key == null) {
cert = new File(FeatureServer.DEFAULT_CERT_NAME);
key = new File(FeatureServer.DEFAULT_KEY_NAME);
}
if (env != null) { // some advanced mocks may want karate.env
System.setProperty(ScriptBindings.KARATE_ENV, env);
}
FeatureServer server = FeatureServer.start(mock, port, ssl, cert, key, null);
if (watch) {
logger.info("--watch enabled, will hot-reload: {}", mock.getName());
FileChangedWatcher watcher = new FileChangedWatcher(mock, server, port, ssl, cert, key);
watcher.watch();
}
server.waitSync();
return null;
}
} |
package com.sun.jna.platform.win32;
import junit.framework.TestCase;
import com.sun.jna.Pointer;
import com.sun.jna.platform.win32.WinDef.HWND;
/**
* @author markus[at]headcrashing[dot]eu
*/
public final class User32UtilTest extends TestCase {
public static final void main(final String[] args) {
junit.textui.TestRunner.run(User32UtilTest.class);
}
public final void testRegisterWindowMessage() {
final int msg = User32Util.registerWindowMessage("RM_UNITTEST");
assertTrue(msg >= 0xC000 && msg <= 0xFFFF);
}
public final void testCreateWindow() {
final HWND hWnd = User32Util.createWindow("Message", null, 0, 0, 0, 0, 0, null, null, null, null);
try {
assertTrue(Pointer.nativeValue(hWnd.getPointer()) > 0);
} finally {
User32Util.destroyWindow(hWnd);
}
}
public final void testCreateWindowEx() {
final HWND hWnd = User32Util.createWindowEx(0, "Message", null, 0, 0, 0, 0, 0, null, null, null, null);
try {
assertTrue(Pointer.nativeValue(hWnd.getPointer()) > 0);
} finally {
User32Util.destroyWindow(hWnd);
}
}
public final void testDestroyWindow() {
User32Util.destroyWindow(User32Util.createWindow("Message", null, 0, 0, 0, 0, 0, null, null, null, null));
}
} |
package org.mozartoz.truffle.translator;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.function.Function;
import org.mozartoz.bootcompiler.ast.BinaryOp;
import org.mozartoz.bootcompiler.ast.BindCommon;
import org.mozartoz.bootcompiler.ast.CallCommon;
import org.mozartoz.bootcompiler.ast.CallStatement;
import org.mozartoz.bootcompiler.ast.CompoundStatement;
import org.mozartoz.bootcompiler.ast.Constant;
import org.mozartoz.bootcompiler.ast.Expression;
import org.mozartoz.bootcompiler.ast.FailStatement;
import org.mozartoz.bootcompiler.ast.IfCommon;
import org.mozartoz.bootcompiler.ast.ListExpression;
import org.mozartoz.bootcompiler.ast.LocalCommon;
import org.mozartoz.bootcompiler.ast.MatchClauseCommon;
import org.mozartoz.bootcompiler.ast.MatchCommon;
import org.mozartoz.bootcompiler.ast.NoElseCommon;
import org.mozartoz.bootcompiler.ast.Node;
import org.mozartoz.bootcompiler.ast.ProcExpression;
import org.mozartoz.bootcompiler.ast.RaiseCommon;
import org.mozartoz.bootcompiler.ast.RawDeclarationOrVar;
import org.mozartoz.bootcompiler.ast.Record;
import org.mozartoz.bootcompiler.ast.RecordField;
import org.mozartoz.bootcompiler.ast.SkipStatement;
import org.mozartoz.bootcompiler.ast.StatAndExpression;
import org.mozartoz.bootcompiler.ast.StatOrExpr;
import org.mozartoz.bootcompiler.ast.Statement;
import org.mozartoz.bootcompiler.ast.TailMarkerStatement;
import org.mozartoz.bootcompiler.ast.TryCommon;
import org.mozartoz.bootcompiler.ast.UnboundExpression;
import org.mozartoz.bootcompiler.ast.Variable;
import org.mozartoz.bootcompiler.ast.VariableOrRaw;
import org.mozartoz.bootcompiler.oz.False;
import org.mozartoz.bootcompiler.oz.OzArity;
import org.mozartoz.bootcompiler.oz.OzAtom;
import org.mozartoz.bootcompiler.oz.OzBuiltin;
import org.mozartoz.bootcompiler.oz.OzFeature;
import org.mozartoz.bootcompiler.oz.OzFloat;
import org.mozartoz.bootcompiler.oz.OzInt;
import org.mozartoz.bootcompiler.oz.OzLiteral;
import org.mozartoz.bootcompiler.oz.OzPatMatCapture;
import org.mozartoz.bootcompiler.oz.OzPatMatConjunction;
import org.mozartoz.bootcompiler.oz.OzPatMatOpenRecord;
import org.mozartoz.bootcompiler.oz.OzPatMatWildcard;
import org.mozartoz.bootcompiler.oz.OzRecord;
import org.mozartoz.bootcompiler.oz.OzRecordField;
import org.mozartoz.bootcompiler.oz.OzValue;
import org.mozartoz.bootcompiler.oz.True;
import org.mozartoz.bootcompiler.oz.UnitVal;
import org.mozartoz.bootcompiler.symtab.Builtin;
import org.mozartoz.bootcompiler.symtab.Symbol;
import org.mozartoz.truffle.nodes.DerefNode;
import org.mozartoz.truffle.nodes.ExecuteValuesNode;
import org.mozartoz.truffle.nodes.OzNode;
import org.mozartoz.truffle.nodes.OzRootNode;
import org.mozartoz.truffle.nodes.TopLevelHandlerNode;
import org.mozartoz.truffle.nodes.builtins.BuiltinsManager;
import org.mozartoz.truffle.nodes.builtins.ExceptionBuiltinsFactory.FailNodeFactory;
import org.mozartoz.truffle.nodes.builtins.ExceptionBuiltinsFactory.RaiseNodeFactory;
import org.mozartoz.truffle.nodes.builtins.IntBuiltinsFactory.DivNodeFactory;
import org.mozartoz.truffle.nodes.builtins.IntBuiltinsFactory.ModNodeFactory;
import org.mozartoz.truffle.nodes.builtins.ListBuiltinsFactory.HeadNodeGen;
import org.mozartoz.truffle.nodes.builtins.ListBuiltinsFactory.TailNodeGen;
import org.mozartoz.truffle.nodes.builtins.NumberBuiltinsFactory.AddNodeFactory;
import org.mozartoz.truffle.nodes.builtins.NumberBuiltinsFactory.MulNodeFactory;
import org.mozartoz.truffle.nodes.builtins.NumberBuiltinsFactory.SubNodeFactory;
import org.mozartoz.truffle.nodes.builtins.RecordBuiltinsFactory.LabelNodeFactory;
import org.mozartoz.truffle.nodes.builtins.ValueBuiltins.DotNode;
import org.mozartoz.truffle.nodes.builtins.ValueBuiltinsFactory.DotNodeFactory;
import org.mozartoz.truffle.nodes.builtins.ValueBuiltinsFactory.EqualNodeFactory;
import org.mozartoz.truffle.nodes.builtins.ValueBuiltinsFactory.GreaterThanNodeFactory;
import org.mozartoz.truffle.nodes.builtins.ValueBuiltinsFactory.LesserThanNodeFactory;
import org.mozartoz.truffle.nodes.builtins.ValueBuiltinsFactory.LesserThanOrEqualNodeFactory;
import org.mozartoz.truffle.nodes.builtins.ValueBuiltinsFactory.NotEqualNodeFactory;
import org.mozartoz.truffle.nodes.call.CallNode;
import org.mozartoz.truffle.nodes.call.TailCallThrowerNode;
import org.mozartoz.truffle.nodes.control.AndNode;
import org.mozartoz.truffle.nodes.control.IfNode;
import org.mozartoz.truffle.nodes.control.NoElseNode;
import org.mozartoz.truffle.nodes.control.SequenceNode;
import org.mozartoz.truffle.nodes.control.SkipNode;
import org.mozartoz.truffle.nodes.control.TryNode;
import org.mozartoz.truffle.nodes.literal.BooleanLiteralNode;
import org.mozartoz.truffle.nodes.literal.ConsLiteralNodeGen;
import org.mozartoz.truffle.nodes.literal.EnsureOzLiteralNode;
import org.mozartoz.truffle.nodes.literal.ListLiteralNode;
import org.mozartoz.truffle.nodes.literal.LiteralNode;
import org.mozartoz.truffle.nodes.literal.LongLiteralNode;
import org.mozartoz.truffle.nodes.literal.MakeDynamicRecordNode;
import org.mozartoz.truffle.nodes.literal.ProcDeclarationNode;
import org.mozartoz.truffle.nodes.literal.RecordLiteralNode;
import org.mozartoz.truffle.nodes.literal.UnboundLiteralNode;
import org.mozartoz.truffle.nodes.local.BindNodeGen;
import org.mozartoz.truffle.nodes.local.InitializeArgNode;
import org.mozartoz.truffle.nodes.local.InitializeTmpNode;
import org.mozartoz.truffle.nodes.local.InitializeVarNode;
import org.mozartoz.truffle.nodes.pattern.PatternMatchConsNodeGen;
import org.mozartoz.truffle.nodes.pattern.PatternMatchDynamicArityNodeGen;
import org.mozartoz.truffle.nodes.pattern.PatternMatchEqualNodeGen;
import org.mozartoz.truffle.nodes.pattern.PatternMatchOpenRecordNodeGen;
import org.mozartoz.truffle.nodes.pattern.PatternMatchRecordNodeGen;
import org.mozartoz.truffle.runtime.Arity;
import org.mozartoz.truffle.runtime.OzCons;
import org.mozartoz.truffle.runtime.Unit;
import scala.collection.JavaConversions;
import com.oracle.truffle.api.RootCallTarget;
import com.oracle.truffle.api.Truffle;
import com.oracle.truffle.api.frame.FrameDescriptor;
import com.oracle.truffle.api.frame.FrameSlot;
import com.oracle.truffle.api.nodes.NodeUtil;
import com.oracle.truffle.api.source.SourceSection;
public class Translator {
static class Environment {
private final Environment parent;
private final FrameDescriptor frameDescriptor;
private final String identifier;
public Environment(Environment parent, FrameDescriptor frameDescriptor, String identifier) {
this.parent = parent;
this.frameDescriptor = frameDescriptor;
this.identifier = identifier;
}
private String symbol2identifier(Symbol symbol) {
return symbol.fullName().intern();
}
public FrameSlot findLocalVariable(Symbol symbol) {
return frameDescriptor.findFrameSlot(symbol2identifier(symbol));
}
public FrameSlot addLocalVariable(Symbol symbol) {
return frameDescriptor.addFrameSlot(symbol2identifier(symbol));
}
}
private Environment environment = new Environment(null, new FrameDescriptor(), "<toplevel>");
private final Environment rootEnvironment = environment;
public Translator() {
}
public FrameSlot addRootSymbol(Symbol symbol) {
return rootEnvironment.addLocalVariable(symbol);
}
private void pushEnvironment(FrameDescriptor frameDescriptor, String identifier) {
environment = new Environment(environment, frameDescriptor, identifier);
}
private void popEnvironment() {
environment = environment.parent;
}
public FrameSlotAndDepth findVariable(Symbol symbol) {
int depth = 0;
Environment environment = this.environment;
while (environment != null) {
FrameSlot slot = environment.findLocalVariable(symbol);
if (slot != null) {
return new FrameSlotAndDepth(slot, depth);
} else {
environment = environment.parent;
depth++;
}
}
throw new Error(symbol.fullName());
}
public OzRootNode translateAST(String description, Statement ast, Function<OzNode, OzNode> wrap) {
OzNode translated = translate(ast);
OzNode wrapped = wrap.apply(translated);
OzNode handler = new TopLevelHandlerNode(wrapped);
SourceSection sourceSection = SourceSection.createUnavailable("top-level", description);
return new OzRootNode(sourceSection, environment.frameDescriptor, handler, 0);
}
OzNode translate(StatOrExpr node) {
if (node instanceof Expression) {
// Literal expressions
if (node instanceof Constant) {
Constant constant = (Constant) node;
return translateConstantNode(constant.value());
} else if (node instanceof Record) {
Record record = (Record) node;
List<RecordField> fields = new ArrayList<>(toJava(record.fields()));
if (record.isCons()) {
return buildCons(translate(fields.get(0).value()), translate(fields.get(1).value()));
} else if (record.hasConstantArity()) {
Arity arity = buildArity(record.getConstantArity());
if (fields.isEmpty()) {
return new LiteralNode(arity.getLabel());
}
OzNode[] values = new OzNode[fields.size()];
for (int i = 0; i < values.length; i++) {
values[i] = translate(fields.get(i).value());
}
return new RecordLiteralNode(arity, values);
} else if (record.fields().size() == 0) {
return new EnsureOzLiteralNode(translate(record.label()));
} else {
OzNode label = translate(record.label());
OzNode[] features = map(record.fields(), field -> translate(field.feature()));
OzNode[] values = map(record.fields(), field -> translate(field.value()));
return new MakeDynamicRecordNode(label, features, values);
}
} else if (node instanceof ListExpression) {
ListExpression list = (ListExpression) node;
OzNode[] elements = map(list.elements(), this::translate);
return new ListLiteralNode(elements);
} else if (node instanceof Variable) {
Variable variable = (Variable) node;
return t(node, findVariable(variable.symbol()).createReadNode());
} else if (node instanceof UnboundExpression) {
return t(node, new UnboundLiteralNode());
} else if (node instanceof BinaryOp) {
BinaryOp binaryOp = (BinaryOp) node;
return translateBinaryOp(binaryOp.operator(),
translate(binaryOp.left()),
translate(binaryOp.right()));
} else if (node instanceof ProcExpression) { // proc/fun literal
return translateProc((ProcExpression) node);
}
}
// Structural nodes
if (node instanceof CompoundStatement) {
CompoundStatement compound = (CompoundStatement) node;
return SequenceNode.sequence(map(compound.statements(), this::translate));
} else if (node instanceof StatAndExpression) {
StatAndExpression statAndExpr = (StatAndExpression) node;
return SequenceNode.sequence(translate(statAndExpr.statement()), translate(statAndExpr.expression()));
} else if (node instanceof LocalCommon) {
LocalCommon local = (LocalCommon) node;
List<OzNode> decls = new ArrayList<>(local.declarations().size());
for (RawDeclarationOrVar variable : toJava(local.declarations())) {
Symbol symbol = ((Variable) variable).symbol();
FrameSlot slot = environment.addLocalVariable(symbol);
// No need to initialize captures, the slot will be set directly
if (!symbol.isCapture()) {
decls.add(t(variable, new InitializeVarNode(slot)));
}
}
return SequenceNode.sequence(decls.toArray(new OzNode[decls.size()]), translate(local.body()));
} else if (node instanceof CallCommon) {
return translateCall((CallCommon) node);
} else if (node instanceof TailMarkerStatement) {
return translateTailCall(((TailMarkerStatement) node).call());
} else if (node instanceof SkipStatement) {
return new SkipNode();
} else if (node instanceof BindCommon) {
BindCommon bind = (BindCommon) node;
Expression left = bind.left();
Expression right = bind.right();
return t(node, BindNodeGen.create(translate(left), translate(right)));
} else if (node instanceof IfCommon) {
IfCommon ifNode = (IfCommon) node;
return new IfNode(translate(ifNode.condition()),
translate(ifNode.truePart()),
translate(ifNode.falsePart()));
} else if (node instanceof MatchCommon) {
return translateMatch((MatchCommon) node);
} else if (node instanceof TryCommon) {
TryCommon tryNode = (TryCommon) node;
FrameSlotAndDepth exceptionVarSlot = findVariable(((Variable) tryNode.exceptionVar()).symbol());
return new TryNode(
exceptionVarSlot.createWriteNode(),
translate(tryNode.body()),
translate(tryNode.catchBody()));
} else if (node instanceof RaiseCommon) {
RaiseCommon raiseNode = (RaiseCommon) node;
return RaiseNodeFactory.create(translate(raiseNode.exception()));
} else if (node instanceof FailStatement) {
return FailNodeFactory.create();
}
throw unknown("expression or statement", node);
}
public OzNode translateProc(ProcExpression procExpression) {
SourceSection sourceSection = t(procExpression);
pushEnvironment(new FrameDescriptor(), sourceSection.getIdentifier());
try {
int arity = procExpression.args().size();
OzNode[] nodes = new OzNode[arity + 1];
int i = 0;
for (VariableOrRaw variable : toJava(procExpression.args())) {
if (variable instanceof Variable) {
FrameSlot argSlot = environment.addLocalVariable(((Variable) variable).symbol());
nodes[i] = new InitializeArgNode(argSlot, i);
i++;
} else {
throw unknown("variable", variable);
}
}
nodes[i] = translate(procExpression.body());
OzNode procBody = SequenceNode.sequence(nodes);
OzRootNode rootNode = new OzRootNode(sourceSection, environment.frameDescriptor, procBody, arity);
RootCallTarget callTarget = Truffle.getRuntime().createCallTarget(rootNode);
return new ProcDeclarationNode(callTarget);
} finally {
popEnvironment();
}
}
private OzNode translateCall(CallCommon call) {
OzNode receiver = translate(call.callable());
OzNode[] argsNodes = map(call.args(), this::translate);
return t(call, CallNode.create(receiver, new ExecuteValuesNode(argsNodes)));
}
private OzNode translateTailCall(CallStatement call) {
OzNode receiver = translate(call.callable());
OzNode[] argsNodes = map(call.args(), this::translate);
return t(call, new TailCallThrowerNode(receiver, new ExecuteValuesNode(argsNodes)));
}
private OzNode translateMatch(MatchCommon match) {
assert match.value() instanceof Variable;
OzNode valueNode = translate(match.value());
StatOrExpr elsePart = match.elsePart();
final OzNode elseNode;
if (elsePart instanceof NoElseCommon) {
elseNode = t(elsePart, new NoElseNode(valueNode));
} else {
elseNode = translate(elsePart);
}
List<MatchClauseCommon> clauses = new ArrayList<MatchClauseCommon>(toJava(match.clauses()));
Collections.reverse(clauses);
OzNode caseNode = elseNode;
for (MatchClauseCommon clause : clauses) {
caseNode = translateMatchClause(copy(valueNode), caseNode, clause);
}
return caseNode;
}
private OzNode translateMatchClause(OzNode valueNode, OzNode elseNode, MatchClauseCommon clause) {
List<OzNode> checks = new ArrayList<>();
List<OzNode> bindings = new ArrayList<>();
translateMatcher(clause.pattern(), valueNode, checks, bindings);
OzNode body = translate(clause.body());
final IfNode matchNode;
if (clause.hasGuard()) {
OzNode guard = translate(clause.guard().get());
// First the checks, then the bindings and then the guard (possibly using the bindings)
bindings.add(guard);
checks.add(SequenceNode.sequence(bindings.toArray(new OzNode[bindings.size()])));
matchNode = new IfNode(new AndNode(checks.toArray(new OzNode[checks.size()])), body, elseNode);
} else {
matchNode = new IfNode(
new AndNode(checks.toArray(new OzNode[checks.size()])),
SequenceNode.sequence(bindings.toArray(new OzNode[bindings.size()]), body),
elseNode);
}
return t((Node) clause, matchNode);
}
private void translateMatcher(Object matcher, OzNode valueNode, List<OzNode> checks, List<OzNode> bindings) {
if (matcher instanceof Constant) {
translateMatcher(((Constant) matcher).value(), valueNode, checks, bindings);
} else if (matcher instanceof OzPatMatWildcard) {
// Nothing to do
} else if (matcher instanceof OzPatMatCapture) {
FrameSlotAndDepth slot = findVariable(((OzPatMatCapture) matcher).variable());
// Set the slot directly since the variable is born here
assert slot.getDepth() == 0;
bindings.add(new InitializeTmpNode(slot.getSlot(), copy(valueNode)));
} else if (matcher instanceof Variable) {
Variable var = (Variable) matcher;
OzNode left = findVariable(var.symbol()).createReadNode();
checks.add(EqualNodeFactory.create(deref(left), deref(copy(valueNode))));
} else if (matcher instanceof OzPatMatConjunction) {
for (OzValue part : toJava(((OzPatMatConjunction) matcher).parts())) {
translateMatcher(part, valueNode, checks, bindings);
}
} else if (matcher instanceof OzFeature) {
Object feature = translateFeature((OzFeature) matcher);
checks.add(PatternMatchEqualNodeGen.create(feature, copy(valueNode)));
} else if (matcher instanceof OzRecord) {
OzRecord record = (OzRecord) matcher;
if (record.isCons()) {
checks.add(PatternMatchConsNodeGen.create(copy(valueNode)));
OzValue head = record.values().apply(0);
translateMatcher(head, HeadNodeGen.create(copy(valueNode)), checks, bindings);
OzValue tail = record.values().apply(1);
translateMatcher(tail, TailNodeGen.create(copy(valueNode)), checks, bindings);
} else {
Arity arity = buildArity(record.arity());
checks.add(PatternMatchRecordNodeGen.create(arity, copy(valueNode)));
for (OzRecordField field : toJava(record.fields())) {
Object feature = translateFeature(field.feature());
DotNode dotNode = DotNodeFactory.create(deref(copy(valueNode)), new LiteralNode(feature));
translateMatcher(field.value(), dotNode, checks, bindings);
}
}
} else if (matcher instanceof Record) {
Record record = (Record) matcher;
// First match the label
translateMatcher(record.label(), LabelNodeFactory.create(copy(valueNode)), checks, bindings);
// Then check if features match
Object[] features = mapObjects(record.fields(), field -> {
Constant constant = (Constant) field.feature();
return translateFeature((OzFeature) constant.value());
});
checks.add(PatternMatchDynamicArityNodeGen.create(features, copy(valueNode)));
int i = 0;
for (RecordField field : toJava(record.fields())) {
Object feature = features[i++];
DotNode dotNode = DotNodeFactory.create(deref(copy(valueNode)), new LiteralNode(feature));
translateMatcher(field.value(), dotNode, checks, bindings);
}
} else if (matcher instanceof OzPatMatOpenRecord) {
OzPatMatOpenRecord record = (OzPatMatOpenRecord) matcher;
Arity arity = buildArity(record.arity());
checks.add(PatternMatchOpenRecordNodeGen.create(arity, copy(valueNode)));
for (OzRecordField field : toJava(record.fields())) {
Object feature = translateFeature(field.feature());
DotNode dotNode = DotNodeFactory.create(deref(copy(valueNode)), new LiteralNode(feature));
translateMatcher(field.value(), dotNode, checks, bindings);
}
} else {
throw unknown("pattern matcher", matcher);
}
}
private OzNode translateConstantNode(OzValue value) {
if (value instanceof OzInt) {
return new LongLiteralNode(((OzInt) value).value());
} else if (value instanceof True) {
return new BooleanLiteralNode(true);
} else if (value instanceof False) {
return new BooleanLiteralNode(false);
} else {
return new LiteralNode(translateConstantValue(value));
}
}
private Object translateConstantValue(OzValue value) {
if (value instanceof OzFeature) {
return translateFeature((OzFeature) value);
} else if (value instanceof OzFloat) {
return ((OzFloat) value).value();
} else if (value instanceof OzRecord) {
OzRecord ozRecord = (OzRecord) value;
if (ozRecord.isCons()) {
Object left = translateConstantValue(ozRecord.fields().apply(0).value());
Object right = translateConstantValue(ozRecord.fields().apply(1).value());
return new OzCons(left, right);
} else {
Arity arity = buildArity(ozRecord.arity());
Object[] values = mapObjects(ozRecord.values(), this::translateConstantValue);
return org.mozartoz.truffle.runtime.OzRecord.buildRecord(arity, values);
}
} else if (value instanceof OzBuiltin) {
Builtin builtin = ((OzBuiltin) value).builtin();
return BuiltinsManager.getBuiltin(builtin.moduleName(), builtin.name());
}
throw unknown("value", value);
}
private static Object translateFeature(OzFeature feature) {
if (feature instanceof OzInt) {
return ((OzInt) feature).value();
} else if (feature instanceof True) {
return true;
} else if (feature instanceof False) {
return false;
} else if (feature instanceof UnitVal) {
return Unit.INSTANCE;
} else if (feature instanceof OzAtom) {
return translateAtom((OzAtom) feature);
} else {
throw unknown("feature", feature);
}
}
private static Object translateLiteral(OzLiteral literal) {
if (literal instanceof OzAtom) {
return translateAtom((OzAtom) literal);
} else {
throw unknown("literal", literal);
}
}
private static String translateAtom(OzAtom atom) {
return atom.value().intern();
}
private OzNode buildCons(OzNode head, OzNode tail) {
return ConsLiteralNodeGen.create(head, tail);
}
private Arity buildArity(OzArity arity) {
Object[] features = mapObjects(arity.features(), Translator::translateFeature);
return Arity.build(translateLiteral(arity.label()), features);
}
private OzNode translateBinaryOp(String operator, OzNode left, OzNode right) {
left = deref(left);
right = deref(right);
switch (operator) {
case "+":
return AddNodeFactory.create(left, right);
case "-":
return SubNodeFactory.create(left, right);
case "*":
return MulNodeFactory.create(left, right);
case "div":
return DivNodeFactory.create(left, right);
case "mod":
return ModNodeFactory.create(left, right);
case "==":
return EqualNodeFactory.create(left, right);
case "\\=":
return NotEqualNodeFactory.create(left, right);
case "<":
return LesserThanNodeFactory.create(left, right);
case "=<":
return LesserThanOrEqualNodeFactory.create(left, right);
case ">":
return GreaterThanNodeFactory.create(left, right);
case ".":
return DotNodeFactory.create(left, right);
default:
throw unknown("operator", operator);
}
}
private OzNode copy(OzNode node) {
return NodeUtil.cloneNode(node);
}
private OzNode deref(OzNode node) {
return DerefNode.create(node);
}
private static <E> Collection<E> toJava(scala.collection.Iterable<E> scalaIterable) {
return JavaConversions.asJavaCollection(scalaIterable);
}
private static <E> OzNode[] map(scala.collection.Iterable<E> scalaIterable, Function<E, OzNode> apply) {
Collection<E> collection = toJava(scalaIterable);
OzNode[] result = new OzNode[collection.size()];
int i = 0;
for (E element : collection) {
result[i++] = apply.apply(element);
}
return result;
}
private static <E> Object[] mapObjects(scala.collection.Iterable<E> scalaIterable, Function<E, Object> apply) {
Collection<E> collection = toJava(scalaIterable);
Object[] result = new Object[collection.size()];
int i = 0;
for (E element : collection) {
result[i++] = apply.apply(element);
}
return result;
}
private static RuntimeException unknown(String type, Object description) {
return new RuntimeException("Unknown " + type + " " + description.getClass() + ": " + description);
}
private <T extends OzNode> T t(Node node, T ozNode) {
SourceSection sourceSection = t(node);
ozNode.setSourceSection(sourceSection);
return ozNode;
}
private <T extends OzNode> T t(Object node, T ozNode) {
return t((Node) node, ozNode);
}
private SourceSection t(Node node) {
if (node.section() != null) {
return sectionWithIdentifier(node.section(), environment.identifier);
} else {
return SourceSection.createUnavailable("unavailable", "");
}
}
private SourceSection t(ProcExpression node) {
if (node.section() != null) {
if (node.name().isDefined()) {
String identifier = ((Variable) node.name().get()).symbol().name();
return sectionWithIdentifier(node.section(), identifier);
} else {
return node.section();
}
} else {
return SourceSection.createUnavailable("unavailable", "");
}
}
private SourceSection sectionWithIdentifier(SourceSection section, String identifier) {
if (section.getSource() == null) {
return section;
}
return section.getSource().createSection(identifier,
section.getStartLine(), section.getStartColumn(), section.getCharIndex(), section.getCharLength());
}
} |
package org.my.scanExample;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import io.card.payment.CardIOActivity;
import io.card.payment.CreditCard;
public class MyScanActivity extends Activity
{
final String TAG = getClass().getName();
private Button scanButton;
private TextView resultTextView;
private int MY_SCAN_REQUEST_CODE = 100; // arbitrary int
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
resultTextView = (TextView)findViewById(R.id.resultTextView);
scanButton = (Button)findViewById(R.id.scanButton);
resultTextView.setText("card.io library version: " + CardIOActivity.sdkVersion() + "\nBuilt: " + CardIOActivity.sdkBuildDate());
}
@Override
protected void onResume() {
super.onResume();
if (CardIOActivity.canReadCardWithCamera(this)) {
scanButton.setText("Scan a credit card with card.io");
}
else {
scanButton.setText("Enter credit card information");
}
}
public void onScanPress(View v) {
// This method is set up as an onClick handler in the layout xml
// e.g. android:onClick="onScanPress"
Intent scanIntent = new Intent(this, CardIOActivity.class);
// customize these values to suit your needs.
scanIntent.putExtra(CardIOActivity.EXTRA_REQUIRE_EXPIRY, true); // default: true
scanIntent.putExtra(CardIOActivity.EXTRA_REQUIRE_CVV, false); // default: false
scanIntent.putExtra(CardIOActivity.EXTRA_REQUIRE_POSTAL_CODE, false); // default: false
// hides the manual entry button
// if set, developers should provide their own manual entry mechanism in the app
scanIntent.putExtra(CardIOActivity.EXTRA_SUPPRESS_MANUAL_ENTRY, false); // default: false
// MY_SCAN_REQUEST_CODE is arbitrary and is only used within this activity.
startActivityForResult(scanIntent, MY_SCAN_REQUEST_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
String resultStr;
if (data != null && data.hasExtra(CardIOActivity.EXTRA_SCAN_RESULT)) {
CreditCard scanResult = data.getParcelableExtra(CardIOActivity.EXTRA_SCAN_RESULT);
// Never log a raw card number. Avoid displaying it, but if necessary use getFormattedCardNumber()
resultStr = "Card Number: " + scanResult.getRedactedCardNumber() + "\n";
// Do something with the raw number, e.g.:
// myService.setCardNumber( scanResult.cardNumber );
if (scanResult.isExpiryValid()) {
resultStr += "Expiration Date: " + scanResult.expiryMonth + "/" + scanResult.expiryYear + "\n";
}
if (scanResult.cvv != null) {
// Never log or display a CVV
resultStr += "CVV has " + scanResult.cvv.length() + " digits.\n";
}
if (scanResult.postalCode != null) {
resultStr += "Postal Code: " + scanResult.postalCode + "\n";
}
}
else {
resultStr = "Scan was canceled.";
}
resultTextView.setText(resultStr);
}
} |
package bisq.core.dao.governance.period;
import bisq.core.dao.DaoSetupService;
import bisq.core.dao.governance.param.Param;
import bisq.core.dao.state.DaoStateListener;
import bisq.core.dao.state.DaoStateService;
import bisq.core.dao.state.GenesisTxInfo;
import bisq.core.dao.state.model.governance.Cycle;
import bisq.core.dao.state.model.governance.DaoPhase;
import com.google.inject.Inject;
import com.google.common.collect.ImmutableList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class CycleService implements DaoStateListener, DaoSetupService {
private final DaoStateService daoStateService;
private final int genesisBlockHeight;
// Constructor
@Inject
public CycleService(DaoStateService daoStateService,
GenesisTxInfo genesisTxInfo) {
this.daoStateService = daoStateService;
this.genesisBlockHeight = genesisTxInfo.getGenesisBlockHeight();
}
// DaoSetupService
@Override
public void addListeners() {
daoStateService.addDaoStateListener(this);
}
@Override
public void start() {
addFirstCycle();
}
// DaoStateListener
@Override
public void onNewBlockHeight(int blockHeight) {
maybeCreateNewCycle(blockHeight, daoStateService.getCycles()).ifPresent(daoStateService::addCycle);
}
// API
public void addFirstCycle() {
daoStateService.addCycle(getFirstCycle());
}
public int getCycleIndex(Cycle cycle) {
Optional<Cycle> previousCycle = getCycle(cycle.getHeightOfFirstBlock() - 1, daoStateService.getCycles());
return previousCycle.map(cycle1 -> getCycleIndex(cycle1) + 1).orElse(0);
}
public boolean isTxInCycle(Cycle cycle, String txId) {
return daoStateService.getTx(txId).filter(tx -> isBlockHeightInCycle(tx.getBlockHeight(), cycle)).isPresent();
}
// Private
private boolean isBlockHeightInCycle(int blockHeight, Cycle cycle) {
return blockHeight >= cycle.getHeightOfFirstBlock() &&
blockHeight <= cycle.getHeightOfLastBlock();
}
private Optional<Cycle> maybeCreateNewCycle(int blockHeight, LinkedList<Cycle> cycles) {
// We want to set the correct phase and cycle before we start parsing a new block.
// For Genesis block we did it already in the start method.
// We copy over the phases from the current block as we get the phase only set in
// applyParamToPhasesInCycle if there was a changeEvent.
// The isFirstBlockInCycle methods returns from the previous cycle the first block as we have not
// applied the new cycle yet. But the first block of the old cycle will always be the same as the
// first block of the new cycle.
Cycle cycle = null;
if (blockHeight > genesisBlockHeight && !cycles.isEmpty() && isFirstBlockAfterPreviousCycle(blockHeight, cycles)) {
// We have the not update daoStateService.getCurrentCycle() so we grab here the previousCycle
Cycle previousCycle = cycles.getLast();
// We create the new cycle as clone of the previous cycle and only if there have been change events we use
// the new values from the change event.
cycle = createNewCycle(blockHeight, previousCycle);
}
return Optional.ofNullable(cycle);
}
private Cycle getFirstCycle() {
// We want to have the initial data set up before the genesis tx gets parsed so we do it here in the constructor
// as onAllServicesInitialized might get called after the parser has started.
// We add the default values from the Param enum to our StateChangeEvent list.
List<DaoPhase> daoPhasesWithDefaultDuration = Arrays.stream(DaoPhase.Phase.values())
.map(this::getPhaseWithDefaultDuration)
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toList());
return new Cycle(genesisBlockHeight, ImmutableList.copyOf(daoPhasesWithDefaultDuration));
}
private Cycle createNewCycle(int blockHeight, Cycle previousCycle) {
List<DaoPhase> daoPhaseList = previousCycle.getDaoPhaseList().stream()
.map(daoPhase -> {
DaoPhase.Phase phase = daoPhase.getPhase();
try {
Param param = Param.valueOf("PHASE_" + phase.name());
int value = daoStateService.getParamValueAsBlock(param, blockHeight);
return new DaoPhase(phase, value);
} catch (Throwable ignore) {
return null;
}
})
.filter(Objects::nonNull)
.collect(Collectors.toList());
return new Cycle(blockHeight, ImmutableList.copyOf(daoPhaseList));
}
private boolean isFirstBlockAfterPreviousCycle(int height, LinkedList<Cycle> cycles) {
int previousBlockHeight = height - 1;
Optional<Cycle> previousCycle = getCycle(previousBlockHeight, cycles);
return previousCycle
.filter(cycle -> cycle.getHeightOfLastBlock() + 1 == height)
.isPresent();
}
private Optional<DaoPhase> getPhaseWithDefaultDuration(DaoPhase.Phase phase) {
return Arrays.stream(Param.values())
.filter(param -> isParamMatchingPhase(param, phase))
.map(param -> new DaoPhase(phase, Integer.parseInt(param.getDefaultValue())))
.findAny(); // We will always have a default value defined
}
private boolean isParamMatchingPhase(Param param, DaoPhase.Phase phase) {
return param.name().contains("PHASE_") && param.name().replace("PHASE_", "").equals(phase.name());
}
private Optional<Cycle> getCycle(int height, LinkedList<Cycle> cycles) {
return cycles.stream()
.filter(cycle -> cycle.getHeightOfFirstBlock() <= height)
.filter(cycle -> cycle.getHeightOfLastBlock() >= height)
.findAny();
}
} |
package org.jboss.forge.service.util;
import static javax.json.Json.createArrayBuilder;
import static javax.json.Json.createObjectBuilder;
import java.util.ArrayList;
import javax.inject.Inject;
import javax.json.JsonArray;
import javax.json.JsonArrayBuilder;
import javax.json.JsonNumber;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import javax.json.JsonString;
import javax.json.JsonValue;
import javax.json.JsonValue.ValueType;
import org.jboss.forge.addon.convert.Converter;
import org.jboss.forge.addon.convert.ConverterFactory;
import org.jboss.forge.addon.ui.controller.CommandController;
import org.jboss.forge.addon.ui.controller.WizardCommandController;
import org.jboss.forge.addon.ui.input.HasCompleter;
import org.jboss.forge.addon.ui.input.InputComponent;
import org.jboss.forge.addon.ui.input.ManyValued;
import org.jboss.forge.addon.ui.input.SelectComponent;
import org.jboss.forge.addon.ui.input.SingleValued;
import org.jboss.forge.addon.ui.input.UICompleter;
import org.jboss.forge.addon.ui.input.UIInput;
import org.jboss.forge.addon.ui.input.UIInputMany;
import org.jboss.forge.addon.ui.input.UISelectMany;
import org.jboss.forge.addon.ui.input.UISelectOne;
import org.jboss.forge.addon.ui.metadata.UICommandMetadata;
import org.jboss.forge.addon.ui.output.UIMessage;
import org.jboss.forge.addon.ui.result.CompositeResult;
import org.jboss.forge.addon.ui.result.Failed;
import org.jboss.forge.addon.ui.result.Result;
import org.jboss.forge.addon.ui.util.InputComponents;
import org.jboss.forge.service.ui.RestUIProvider;
/**
* Describes commands
*
* @author <a href="mailto:ggastald@redhat.com">George Gastaldi</a>
*/
public class UICommandHelper
{
private final ConverterFactory converterFactory;
@Inject
public UICommandHelper(ConverterFactory converterFactory)
{
this.converterFactory = converterFactory;
}
public void describeController(JsonObjectBuilder builder, CommandController controller)
{
describeMetadata(builder, controller);
describeCurrentState(builder, controller);
describeInputs(builder, controller);
}
public void describeCurrentState(JsonObjectBuilder builder, CommandController controller)
{
JsonObjectBuilder stateBuilder = createObjectBuilder();
stateBuilder.add("valid", controller.isValid());
stateBuilder.add("canExecute", controller.canExecute());
if (controller instanceof WizardCommandController)
{
stateBuilder.add("wizard", true);
stateBuilder.add("canMoveToNextStep", ((WizardCommandController) controller).canMoveToNextStep());
stateBuilder.add("canMoveToPreviousStep", ((WizardCommandController) controller).canMoveToPreviousStep());
}
else
{
stateBuilder.add("wizard", false);
}
builder.add("state", stateBuilder);
}
public void describeMetadata(JsonObjectBuilder builder, CommandController controller)
{
UICommandMetadata metadata = controller.getMetadata();
JsonObjectBuilder metadataBuilder = createObjectBuilder();
metadataBuilder.add("deprecated", metadata.isDeprecated());
addOptional(metadataBuilder, "category", metadata.getCategory());
addOptional(metadataBuilder, "name", metadata.getName());
addOptional(metadataBuilder, "description", metadata.getDescription());
addOptional(metadataBuilder, "deprecatedMessage", metadata.getDeprecatedMessage());
builder.add("metadata", metadataBuilder);
}
@SuppressWarnings("unchecked")
public void describeInputs(JsonObjectBuilder builder, CommandController controller)
{
// Add inputs
JsonArrayBuilder inputBuilder = createArrayBuilder();
for (InputComponent<?, ?> input : controller.getInputs().values())
{
JsonObjectBuilder objBuilder = createObjectBuilder()
.add("name", input.getName())
.add("shortName", String.valueOf(input.getShortName()))
.add("valueType", input.getValueType().getName())
.add("inputType", InputComponents.getInputType(input))
.add("enabled", input.isEnabled())
.add("required", input.isRequired())
.add("deprecated", input.isDeprecated())
.add("label", InputComponents.getLabelFor(input, false));
addOptional(objBuilder, "description", input.getDescription());
addOptional(objBuilder, "note", input.getNote());
Converter<Object, String> inputConverter = null;
if (input instanceof SelectComponent)
{
SelectComponent<?, Object> selectComponent = (SelectComponent<?, Object>) input;
inputConverter = InputComponents.getItemLabelConverter(converterFactory, selectComponent);
JsonArrayBuilder valueChoices = createArrayBuilder();
for (Object valueChoice : selectComponent.getValueChoices())
{
valueChoices.add(inputConverter.convert(valueChoice));
}
objBuilder.add("valueChoices", valueChoices);
if (input instanceof UISelectMany)
{
objBuilder.add("class", UISelectMany.class.getSimpleName());
}
else
{
objBuilder.add("class", UISelectOne.class.getSimpleName());
}
}
else
{
if (input instanceof UIInputMany)
{
objBuilder.add("class", UIInputMany.class.getSimpleName());
}
else
{
objBuilder.add("class", UIInput.class.getSimpleName());
}
}
if (inputConverter == null)
{
inputConverter = (Converter<Object, String>) converterFactory
.getConverter(input.getValueType(), String.class);
}
if (input instanceof ManyValued)
{
ManyValued<?, Object> many = (ManyValued<?, Object>) input;
JsonArrayBuilder manyValues = createArrayBuilder();
for (Object item : many.getValue())
{
manyValues.add(inputConverter.convert(item));
}
objBuilder.add("value", manyValues);
}
else
{
SingleValued<?, Object> single = (SingleValued<?, Object>) input;
Object value = single.getValue();
if (value != null && !(value instanceof Number) && !(value instanceof Boolean))
{
value = inputConverter.convert(value);
}
addOptional(objBuilder, "value", value);
}
if (input instanceof HasCompleter)
{
HasCompleter<?, Object> hasCompleter = (HasCompleter<?, Object>) input;
UICompleter<Object> completer = hasCompleter.getCompleter();
if (completer != null)
{
JsonArrayBuilder typeAheadData = createArrayBuilder();
Iterable<Object> valueChoices = completer.getCompletionProposals(controller.getContext(),
(InputComponent<?, Object>) input,
"");
for (Object valueChoice : valueChoices)
{
typeAheadData.add(inputConverter.convert(valueChoice));
}
objBuilder.add("typeAheadData", typeAheadData);
}
}
inputBuilder.add(objBuilder);
}
builder.add("inputs", inputBuilder);
}
public void describeValidation(JsonObjectBuilder builder, CommandController controller)
{
// Add messages
JsonArrayBuilder messages = createArrayBuilder();
for (UIMessage message : controller.validate())
{
JsonObjectBuilder messageObj = createObjectBuilder()
.add("description", message.getDescription())
.add("severity", message.getSeverity().name());
if (message.getSource() != null)
messageObj.add("input", message.getSource().getName());
messages.add(messageObj);
}
builder.add("messages", messages);
}
public void describeExecution(JsonObjectBuilder builder, CommandController controller) throws Exception
{
Result result = controller.execute();
describeResult(builder, result);
// Get out and err
RestUIProvider provider = (RestUIProvider) controller.getContext().getProvider();
builder.add("out", provider.getOut());
builder.add("err", provider.getErr());
}
public void populateControllerAllInputs(JsonObject content, CommandController controller) throws Exception
{
populateController(content, controller);
int stepIndex = content.getInt("stepIndex", 0);
if (controller instanceof WizardCommandController)
{
WizardCommandController wizardController = (WizardCommandController) controller;
for (int i = 0; i < stepIndex && wizardController.canMoveToNextStep(); i++)
{
wizardController.next().initialize();
populateController(content, wizardController);
}
}
}
public void populateController(JsonObject content, CommandController controller)
{
JsonArray inputArray = content.getJsonArray("inputs");
for (int i = 0; i < inputArray.size(); i++)
{
JsonObject input = inputArray.getJsonObject(i);
String inputName = input.getString("name");
JsonValue valueObj = input.get("value");
Object inputValue = null;
if (valueObj != null)
{
switch (valueObj.getValueType())
{
case ARRAY:
ArrayList<String> list = new ArrayList<>();
for (JsonValue value : (JsonArray) valueObj)
{
if (value.getValueType() == ValueType.STRING)
{
list.add(((JsonString) value).getString());
}
}
inputValue = list;
break;
case FALSE:
inputValue = false;
break;
case TRUE:
inputValue = true;
break;
case NUMBER:
inputValue = ((JsonNumber) valueObj).intValue();
break;
case STRING:
inputValue = ((JsonString) valueObj).getString();
break;
default:
break;
}
}
if (controller.hasInput(inputName) && inputValue != null)
controller.setValueFor(inputName, inputValue);
}
}
public void describeResult(JsonObjectBuilder builder, Result result)
{
JsonArrayBuilder array = createArrayBuilder();
collectResults(array, result);
builder.add("results", array);
}
private void collectResults(JsonArrayBuilder results, Result result)
{
if (result instanceof CompositeResult)
{
for (Result r : ((CompositeResult) result).getResults())
{
collectResults(results, r);
}
}
else
{
results.add(describeSingleResult(result));
}
}
private JsonObjectBuilder describeSingleResult(Result result)
{
JsonObjectBuilder builder = createObjectBuilder();
builder.add("status", (result instanceof Failed) ? "FAILED" : "SUCCESS");
if (result != null)
addOptional(builder, "message", result.getMessage());
return builder;
}
private void addOptional(JsonObjectBuilder builder, String name, Object value)
{
if (value != null)
{
if (value instanceof Boolean)
{
builder.add(name, (Boolean) value);
}
else if (value instanceof Number)
{
builder.add(name, ((Number) value).intValue());
}
else
{
builder.add(name, value.toString());
}
}
}
} |
package ch.idsia.mario.engine.level;
import ch.idsia.mario.engine.sprites.Enemy;
import java.util.Random;
/**
* Using this class is very simple. Just call <b>createMethod</b> with params:
* <ul>
* <li>width -- width of the level in cells. On the screen one cell has 16 pixels </li>
* <li>height -- height of the level in cells. On the screen one cell has 16 pixels </li>
* <li>seed -- use this param to make a globalRandom level.
* On different machines with the same seed param there will be one level</li>
* <li>difficulty -- use this param to change difficult of the level.
* On different machines with the same seed param there will be one level</li>
* <li>type -- type of the level. One of Overground, Underground, Castle.</li>
* </ul>
*
* @see #TYPE_OVERGROUND
* @see #TYPE_UNDERGROUND
* @see #TYPE_CASTLE
*
*/
public class LevelGenerator
{
public static final int TYPE_OVERGROUND = 0;
public static final int TYPE_UNDERGROUND = 1;
public static final int TYPE_CASTLE = 2;
public static final int DEFAULT_FLOOR = -1;
private int[] cmdArgs; //ATTENTION: not cloned.
//TODO: length of the level shouldn't be fewer than LevelLengthMinThreshold
public static final int LevelLengthMinThreshold = 50; // minimal length of the level. used in ToolsConfigurator
private int levelDifficulty;
public static Level createLevel(int[] args)
{
LevelGenerator levelGenerator = new LevelGenerator(args);
return levelGenerator.createLevel(args[4], args[2], args[5]);
}
private int width;
private int height;
Level level;
final static Random globalRandom = new Random();
final static Random creaturesRandom = new Random();
private static final int ODDS_STRAIGHT = 0;
private static final int ODDS_HILL_STRAIGHT = 1;
private static final int ODDS_TUBES = 2;
private static final int ODDS_GAPS = 3;
private static final int ODDS_CANNONS = 4;
private static final int ODDS_DEAD_ENDS = 5;
private int[] odds = new int[6];
private int totalOdds;
private int difficulty; //level difficulty
private int type; //level type
//constants for dead ends
private static final boolean RIGHT_DIRECTION_BOTTOM = false;
private static final int ANY_HEIGHT = -1;
private static final int INFINITY_FLOOR_HEIGHT = Integer.MAX_VALUE;
//Level customization counters
private int deadEndsCount = 0;
private int cannonsCount = 0;
private int hillStraightCount = 0;
private int tubesCount = 0;
private int blocksCount = 0;
private int coinsCount = 0;
private int gapsCount = 0;
private int hiddenBlocksCount = 0;
private LevelGenerator(int[] args)
{
this.width = args[3];
this.height = args[19];
this.cmdArgs = args;
}
private Level createLevel(long seed, int difficulty, int type)
{
this.type = type;
this.difficulty = difficulty;
odds[ODDS_STRAIGHT] = 20;
odds[ODDS_HILL_STRAIGHT] = 1;
odds[ODDS_TUBES] = 2 + 1 * difficulty;
this.levelDifficulty = difficulty;
odds[ODDS_GAPS] = 3 * difficulty;
odds[ODDS_CANNONS] = -10 + 5 * difficulty;
odds[ODDS_DEAD_ENDS] = 2 + 2 * difficulty;
if (type != LevelGenerator.TYPE_OVERGROUND)
{
odds[ODDS_HILL_STRAIGHT] = 0; //if not overground then there are no hill straight
}
for (int i = 0; i < odds.length; i++)
{
if (odds[i] < 0) odds[i] = 0;
totalOdds += odds[i];
odds[i] = totalOdds - odds[i];
}
level = new Level(width, height);
globalRandom.setSeed(seed);
int length = 0; //total level length
//mario starts on straight
length += buildStraight(0, level.width, true, DEFAULT_FLOOR, INFINITY_FLOOR_HEIGHT);
while (length < level.width - 64)
{
length += buildZone(length, level.width - length, ANY_HEIGHT, DEFAULT_FLOOR, INFINITY_FLOOR_HEIGHT);
}
int floor = height -1 - globalRandom.nextInt(4); //floor of the exit line
//coordinates of finish
level.xExit = length + 8;
level.yExit = floor;
//fix floor
for (int x = length; x < level.width; x++)
{
for (int y = 0; y < height; y++)
{
if (y >= floor)
{
level.setBlock(x, y, (byte) (1 + 9 * 16));
}
}
}
//if underground or castle then built ceiling
if (type == LevelGenerator.TYPE_CASTLE || type == LevelGenerator.TYPE_UNDERGROUND)
{
int ceiling = 0;
int run = 0;
for (int x = 0; x < level.width; x++)
{
if (run-- <= 0 && x > 4)
{
ceiling = globalRandom.nextInt(4);
run = globalRandom.nextInt(4) + 4;
}
for (int y = 0; y < level.height; y++)
{
if ((x > 4 && y <= ceiling) || x < 1)
{
level.setBlock(x, 0, (byte) (1 + 9 * 16));
}
}
}
}
fixWalls();
return level;
}
private int buildZone(int x, int maxLength, int maxHeight, int floor, int floorHeight)
{
int t = globalRandom.nextInt(totalOdds);
int type = 0;
//calculate what will be built
for (int i = 0; i < odds.length; i++)
{
if (odds[i] <= t)
{
type = i;
}
}
switch (type)
{
case ODDS_STRAIGHT:
return buildStraight(x, maxLength, false, floor, floorHeight);
case ODDS_HILL_STRAIGHT:
if( floor == DEFAULT_FLOOR && hillStraightCount < cmdArgs[22] )
{
hillStraightCount++;
return buildHillStraight(x, maxLength, floor);
}
else
{
return 0;
}
case ODDS_TUBES:
if( tubesCount < cmdArgs[23] )
{
//increment of tubesCount is inside of the method
return buildTubes(x, maxLength, maxHeight, floor, floorHeight);
}
else
{
return 0;
}
case ODDS_GAPS:
if ((floor > 2 || floor == ANY_HEIGHT) && gapsCount < cmdArgs[26])
{
gapsCount++;
return buildGap(x, 12, maxHeight, floor, floorHeight);
}
else
{
return 0;
}
case ODDS_CANNONS:
if (cannonsCount < cmdArgs[21])
{
//increment of cannons is inside of the method
return buildCannons(x, maxLength, maxHeight, floor, floorHeight);
}
else
{
return 0;
}
case ODDS_DEAD_ENDS:
{
if (floor == DEFAULT_FLOOR && deadEndsCount < cmdArgs[20]) //if method was not called from buildDeadEnds
{
deadEndsCount++;
return buildDeadEnds(x, maxLength);
}
}
}
return 0;
}
/*
first component of sum : position on Y axis
second component of sum : position on X axis
starting at 0
*16 because size of the picture is 16x16 pixels
0+9*16 -- left side of the ground
1+9*16 -- upper side of ground; common block telling "it's smth (ground) here". Is processed further.
2+9*16 -- right side of the earth
3+9*16 -- peice of the earth
9+0*16 -- block of a ladder
14+0*16 -- cannon barrel
14+1*16 -- base for cannon barrel
14+2*16 -- cannon pole
4+8*16 -- left piece of a hill of ground
4+11*16 -- left piece of a hill of ground as well
6+8*16 -- right upper peice of a hill
6+11*16 -- right upper peice of a hill on earth
2+2*16 -- animated coin
4+2+1*16 -- animated cube with question mark
4+1+1*16 -- animated cube with question mark
2+1*16 -- animated brick
1+1*16 -- animated brick
0+1*16 -- animated brick
1+10*16 -- earth, bottom piece
1+8*16 -- earth, upper piece
3+10*16 -- piece of earth
3+11*16 -- piece of earth
2+8*16 -- right part of earth
0+8*16 -- left upper part of earth
3+8*16 -- piece of earth
2+10*16 -- right bottomp iece of earth
0+10*16 -- left bottom piece of earth
*/
//x0 - first block to start from
//maxLength - maximal length of the zone
private int buildDeadEnds( int x0, int maxLength )
{
//first of all build pre dead end zone
int floor = height - 2 - globalRandom.nextInt( 2 ); //floor of pre dead end zone
int length = 0; // total zone length
int preDeadEndLength = 7 + globalRandom.nextInt(10);
int rHeight = floor-1; //rest height
length += buildStraight(x0, preDeadEndLength, true, floor, INFINITY_FLOOR_HEIGHT);//buildZone( x0, x0+preDeadEndLength, floor ); //build pre dead end zone
buildBlocks( x0, x0+preDeadEndLength, floor, true, 0, 0, true );
//correct direction
//true - top, false = bottom
globalRandom.nextInt();
int k = globalRandom.nextInt(5);//(globalRandom.nextInt() % (this.levelDifficulty+1));
boolean direction = globalRandom.nextInt( k+1 ) != 1;
int separatorY = 3 + globalRandom.nextInt(rHeight-7); //Y coordinate of the top line of the separator
//Y coordinate of the bottom line of the separator is determined as separatorY + separatorHeight
int separatorHeight = 2 + globalRandom.nextInt(2);
int nx = x0 + length;
int depth = 12 + globalRandom.nextInt(15) + this.difficulty;
if (depth + length > maxLength)
{
while (depth + length > maxLength)
{
depth
}
}
int tLength = 0;
int bSpace = floor - (separatorY + separatorHeight);
if (bSpace < 4)
{
while (bSpace < 4)
{
separatorY -= 1;
bSpace = floor - (separatorY + separatorHeight);
}
}
int wallWidth = 2 + globalRandom.nextInt(3);
while( tLength < depth ) //top part
{
tLength += buildZone(nx+tLength,depth-tLength, separatorY-1, separatorY, separatorHeight);
}
tLength = 0;
while( tLength < depth ) //bottom part
{
tLength += buildZone( nx+tLength, depth-tLength, bSpace, floor, INFINITY_FLOOR_HEIGHT);
}
for( int x = nx; x < nx + depth; x++ )
{
for( int y = 0; y < height; y++ )
{
if( x-nx >= depth-wallWidth )
{
if (direction == RIGHT_DIRECTION_BOTTOM) //wall on the top
{
if( y <= separatorY)// + separatorHeight )
{
level.setBlock(x, y, (byte) (1 + 9 * 16));
}
}
else
{
if( y >= separatorY )
{
level.setBlock(x, y, (byte) (1 + 9 * 16));
}
}
}
}
}
return length+tLength;
}
private int buildGap(int xo, int maxLength, int maxHeight, int vfloor, int floorHeight)
{
int gs = globalRandom.nextInt(4) + 2; //GapStairs
int gl = globalRandom.nextInt(2) + 2; //GapLength
// System.out.println("globalRandom.nextInt() % this.levelDifficulty+1 = " +
globalRandom.nextInt();
int length = gs * 2 + gl + (globalRandom.nextInt() % this.levelDifficulty+1);
boolean hasStairs = globalRandom.nextInt(3) == 0;
if(maxHeight <= 5 && maxHeight != ANY_HEIGHT) //TODO: gs must be smaller than maxHeigth
{
hasStairs = false;
}
int floor = vfloor;
if( vfloor == DEFAULT_FLOOR)
{
floor = height - 1 - globalRandom.nextInt(4);
}
else
{
globalRandom.nextInt();
if (floor > 1)
{
floor -= 1;
}
}
if( floorHeight == INFINITY_FLOOR_HEIGHT )
{
floorHeight = height - floor;
}
for (int x = xo; x < xo + length; x++)
{
if (x < xo + gs || x > xo + length - gs - 1)
{
for (int y = 0; y < height; y++)
{
if (y >= floor && y <= floor + floorHeight)
{
level.setBlock(x, y, (byte) (1 + 9 * 16));
}
else if (hasStairs)
{
if (x < xo + gs)
{
if (y >= floor - (x - xo) + 1 && y <= floor + floorHeight)
{
level.setBlock(x, y, (byte) (9 + 0 * 16));
}
}
else
{
if (y >= floor - ((xo + length) - x) + 2 && y <= floor + floorHeight)
{
level.setBlock(x, y, (byte) (9 + 0 * 16));
}
}
}
}
}
}
if (length < 0) length = 1;
if (length > maxLength) length = maxLength;
// System.out.println("length = " + length);
return length;
}
private int buildCannons(int xo, int maxLength, int maxHeight, int vfloor, int floorHeight)
{
int length = globalRandom.nextInt(10) + 2;
if (length > maxLength) length = maxLength;
int floor = vfloor;
if( vfloor == DEFAULT_FLOOR)
{
floor = height - 1 - globalRandom.nextInt(4);
}
else
{
globalRandom.nextInt();
}
if( floorHeight == INFINITY_FLOOR_HEIGHT )
{
floorHeight = height - floor;
}
int xCannon = xo + 1 + globalRandom.nextInt(4);
for (int x = xo; x < xo + length; x++)
{
if (x > xCannon)
{
xCannon += 2 + globalRandom.nextInt(4);
cannonsCount++;
}
if (xCannon == xo + length - 1)
{
xCannon += 10;
}
int cannonHeight = floor - globalRandom.nextInt(3) - 1; //cannon height is a Y coordinate of top part of the cannon
if (maxHeight != ANY_HEIGHT)
{
//maxHeight -= 2;
if (floor - cannonHeight >= maxHeight)
{
if (maxHeight > 4)
{
maxHeight = 4;
}
while( floor - cannonHeight > maxHeight )
{
cannonHeight++;
}
}
}
for (int y = 0; y < height; y++)
{
if (y >= floor && y <= floor + floorHeight)
{
level.setBlock(x, y, (byte) (1 + 9 * 16));
}
else if (cannonsCount <= cmdArgs[21])
{
if (x == xCannon && y >= cannonHeight && y <= floor)// + floorHeight)
{
if (y == cannonHeight)
{
level.setBlock(x, y, (byte) (14 + 0 * 16));
}
else if (y == cannonHeight + 1)
{
level.setBlock(x, y, (byte) (14 + 1 * 16));
}
else
{
level.setBlock(x, y, (byte) (14 + 2 * 16));
}
}
}
}
}
return length;
}
private int buildHillStraight(int xo, int maxLength, int vfloor)
{
int length = globalRandom.nextInt(10) + 10;
if (length > maxLength)
{
length = maxLength;
}
/* if( maxLength < 10 )
{
return 0;
}
*/
int floor = vfloor;
if( vfloor == DEFAULT_FLOOR)
{
floor = height - 1 - globalRandom.nextInt(4);
}
else
{
globalRandom.nextInt();
}
for (int x = xo; x < xo + length; x++)
{
for (int y = 0; y < height; y++)
{
if (y >= floor)
{
level.setBlock(x, y, (byte) (1 + 9 * 16));
}
}
}
addEnemyLine(xo + 1, xo + length - 1, floor - 1);
int h = floor;
boolean keepGoing = true;
boolean[] occupied = new boolean[length];
while (keepGoing)
{
h = h - 2 - globalRandom.nextInt(3);
if (h <= 0)
{
keepGoing = false;
}
else
{
int l = globalRandom.nextInt(5) + 3;
int xxo = globalRandom.nextInt(length - l - 2) + xo + 1;
if (occupied[xxo - xo] || occupied[xxo - xo + l] || occupied[xxo - xo - 1] || occupied[xxo - xo + l + 1])
{
keepGoing = false;
}
else
{
occupied[xxo - xo] = true;
occupied[xxo - xo + l] = true;
addEnemyLine(xxo, xxo + l, h - 1);
if (globalRandom.nextInt(4) == 0)
{
decorate(xxo - 1, xxo + l + 1, h, false);
keepGoing = false;
}
for (int x = xxo; x < xxo + l; x++)
{
for (int y = h; y < floor; y++)
{
int xx = 5;
if (x == xxo) xx = 4;
if (x == xxo + l - 1) xx = 6;
int yy = 9;
if (y == h) yy = 8;
if (level.getBlock(x, y) == 0)
{
level.setBlock(x, y, (byte) (xx + yy * 16));
}
else
{
if (level.getBlock(x, y) == (byte) (4 + 8 * 16)) level.setBlock(x, y, (byte) (4 + 11 * 16));
if (level.getBlock(x, y) == (byte) (6 + 8 * 16)) level.setBlock(x, y, (byte) (6 + 11 * 16));
}
}
}
}
}
}
return length;
}
/*
0)goomba
1)green coopa
2)winged green coopa
3)red coopa
4)winged red coopa
5)spiky
6)winged spiky
*/
private void addEnemyLine(int x0, int x1, int y)
{
String creatures = String.valueOf(cmdArgs[28]);
while (creatures.length() < 7)
{
creatures = "0"+creatures;
}
boolean canAdd = true;
for (int x = x0; x < x1; x++)
{
if (level.getBlock( x, y ) == -95)
{
canAdd = false;
break;
}
}
if (!canAddEnemyLine(x0, x1, y))
{
canAdd = false;
}
if(!canAdd) return;
for (int x = x0; x < x1; x++)
{
if (creaturesRandom.nextInt(35) < difficulty + 1)
{
if (creatures.equals("1111111"))
{ //difficulty of creatures on the level depends on the difficulty of the level
int type = creaturesRandom.nextInt(4);
if (difficulty < 1)
{
type = Enemy.ENEMY_GOOMBA;
}
else if (difficulty < 3)
{
type = creaturesRandom.nextInt(3);
}
level.setSpriteTemplate(x, y, new SpriteTemplate(type, creaturesRandom.nextInt(35) < difficulty));
}
else
{
boolean allowable = false;
int type = creaturesRandom.nextInt(4);
if (difficulty < 3)
{
creaturesRandom.nextInt(3);
}
Random locRnd = new Random();
do
{
type = locRnd.nextInt(7);
if (type == 7)
{
type
}
if (creatures.charAt(type) == '1')
{
allowable = true;
}
}
while (!allowable);
boolean winged = (type > 3);
if (type > 3)
{
type -= 3;
}
level.setSpriteTemplate(x, y, new SpriteTemplate(type, winged));
}
}
}
}
private int buildTubes(int xo, int maxLength, int maxHeight, int vfloor, int floorHeight)
{
int tubes = 0;
int length = globalRandom.nextInt(10) + 5;
if (length > maxLength) length = maxLength;
int floor = vfloor;
if( vfloor == DEFAULT_FLOOR)
{
floor = height - 1 - globalRandom.nextInt(4);
}
else
{
globalRandom.nextInt();
}
int xTube = xo + 1 + globalRandom.nextInt(4);
int tubeHeight = floor - globalRandom.nextInt(3) - 1;
if (maxHeight != ANY_HEIGHT)
{
if (floor - tubeHeight > maxHeight)
{
if (maxHeight > 4)
{
maxHeight = 4;
}
while( floor - tubeHeight > maxHeight )
{
tubeHeight++;
}
}
}
//TODO: make this part like in BuildStraight. Not critical but unity of code style
if( floorHeight == INFINITY_FLOOR_HEIGHT )
{
floorHeight = height - floor;
}
for (int x = xo; x < xo + length; x++)
{
if (x > xTube + 1)
{
xTube += 3 + globalRandom.nextInt(4);
tubeHeight = floor - globalRandom.nextInt(2) - 2;
if (maxHeight != ANY_HEIGHT)
{
while( floor - tubeHeight > maxHeight-1 )
{
tubeHeight++;
}
}
}
if (xTube >= xo + length - 2)
{
xTube += 10;
}
if (x == xTube && globalRandom.nextInt(11) < difficulty + 1 && cmdArgs[28] == 1)
{
level.setSpriteTemplate(x, tubeHeight, new SpriteTemplate(Enemy.ENEMY_FLOWER, false));
}
for (int y = 0; y < floor+floorHeight; y++)
{
if (y >= floor && y <= floor+floorHeight)
{
level.setBlock(x, y, (byte) (1 + 9 * 16));
}
else
{
if ((x == xTube || x == xTube + 1) && y >= tubeHeight)
{
int xPic = 10 + x - xTube;
if (y == tubeHeight)
{
level.setBlock(x, y, (byte) (xPic + 0 * 16));
if (x == xTube)
{
tubesCount++;
}
}
else
{
level.setBlock(x, y, (byte) (xPic + 1 * 16));
}
}
}
}
}
return length;
}
// parameter safe should be set to true iff length of the Straight > 10.
// minimal length = 2
//floorHeight - height of the floor. used for building of the top part of the dead end separator
private int buildStraight(int xo, int maxLength, boolean safe, int vfloor, int floorHeight)
{
int length;
if( floorHeight != INFINITY_FLOOR_HEIGHT )
{
length = maxLength;
}
else
{
length = globalRandom.nextInt(10) + 2;
if (safe) length = 10 + globalRandom.nextInt(5);
if (length > maxLength) length = maxLength;
}
int floor = vfloor;
if( vfloor == DEFAULT_FLOOR)
{
floor = height - 1 - globalRandom.nextInt(4);
}
else
{
globalRandom.nextInt();
}
int y1 = height;
if( floorHeight != INFINITY_FLOOR_HEIGHT )
{
y1 = floor + floorHeight;
}
for (int x = xo; x < xo + length; x++)
{
for (int y = floor; y < y1; y++)
{
if (y >= floor)
{
level.setBlock(x, y, (byte) (1 + 9 * 16));
}
}
}
if (!safe)
{
if (length > 5)
{
decorate(xo, xo + length, floor, false);
}
}
return length;
}
private boolean canBuildBlocks( int x0, int floor, boolean isHB )
{
if ((blocksCount >= cmdArgs[24] && !isHB))
{
return false;
}
boolean res = true;
if( floor < 4 )
{
return false;
}
for (int y = 0; y < 4; y++)
{
if (level.getBlock(x0,floor-y) != 0)
{
res = false;
break;
}
}
return res;
}
private void buildBlocks(int x0, int x1, int floor, boolean pHB, int pS, int pE, boolean onlyHB)
{
if (blocksCount > cmdArgs[24])
{
return;
}
int s = pS; //Start
int e = pE; //End
boolean hb = pHB;
if( onlyHB )
hb = onlyHB;
while(floor - 4 > 0) //minimal distance between the bricks line and floor is 4
{
if ((x1 - 1 - e) - (x0 + 1 + s) > 0) //minimal number of bricks in the line is positive value
{
for (int x = x0 + s; x < x1 - e; x++)
{
if(hb && cmdArgs[27] != 0) //if hidden blocks to be built
{
boolean isBlock = globalRandom.nextInt(2) == 1;
if(isBlock && canBuildBlocks(x, floor-4, true))
{
level.setBlock(x, floor - 4, (byte) (1)); //hidden block
}
}
else
{
boolean canDeco = false; //can add enemy line and coins
//decorate( x0, x1, floor, true );
if (x != x0 + 1 && x != x1 - 2 && globalRandom.nextInt(3) == 0)
{
if (canBuildBlocks(x, floor-4, false))
{
blocksCount++;
if ((globalRandom.nextInt(4) == 0))
{
level.setBlock(x, floor - 4, (byte) (4 + 2 + 1 * 16)); //a rock with animated question symbol with flower. when broken becomes a rock
}
else
{
level.setBlock(x, floor - 4, (byte) (4 + 1 + 1 * 16)); //a brick with animated question symbol. when broken becomes a rock
}
canDeco = true;
}
}
else if (globalRandom.nextInt(4) == 0)
{
if (canBuildBlocks(x, floor-4, false))
{
blocksCount++;
if (globalRandom.nextInt(4) == 0)
{
level.setBlock(x, floor - 4, (byte) (2 + 1 * 16)); //a brick with a flower. when broken becomes a rock
}
else
{
level.setBlock(x, floor - 4, (byte) (1 + 1 * 16)); //a brick with a coin. when broken becomes a rock
}
canDeco = true;
}
}
else if(globalRandom.nextInt(2)==1 && canBuildBlocks(x, floor-4, false))
{
blocksCount++;
level.setBlock(x, floor - 4, (byte) (0 + 1 * 16)); //a break brick
canDeco = true;
}
if (canDeco)
{
if( globalRandom.nextInt(4) == 2 ) addEnemyLine(x0 + 1, x1 - 1, floor - 1);
buildCoins( x0, x1, floor, s, e );
}
}
}
if (onlyHB)
{
hb = true;
}
else
{
hb = globalRandom.nextBoolean();//globalRandom.nextInt(3) == globalRandom.nextInt(3);
}
}
floor -= 4;
s = globalRandom.nextInt(4);
e = globalRandom.nextInt(4);
}
globalRandom.nextBoolean();
}
private void buildCoins( int x0, int x1, int floor, int s, int e )
{
if( floor - 2 < 0 ) return;
if ((x1 - 1 - e) - (x0 + 1 + s) > 1)
{
for (int x = x0 + 1 + s; x < x1 - 1 - e; x++)
{
if (coinsCount >= cmdArgs[25])
{
break;
}
if( level.getBlock( x, floor - 2 ) == 0 ) //if cell (x, floor-2) is empty
{
coinsCount++;
level.setBlock(x, floor - 2, (byte) (2 + 2 * 16)); //coin
}
}
}
}
private boolean canAddEnemyLine( int x0, int x1, int floor )
{
if (cmdArgs[28] == 0x0) //not one bit selected
{
return false;
}
boolean res = true;
for (int x = x0; x < x1; x++)
{
for (int y = floor; y > floor-2; y
{
if (level.getBlock(x, y) != 0)
{
res = false;
break;
}
}
}
return res;
}
private void decorate(int x0, int x1, int floor, boolean recurs)
{
if (floor < 1) return;
int s = globalRandom.nextInt(4);
int e = globalRandom.nextInt(4);
boolean hb = ((globalRandom.nextInt(levelDifficulty+1) % (levelDifficulty + 1))) > 0.5;
if (!hb)
{
addEnemyLine(x0 + 1, x1 - 1, floor - 1);
}
if (floor - 2 > 0 && !hb )
{
buildCoins( x0, x1, floor, s, e );
}
if (!recurs) buildBlocks( x0, x1, floor, hb, s, e, false);
int length = x1 - x0 - 2;
if (length > 2)
{
//decorate(x0, x1, floor - 4);
globalRandom.nextInt();
}
}
private void fixWalls()
{
boolean[][] blockMap = new boolean[width + 1][height + 1];
for (int x = 0; x < width + 1; x++)
{
for (int y = 0; y < height + 1; y++)
{
int blocks = 0;
for (int xx = x - 1; xx < x + 1; xx++)
{
for (int yy = y - 1; yy < y + 1; yy++)
{
if (level.getBlockCapped(xx, yy) == (byte) (1 + 9 * 16)) blocks++;
}
}
blockMap[x][y] = blocks == 4;
}
}
blockify(level, blockMap, width + 1, height + 1);
}
private void blockify(Level level, boolean[][] blocks, int width, int height)
{
int to = 0;
if (type == LevelGenerator.TYPE_CASTLE)
{
to = 4 * 2;
}
else if (type == LevelGenerator.TYPE_UNDERGROUND)
{
to = 4 * 3;
}
boolean[][] b = new boolean[2][2];
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
for (int xx = x; xx <= x + 1; xx++)
{
for (int yy = y; yy <= y + 1; yy++)
{
int _xx = xx;
int _yy = yy;
if (_xx < 0) _xx = 0;
if (_yy < 0) _yy = 0;
if (_xx > width - 1) _xx = width - 1;
if (_yy > height - 1) _yy = height - 1;
b[xx - x][yy - y] = blocks[_xx][_yy];
}
}
if (b[0][0] == b[1][0] && b[0][1] == b[1][1])
{
if (b[0][0] == b[0][1])
{
if (b[0][0])
{
level.setBlock(x, y, (byte) (1 + 9 * 16 + to));
}
else
{
// KEEP OLD BLOCK!
}
}
else
{
if (b[0][0])
{
level.setBlock(x, y, (byte) (1 + 10 * 16 + to));
}
else
{
level.setBlock(x, y, (byte) (1 + 8 * 16 + to));
}
}
}
else if (b[0][0] == b[0][1] && b[1][0] == b[1][1])
{
if (b[0][0])
{
level.setBlock(x, y, (byte) (2 + 9 * 16 + to));
}
else
{
level.setBlock(x, y, (byte) (0 + 9 * 16 + to));
}
}
else if (b[0][0] == b[1][1] && b[0][1] == b[1][0])
{
level.setBlock(x, y, (byte) (1 + 9 * 16 + to));
}
else if (b[0][0] == b[1][0])
{
if (b[0][0])
{
if (b[0][1])
{
level.setBlock(x, y, (byte) (3 + 10 * 16 + to));
}
else
{
level.setBlock(x, y, (byte) (3 + 11 * 16 + to));
}
}
else
{
if (b[0][1])
{
level.setBlock(x, y, (byte) (2 + 8 * 16 + to));
}
else
{
level.setBlock(x, y, (byte) (0 + 8 * 16 + to));
}
}
}
else if (b[0][1] == b[1][1])
{
if (b[0][1])
{
if (b[0][0])
{
level.setBlock(x, y, (byte) (3 + 9 * 16 + to));
}
else
{
level.setBlock(x, y, (byte) (3 + 8 * 16 + to));
}
}
else
{
if (b[0][0])
{
level.setBlock(x, y, (byte) (2 + 10 * 16 + to));
}
else
{
level.setBlock(x, y, (byte) (0 + 10 * 16 + to));
}
}
}
else
{
level.setBlock(x, y, (byte) (0 + 1 * 16 + to));
}
}
}
}
} |
package com.gentics.cailun.core.data.model;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
import org.neo4j.graphdb.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import com.gentics.cailun.core.data.model.auth.Group;
import com.gentics.cailun.core.data.model.auth.User;
import com.gentics.cailun.core.repository.GroupRepository;
import com.gentics.cailun.test.AbstractDBTest;
public class GroupTest extends AbstractDBTest {
@Autowired
GroupRepository groupRepository;
@Before
public void setup() throws Exception {
setupData();
}
@Test
public void testUserGroup() {
User user = new User("testuser");
Group group = new Group("test group");
try (Transaction tx = graphDb.beginTx()) {
group.addUser(user);
group = groupRepository.save(group);
tx.success();
}
group = groupService.reload(group);
assertEquals("The group should contain one member.", 1, group.getUsers().size());
try (Transaction tx = graphDb.beginTx()) {
User userOfGroup = group.getUsers().iterator().next();
neo4jTemplate.fetch(userOfGroup);
assertEquals("Username did not match the expected one.", user.getUsername(), userOfGroup.getUsername());
tx.success();
}
}
@Test
public void testRootGroupNode() {
int nGroupsBefore = groupRepository.findRoot().getGroups().size();
Group group = new Group("test group2");
try (Transaction tx = graphDb.beginTx()) {
groupRepository.save(group);
tx.success();
}
int nGroupsAfter = groupRepository.findRoot().getGroups().size();
assertEquals(nGroupsBefore + 1, nGroupsAfter);
}
} |
package codeOrchestra.colt.core.ui;
import codeOrchestra.colt.core.COLTException;
import codeOrchestra.colt.core.COLTProjectManager;
import codeOrchestra.colt.core.RecentProjects;
import codeOrchestra.colt.core.errorhandling.ErrorHandler;
import codeOrchestra.colt.core.http.CodeOrchestraRPCHttpServer;
import codeOrchestra.colt.core.http.CodeOrchestraResourcesHttpServer;
import codeOrchestra.colt.core.license.*;
import codeOrchestra.colt.core.loading.LiveCodingHandlerManager;
import codeOrchestra.colt.core.model.COLTProject;
import codeOrchestra.colt.core.model.listener.ProjectListener;
import codeOrchestra.colt.core.model.monitor.ChangingMonitor;
import codeOrchestra.colt.core.rpc.COLTRemoteServiceServlet;
import codeOrchestra.colt.core.tracker.GAController;
import codeOrchestra.colt.core.ui.dialog.COLTDialogs;
import codeOrchestra.lcs.license.COLTRunningKey;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.geometry.Rectangle2D;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SeparatorMenuItem;
import javafx.scene.effect.DropShadow;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Priority;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Screen;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.util.Duration;
import org.controlsfx.control.action.Action;
import org.controlsfx.dialog.Dialog;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* @author Alexander Eliseyev
*/
public class COLTApplication extends Application {
private static COLTApplication instance;
private static final int SPLASH_WIDTH = 480;
private static final int SPLASH_HEIGHT = 320;
private Timeline timeline;
private Menu recentProjectsSubMenu;
public static COLTApplication get() {
return instance;
}
private StackPane splashLayout;
private Stage mainStage;
private VBox root;
private Node currentPluginNode;
private Stage primaryStage;
public static long timeStarted;
public ArrayList<MenuItem> menuItems = new ArrayList<>();
@Override
public void start(Stage primaryStage) throws Exception {
instance = this;
this.primaryStage = primaryStage;
GAController.getInstance().start(primaryStage);
initSplash();
initMainStage();
showSplash();
timeline = new Timeline(new KeyFrame(new Duration(1000), actionEvent -> {
timeline.stop();
Platform.runLater(this::doAfterUIInit);
}));
timeline.play();
}
private void showSplash() {
Scene splashScene = new Scene(splashLayout);
primaryStage.initStyle(StageStyle.UNDECORATED);
final Rectangle2D bounds = Screen.getPrimary().getBounds();
primaryStage.setScene(splashScene);
primaryStage.setX(bounds.getMinX() + bounds.getWidth() / 2 - SPLASH_WIDTH / 2);
primaryStage.setY(bounds.getMinY() + bounds.getHeight() / 2 - SPLASH_HEIGHT / 2);
primaryStage.show();
}
private void initSplash() {
splashLayout = new StackPane();
String imagePath = getClass().getResource("splash.png").toString();
Image image = new Image(imagePath);
splashLayout.getChildren().add(new ImageView(image));
splashLayout.setEffect(new DropShadow());
}
private void initMainStage() {
mainStage = new Stage(StageStyle.DECORATED);
mainStage.setOnCloseRequest(windowEvent -> {
if (ChangingMonitor.getInstance().isChanged()) {
Action action = COLTDialogs.showCloseProjectDialog(primaryStage);
if (action == Dialog.Actions.CANCEL) {
windowEvent.consume();
} else if (action == Dialog.Actions.YES) {
try {
COLTProjectManager.getInstance().save();
} catch (COLTException e) {
ErrorHandler.handle(e, "Can't save project");
}
}
}
if (!windowEvent.isConsumed()) {
dispose();
}
});
root = new VBox();
root.setFillWidth(true);
root.setMaxHeight(Double.MAX_VALUE);
mainStage.setTitle("COLT 1.2");
mainStage.setScene(new Scene(root, 800, 700));
Menu fileMenu = new Menu("File");
MenuItem openProjectMenuItem = new MenuItem("Open Project");
openProjectMenuItem.setOnAction(t -> {
FileChooser fileChooser = new FileChooser();
fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("COLT", "*.colt"));
File file = fileChooser.showOpenDialog(primaryStage.getScene().getWindow());
if (file != null) {
try {
COLTProjectManager.getInstance().load(file.getPath());
ChangingMonitor.getInstance().reset();
} catch (COLTException e) {
ErrorHandler.handle(e, "Can't load the project");
}
}
});
MenuItem saveProjectMenuItem = new MenuItem("Save Project");
saveProjectMenuItem.setOnAction(t -> {
try {
COLTProjectManager.getInstance().save();
} catch (COLTException e) {
ErrorHandler.handle(e, "Can't save the project");
}
});
saveProjectMenuItem.setDisable(true);
COLTProjectManager.getInstance().addProjectListener(new ProjectListener() {
@Override
public void onProjectLoaded(COLTProject project) {
saveProjectMenuItem.setDisable(false);
}
@Override
public void onProjectUnloaded(COLTProject project) {
saveProjectMenuItem.setDisable(true);
}
});
MenuItem newProjectMenuItem = new MenuItem("New Project");
newProjectMenuItem.setOnAction(t -> {
String projectName = COLTDialogs.showCreateProjectDialog(primaryStage);
if (projectName != null) {
FileChooser fileChooser = new FileChooser();
fileChooser.setInitialFileName(projectName);
fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("COLT", "*.colt"));
File file = fileChooser.showSaveDialog(primaryStage);
if (file != null) {
try {
// TODO: a handler must be defined by the user (AS, JS, etc)
COLTProjectManager.getInstance().create("AS", projectName, file);
ChangingMonitor.getInstance().reset();
} catch (COLTException e) {
ErrorHandler.handle(e, "Can't create a new project");
}
}
}
});
MenuItem exitMenuItem = new MenuItem("Exit");
exitMenuItem.setOnAction(t -> {
System.exit(0);
});
recentProjectsSubMenu = new Menu("Open Recent");
refreshRecentProjectsMenu();
COLTProjectManager.getInstance().addProjectListener(new ProjectListener() {
@Override
public void onProjectLoaded(COLTProject project) {
refreshRecentProjectsMenu();
}
@Override
public void onProjectUnloaded(COLTProject project) {
}
});
menuItems.add(newProjectMenuItem);
menuItems.add(openProjectMenuItem);
menuItems.add(saveProjectMenuItem);
fileMenu.getItems().addAll(newProjectMenuItem, new SeparatorMenuItem(), openProjectMenuItem, recentProjectsSubMenu, saveProjectMenuItem, new SeparatorMenuItem(), exitMenuItem);
Menu helpMenu = new Menu("Help");
final MenuItem enterSerialItem = new MenuItem("Enter Serial Number");
enterSerialItem.setOnAction(t -> {
ExpirationHelper.getExpirationStrategy().showSerialNumberDialog();
});
enterSerialItem.setDisable(ExpirationHelper.getExpirationStrategy().isTrialOnly() || !CodeOrchestraLicenseManager.noSerialNumberPresent());
CodeOrchestraLicenseManager.addListener(() -> {
enterSerialItem.setDisable(false);
});
helpMenu.getItems().add(enterSerialItem);
MenuBar menuBar = new MenuBar();
menuBar.getMenus().add(fileMenu);
menuBar.getMenus().add(helpMenu);
menuBar.setUseSystemMenuBar(true);
root.getChildren().add(menuBar);
}
private void refreshRecentProjectsMenu() {
recentProjectsSubMenu.getItems().removeAll();
List<String> recentProjectsPaths = RecentProjects.getRecentProjectsPaths();
if (recentProjectsPaths.isEmpty()) {
recentProjectsSubMenu.setDisable(true);
return;
}
recentProjectsSubMenu.setDisable(false);
for (String recentProjectsPath : recentProjectsPaths) {
MenuItem openRecentProjectItem = new MenuItem(recentProjectsPath);
final File projectFile = new File(recentProjectsPath);
if (!projectFile.exists() || projectFile.isDirectory()) {
continue;
}
openRecentProjectItem.setOnAction(actionEvent -> {
try {
COLTProjectManager.getInstance().load(projectFile.getPath());
ChangingMonitor.getInstance().reset();
} catch (COLTException e) {
ErrorHandler.handle(e, "Can't load a project " + recentProjectsPath);
}
});
recentProjectsSubMenu.getItems().add(openRecentProjectItem);
}
}
private void dispose() {
COLTRunningKey.setRunning(false);
LiveCodingHandlerManager.getInstance().dispose();
CodeOrchestraResourcesHttpServer.getInstance().dispose();
CodeOrchestraRPCHttpServer.getInstance().dispose();
Platform.exit();
}
private void doAfterUIInit() {
// COLT-287
System.setProperty ("jsse.enableSNIExtension", "false");
StartupInterceptType startupInterceptType = StartupInterceptor.getInstance().interceptStart();
if (startupInterceptType != StartupInterceptType.START) {
System.exit(1);
}
COLTRunningKey.setRunning(true);
CodeOrchestraResourcesHttpServer.getInstance().init();
CodeOrchestraRPCHttpServer.getInstance().init();
CodeOrchestraRPCHttpServer.getInstance().addServlet(COLTRemoteServiceServlet.getInstance(), "/coltService");
primaryStage.hide();
primaryStage = mainStage;
GAController.getInstance().start(primaryStage);
primaryStage.show();
// Open most recent project
for (String recentProjectPath : RecentProjects.getRecentProjectsPaths()) {
File projectFile = new File(recentProjectPath);
if (projectFile.exists()) {
try {
COLTProjectManager.getInstance().load(projectFile.getPath());
ChangingMonitor.getInstance().reset();
break;
} catch (COLTException e) {
// ignore
}
}
}
}
public Stage getPrimaryStage() {
return primaryStage;
}
public void setPluginPane(Node node) {
if (currentPluginNode != null) {
root.getChildren().remove(currentPluginNode);
}
currentPluginNode = node;
VBox.setVgrow(currentPluginNode, Priority.ALWAYS);
root.getChildren().add(node);
}
public static void main(String[] args) {
timeStarted = System.currentTimeMillis();
launch(args);
}
} |
package com.afollestad.silk.cache;
import android.os.Handler;
import com.afollestad.silk.adapters.SilkAdapter;
import com.afollestad.silk.fragments.SilkCachedFeedFragment;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Handles caching feeds locally.
*
* @author Aidan Follestad (afollestad)
*/
public final class SilkCacheManager<T extends SilkComparable> extends SilkCacheManagerBase<T> {
public interface RemoveFilter<T> {
public boolean shouldRemove(T item);
}
public interface FindCallback<T> {
public void onFound(T item);
public void onNothing();
public void onError(Exception e);
}
public interface CommitCallback extends SimpleCommitCallback {
public void onCommitted(boolean returnValue);
}
public interface SimpleCommitCallback {
public void onError(Exception e);
}
/**
* Initializes a new SilkCacheManager, using the default cache file and default cache directory.
*/
public SilkCacheManager() throws Exception {
super(null, null);
}
/**
* Initializes a new SilkCacheManager, using the default cache directory.
*
* @param cacheName The name of the cache, must be unique from other feed caches, but must also be valid for being in a file name.
*/
public SilkCacheManager(String cacheName) {
super(cacheName, null);
}
/**
* Initializes a new SilkCacheManager.
*
* @param cacheName The name of the cache, must be unique from other feed caches, but must also be valid for being in a file name.
* @param cacheDir The directory that the cache file will be stored in, defaults to a folder called "Silk" in your external storage directory.
*/
public SilkCacheManager(String cacheName, File cacheDir) {
super(cacheName, cacheDir);
}
/**
* Sets the handler used when making callbacks from separate threads. This should be used if you didn't
* instantiate the cache manager from the UI thread.
*/
public SilkCacheManager<T> setHandler(Handler handler) {
super.mHandler = handler;
return this;
}
/**
* Forces the cache manager to reload its buffer from the cache file.
*/
public SilkCacheManager<T> forceReload() {
super.buffer = null;
reloadIfNeeded();
return this;
}
/**
* Appends a single item to the cache.
*/
public SilkCacheManager<T> append(T toAdd) {
if (toAdd == null || toAdd.shouldIgnore()) {
log("Item passed to append() was null or marked for ignoring.");
return this;
}
reloadIfNeeded();
super.buffer.add(toAdd);
log("Appended 1 item to the cache.");
return this;
}
/**
* Appends a collection of items to the cache.
*/
public SilkCacheManager<T> append(List<T> toAppend) {
if (toAppend == null || toAppend.size() == 0) {
log("List passed to append() was null or empty.");
return this;
}
reloadIfNeeded();
int count = 0;
for (T item : toAppend) {
if (item.shouldIgnore()) continue;
super.buffer.add(item);
count++;
}
log("Appended " + count + " items to the cache.");
return this;
}
/**
* Appends an array of items to the cache.
*/
public SilkCacheManager<T> append(T[] toAppend) {
if (toAppend == null || toAppend.length == 0) {
log("Array passed to append() was null or empty.");
return this;
}
append(new ArrayList<T>(Arrays.asList(toAppend)));
return this;
}
/**
* Appends the contents of a {@link SilkAdapter} to the cache, and resets the adapter's changed state to unchanged.
* If the adapter is marked as unchanged already, its contents will not be written.
*/
public SilkCacheManager<T> append(SilkAdapter<T> adapter) {
if (adapter == null || adapter.getCount() == 0) {
log("Adapter passed to append() was null.");
return this;
}
if (!adapter.isChanged()) {
log("The adapter has not been changed, skipped writing to " + super.getCacheFile().getName());
return this;
}
adapter.resetChanged();
append(adapter.getItems());
return this;
}
/**
* Updates an item in the cache, using isSameAs() from SilkComparable to find the item.
*
* @param appendIfNotFound Whether or not the item will be appended to the end of the cache if it's not found.
*/
public SilkCacheManager<T> update(T toUpdate, boolean appendIfNotFound) {
if (toUpdate == null || toUpdate.shouldIgnore()) {
log("Item passed to update() was null or marked for ignoring.");
return this;
}
reloadIfNeeded();
if (super.buffer.size() == 0) {
log("Cache buffer is empty.");
return this;
}
boolean found = false;
for (int i = 0; i < buffer.size(); i++) {
if (buffer.get(i).isSameAs(toUpdate)) {
buffer.set(i, toUpdate);
found = true;
break;
}
}
if (found) {
log("Updated 1 item in the cache.");
} else if (appendIfNotFound) {
append(toUpdate);
}
return this;
}
/**
* Overwrites all items in the cache with a set of items from an array.
* <p/>
* This is equivalent to calling clear() and then append().
*/
public SilkCacheManager<T> set(T[] toSet) {
set(new ArrayList<T>(Arrays.asList(toSet)));
return this;
}
/**
* Overwrites all items in the cache with a set of items from a collection.
* <p/>
* This is equivalent to calling clear() and then append().
*/
public SilkCacheManager<T> set(List<T> toSet) {
clear();
append(toSet);
return this;
}
/**
* Overwrites all items in the cache with a set of items from a collection.
* <p/>
* This is equivalent to calling clear() and then append().
*/
public SilkCacheManager<T> set(SilkAdapter<T> adapter) {
clear();
append(adapter);
return this;
}
/**
* Removes a single item from the cache, uses isSameAs() from the {@link SilkComparable} to find the item.
*/
public SilkCacheManager<T> remove(final T toRemove) throws Exception {
if (toRemove == null) {
log("Item passed to remove() was null.");
return this;
}
remove(new RemoveFilter<T>() {
@Override
public boolean shouldRemove(T item) {
return item.isSameAs(toRemove);
}
}, true);
return this;
}
/**
* Removes items from the cache based on a filter that makes decisions. Returns a list of items that were removed.
*
* @param removeOne If true, it will remove one and stop searching, which can improve performance. Otherwise it'll search through the entire cache and remove multiple entries that match the filter.
*/
public SilkCacheManager<T> remove(RemoveFilter<T> filter, boolean removeOne) throws Exception {
if (filter == null) throw new IllegalArgumentException("You must specify a RemoveFilter.");
reloadIfNeeded();
if (super.buffer.size() == 0) {
log("Cache buffer is empty.");
return this;
}
ArrayList<Integer> removeIndexes = new ArrayList<Integer>();
for (int i = 0; i < super.buffer.size(); i++) {
if (filter.shouldRemove(super.buffer.get(i))) {
removeIndexes.add(i);
if (removeOne) break;
}
}
for (Integer i : removeIndexes)
super.buffer.remove(i.intValue());
log("Removed " + removeIndexes.size() + " items from " + super.getCacheFile().getName());
return this;
}
/**
* Finds an item in the cache using isSameAs() from SilkComparable.
*
* @param query An item that will match up with another item using SilkComparable.isSameAs().
*/
public T find(T query) throws Exception {
if (query == null) {
log("Item passed to find() was null.");
return null;
}
reloadIfNeeded();
log("Searching " + super.buffer.size() + " items...");
if (super.buffer.size() == 0) {
log("Cache buffer is empty.");
return null;
}
for (int i = 0; i < super.buffer.size(); i++) {
T currentItem = super.buffer.get(i);
if (currentItem.isSameAs(query))
return currentItem;
}
return null;
}
/**
* Clears all items from the cahce.
*/
public SilkCacheManager clear() {
log("Cache was cleared.");
super.buffer.clear();
return this;
}
/**
* Gets the total number of items in the cache.
*/
public int size() throws Exception {
return super.buffer.size();
}
/**
* Reads from the manager's cache file into a {@link SilkAdapter}, and notifies a {@link SilkCachedFeedFragment} when it's loading and done loading.
*
* @param adapter The adapter that items will be added to.
* @param fragment The optional fragment that will receive loading notifications.
*/
public void readAsync(final SilkAdapter<T> adapter, final SilkCachedFeedFragment fragment) {
if (adapter == null) throw new IllegalArgumentException("The adapter parameter cannot be null.");
else if (fragment != null && fragment.isLoading()) return;
if (fragment != null) fragment.setLoading(false);
runPriorityThread(new Runnable() {
@Override
public void run() {
try {
reloadIfNeeded();
if (buffer.isEmpty()) {
runOnUiThread(new Runnable() {
@Override
public void run() {
adapter.clear();
if (fragment != null) {
fragment.setLoadFromCacheComplete(false);
fragment.onCacheEmpty();
}
adapter.resetChanged();
}
});
return;
}
runOnUiThread(new Runnable() {
@Override
public void run() {
adapter.set(buffer);
if (fragment != null) fragment.setLoadFromCacheComplete(false);
adapter.resetChanged();
}
});
} catch (RuntimeException e) {
e.printStackTrace();
runOnUiThread(new Runnable() {
@Override
public void run() {
if (fragment != null) {
fragment.setLoadFromCacheComplete(true);
if (adapter.getCount() == 0) fragment.onCacheEmpty();
}
adapter.resetChanged();
}
});
}
}
});
}
/**
* Finds an item in the cache using isSameAs() from SilkComparable on a separate thread, and posts
* results to a callback.
*
* @param query An item that will match up with another item via isSameAs().
*/
public void findAsync(final T query, final FindCallback<T> callback) {
if (callback == null) throw new IllegalArgumentException("You must specify a callback");
runPriorityThread(new Runnable() {
@Override
public void run() {
try {
final T result = find(query);
mHandler.post(new Runnable() {
@Override
public void run() {
if (result == null) callback.onNothing();
else callback.onFound(result);
}
});
} catch (final Exception e) {
e.printStackTrace();
log("Cache find error: " + e.getMessage());
mHandler.post(new Runnable() {
@Override
public void run() {
callback.onError(e);
}
});
}
}
});
}
} |
package com.cardshifter.gdx;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Net;
import com.badlogic.gdx.net.Socket;
import com.badlogic.gdx.net.SocketHints;
import com.cardshifter.api.messages.Message;
import com.cardshifter.api.serial.ByteTransformer;
import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.LogManager;
import org.apache.log4j.spi.LoggingEvent;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class CardshifterClient implements Runnable {
private final Socket socket;
private final OutputStream output;
private final InputStream input;
private final ByteTransformer transformer;
private final CardshifterMessageHandler handler;
public CardshifterClient(String host, int port, CardshifterMessageHandler handler) {
socket = Gdx.net.newClientSocket(Net.Protocol.TCP, host, port, new SocketHints());
output = socket.getOutputStream();
input = socket.getInputStream();
transformer = new ByteTransformer();
this.handler = handler;
try {
output.write("{ \"command\": \"serial\", \"type\": \"1\" }".getBytes());
output.flush();
Gdx.app.log("Client", "Sent serial type");
LogManager.getRootLogger().addAppender(new AppenderSkeleton() {
@Override
protected void append(LoggingEvent event) {
Gdx.app.log(event.getLoggerName(), String.valueOf(event.getMessage()));
}
@Override
public void close() {
}
@Override
public boolean requiresLayout() {
return false;
}
});
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
new Thread(this).start();
}
@Override
public void run() {
try {
DataInputStream dataIn = new DataInputStream(input);
while (true) {
Gdx.app.log("Client", "listening for input");
byte[] bytes = new byte[1024];
try {
int read = dataIn.readInt();
dataIn.read(bytes, 0, read);
Message message = transformer.readOnce(input);
handler.handle(message);
} catch (Exception e) {
e.printStackTrace();
break;
}
}
}
catch (Exception ex) {
ex.printStackTrace();
}
Gdx.app.log("Client", "Stopped listening");
}
public void send(Message message) {
try {
transformer.send(message, output);
Gdx.app.log("Outgoing", message.toString());
output.flush();
} catch (Throwable e) {
Gdx.app.log("Outgoing", "Error " + e);
e.printStackTrace();
}
}
} |
package org.treetank.access;
import static com.google.common.base.Objects.toStringHelper;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static org.treetank.access.PageReadTrx.nodePageOffset;
import java.io.File;
import java.util.Iterator;
import java.util.Map;
import org.treetank.access.conf.ContructorProps;
import org.treetank.api.IMetaEntry;
import org.treetank.api.INode;
import org.treetank.api.IPageWriteTrx;
import org.treetank.api.ISession;
import org.treetank.cache.BerkeleyPersistenceLog;
import org.treetank.cache.LRUCache;
import org.treetank.cache.LogKey;
import org.treetank.cache.NodePageContainer;
import org.treetank.exception.TTException;
import org.treetank.exception.TTIOException;
import org.treetank.io.IBackendWriter;
import org.treetank.page.IConstants;
import org.treetank.page.IndirectPage;
import org.treetank.page.MetaPage;
import org.treetank.page.NodePage;
import org.treetank.page.NodePage.DeletedNode;
import org.treetank.page.RevisionRootPage;
import org.treetank.page.UberPage;
import org.treetank.page.interfaces.IReferencePage;
/**
* <h1>PageWriteTrx</h1>
*
* <p>
* See {@link PageReadTrx}.
* </p>
*/
public final class PageWriteTrx implements IPageWriteTrx {
/** Page writer to serialize. */
private final IBackendWriter mPageWriter;
/** Cache to store the changes in this writetransaction. */
private final LRUCache mLog;
/** Reference to the actual uberPage. */
private UberPage mNewUber;
/** Reference to the actual revRoot. */
private RevisionRootPage mNewRoot;
/** Last reference to the actual namePage. */
private MetaPage mNewName;
/** Delegate for read access. */
private PageReadTrx mDelegate;
/**
* Standard constructor.
*
*
* @param pSession
* {@link ISession} reference
* @param pUberPage
* root of resource
* @param pWriter
* writer where this transaction should write to
* @param pRepresentRev
* revision represent
* @param pStoreRev
* revision store
* @throws TTIOException
* if IO Error
*/
protected PageWriteTrx(final ISession pSession, final UberPage pUberPage, final IBackendWriter pWriter,
final long pRepresentRev) throws TTException {
mPageWriter = pWriter;
mLog =
new LRUCache(new BerkeleyPersistenceLog(new File(pSession.getConfig().mProperties
.getProperty(org.treetank.access.conf.ContructorProps.STORAGEPATH)),
pSession.getConfig().mNodeFac, pSession.getConfig().mMetaFac));
setUpTransaction(pUberPage, pSession, pRepresentRev, pWriter);
}
/**
* Prepare a node for modification. This is getting the node from the
* (persistence) layer, storing the page in the cache and setting up the
* node for upcoming modification. Note that this only occurs for {@link INode}s.
*
* @param pNodeKey
* key of the node to be modified
* @return an {@link INode} instance
* @throws TTIOException
* if IO Error
*/
public INode prepareNodeForModification(final long pNodeKey) throws TTException {
checkArgument(pNodeKey >= 0);
final long seqNodePageKey = pNodeKey >> IConstants.INP_LEVEL_PAGE_COUNT_EXPONENT[3];
final int nodePageOffset = nodePageOffset(pNodeKey);
final int lastIndirectOffset = (int)pNodeKey >> IConstants.INP_LEVEL_PAGE_COUNT_EXPONENT[2];
NodePageContainer container = prepareNodePage(lastIndirectOffset, seqNodePageKey);
INode node = ((NodePage)container.getModified()).getNode(nodePageOffset);
if (node == null) {
final INode oldNode = ((NodePage)container.getComplete()).getNode(nodePageOffset);
checkNotNull(oldNode);
node = oldNode;
((NodePage)container.getModified()).setNode(nodePageOffset, node);
}
return node;
}
/**
* Finishing the node modification. That is storing the node including the
* page in the cache.
*
* @param pNode
* the node to be modified
* @throws TTIOException
*/
public void finishNodeModification(final INode pNode) throws TTIOException {
final long seqNodePageKey = pNode.getNodeKey() >> IConstants.INP_LEVEL_PAGE_COUNT_EXPONENT[3];
final int nodePageOffset = nodePageOffset(pNode.getNodeKey());
LogKey key = new LogKey(false, IConstants.INP_LEVEL_PAGE_COUNT_EXPONENT.length, seqNodePageKey);
NodePageContainer container = mLog.get(key);
NodePage page = (NodePage)container.getModified();
page.setNode(nodePageOffset, pNode);
mLog.put(key, container);
}
/**
* {@inheritDoc}
*/
public long setNode(final INode pNode) throws TTException {
// Allocate node key and increment node count.
final long nodeKey = pNode.getNodeKey();
final long seqPageKey = nodeKey >> IConstants.INP_LEVEL_PAGE_COUNT_EXPONENT[3];
final int nodePageOffset = nodePageOffset(nodeKey);
final int lastIndirectOffset = (int)(nodeKey >> IConstants.INP_LEVEL_PAGE_COUNT_EXPONENT[2]);
NodePageContainer container = prepareNodePage(lastIndirectOffset, seqPageKey);
final NodePage page = ((NodePage)container.getModified());
page.setNode(nodePageOffset, pNode);
mLog.put(new LogKey(false, IConstants.INP_LEVEL_PAGE_COUNT_EXPONENT.length, seqPageKey), container);
return nodeKey;
}
/**
* Removing a node from the storage.
*
* @param pNode
* {@link INode} to be removed
* @throws TTIOException
* if the removal fails
*/
public void removeNode(final INode pNode) throws TTException {
assert pNode != null;
final long nodePageKey = pNode.getNodeKey() >> IConstants.INP_LEVEL_PAGE_COUNT_EXPONENT[3];
final int lastIndirectOffset = (int)nodePageKey >> IConstants.INP_LEVEL_PAGE_COUNT_EXPONENT[2];
NodePageContainer container = prepareNodePage(lastIndirectOffset, nodePageKey);
final INode delNode = new DeletedNode(pNode.getNodeKey());
((NodePage)container.getComplete()).setNode(nodePageOffset(pNode.getNodeKey()), delNode);
((NodePage)container.getModified()).setNode(nodePageOffset(pNode.getNodeKey()), delNode);
mLog.put(new LogKey(false, IConstants.INP_LEVEL_PAGE_COUNT_EXPONENT.length, nodePageKey), container);
}
/**
* {@inheritDoc}
*/
public INode getNode(final long pNodeKey) throws TTIOException {
// Calculate page and node part for given nodeKey.
final long nodePageKey = pNodeKey >> IConstants.INP_LEVEL_PAGE_COUNT_EXPONENT[3];
final int nodePageOffset = nodePageOffset(pNodeKey);
final NodePageContainer container =
mLog.get(new LogKey(false, IConstants.INP_LEVEL_PAGE_COUNT_EXPONENT.length, nodePageKey));
// Page was not modified yet, delegate to read or..
if (container == null) {
return mDelegate.getNode(pNodeKey);
}// ...page was modified, but not this node, take the complete part, or...
else if (((NodePage)container.getModified()).getNode(nodePageOffset) == null) {
final INode item = ((NodePage)container.getComplete()).getNode(nodePageOffset);
return mDelegate.checkItemIfDeleted(item);
}// ...page was modified and the modification touched this node.
else {
final INode item = ((NodePage)container.getModified()).getNode(nodePageOffset);
return mDelegate.checkItemIfDeleted(item);
}
}
/**
* Creating a namekey for a given name.
*
* @param pName
* for which the key should be created.
* @return an int, representing the namekey
* @throws TTIOException
* if something odd happens while storing the new key
*/
public void createEntry(final IMetaEntry key, IMetaEntry value) throws TTIOException {
mNewName.setEntry(key, value);
}
public void commit() throws TTException {
Iterator<Map.Entry<LogKey, NodePageContainer>> entries = mLog.getIterator();
while (entries.hasNext()) {
Map.Entry<LogKey, NodePageContainer> next = entries.next();
mPageWriter.write(next.getValue().getModified());
}
mPageWriter.write(mNewName);
mPageWriter.write(mNewRoot);
mPageWriter.writeUberPage(mNewUber);
mLog.clear();
((Session)mDelegate.mSession).setLastCommittedUberPage(mNewUber);
setUpTransaction(mNewUber, mDelegate.mSession, mNewUber.getRevisionNumber(), mPageWriter);
}
/**
* {@inheritDoc}
*
* @throws TTIOException
* if something weird happened in the storage
*/
public boolean close() throws TTIOException {
if (!mDelegate.isClosed()) {
mDelegate.close();
mLog.clear();
mDelegate.mSession.deregisterPageTrx(this);
// mPageWriter.close();
return true;
} else {
return false;
}
}
public long incrementNodeKey() {
return mNewRoot.incrementMaxNodeKey();
}
private NodePageContainer prepareNodePage(final int pIndirectOffset, final long pSeqPageKey)
throws TTException {
LogKey key = new LogKey(false, IConstants.INP_LEVEL_PAGE_COUNT_EXPONENT.length, pSeqPageKey);
// See if on nodePageLevel, there are any pages...
NodePageContainer container = mLog.get(key);
// ... and start dereferencing of not.
if (container == null) {
LogKey indirectKey = preparePathToLeaf(false, mNewRoot, pIndirectOffset);
NodePageContainer indirectContainer = mLog.get(indirectKey);
int nodeOffset = nodePageOffset(pSeqPageKey);
long pageKey = ((IndirectPage)indirectContainer.getModified()).getReferenceKeys()[nodeOffset];
long newPageKey = mNewUber.incrementPageCounter();
if (pageKey != 0) {
NodePage[] pages = mDelegate.getSnapshotPages(pSeqPageKey);
checkState(pages.length > 0);
if (mNewRoot.getRevision()
% Integer.parseInt(mDelegate.mSession.getConfig().mProperties
.getProperty(ContructorProps.NUMBERTORESTORE)) == 0) {
container =
mDelegate.mSession.getConfig().mRevision.combinePagesForModification(newPageKey,
pages, true);
} else {
container =
mDelegate.mSession.getConfig().mRevision.combinePagesForModification(newPageKey,
pages, false);
}
} else {
NodePage newPage = new NodePage(newPageKey);
container = new NodePageContainer(newPage, newPage);
}
((IndirectPage)indirectContainer.getModified()).setReferenceKey(nodeOffset, newPageKey);
mLog.put(indirectKey, indirectContainer);
mLog.put(key, container);
}
return container;
}
/**
* Getting a NodePageContainer containing the last IndirectPage with the reference to any new/modified
* page.
*
* @param pIsRootLevel
* is this dereferencing walk based on the the search after a RevRoot or a NodePage. Needed
* because of the same keys in both subtrees.
* @param pPage
* where to start the tree-walk: either from an UberPage (related to new
* RevisionRootPages) or from a RevisionRootPage (related to new NodePages).
* @param pSeqPageKey
* the key of the page mapped to the layer
* @return the key the container representing the last level
* @throws TTException
*/
private LogKey preparePathToLeaf(final boolean pIsRootLevel, final IReferencePage pPage,
final long pSeqPageKey) throws TTException {
// Initial state pointing to the indirect page of level 0.
int offset = -1;
int parentOffset = IReferencePage.GUARANTEED_INDIRECT_OFFSET;
long levelKey = pSeqPageKey;
IReferencePage page = null;
IReferencePage parentPage = pPage;
LogKey key = null;
LogKey parentKey = new LogKey(pIsRootLevel, -1, 0);
// Iterate through all levels.
for (int level = 0; level < IConstants.INP_LEVEL_PAGE_COUNT_EXPONENT.length; level++) {
offset = (int)(levelKey >> IConstants.INP_LEVEL_PAGE_COUNT_EXPONENT[level]);
levelKey -= offset << IConstants.INP_LEVEL_PAGE_COUNT_EXPONENT[level];
// for each level, take a sharp look if the indirectpage was already modified within this
// transaction
key = new LogKey(pIsRootLevel, level, parentOffset * IConstants.CONTENT_COUNT + offset);
NodePageContainer container = mLog.get(key);
// if not...
if (container == null) {
// ...generating a new page and let it point to the last offset of the last page and ...
final long newKey = mNewUber.incrementPageCounter();
page = new IndirectPage(newKey);
// ...check if there is an existing indirect page...
if (parentPage.getReferenceKeys()[parentOffset] != 0) {
IndirectPage oldPage;
// ...try to retrieve the former page from the log..
LogKey oldKey =
new LogKey(pIsRootLevel, level, parentOffset * IConstants.CONTENT_COUNT + offset - 1);
NodePageContainer oldContainer = mLog.get(oldKey);
// ..since then the page was entirely filled. If not, read the page from a former
// revision..
if (oldContainer == null) {
// ..from the persistent storage ...
oldPage = (IndirectPage)mPageWriter.read(parentPage.getReferenceKeys()[parentOffset]);
// ...and copy all references and put it in the transaction log.
for (int i = 0; i < oldPage.getReferenceKeys().length; i++) {
page.setReferenceKey(i, oldPage.getReferenceKeys()[i]);
}
} else {
parentOffset = offset;
}
}
// Set the reference to the current revision..
parentPage.setReferenceKey(parentOffset, newKey);
container = new NodePageContainer(parentPage, parentPage);
// .. and put the parent-reference to the log as well as the reference of the..
mLog.put(parentKey, container);
// ...current page.
container = new NodePageContainer(page, page);
mLog.put(key, container);
} else {
page = (IndirectPage)container.getModified();
}
// finally, set the new pagekey for the next level
parentKey = key;
parentPage = page;
parentOffset = offset;
}
// Return reference to leaf of indirect tree.
return key;
}
private void setUpTransaction(final UberPage pUberPage, final ISession pSession,
final long pRepresentRev, final IBackendWriter pWriter) throws TTException {
mNewUber =
new UberPage(pUberPage.incrementPageCounter(), pUberPage.getRevisionNumber() + 1, pUberPage
.getPageCounter());
mNewUber.setReferenceKey(IReferencePage.GUARANTEED_INDIRECT_OFFSET,
pUberPage.getReferenceKeys()[IReferencePage.GUARANTEED_INDIRECT_OFFSET]);
mDelegate = new PageReadTrx(pSession, pUberPage, pRepresentRev, pWriter);
// Get previous revision root page..
final RevisionRootPage previousRevRoot = mDelegate.getActualRevisionRootPage();
// ...and using this data to initialize a fresh revision root including the pointers.
mNewRoot =
new RevisionRootPage(mNewUber.incrementPageCounter(), pRepresentRev + 1, previousRevRoot
.getMaxNodeKey());
mNewRoot.setReferenceKey(IReferencePage.GUARANTEED_INDIRECT_OFFSET, previousRevRoot
.getReferenceKeys()[IReferencePage.GUARANTEED_INDIRECT_OFFSET]);
// Prepare indirect tree to hold reference to prepared revision root
// nodePageReference.
long lastIndirectKey =
(mNewUber.getRevisionNumber() - ((mNewUber.getRevisionNumber() >> IConstants.INP_LEVEL_PAGE_COUNT_EXPONENT[2]) << IConstants.INP_LEVEL_PAGE_COUNT_EXPONENT[2]));
LogKey indirectKey = preparePathToLeaf(true, mNewUber, lastIndirectKey);
NodePageContainer indirectContainer = mLog.get(indirectKey);
int offset = nodePageOffset(mNewUber.getRevisionNumber());
((IndirectPage)indirectContainer.getModified()).setReferenceKey(offset, mNewRoot.getPageKey());
mLog.put(indirectKey, indirectContainer);
// Setting up a new namepage
Map<IMetaEntry, IMetaEntry> oldMap = mDelegate.mMetaPage.getMetaMap();
mNewName = new MetaPage(mNewUber.incrementPageCounter());
for (IMetaEntry key : oldMap.keySet()) {
mNewName.setEntry(key, oldMap.get(key));
}
mNewRoot.setReferenceKey(RevisionRootPage.NAME_REFERENCE_OFFSET, mNewName.getPageKey());
}
/**
* Current reference to actual rev-root page.
*
* @return the current revision root page
*/
public RevisionRootPage getActualRevisionRootPage() {
return mNewRoot;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isClosed() {
return mDelegate.isClosed();
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return toStringHelper(this).add("mPageWriter", mPageWriter).add("mLog", mLog).add("mRootPage",
mNewRoot).add("mDelegate", mDelegate).toString();
}
/**
* {@inheritDoc}
*/
@Override
public MetaPage getMetaPage() {
return mNewName;
}
} |
package com.centerkey.utils;
import java.util.Arrays;
import javax.swing.JOptionPane;
public class BareBonesBrowserLaunch {
static final String[] browsers = { "google-chrome", "firefox", "opera",
"epiphany", "konqueror", "conkeror", "midori", "kazehakase", "mozilla" };
static final String errMsg = "Error attempting to launch web browser";
public static void openURL(String url) {
try { //attempt to use Desktop library from JDK 1.6+
Class<?> d = Class.forName("java.awt.Desktop");
d.getDeclaredMethod("browse", new Class[] {java.net.URI.class}).invoke(
d.getDeclaredMethod("getDesktop").invoke(null),
new Object[] {java.net.URI.create(url)});
//above code mimicks: java.awt.Desktop.getDesktop().browse()
}
catch (Exception ignore) { //library not available or failed
String osName = System.getProperty("os.name");
try {
if (osName.startsWith("Mac OS")) {
Class.forName("com.apple.eio.FileManager").getDeclaredMethod(
"openURL", new Class[] {String.class}).invoke(null,
new Object[] {url});
}
else if (osName.startsWith("Windows"))
Runtime.getRuntime().exec(
"rundll32 url.dll,FileProtocolHandler " + url);
else { //assume Unix or Linux
String browser = null;
for (String b : browsers)
if (browser == null && Runtime.getRuntime().exec(new String[]
{"which", b}).getInputStream().read() != -1)
Runtime.getRuntime().exec(new String[] {browser = b, url});
if (browser == null)
throw new Exception(Arrays.toString(browsers));
}
}
catch (Exception e) {
JOptionPane.showMessageDialog(null, errMsg + "\n" + e.toString());
}
}
}
} |
package etf.si.projekat.data_vision;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import java.awt.Button;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextField;
import ba.unsa.etf.si.beans.DeviceName;
import ba.unsa.etf.si.beans.DeviceType;
import ba.unsa.etf.si.hibernate_klase.HibernateDeviceName;
import ba.unsa.etf.si.hibernate_klase.HibernateDeviceType;
import java.awt.Color;
public class AddDevice extends JFrame { //extends JFrame
private JPanel contentPane;
private JTextField textField_2;
private JTextField textField_3;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
AddDevice frame = new AddDevice();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public AddDevice() {
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblGraphType = new JLabel("Device name");
lblGraphType.setBounds(98, 84, 73, 14);
contentPane.add(lblGraphType);
JLabel lblTimeIntervalFrom = new JLabel("Device type");
lblTimeIntervalFrom.setBounds(98, 139, 111, 14);
contentPane.add(lblTimeIntervalFrom);
Button button = new Button("Continue");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(textField_2.getText().isEmpty() || textField_3.getText().isEmpty() || textField_2.getText().matches("\\s+")|| textField_3.getText().matches("\\s+")){
JOptionPane.showMessageDialog(null, "Nisu sva polja ispunjena", "AlertBox", JOptionPane.WARNING_MESSAGE);
}
else{
DeviceName dn = new DeviceName();
dn.setName(textField_2.getText());
HibernateDeviceName hdn = new HibernateDeviceName();
hdn.addDeviceName(dn);
DeviceType dt = new DeviceType();
dt.setType(textField_3.getText());
HibernateDeviceType hdt = new HibernateDeviceType();
hdt.addDeviceType(dt);
JOptionPane.showMessageDialog(null, "Novi uređaj dodan", "InfoBox", JOptionPane.INFORMATION_MESSAGE);
dispose();
}
}
});
button.setBounds(354, 230, 70, 22);
contentPane.add(button);
Button button_1 = new Button("Cancel");
button_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
}
});
button_1.setBounds(278, 230, 70, 22);
contentPane.add(button_1);
JPanel panel = new JPanel();
panel.setBackground(new Color(0, 191, 255));
panel.setBounds(0, 0, 434, 36);
contentPane.add(panel);
JPanel panel_1 = new JPanel();
panel_1.setBackground(new Color(0, 191, 255));
panel_1.setBounds(0, 218, 434, 54);
contentPane.add(panel_1);
textField_2 = new JTextField();
textField_2.setBounds(181, 81, 86, 20);
contentPane.add(textField_2);
textField_2.setColumns(10);
textField_3 = new JTextField();
textField_3.setBounds(180, 136, 86, 20);
contentPane.add(textField_3);
textField_3.setColumns(10);
}
} |
package com.github.noxan.aves.demo.chat;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.github.noxan.aves.auth.session.SessionManager;
import com.github.noxan.aves.auth.storage.InMemoryUsernamePasswordStorage;
import com.github.noxan.aves.net.Connection;
import com.github.noxan.aves.server.ServerHandler;
import com.github.noxan.aves.server.SocketServer;
public class ChatServer implements ServerHandler {
public static void main(String[] args) {
ChatServer server = new ChatServer();
try {
server.start();
} catch(IOException e) {
e.printStackTrace();
}
}
private Logger logger = Logger.getLogger(getClass().getName());
private InMemoryUsernamePasswordStorage storage;
private SessionManager sessionManager;
public ChatServer() {
storage = new InMemoryUsernamePasswordStorage();
sessionManager = new SessionManager(storage);
}
public void start() throws IOException {
server.start();
}
@Override
public void readData(Connection connection, Object data) {
logger.log(Level.INFO, data.toString());
}
@Override
public void clientConnect(Connection connection) {
logger.log(Level.INFO, connection + " connected");
}
@Override
public void clientDisconnect(Connection connection) {
logger.log(Level.INFO, connection + " disconnected");
}
@Override
public void clientLost(Connection connection) {
logger.log(Level.INFO, connection + " lost");
}
} |
package com.haxademic.core.math.easing;
public class LinearFloat
implements IEasingValue {
public float _val, _target, _inc;
public int _delay;
public LinearFloat( float value, float inc ) {
_val = value;
_target = value;
_inc = inc;
_delay = 0;
}
public float value() {
return _val;
}
public float target() {
return _target;
}
public void setCurrent( float value ) {
_val = value;
}
public void setTarget( float value ) {
_target = value;
}
public void setInc( float value ) {
_inc = value;
}
public void setDelay( int frames ) {
_delay = frames;
}
// mask to be swappable with EasingFloat
public void update(boolean bool) {
update();
}
public void update() {
if( _delay > 0 ) { _delay--; return; }
if( _val != _target ) {
boolean switchedSides = false;
if( _val < _target ) {
_val += _inc;
if( _val > _target ) switchedSides = true;
} else {
_val -= _inc;
if( _val < _target ) switchedSides = true;
}
if( switchedSides == true ) {
_val = _target;
}
}
}
} |
package com.basilgregory.onamsample;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import com.basilgregory.onam.android.Entity;
import com.basilgregory.onam.annotations.DB;
import com.basilgregory.onamsample.adapter.PostsAdapter;
import com.basilgregory.onamsample.entities.Comment;
import com.basilgregory.onamsample.entities.Post;
import com.basilgregory.onamsample.entities.User;
import com.basilgregory.onamsample.listeners.ClickListener;
import com.basilgregory.onamsample.listeners.RecyclerTouchListener;
import java.util.List;
/**
* This is where your database name along with the entity class names is to be provided.
* Both are mandatory
* No explicit naming convention needed.
* Ideally #{DB} should be added to the activity that will be called every time application is opened fresh.
*
*/
@DB(name = "blog_db",
tables = {Post.class,Comment.class,User.class
}, version = 1)
public class AllPostsActivity extends AppCompatActivity {
PostsAdapter postsAdapter;
RecyclerView posts;
FloatingActionButton addPlan;
List<Post> postList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_all_posts);
//This init should be called in the activity #{onCreate} where you have #{DB} annotation added.
Entity.init(this, true, false);
registerUser();
connectViews();
}
/**
* Function checks for user with primary key 1 in database, and if no user is found will create a John doe.
* This user will be assigned to all posts and comments made from the app.
*/
private void registerUser(){
if (User.find(User.class,1) != null) return;
User user = new User();
user.setName("John Doe");
user.setBio("Developer");
user.save();
}
@Override
protected void onResume() {
super.onResume();
if (postsAdapter == null) return;
fetchAllPosts();
postsAdapter.setPosts(postList);
postsAdapter.notifyDataSetChanged();
}
private void connectViews(){
fetchAllPosts();
postsAdapter = new PostsAdapter(postList);
addPlan = (FloatingActionButton) findViewById(R.id.addPlan);
addPlan.setOnClickListener(addNewPlan);
posts = (RecyclerView) findViewById(R.id.posts);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
posts.setLayoutManager(mLayoutManager);
posts.setItemAnimator(new DefaultItemAnimator());
posts.setAdapter(postsAdapter);
posts.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), posts, new ClickListener() {
@Override
public void onClick(View view, int position) {
if (postList == null || postList.size() < 1) return;
startActivity(new Intent(AllPostsActivity.this,PostDetailsActivity.class)
.putExtra("post_id",postList.get(position).getId()));
}
@Override
public void onLongClick(View view, int position) {
}
}));
postsAdapter.notifyDataSetChanged();
}
View.OnClickListener addNewPlan = new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(AllPostsActivity.this,AddPostActivity.class));
}
};
private void fetchAllPosts(){
postList = Post.findAll(Post.class,null,null);
}
} |
package com.mararok.epiccore.entity;
import java.util.ArrayList;
import java.util.List;
/**
* Extends Entity type with tracking properties changes
* Lazy create changed properties list for memory saves
*/
public class ObservedEntity extends Entity {
private List<PropertyEntry> changedProperties;
public ObservedEntity(int id) {
super(id);
}
/**
* Execute when some property changes value.
*/
protected void onChangeProperty(String name, Object newValue) {
if (!hasAnyChangedProperties()) {
changedProperties = new ArrayList<PropertyEntry>();
}
PropertyEntry propertyEntry = getChangedProperty(name);
if (propertyEntry != null) {
propertyEntry.value = newValue;
} else {
changedProperties.add(new PropertyEntry(name, newValue));
}
}
/**
* Returns new property value if property was changed
*/
public PropertyEntry getChangedProperty(String name) {
if (hasAnyChangedProperties()) {
for (PropertyEntry entry : changedProperties) {
if (entry.name.equalsIgnoreCase(name)) {
return entry;
}
}
}
return null;
}
/**
* Returns all changed properties list
*/
public PropertyEntry[] getChangedProperties() {
PropertyEntry[] list = null;
if (hasAnyChangedProperties()) {
list = new PropertyEntry[changedProperties.size()];
int index = 0;
for (PropertyEntry property : changedProperties) {
list[index++] = new PropertyEntry(property.name, property.value);
}
}
return list;
}
public void clearChanges() {
changedProperties = null;
}
public boolean hasAnyChangedProperties() {
return changedProperties != null;
}
public class PropertyEntry {
public String name;
public Object value;
public PropertyEntry(String name, Object value) {
this.name = name;
this.value = value;
}
}
} |
package com.opengamma.engine.position;
import java.io.Serializable;
import java.math.BigDecimal;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import com.opengamma.engine.security.Security;
import com.opengamma.id.Identifier;
import com.opengamma.id.IdentifierBundle;
import com.opengamma.util.ArgumentChecker;
import com.opengamma.util.CompareUtils;
/**
* A simple JavaBean-based implementation of {@link Position}.
*
* @author kirk
*/
public class PositionBean implements Position, Serializable {
private final BigDecimal _quantity;
private final IdentifierBundle _securityKey;
private Security _security;
private Identifier _identityKey;
public PositionBean(BigDecimal quantity, Identifier identifier) {
_quantity = quantity;
_securityKey = new IdentifierBundle(identifier);
_security = null;
}
public PositionBean(BigDecimal quantity, IdentifierBundle securityKey) {
_quantity = quantity;
_securityKey = securityKey;
_security = null;
}
public PositionBean(BigDecimal quantity, IdentifierBundle securityKey, Security security) {
_quantity = quantity;
_securityKey = securityKey;
_security = security;
}
public PositionBean(BigDecimal quantity, Security security) {
_quantity = quantity;
_security = security;
_securityKey = security.getIdentifiers() != null ? new IdentifierBundle(security.getIdentifiers()) : null;
}
@Override
public BigDecimal getQuantity() {
return _quantity;
}
@Override
public IdentifierBundle getSecurityKey() {
return _securityKey;
}
@Override
public Security getSecurity() {
return _security;
}
public void setSecurity(Security security) {
_security = security;
}
/**
* @return the identityKey
*/
public Identifier getIdentityKey() {
return _identityKey;
}
/**
* @param identityKey the identityKey to set
*/
public void setIdentityKey(String identityKey) {
_identityKey = new Identifier(POSITION_IDENTITY_KEY_DOMAIN, identityKey);
}
public void setIdentityKey(Identifier identityKey) {
ArgumentChecker.checkNotNull(identityKey, "Identity key");
if (!POSITION_IDENTITY_KEY_DOMAIN.equals(identityKey.getScheme())) {
throw new IllegalArgumentException("Wrong domain specified:" + identityKey.getScheme());
}
_identityKey = identityKey;
}
@Override
public boolean equals(Object obj) {
if(this == obj) {
return true;
}
if(obj == null) {
return false;
}
if(!(obj instanceof PositionBean)) {
return false;
}
PositionBean other = (PositionBean) obj;
// Use comparison here to deal with scale issues with BigDecimal comparisons.
if(CompareUtils.compareWithNull(getQuantity(), other.getQuantity()) != 0) {
return false;
}
if(!ObjectUtils.equals(getSecurityKey(), other.getSecurityKey())) {
return false;
}
if(!ObjectUtils.equals(getSecurity(), other.getSecurity())) {
return false;
}
return true;
}
@Override
public int hashCode() {
int hashCode = 65;
hashCode += getQuantity().hashCode();
if(getSecurityKey() != null) {
hashCode <<= 5;
hashCode += getSecurityKey().hashCode();
} else if(getSecurity() != null) {
hashCode <<= 5;
hashCode += getSecurity().hashCode();
}
return hashCode;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
}
} |
package com.qmetry.qaf.automation.tools;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.stream.Collectors;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.io.IOUtils;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.HttpRequest;
import org.apache.hc.core5.http.impl.bootstrap.HttpServer;
import org.apache.hc.core5.http.impl.bootstrap.ServerBootstrap;
import org.apache.hc.core5.http.io.entity.FileEntity;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.json.JSONObject;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.qmetry.qaf.automation.core.ConfigurationManager;
import com.qmetry.qaf.automation.keys.ApplicationProperties;
import com.qmetry.qaf.automation.step.StepNotFoundException;
import com.qmetry.qaf.automation.step.StringTestStep;
import com.qmetry.qaf.automation.util.FileUtil;
import com.qmetry.qaf.automation.util.JSONUtil;
import com.qmetry.qaf.automation.util.StringUtil;
import com.qmetry.qaf.automation.ws.Response;
import com.qmetry.qaf.automation.ws.rest.RestTestBase;
/**
* @author chirag.jayswal
*
*/
public class RepoEditor {
/**
* @param args
*/
public static void main(String[] args) {
int port = ConfigurationManager.getBundle().getInt("repoeditor.server.port",2612);
final HttpServer server = createServer(port);
try {
server.start();
System.out.println("server started on port: " + port);
System.out.println("type \"exit\" to stop server.");
try (Scanner s = new Scanner(System.in)) {
s.next("exit");
}
System.exit(0);
} catch (IOException e) {
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
private static HttpServer createServer(int port) {
HttpServer server = ServerBootstrap.bootstrap().setListenerPort(port).register("/", (req, res, c) -> {
res.setEntity(new FileEntity(new File("dashboard.htm"), ContentType.TEXT_HTML));
}).register("/browse", (req, res, c) -> {
res.setEntity(new StringEntity(browse("."), ContentType.TEXT_HTML));
}).register("/executeRequest", (req, res, ctx) -> {
try {
String reqCall = IOUtils.toString(req.getEntity().getContent(), StandardCharsets.UTF_8);
Object[] args = JSONUtil.toObject(reqCall, Object[].class);
StringTestStep.execute("userRequestsWithData", args);
Response result = new RestTestBase().getResponse();
String resStr = new JSONObject(result).toString();
res.setEntity(new StringEntity(resStr, ContentType.APPLICATION_JSON));
} catch (StepNotFoundException se) {
res.setEntity(new StringEntity("ERROR: Add qaf-support-ws library dependency!...",
ContentType.TEXT_PLAIN));
} catch (Throwable t) {
t.printStackTrace();
res.setEntity(new StringEntity(t.getMessage(), ContentType.TEXT_PLAIN));
}
}).register("/executeStep", (req, res, ctx) -> {
Map<String, Object> responseToreturn = new HashMap<String, Object>();
try {
String reqCall = IOUtils.toString(req.getEntity().getContent(), StandardCharsets.UTF_8);
Map<String, Object> reqMap = JSONUtil.toMap(reqCall);
Object result = StringTestStep.execute(reqMap.get("step").toString(), ((List<Object>)reqMap.get("args")).toArray(new Object[] {}));
responseToreturn.put("result", result);
}catch (Throwable t) {
t.printStackTrace();
responseToreturn.put("error", t.getMessage());
}
res.setEntity(new StringEntity(JSONUtil.toString(responseToreturn), ContentType.APPLICATION_JSON));
}).register("/repo-editor", (req, res, ctx) -> {
try {
Map<String, String> queryParams = getQueryParams(req);
System.out.println(queryParams);
if (!queryParams.isEmpty()) {
switch (queryParams.getOrDefault("operation", "")) {
case "get_prop":
res.setEntity(new StringEntity(ConfigurationManager.getBundle().getString(queryParams.getOrDefault("name",""),""),
ContentType.APPLICATION_JSON));
case "get_node":
res.setEntity(new StringEntity(JSONUtil.toString(getNodes(queryParams.get("id"))),
ContentType.APPLICATION_JSON));
break;
case "get_wsc_content":
Map<String, Object> wsc = getWSCNodeContent(queryParams.get("path"), queryParams.get("name"));
if(wsc.containsKey("reference")) {
wsc.put("refObj",JSONUtil.toObject(ConfigurationManager.getBundle().getString(wsc.get("reference").toString(),"{}")));
}
res.setEntity(new StringEntity(
JSONUtil.toString(wsc ),
ContentType.APPLICATION_JSON));
break;
case "get_grpc_content":
try {
Object result = StringTestStep.execute("getGRPCMethodDetails", queryParams.get("path"),queryParams.get("name"));
res.setEntity(new StringEntity(JSONUtil.toString(result), ContentType.APPLICATION_JSON));
} catch (StepNotFoundException se) {
res.setEntity(new StringEntity("ERROR: Add qaf-support-grpc library dependency!...",
ContentType.TEXT_PLAIN));
} catch (Throwable t) {
t.printStackTrace();
res.setEntity(new StringEntity(t.getMessage(), ContentType.TEXT_PLAIN));
}
break;
case "get_content":
res.setEntity(new StringEntity(
JSONUtil.toString(getContent(queryParams.get("path"))),
ContentType.APPLICATION_JSON));
break;
case "save_wsc":
// create file, create/rename request call
String message = "Saved " + queryParams.get("path");
String content = IOUtils.toString(req.getEntity().getContent(), StandardCharsets.UTF_8);
saveWsc(JSONUtil.toMap(content), queryParams);
res.setEntity(new StringEntity(message, ContentType.TEXT_PLAIN));
break;
case "save_loc":
String data = IOUtils.toString(req.getEntity().getContent(), StandardCharsets.UTF_8);
saveContent(JSONUtil.toObject(data, List.class), queryParams.get("path"));
break;
case "save_file":
String fileContent = IOUtils.toString(req.getEntity().getContent(), StandardCharsets.UTF_8);
FileUtil.writeStringToFile(new File( queryParams.get("path")), fileContent, ApplicationProperties.LOCALE_CHAR_ENCODING.getStringVal("UTF-8"));
break;
case "load_file":
ConfigurationManager.getBundle().load(new String[] {queryParams.get("path")});
break;
case "move_node":
res.setEntity(new StringEntity(JSONUtil.toString(moveNode(queryParams)),
ContentType.APPLICATION_JSON));
break;
case "copy_node":
res.setEntity(new StringEntity(JSONUtil.toString(copyNode(queryParams)),
ContentType.APPLICATION_JSON));
break;
case "rename_node":
res.setEntity(new StringEntity(JSONUtil.toString(rename(queryParams)),
ContentType.APPLICATION_JSON));
break;
case "create_node":
res.setEntity(new StringEntity(JSONUtil.toString(create(queryParams)),
ContentType.APPLICATION_JSON));
break;
case "delete_node":
delete(queryParams);
break;
default:
break;
}
} else {
res.setEntity(new FileEntity(new File("repo-editor.html"), ContentType.TEXT_HTML));
}
} catch (Exception e) {
res.setCode(400);
res.setEntity(new StringEntity(e.getMessage(), ContentType.TEXT_PLAIN));
}
}).register("*", (req, res, ctx) -> {
String endpoint;
try {
endpoint = req.getPath().substring(1).split("\\?", 2)[0];
endpoint = req.getUri().getPath().substring(1);
} catch (URISyntaxException e1) {
endpoint = req.getPath().substring(1).split("\\?", 2)[0];
}
File file = new File(endpoint);
boolean exist = file.exists();
switch (req.getMethod().toUpperCase()) {
case "GET":
if (exist) {
if (file.isDirectory()) {
res.setEntity(new StringEntity(browse(endpoint), ContentType.TEXT_HTML));
} else {
res.setEntity(new FileEntity(file, getContentType(endpoint)));
}
} else {
res.setCode(404);
res.setReasonPhrase("Not avialable");
res.setEntity(new StringEntity(req.getPath() + " not avialable."));
}
break;
default:
break;
}
}).create();
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
System.out.println("stoping server!....");
server.stop();
}));
return server;
}
private static String browse(String dir) {
try {
return Files.list(new File(dir).toPath())
.map(p -> String.format("<a href=\"/%s\">%s</a>", p, p.toString().replace(dir, "")))
.collect(Collectors.joining("<br>"));
} catch (IOException e) {
return e.getMessage();
}
}
private static ContentType getContentType(final String filename) {
try {
if (filename.endsWith(".js")) {
return ContentType.create("text/javascript", "UTF-8");
}
if (filename.endsWith(".css")) {
return ContentType.create("text/css", "UTF-8");
}
if (filename.endsWith(".wsc")) {
return ContentType.APPLICATION_JSON;
}
if (filename.endsWith(".loc")) {
return ContentType.APPLICATION_JSON;
}
if (filename.endsWith(".png")) {
return ContentType.IMAGE_PNG;
}
if (filename.endsWith(".svg")) {
return ContentType.IMAGE_SVG;
}
return ContentType.create(Files.probeContentType(new File(filename).toPath()));
} catch (Exception e) {
return ContentType.TEXT_PLAIN;
}
}
private static Map<String, String> getQueryParams(HttpRequest request) {
Map<String, String> query_pairs = new LinkedHashMap<String, String>();
try {
String query = request.getUri().getQuery();
String[] pairs = query.split("&");
for (String pair : pairs) {
try {
String kv[] = pair.split("=", 2);
query_pairs.put(URLDecoder.decode(kv[0], "UTF-8"), URLDecoder.decode(kv[1], "UTF-8"));
} catch (UnsupportedEncodingException | ArrayIndexOutOfBoundsException e) {
}
}
} catch (Throwable e1) {
}
return query_pairs;
}
@SuppressWarnings("unchecked")
private static Map<String, Object> getWSCNodeContent(String path, String name) {
Map<String, Object> fileContent = getWSCFile(path);
return (Map<String, Object>) fileContent.getOrDefault(name, Collections.emptyMap());
}
private static Map<String, String> copyNode(Map<String, String> queryParams) throws IOException {
File parent = new File(queryParams.get("parent"));
String id = queryParams.get("id");
if (id.indexOf("
if (parent.getName().endsWith(".wsc")) {
String[] parts = id.split("
// src
Map<String, Object> fileContent = getWSCFile(parts[0]);
Object wsc = fileContent.remove(parts[1]);
// dest
fileContent = getWSCFile(parent.getPath());
fileContent.put(parts[1], wsc);
saveWSCFile(fileContent, parent.getPath());
id = queryParams.get("parent") + "#" + parts[1];
} else {
throw new IOException("Can't cop request call to" + parent.getName());
}
} else {
File src = new File(id);
File dest = new File(parent, src.getName());
Files.copy(src.toPath(), dest.toPath());
id = dest.getPath();
}
queryParams.clear();
queryParams.put("id", id);
return queryParams;
}
private static Map<String, String> moveNode(Map<String, String> queryParams) throws IOException {
String nodeName = queryParams.get("name");
File parent = new File(queryParams.get("parent"));
File oldParent = new File(queryParams.get("oldParent"));
String id = queryParams.get("parent") + "/" + nodeName;
if (oldParent.isFile()) {
if (parent.getName().endsWith(".wsc") || parent.getParent().contains(".wsc")) {
if (parent.getParent().contains(".wsc")) {
parent = parent.getParentFile();
}
// move wsc
Map<String, Object> fileContent = getWSCFile(oldParent.getPath());
Object wsc = fileContent.remove(nodeName);
saveWSCFile(fileContent, oldParent.getPath());
fileContent = getWSCFile(parent.getPath());
fileContent.put(nodeName, wsc);
saveWSCFile(fileContent, parent.getPath());
id= parent.getPath() + "#" +nodeName;
} else {
throw new IOException("Can't move request call to" + parent.getName());
}
} else {
// move file or folder
System.out.println("moving file!....");
Files.move(new File(oldParent, nodeName).toPath(), new File(parent, nodeName).toPath());
}
queryParams.clear();
queryParams.put("id", id);
return queryParams;
}
private static void delete(Map<String, String> queryParams) throws IOException {
String id = queryParams.get("id").replace('
File target = new File(id);
if (target.exists()) {
FileUtil.deleteQuietly(target);
} else if (target.getParent().endsWith(".wsc")) {
Map<String, Object> fileContent = getWSCFile(target.getParent());
fileContent.remove(target.getName());
saveWSCFile(fileContent, target.getParent());
}
}
private static void saveWsc(Map<String, Object> content, Map<String, String> queryParams) throws IOException {
String path = queryParams.get("path");
if (StringUtil.isNotBlank(queryParams.get("name"))) {
Map<String, Object> fileContent = getWSCFile(path);
fileContent.put(queryParams.get("name"), content);
saveWSCFile(fileContent, path);
}
}
private static Map<String, String> rename(Map<String, String> queryParams) throws IOException {
String old = queryParams.get("old");
String id = queryParams.get("id").replace('
String newName = queryParams.get("text");
File file = new File(id);
File parent = file.getParentFile();
if (parent.getName().endsWith("wsc")) {
file = parent;
if (!file.exists()) {
FileUtil.checkCreateDir(file.getParent());
}
Map<String, Object> fileContent = getWSCFile(file.getPath());
if (StringUtil.isNotBlank(newName)) {
Object val = fileContent.remove(queryParams.getOrDefault("old", ""));
if (null == val) {
val = JSONUtil.toObject("{}");
}
fileContent.put(newName, val);
}
saveWSCFile(fileContent, file.getPath());
id=file.getPath()+"#"+newName;
} else {
if (StringUtil.isNotBlank(old)) {
File oldFile = new File(parent, old);
File newFile = new File(parent, newName);
if(oldFile.exists()) {
oldFile.renameTo(newFile);
}else {
FileUtil.checkCreateDir(parent.getParent());
}
id=newFile.getPath();
}
}
queryParams.clear();
queryParams.put("id", id);
return queryParams;
}
private static Map<String, String> create(Map<String, String> queryParams) throws IOException {
String type = queryParams.get("type");
String id = queryParams.get("id");
String name = queryParams.get("text");
File parent = new File(queryParams.get("id"));
if (parent.getName().endsWith("wsc")) {
if (!parent.exists()) {
FileUtil.checkCreateDir(parent.getParent());
}
Map<String, Object> fileContent = getWSCFile(parent.getPath());
if (StringUtil.isNotBlank(name)) {
name=name.replace(' ', '.');
int cnt=2;
if(ConfigurationManager.getBundle().containsKey(name)) {
while(ConfigurationManager.getBundle().containsKey(name + cnt)) {cnt++;};
name=name+cnt;
}
fileContent.put(name, JSONUtil.toObject("{}"));
//ConfigurationManager.getBundle().setProperty(name,"");
saveWSCFile(fileContent, parent.getPath());
}
id=id+"#"+name;
} else {
File file = new File(parent,name);
if(type.equalsIgnoreCase("folder")) {
if(file.exists()) {
int cnt=2;
while(new File(name + cnt).exists()) {cnt++;};
name=name+cnt;
}
file = new File(parent,name);
FileUtil.checkCreateDir(file.getPath());
}else {
file.createNewFile();
}
id=file.getPath();
}
queryParams.clear();
queryParams.put("id", id);
queryParams.put("text", name);
return queryParams;
}
private static Object[] getNodes(String id) {
try {
if (id.equalsIgnoreCase("
File tdir = new File("resources");
boolean dirExists = tdir.exists();
if (!dirExists) {
dirExists = tdir.mkdirs();
//FileUtil.
}
Map<String, Object> rootNode = new HashMap<String, Object>();
rootNode.put("text", "resources");
rootNode.put("id", "resources");
rootNode.put("type", "folder");
rootNode.put("children", getNodes("resources"));
return new Object[] { rootNode };
}
File parent = new File(id);
if (parent.getName().endsWith(".wsc")) {
Map<String, Object> fileContent = new LinkedHashMap<String, Object>();
if (parent.exists()) {
fileContent = getWSCFile(parent.getPath());//JSONUtil.getJsonObjectFromFile(parent.getPath(), Map.class);
}
return fileContent.keySet().stream().map(k -> {
Map<String, Object> node = new HashMap<String, Object>();
node.put("text", k);
node.put("id", id + "
node.put("type", "node");
return node;
}).toArray();
}
if (parent.getName().endsWith(".proto")) {
@SuppressWarnings("unchecked")
List<String> result = (List<String>) StringTestStep.execute("getGRPCMethodNames", parent.getPath());
System.err.println(result);
System.out.println(parent);
return result.stream().map(k -> {
Map<String, Object> node = new HashMap<String, Object>();
node.put("text", k);
node.put("id", id + "
node.put("type", "node-grpc");
return node;
}).toArray();
}
//".wsc",".loc",".proto","json", "properties", "xml","txt", "csv"
String[] allowedTypes = ConfigurationManager.getBundle().getStringArray("repoeditor.filetypes", ".wsc",".loc",".proto");
Object[] nodes = Files.list(parent.toPath())
.filter(p -> p.toFile().isDirectory() || StringUtil.endsWithAny(p.toString(), allowedTypes))
.map(p -> {
Map<String, Object> node = new HashMap<String, Object>();
node.put("text", p.toFile().getName());
node.put("id", p.toString());
if (p.toFile().isDirectory()) {
node.put("children", true);
node.put("type", "folder");
} else {
String type = FileUtil.getExtention(p.toString());
node.put("type", "file-"+type);
node.put("children", "wscproto".indexOf(type)>=0);
}
return node;
}).toArray();
return (nodes);
} catch (IOException e) {
return new Object[0];
}
}
@SuppressWarnings("unchecked")
private static List<Map<String, Object>> getContent(String file) {
List<Map<String, Object>> fileContent = new LinkedList<Map<String, Object>>();
try {
PropertiesConfiguration propertiesConfiguration = new PropertiesConfiguration();
propertiesConfiguration.setEncoding(ApplicationProperties.LOCALE_CHAR_ENCODING.getStringVal("UTF-8"));
propertiesConfiguration.setDelimiterParsingDisabled(true);
propertiesConfiguration.load(new FileInputStream(file));
Iterator<String> iter = propertiesConfiguration.getKeys();
if(file.endsWith(".wsc")) {
Map<String, Object> contenct = new LinkedHashMap<>();
while(iter.hasNext()) {
String key = iter.next();
String value = propertiesConfiguration.getString(key);
contenct.put(key, JSONUtil.toObject(value));
}
fileContent.add(contenct);
}
if(file.endsWith(".loc")) {
while(iter.hasNext()) {
String key = iter.next();
String value = propertiesConfiguration.getString(key);
Object obj = JSONUtil.toObject(value);
Map<String, Object> entry = new LinkedHashMap<>();
entry.put("key", key);
if(obj instanceof Map) {
entry.putAll((Map<String, Object>)obj);
}else {
entry.put("locator", value);
}
fileContent.add(entry);
}
}
} catch (ConfigurationException e) {
} catch (FileNotFoundException e) {
}
return fileContent;
}
private static Map<String, Object> getWSCFile(String file){
List<Map<String, Object>> content = getContent(file);
return content.isEmpty()?JSONUtil.toMap("{}"):content.get(0);
}
private static void saveContent(List<Map<String, Object>> data, String file) throws IOException {
Gson gson = new GsonBuilder().disableHtmlEscaping().serializeNulls().create();
String fileContent = null;
if(file.endsWith("wsc")) {
fileContent = data.get(0).entrySet().stream().map((e) -> e.getKey() +"=" + gson.toJson(e.getValue())).collect(Collectors.joining("\n"));
}else if(file.endsWith(".loc")) {
fileContent = data.stream().map(e->e.remove("key").toString()+"="+gson.toJson(e)).collect(Collectors.joining("\n"));
}
if(null!=fileContent) {
FileUtil.writeStringToFile(new File(file), fileContent, ApplicationProperties.LOCALE_CHAR_ENCODING.getStringVal("UTF-8"));
}
//to keep track added/updated wsc and properties
ConfigurationManager.addBundle(file);
}
private static void saveWSCFile(Map<String, Object> data,String file) throws IOException{
List<Map<String, Object>> fileContent = new LinkedList<Map<String, Object>>();
fileContent.add(data);
saveContent(fileContent,file);
}
} |
package org.diqube.server;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Collection;
import java.util.Properties;
import org.diqube.data.ColumnType;
import org.diqube.data.Table;
import org.diqube.data.TableFactory;
import org.diqube.data.TableShard;
import org.diqube.execution.TableRegistry;
import org.diqube.loader.CsvLoader;
import org.diqube.loader.DiqubeLoader;
import org.diqube.loader.JsonLoader;
import org.diqube.loader.LoadException;
import org.diqube.loader.Loader;
import org.diqube.loader.LoaderColumnInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Loads the table shard whose data is referred to by a .control file.
*
* @author Bastian Gloeckle
*/
public class ControlFileLoader {
private static final Logger logger = LoggerFactory.getLogger(ControlFileLoader.class);
public static final String KEY_FILE = "file";
public static final String KEY_TYPE = "type";
public static final String KEY_TABLE = "table";
public static final String KEY_FIRST_ROWID = "firstRowId";
public static final String KEY_COLTYPE_PREFIX = "columnType.";
public static final String KEY_DEFAULT_COLTYPE = "defaultColumnType";
public static final String TYPE_CSV = "csv";
public static final String TYPE_JSON = "json";
public static final String TYPE_DIQUBE = "diqube";
private File controlFile;
private TableRegistry tableRegistry;
private TableFactory tableFactory;
private CsvLoader csvLoader;
private JsonLoader jsonLoader;
private DiqubeLoader diqubeLoader;
public ControlFileLoader(TableRegistry tableRegistry, TableFactory tableFactory, CsvLoader csvLoader,
JsonLoader jsonLoader, DiqubeLoader diqubeLoader, File controlFile) {
this.tableRegistry = tableRegistry;
this.tableFactory = tableFactory;
this.csvLoader = csvLoader;
this.jsonLoader = jsonLoader;
this.diqubeLoader = diqubeLoader;
this.controlFile = controlFile;
}
private ColumnType resolveColumnType(String controlFileString) throws LoadException {
try {
return ColumnType.valueOf(controlFileString.toUpperCase());
} catch (RuntimeException e) {
throw new LoadException(controlFileString + " is no valid ColumnType.");
}
}
/**
* Loads the table shard synchronously.
*
* <p>
* This method will automatically retry loading the .control file if it fails - this is needed if the control file has
* not been written completely yet. If the validation/loading of the control file still fails after a few attempts, a
* {@link LoadException} will be thrown.
*
* @return The name of the table under which it was registered at {@link TableRegistry}.
*/
public String load() throws LoadException {
Properties controlProperties;
String fileName;
String tableName;
String type;
long firstRowId;
LoaderColumnInfo columnInfo;
File file;
Object sync = new Object();
// We retry executing the following loading/validation of the control file itself. It could be that the load method
// gets called too early, when the control file has not been fully written, therefore we'll retry.
int maxRetries = 5;
for (int retryNo = 0;; retryNo++) {
try {
controlProperties = new Properties();
try (InputStream controlFileInputStream = new FileInputStream(controlFile)) {
controlProperties.load(controlFileInputStream);
} catch (IOException e) {
throw new LoadException("Could not load information of control file " + controlFile.getAbsolutePath(), e);
}
fileName = controlProperties.getProperty(KEY_FILE);
tableName = controlProperties.getProperty(KEY_TABLE);
type = controlProperties.getProperty(KEY_TYPE);
String firstRowIdString = controlProperties.getProperty(KEY_FIRST_ROWID);
if (fileName == null || tableName == null || firstRowIdString == null || type == null
|| !(type.equals(TYPE_CSV) || type.equals(TYPE_JSON) || type.equals(TYPE_DIQUBE)))
throw new LoadException("Invalid control file " + controlFile.getAbsolutePath());
try {
firstRowId = Long.parseLong(firstRowIdString);
} catch (NumberFormatException e) {
throw new LoadException(
"Invalid control file " + controlFile.getAbsolutePath() + " (FirstRowId is no valid number)");
}
ColumnType defaultColumnType;
String defaultColumnTypeString = controlProperties.getProperty(KEY_DEFAULT_COLTYPE);
if (defaultColumnTypeString == null)
defaultColumnType = ColumnType.STRING;
else
defaultColumnType = resolveColumnType(defaultColumnTypeString);
columnInfo = new LoaderColumnInfo(defaultColumnType);
for (Object key : controlProperties.keySet()) {
String keyString = (String) key;
if (keyString.startsWith(KEY_COLTYPE_PREFIX)) {
String val = controlProperties.getProperty(keyString);
keyString = keyString.substring(KEY_COLTYPE_PREFIX.length());
// TODO #13 LoaderColumnInfo should be able to handle repeated columns nicely.
columnInfo.registerColumnType(keyString, resolveColumnType(val));
}
}
file = controlFile.toPath().resolveSibling(fileName).toFile();
if (!file.exists() || !file.isFile())
throw new LoadException("File " + file.getAbsolutePath() + " does not exist or is no file.");
break;
} catch (LoadException e) {
if (retryNo == maxRetries - 1) {
throw e;
}
logger.info("Was not able to load control file {}, will retry. Error: {}", controlFile.getAbsolutePath(),
e.getMessage());
synchronized (sync) {
try {
sync.wait(200);
} catch (InterruptedException e1) {
throw new LoadException("Interrupted while waiting to retry loading control file", e1);
}
}
}
}
if (tableRegistry.getTable(tableName) != null)
// TODO #33 support loading multiple shards of a table from multiple control files (and removing them
// correctly).
throw new LoadException("Table '" + tableName + "' already exists.");
Loader loader;
switch (type) {
case TYPE_CSV:
loader = csvLoader;
break;
case TYPE_JSON:
loader = jsonLoader;
break;
case TYPE_DIQUBE:
loader = diqubeLoader;
break;
default:
throw new LoadException("Unkown input file type.");
}
TableShard newTableShard = loader.load(firstRowId, file.getAbsolutePath(), tableName, columnInfo);
Collection<TableShard> newTableShardCollection = Arrays.asList(new TableShard[] { newTableShard });
Table newTable = tableFactory.createTable(tableName, newTableShardCollection);
tableRegistry.addTable(tableName, newTable);
return tableName;
}
} |
package nars.plugin.mental;
import java.util.ArrayList;
import java.util.HashMap;
import nars.core.EventEmitter;
import nars.core.EventEmitter.EventObserver;
import nars.core.Events;
import nars.core.NAR;
import nars.core.Parameters;
import nars.core.Plugin;
import nars.entity.Stamp;
import nars.entity.Task;
import nars.language.Term;
/**
*
* @author tc
*/
public class ClassicalConditioningHelper implements Plugin {
public EventEmitter.EventObserver obs;
public float saved_priority;
public ArrayList<Task> lastElems=new ArrayList<>();
public int maxlen=20;
public int conditionAllNSteps=5;
public int cnt=0;
NAR nar;
public void classicalConditioning() {
ArrayList<Task> st=new ArrayList(lastElems.size());
Task lastt=null;
for(Task t: lastElems) {
st.add(t);
if(lastt!=null && Math.abs(t.sentence.getOccurenceTime()-lastt.sentence.getOccurenceTime())>nar.param.duration.get()*100) {
st.add(null); //pause
}
lastt=t;
}
st.add(0, null);
st.add(null); //empty space
HashMap<Term,ArrayList<Task>> theories=new HashMap<>();
for(int k=0;k<st.size();k++) {
for(int i=1;i<st.size()-1;i++) {
Task ev=st.get(i);
Task lastev=st.get(i-1);
//if(desired)
//theories[ev.sentence.term]=new ArrayList<>();
}
}
//ok st is prepared
/*
from copy import deepcopy
def conditioning2(Sequence):
st=" "+Sequence+" "
dc=set([a for a in st]) #unconditional and conditioned stimulus / events of high desire, currently we use all
theories={}
for i in range(len(st)):
dc2=deepcopy(dc)
for i in range(1,len(st)-1):
ev, lastev=st[i], st[i-1]
if ev in dc:
theories[ev]=lastev+ev #forward/simultaneous conditioning with blocking and inhibition:
dc2.add(lastev) #to allow multiple forward conditionings, this means deriving lastev as a desired subgoal
for j in range(i,len(st)-1):
ev2, lastev2=st[j], st[j-1]
if lastev2==lastev and ev2!=ev and ev in theories.keys():
del theories[ev] #extinction
dc=dc2
#higher order conditioning
theories=theories.values()
for i in range(2):
theories2=deepcopy(theories)
for A in theories:
for B in theories:
if len(A)==1 or len(B)==1 :
continue
A=A.replace(" ","")
B=B.replace(" ","")
caseA= A[-1]==B[0]
caseB= len(A)>2 and len(B)>1 and A[-1]==B[1] and A[-2]==B[0]
if len(A)>1 and len(B)>1 and caseA or caseB:
if caseA: compoundT=A[0:-1]+B
if caseB: compoundT=A[0:-2]+B
theories2=theories2+[compoundT]
theories=theories2
print "found theories:"
Filtered=[a for a in list(set([a.replace(" ","") for a in theories])) if len(a)>1]
Ret=[(a,float(st.count(a))*float(len(a))) for a in Filtered]
for (a,b) in Ret:
for (c,d) in Ret:
if a!=c and a in c and d>=b:
if (a,b) in Ret:
Ret.remove((a,b))
Maxc=max([b for (a,b) in Ret] if len(Ret)>0 else [0])
return [(a,b) for (a,b) in Ret if b==Maxc] #
a="uab wab kabi"
print "forward conditioning: \n" + a
print conditioning2(a)
print
a="kacf guacf wacfg"
print "higher order conditioning: \n" + a
print conditioning2(a)
print
a="cb cb cb ab"
print "inhibition: \n" + a
print conditioning2(a)
print
a="ab ab ab a"
print "extinction: \n" + a
print conditioning2(a)
print
a="abc abc abc ab"
print "extinction: \n" + a
print conditioning2(a)
print
a="AB AB AB CB CBF CBF CBF"
print "inhibition: \n" + a
print conditioning2(a)
*/
}
@Override
public boolean setEnabled(NAR n, boolean enabled) {
this.nar=n;
if(obs==null) {
saved_priority=Parameters.DEFAULT_JUDGMENT_PRIORITY;
obs=new EventObserver() {
@Override
public void event(Class event, Object[] a) {
if (event!=Events.Perceive.class)
return;
Task task = (Task)a[0];
if(task.sentence.stamp.getOccurrenceTime()!=Stamp.ETERNAL) {
lastElems.add(task);
if(lastElems.size()>maxlen) {
lastElems.remove(0);
}
if(cnt%conditionAllNSteps==0) {
classicalConditioning();
}
cnt++;
}
}
};
}
if(enabled) {
Parameters.DEFAULT_JUDGMENT_PRIORITY=(float) 0.01;
} else {
Parameters.DEFAULT_JUDGMENT_PRIORITY=saved_priority;
}
n.memory.event.set(obs, enabled, Events.Perceive.class);
return true;
}
} |
package com.newyith.fortressmod;
import java.util.Arrays;
import com.google.common.base.Function;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.newyith.fortressmod.client.GuiHandler;
import net.minecraft.block.Block;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.common.MinecraftForge;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.EventHandler;
import cpw.mods.fml.common.Mod.Instance;
import cpw.mods.fml.common.SidedProxy;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.registry.GameRegistry;
@Mod(modid = ModInfo.MODID, name = ModInfo.NAME, version = ModInfo.VERSION)
public class FortressMod
{
@Instance(value = ModInfo.MODID)
public static FortressMod modInstance;
public static Block fortressGenerator;
public static Block fortressGeneratorOn;
public static Block fortressGeneratorClogged;
public static Block fortressEmergencyKey;
public static CreativeTabs tabName = new CreativeTabs("tabName") {
public Item getTabIconItem() {
return Items.arrow;
}
};
public static Block fortressBedrock;
public static Block fortressGlass;
//*/
//*/
//*/ |
package org.cluj.bus.model;
import java.util.Collection;
public class BusInfo
{
private String busId;
private String busName;
private String busDisplayImage;
private Collection<IndividualBusInfo> individualBusInfos;
public String getBusId()
{
return busId;
}
public void setBusId(String busId)
{
this.busId = busId;
}
public String getBusName()
{
return busName;
}
public void setBusName(String busName)
{
this.busName = busName;
}
public String getBusDisplayImage()
{
return busDisplayImage;
}
public void setBusDisplayImage(String busDisplayImage)
{
this.busDisplayImage = busDisplayImage;
}
public Collection<IndividualBusInfo> getIndividualBusInfos()
{
return individualBusInfos;
}
public void setIndividualBusInfos(Collection<IndividualBusInfo> individualBusInfos)
{
this.individualBusInfos = individualBusInfos;
}
} |
package com.qwertygid.deutschsim;
import javax.swing.SwingUtilities;
import com.qwertygid.deutschsim.GUI.GUI;
public class DeutschSim {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new GUI();
}
});
}
} |
package com.dmillerw.remoteIO.core;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.LinkedList;
import java.util.logging.Level;
import net.minecraft.block.Block;
import net.minecraft.tileentity.TileEntity;
import buildcraft.api.gates.IAction;
import buildcraft.api.gates.IActionProvider;
import buildcraft.api.gates.ITrigger;
import buildcraft.api.gates.ITriggerProvider;
import buildcraft.api.transport.IPipe;
import com.dmillerw.remoteIO.block.tile.TileEntityIO;
import cpw.mods.fml.common.FMLLog;
import cpw.mods.fml.common.Loader;
public class BCGateHandler {
public static final String BC_API_GATE_PACKAGE = "buildcraft.api.gates";
public static final String BC_ACTION_MANAGER_CLASS = BC_API_GATE_PACKAGE + ".ActionManager";
public static final String BC_TRIGGER_PROVIDER_LIST = "triggerProviders";
public static final String BC_ACTION_PROVIDER_LIST = "actionProviders";
public static final String BC_ACTION_MANAGER_REGISTER_TRIGGER = "registerTriggerProvider";
public static final String BC_ACTION_MANAGER_REGISTER_ACTION = "registerActionProvider";
public static void inject() {
try {
if (Loader.isModLoaded("BuildCraft|Core")) {
Class actionManager = Class.forName(BC_ACTION_MANAGER_CLASS);
Method registerTrigger = actionManager.getMethod(BC_ACTION_MANAGER_REGISTER_TRIGGER, ITriggerProvider.class);
registerTrigger.invoke(null, new IOTriggerProvider());
Method registerAction = actionManager.getMethod(BC_ACTION_MANAGER_REGISTER_ACTION, IActionProvider.class);
registerAction.invoke(null, new IOActionProvider());
}
} catch(Exception ex) {
FMLLog.log(Level.WARNING, "[RemoteIO] Failed to register main trigger provider!", new Object[0]);
}
}
public static LinkedList<ITrigger> getTriggersForIO(TileEntityIO tile) {
LinkedList<ITrigger> triggers = new LinkedList<ITrigger>();
try {
Class actionManager = Class.forName(BC_ACTION_MANAGER_CLASS);
Field triggerProviders = actionManager.getDeclaredField(BC_TRIGGER_PROVIDER_LIST);
triggerProviders.setAccessible(true);
LinkedList<ITriggerProvider> providers = (LinkedList<ITriggerProvider>) triggerProviders.get(actionManager);
for (ITriggerProvider provider : providers) {
if (provider != null && !(provider instanceof IOTriggerProvider)) {
LinkedList<ITrigger> providedTriggers = provider.getNeighborTriggers(tile.blockType, tile);
if (providedTriggers != null) {
for (ITrigger trigger : providedTriggers) {
if (trigger != null) {
triggers.add(trigger);
}
}
}
}
}
} catch(Exception ex) {
FMLLog.log(Level.WARNING, "[RemoteIO] Failed to grab triggers for IO block connection!", new Object[0]);
ex.printStackTrace();
}
return triggers;
}
public static LinkedList<IAction> getActionsForIO(TileEntityIO tile) {
LinkedList<IAction> actions = new LinkedList<IAction>();
try {
Class actionManager = Class.forName(BC_ACTION_MANAGER_CLASS);
Field actionProviders = actionManager.getDeclaredField(BC_ACTION_PROVIDER_LIST);
actionProviders.setAccessible(true);
LinkedList<IActionProvider> providers = (LinkedList<IActionProvider>) actionProviders.get(actionManager);
for (IActionProvider provider : providers) {
if (provider != null && !(provider instanceof IOActionProvider)) {
LinkedList<IAction> providedActions = provider.getNeighborActions(tile.blockType, tile);
if (providedActions != null) {
for (IAction action : providedActions) {
if (action != null) {
actions.add(action);
}
}
}
}
}
} catch(Exception ex) {
FMLLog.log(Level.WARNING, "[RemoteIO] Failed to grab actions for IO block connection!", new Object[0]);
}
return actions;
}
public static class IOTriggerProvider implements ITriggerProvider {
@Override
public LinkedList<ITrigger> getPipeTriggers(IPipe pipe) {
return null;
}
@Override
public LinkedList<ITrigger> getNeighborTriggers(Block block, TileEntity tile) {
if (tile instanceof TileEntityIO) {
return getTriggersForIO((TileEntityIO) tile);
}
return null;
}
}
public static class IOActionProvider implements IActionProvider {
@Override
public LinkedList<IAction> getNeighborActions(Block block, TileEntity tile) {
if (tile instanceof TileEntityIO) {
return getActionsForIO((TileEntityIO) tile);
}
return null;
}
}
} |
import java.awt.*;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.awt.geom.Point2D.Double;
import java.awt.geom.RoundRectangle2D;
public class NodeShape extends TreeNode {
final private static int RADIUS = 17;
private int size = RADIUS;
final private static int MAX_RADIUS = 30;
final private static int X_SHIFT = 50;
final private static int Y_SHIFT = 50;
final private static double CONSTANT_OF_CENTER = 1.177793508745657;
Point2D.Double center = null;
Shape shape = null;
private boolean black = true;
private boolean selected = false;
private long timeSelected;
private static final int GROW_RATE = 200;
private static final int SHRINK_RATE = 50;
private static final String FONT_NAME = "Georgia";
private static final int MIN_FONT_SIZE = 4;
private static final int MAX_FONT_SIZE = 6;
private int fontSize = MIN_FONT_SIZE;
private static final int MIN_Y_SCALE = 2;
private static final int MAX_Y_SCALE = 6;
private int yScale = MIN_Y_SCALE;
private static final int MIN_DELTA_Y = 5;
private static final int MAX_DELTA_Y = 10;
private int deltaY = MIN_DELTA_Y;
public NodeShape(Person pVal, TreeNode pLkid, TreeNode pRkid) {
super(pVal, pLkid, pRkid);
}
/**
* Gives you the node that is contained in the point
*
* @param point2d
* @return
*/
public NodeShape contains(Point2D point2d) {
if (shape != null) {
if (shape.contains(point2d)) {
return this;
} else {
if (getRkid() != null) {
NodeShape temp = ((NodeShape) getRkid()).contains(point2d);
if (temp != null) {
return temp;
}
}
if (getLkid() != null) {
NodeShape temp = ((NodeShape) getLkid()).contains(point2d);
if (temp != null) {
return temp;
}
}
}
}
return null;
}
public int totalNodesInTree() {
int res = 1;
if (this.getRkid() != null) {
res += ((NodeShape) getRkid()).totalNodesInTree();
}
if (this.getLkid() != null) {
res += ((NodeShape) getLkid()).totalNodesInTree();
}
return res;
}
public void prepareDrawFromThisNode() {
this.center = new Point2D.Double();
this.shape = new RoundRectangle2D.Double(center.x - size, center.y
- size, size * 2, size * 2, 30, 14);
if (this.getRkid() != null) {
((NodeShape) getRkid()).prepare(center, true);
}
if (this.getLkid() != null) {
((NodeShape) getLkid()).prepare(center, false);
}
}
public void draw(Graphics2D gd) {
if (this.getRkid() != null) {
NodeShape rightKid = ((NodeShape) getRkid());
gd.draw(new Line2D.Double(this.center, rightKid.center));
rightKid.draw(gd);
}
if (this.getLkid() != null) {
NodeShape leftKid = ((NodeShape) getLkid());
gd.draw(new Line2D.Double(this.center, leftKid.center));
leftKid.draw(gd);
}
gd.setColor(gd.getBackground());
if (selected) {
if (size != MAX_RADIUS) {
size += (int) ((System.currentTimeMillis() - timeSelected) / GROW_RATE);
size = Math.min(size, MAX_RADIUS);
shape = new RoundRectangle2D.Double(center.x - size, center.y
- size, size * 2, size * 2, 30, 18);
}
if (fontSize != MAX_FONT_SIZE) {
fontSize += (int) ((System.currentTimeMillis() - timeSelected) / GROW_RATE);
fontSize = Math.min(fontSize, MAX_FONT_SIZE);
}
if (yScale != MAX_Y_SCALE) {
yScale += (int) ((System.currentTimeMillis() - timeSelected) / GROW_RATE);
yScale = Math.min(yScale, MAX_Y_SCALE);
}
if (deltaY != MAX_DELTA_Y) {
deltaY += (int) ((System.currentTimeMillis() - timeSelected) / GROW_RATE);
deltaY = Math.min(deltaY, MAX_DELTA_Y);
}
} else {
if (size != RADIUS) {
size -= (int) ((System.currentTimeMillis() - timeSelected) / SHRINK_RATE);
size = Math.max(size, RADIUS);
shape = new RoundRectangle2D.Double(center.x - size, center.y
- size, size * 2, size * 2, 30, 18);
}
if (fontSize != MIN_FONT_SIZE) {
fontSize -= (int) ((System.currentTimeMillis() - timeSelected) / SHRINK_RATE);
fontSize = Math.max(fontSize, MIN_FONT_SIZE);
}
if (yScale != MIN_Y_SCALE) {
yScale -= (int) ((System.currentTimeMillis() - timeSelected) / SHRINK_RATE);
yScale = Math.max(yScale, MIN_Y_SCALE);
}
if (deltaY != MIN_DELTA_Y) {
deltaY -= (int) ((System.currentTimeMillis() - timeSelected) / SHRINK_RATE);
deltaY = Math.max(deltaY, MIN_Y_SCALE);
}
}
gd.fill(shape);
gd.setColor(getColor());
gd.draw(shape);
String[] words = new String[4];
int i = 0;
for (String s : getVal().allFields().split(",")) {
words[i++] = s;
}
// centers the text for each node
gd.setColor(Color.black);
String first;
String last;
String age = "Age: " + words[2];
String state = "State: " + words[3];
if (black) {
first = "First: " + words[0];
last = "Last: " + words[1];
} else {
first = "First Name: " + words[0];
last = "Last Name: " + words[1];
}
gd.setFont(new Font(FONT_NAME, Font.PLAIN, fontSize));
int alignX = size - 2;
int alignY = fontSize + yScale;
gd.drawString(first, (int) (center.x - alignX), (int) center.y - alignY);
gd.drawString(last, (int) (center.x - alignX), (int) (center.y - alignY + deltaY));
gd.drawString(age, (int) (center.x - alignX), (int) (center.y - alignY + (deltaY * 2)));
gd.drawString(state, (int) (center.x - alignX), (int) center.y - alignY + (deltaY * 3));
}
private int max(int... ints) {
if (ints.length < 1) {
return Integer.MAX_VALUE;
}
int max = ints[0];
for (int i = 1; i < ints.length; i++) {
if (ints[i] > max) {
max = ints[i];
}
}
return max;
}
public void select() {
timeSelected = System.currentTimeMillis();
selected = true;
black = false;
}
public void unselect() {
timeSelected = System.currentTimeMillis();
selected = false;
black = true;
}
public void toggleColor() {
black = !black;
}
private Color getColor() {
if (black) {
return Color.black;
} else {
return Color.red;
}
}
/**
* @param gd
* @param initialPoint
* @param depth
*/
private void prepare(Double initialPoint, boolean rightOfParent) {
double centerOfCircleYCoordinate = initialPoint.getY() + Y_SHIFT;
double centerOfCircleXCoordinate = 1;
if (rightOfParent) {
if (getLkid() != null) {
centerOfCircleXCoordinate += ((NodeShape) getLkid())
.totalNodesInTree();
}
} else {
if (getRkid() != null) {
centerOfCircleXCoordinate += ((NodeShape) getRkid())
.totalNodesInTree();
}
centerOfCircleXCoordinate *= -1;
}
centerOfCircleXCoordinate = centerOfCircleXCoordinate * X_SHIFT
+ initialPoint.getX();
this.center = new Point2D.Double(centerOfCircleXCoordinate, centerOfCircleYCoordinate);
this.shape = new RoundRectangle2D.Double(center.x - size, center.y
- size, size * 2, size * 2, 30, 18);
if (this.getRkid() != null) {
((NodeShape) getRkid()).prepare(center, true);
}
if (this.getLkid() != null) {
((NodeShape) getLkid()).prepare(center, false);
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (black ? 1231 : 1237);
result = prime * result + ((center == null) ? 0 : center.hashCode());
result = prime * result + (selected ? 1231 : 1237);
result = prime * result + ((shape == null) ? 0 : shape.hashCode());
result = prime * result + size;
result = prime * result + (int) (timeSelected ^ (timeSelected >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
NodeShape other = (NodeShape) obj;
if (black != other.black) {
return false;
}
if (center == null) {
if (other.center != null) {
return false;
}
} else if (!center.equals(other.center)) {
return false;
}
if (selected != other.selected) {
return false;
}
if (shape == null) {
if (other.shape != null) {
return false;
}
} else if (!shape.equals(other.shape)) {
return false;
}
if (size != other.size) {
return false;
}
if (timeSelected != other.timeSelected) {
return false;
}
return true;
}
} |
package cx2x.translator.language;
import cx2x.translator.common.ClawConstant;
import cx2x.translator.language.helper.accelerator.AcceleratorDirective;
import cx2x.translator.language.helper.target.Target;
import org.junit.Test;
import java.util.Arrays;
import static org.junit.Assert.assertEquals;
/**
* Test the features of various enumeration in the CLAW translator.
*
* @author clementval
*/
public class ClawEnumTest {
@Test
public void TargetTest() {
assertEquals(Target.CPU, Target.fromString(ClawConstant.TARGET_CPU));
assertEquals(Target.GPU, Target.fromString(ClawConstant.TARGET_GPU));
assertEquals(Target.MIC, Target.fromString(ClawConstant.TARGET_MIC));
assertEquals(Target.CPU, Target.fromString("unknown"));
assertEquals(Target.CPU, Target.fromString(null));
assertEquals(Target.CPU, Target.fromString(""));
assertEquals(Arrays.asList(ClawConstant.TARGET_CPU, ClawConstant.TARGET_GPU,
ClawConstant.TARGET_MIC), Target.availableTargets());
}
@Test
public void AcceleratorDirectiveTest() {
assertEquals(AcceleratorDirective.NONE,
AcceleratorDirective.fromString(ClawConstant.DIRECTIVE_NONE));
assertEquals(AcceleratorDirective.OPENACC,
AcceleratorDirective.fromString(ClawConstant.DIRECTIVE_OPENACC));
assertEquals(AcceleratorDirective.OPENMP,
AcceleratorDirective.fromString(ClawConstant.DIRECTIVE_OPENMP));
assertEquals(AcceleratorDirective.NONE,
AcceleratorDirective.fromString("unknown"));
assertEquals(AcceleratorDirective.NONE,
AcceleratorDirective.fromString(null));
assertEquals(AcceleratorDirective.NONE,
AcceleratorDirective.fromString(""));
assertEquals(Arrays.asList(ClawConstant.DIRECTIVE_NONE,
ClawConstant.DIRECTIVE_OPENACC, ClawConstant.DIRECTIVE_OPENMP),
AcceleratorDirective.availableDirectiveLanguage());
assertEquals(ClawConstant.OPENACC_PREFIX,
AcceleratorDirective.getPrefix(AcceleratorDirective.OPENACC));
assertEquals(ClawConstant.OPENMP_PREFIX,
AcceleratorDirective.getPrefix(AcceleratorDirective.OPENMP));
assertEquals(null,
AcceleratorDirective.getPrefix(AcceleratorDirective.NONE));
assertEquals(null, AcceleratorDirective.getPrefix(null));
}
} |
package org.jgrapes.io.util;
import java.beans.ConstructorProperties;
import java.lang.management.ManagementFactory;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.nio.Buffer;
import java.time.Duration;
import java.util.Collections;
import java.util.HashMap;
import java.util.IntSummaryStatistics;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.WeakHashMap;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiFunction;
import java.util.function.Supplier;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import javax.management.InstanceAlreadyExistsException;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;
import org.jgrapes.core.Components;
import org.jgrapes.core.Components.Timer;
import org.jgrapes.io.IOSubchannel;
import org.jgrapes.io.events.Output;
/**
* A queue based buffer pool. Using buffers from a pool is an important
* feature for limiting the computational resources for an {@link IOSubchannel}.
* A producer of {@link Output} events that simply creates its own buffers
* may produce and enqueue a large number of events that are not consumed
* as fast as they are produced.
*
* Using a buffer pool with a typical size of two synchronizes the
* producer and the consumers of events nicely. The producer
* (thread) holds one buffer and fills it, the consumer (thread) holds
* the other buffer and works with its content. If the producer finishes
* before the consumer, it has to stop until the consumer has processed
* previous event and releases the buffer. The consumer can continue
* without delay, because the data has already been prepared and enqueued
* as the next event.
*
* One of the biggest problems when using a pool can be to identify
* leaking buffers, i.e. buffers that are not properly returned to the pool.
* This implementation therefore tracks all created buffers
* (with a small overhead) and logs a warning if a buffer is no longer
* used (referenced) but has not been returned to the pool. If the
* log level for {@link ManagedBufferPool} is set to {@link Level#FINE},
* the warning also includes a stack trace of the call to {@link #acquire()}
* that handed out the buffer. Providing this information in addition
* obviously requires a larger overhead and is therefore limited to the
* finer log levels.
*
* @param <W> the type of the wrapped (managed) buffer
* @param <T> the type of the content buffer that is wrapped
*/
@SuppressWarnings({ "PMD.ExcessiveImports", "PMD.NcssCount",
"PMD.EmptyCatchBlock" })
public class ManagedBufferPool<W extends ManagedBuffer<T>, T extends Buffer>
implements BufferCollector<W> {
@SuppressWarnings("PMD.FieldNamingConventions")
protected static final Logger logger
= Logger.getLogger(ManagedBufferPool.class.getName());
private static long defaultDrainDelay = 1500;
private static long acquireWarningLimit = 1000;
private String name = Components.objectName(this);
private BiFunction<T, BufferCollector<W>, W> wrapper;
private Supplier<T> bufferFactory;
private BufferMonitor bufferMonitor;
private BlockingQueue<W> queue;
private int bufferSize = -1;
private int preservedBufs;
private int maximumBufs;
private AtomicInteger createdBufs;
private long drainDelay = -1;
private final AtomicReference<Timer> idleTimer
= new AtomicReference<>(null);
/**
* Sets the default delay after which buffers are removed from
* the pool. The default value is 1500ms.
*
* @param delay the delay in ms
*/
public static void setDefaultDrainDelay(long delay) {
defaultDrainDelay = delay;
}
/**
* Returns the default drain delay.
*
* @return the delay
*/
public static long defaultDrainDelay() {
return defaultDrainDelay;
}
/**
* Create a pool that contains a varying number of (wrapped) buffers.
* The pool is initially empty. When buffers are requested and none
* are left in the pool, new buffers are created up to the given
* upper limit. Recollected buffers are put in the pool until it holds
* the number specified by the lower threshold. Any additional
* recollected buffers are discarded.
*
* @param wrapper the function that converts buffers to managed buffers
* @param bufferFactory a function that creates a new buffer
* @param lowerThreshold the number of buffers kept in the pool
* @param upperLimit the maximum number of buffers
*/
public ManagedBufferPool(BiFunction<T, BufferCollector<W>, W> wrapper,
Supplier<T> bufferFactory, int lowerThreshold, int upperLimit) {
this.wrapper = wrapper;
this.bufferFactory = bufferFactory;
preservedBufs = lowerThreshold;
maximumBufs = upperLimit;
createdBufs = new AtomicInteger();
queue = new ArrayBlockingQueue<>(lowerThreshold);
bufferMonitor = new BufferMonitor(upperLimit);
MBeanView.addPool(this);
}
/**
* Create a pool that keeps up to the given number of (wrapped) buffers
* in the pool and also uses that number as upper limit.
*
* @param wrapper the function that converts buffers to managed buffers
* @param bufferFactory a function that creates a new buffer
* @param buffers the number of buffers
*/
public ManagedBufferPool(BiFunction<T, BufferCollector<W>, W> wrapper,
Supplier<T> bufferFactory, int buffers) {
this(wrapper, bufferFactory, buffers, buffers);
}
/**
* Sets a name for this pool (to be used in status reports).
*
* @param name the name
* @return the object for easy chaining
*/
public ManagedBufferPool<W, T> setName(String name) {
this.name = name;
return this;
}
/**
* Returns the name of this pool.
*
* @return the name
*/
public String name() {
return name;
}
/**
* Sets the delay after which buffers are removed from
* the pool.
*
* @param delay the delay
* @return the object for easy chaining
*/
public ManagedBufferPool<W, T> setDrainDelay(long delay) {
this.drainDelay = delay;
return this;
}
private W createBuffer() {
createdBufs.incrementAndGet();
W buffer = wrapper.apply(this.bufferFactory.get(), this);
bufferMonitor.put(buffer, new BufferProperties());
bufferSize = buffer.capacity();
return buffer;
}
/**
* Removes the buffer from the pool.
*
* @param buffer the buffer to remove
*/
private void removeBuffer(W buffer) {
createdBufs.decrementAndGet();
if (bufferMonitor.remove(buffer) == null) {
if (logger.isLoggable(Level.FINE)) {
logger.log(Level.WARNING,
"Attempt to remove unknown buffer from pool.",
new Throwable());
} else {
logger.warning("Attempt to remove unknown buffer from pool.");
}
}
}
/**
* Returns the size of the buffers managed by this pool.
*
* @return the buffer size
*/
public int bufferSize() {
if (bufferSize < 0) {
createBuffer().unlockBuffer();
}
return bufferSize;
}
/**
* Acquires a managed buffer from the pool. If the pool is empty,
* waits for a buffer to become available. The acquired buffer has
* a lock count of one.
*
* @return the acquired buffer
* @throws InterruptedException if the current thread is interrupted
*/
@SuppressWarnings("PMD.GuardLogStatement")
public W acquire() throws InterruptedException {
// Stop draining, because we obviously need this kind of buffers
Optional.ofNullable(idleTimer.getAndSet(null)).ifPresent(
timer -> timer.cancel());
if (createdBufs.get() < maximumBufs) {
// Haven't reached maximum, so if no buffer is queued, create one.
W buffer = queue.poll();
if (buffer != null) {
buffer.lockBuffer();
return buffer;
}
return createBuffer();
}
// Wait for buffer to become available.
if (logger.isLoggable(Level.FINE)) {
// If configured, log message after waiting some time.
W buffer = queue.poll(acquireWarningLimit, TimeUnit.MILLISECONDS);
if (buffer != null) {
buffer.lockBuffer();
return buffer;
}
logger.log(Level.FINE,
Thread.currentThread().getName() + " waiting > "
+ acquireWarningLimit + "ms for buffer, while executing:",
new Throwable());
}
W buffer = queue.take();
buffer.lockBuffer();
return buffer;
}
/**
* Re-adds the buffer to the pool. The buffer is cleared.
*
* @param buffer the buffer
* @see org.jgrapes.io.util.BufferCollector#recollect(org.jgrapes.io.util.ManagedBuffer)
*/
@Override
public void recollect(W buffer) {
if (queue.size() < preservedBufs) {
long effectiveDrainDelay
= drainDelay > 0 ? drainDelay : defaultDrainDelay;
if (effectiveDrainDelay > 0) {
// Enqueue
buffer.clear();
queue.add(buffer);
Timer old = idleTimer.getAndSet(Components.schedule(this::drain,
Duration.ofMillis(effectiveDrainDelay)));
if (old != null) {
old.cancel();
}
return;
}
}
// Discard
removeBuffer(buffer);
}
@SuppressWarnings("PMD.UnusedFormalParameter")
private void drain(Timer timer) {
idleTimer.set(null);
while (true) {
W buffer = queue.poll();
if (buffer == null) {
break;
}
removeBuffer(buffer);
}
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder(50);
builder.append("ManagedBufferPool [");
if (queue != null) {
builder.append("queue=");
builder.append(queue);
}
builder.append(']');
return builder.toString();
}
/**
* Buffer properties.
*/
private static class BufferProperties {
private StackTraceElement[] createdBy;
/**
* Instantiates new buffer properties.
*/
public BufferProperties() {
if (logger.isLoggable(Level.FINE)) {
createdBy = Thread.currentThread().getStackTrace();
}
}
/**
* Returns where the buffer was created.
*
* @return the stack trace element[]
*/
@SuppressWarnings("PMD.MethodReturnsInternalArray")
public StackTraceElement[] createdBy() {
return createdBy;
}
}
/**
* This is basically a WeakHashMap. We cannot use WeakHashMap
* because there is no "hook" into the collection of orphaned
* references, which is what we want here.
*/
@SuppressWarnings("PMD.DataflowAnomalyAnalysis")
private class BufferMonitor {
private Entry<W>[] data;
private int indexMask;
private final ReferenceQueue<W> orphanedEntries
= new ReferenceQueue<>();
/**
* An Entry.
*
* @param <B> the generic type
*/
private class Entry<B extends ManagedBuffer<?>> extends WeakReference<B>
implements Map.Entry<B, BufferProperties> {
/* default */ final int index;
/* default */ BufferProperties props;
/* default */ Entry<B> next;
/**
* Instantiates a new entry.
*
* @param buffer the buffer
* @param props the props
* @param queue the queue
* @param index the index
* @param next the next
*/
/* default */ Entry(B buffer, BufferProperties props,
ReferenceQueue<B> queue, int index, Entry<B> next) {
super(buffer, queue);
this.index = index;
this.props = props;
this.next = next;
}
@Override
public B getKey() {
return get();
}
@Override
public BufferProperties getValue() {
return props;
}
@Override
public BufferProperties setValue(BufferProperties props) {
return this.props = props;
}
}
/**
* @param data
*/
@SuppressWarnings("unchecked")
public BufferMonitor(int maxBuffers) {
int lists = 1;
while (lists < maxBuffers) {
lists <<= 1;
indexMask = (indexMask << 1) + 1;
}
data = new Entry[lists];
}
/**
* Put an entry in the map.
*
* @param buffer the buffer
* @param properties the properties
* @return the buffer properties
*/
@SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
public BufferProperties put(W buffer, BufferProperties properties) {
check();
int index = buffer.hashCode() & indexMask;
synchronized (data) {
Entry<W> entry = data[index];
Entry<W> prev = null;
while (true) {
if (entry == null) {
// Not found, create new.
entry = new Entry<>(buffer, properties,
orphanedEntries, index, null);
if (prev == null) {
data[index] = entry; // Is first.
} else {
prev.next = entry; // Is next (last).
}
return properties;
}
if (entry.getKey() == buffer) {
// Found, update.
BufferProperties old = entry.getValue();
entry.setValue(properties);
return old;
}
prev = entry;
entry = entry.next;
}
}
}
/**
* Returns the properties for the given buffer.
*
* @param buffer the buffer
* @return the buffer properties
*/
@SuppressWarnings("unused")
public BufferProperties get(ManagedBuffer<?> buffer) {
check();
int index = buffer.hashCode() & indexMask;
synchronized (data) {
Entry<W> entry = data[index];
while (entry != null) {
if (entry.getKey() == buffer) {
return entry.getValue();
}
entry = entry.next;
}
return null;
}
}
/**
* Removes the given buffer.
*
* @param buffer the buffer
* @return the buffer properties
*/
public BufferProperties remove(ManagedBuffer<?> buffer) {
check();
int index = buffer.hashCode() & indexMask;
synchronized (data) {
Entry<W> entry = data[index];
Entry<W> prev = null;
while (entry != null) {
if (entry.getKey() == buffer) {
if (prev == null) {
data[index] = entry.next; // Was first.
} else {
prev.next = entry.next;
}
return entry.getValue();
}
prev = entry;
entry = entry.next;
}
return null;
}
}
@SuppressWarnings("PMD.CompareObjectsWithEquals")
private BufferProperties remove(Entry<W> toBeRemoved) {
synchronized (data) {
Entry<W> entry = data[toBeRemoved.index];
Entry<W> prev = null;
while (entry != null) {
if (entry == toBeRemoved) {
if (prev == null) {
data[toBeRemoved.index] = entry.next; // Was first.
} else {
prev.next = entry.next;
}
return entry.getValue();
}
prev = entry;
entry = entry.next;
}
return null;
}
}
private void check() {
while (true) {
@SuppressWarnings("unchecked")
Entry<W> entry = (Entry<W>) orphanedEntries.poll();
if (entry == null) {
return;
}
// Managed buffer has not been properly recollected, fix.
BufferProperties props = remove(entry);
if (props == null) {
return;
}
createdBufs.decrementAndGet();
// Create warning
if (logger.isLoggable(Level.WARNING)) {
@SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
final StringBuilder msg = new StringBuilder(
"Orphaned buffer from pool ");
msg.append(name());
StackTraceElement[] trace = props.createdBy();
if (trace != null) {
msg.append(", created");
for (StackTraceElement e : trace) {
msg.append(System.lineSeparator());
msg.append("\tat ");
msg.append(e.toString());
}
}
logger.warning(msg.toString());
}
}
}
}
/**
* An MBean interface for getting information about the managed
* buffer pools. Note that created buffer pools are tracked using
* weak references. Therefore, the MBean may report more pools than
* are really in use.
*/
public interface ManagedBufferPoolMXBean {
/**
* Information about a single managed pool.
*/
@SuppressWarnings("PMD.DataClass")
class PoolInfo {
private final int created;
private final int pooled;
private final int preserved;
private final int maximum;
private final int bufferSize;
/**
* Instantiates a new pool info.
*
* @param created the created
* @param pooled the pooled
* @param preserved the preserved
* @param maximum the maximum
* @param bufferSize the buffer size
*/
@ConstructorProperties({ "created", "pooled",
"preserved", "maximum", "bufferSize" })
public PoolInfo(int created, int pooled,
int preserved, int maximum, int bufferSize) {
this.created = created;
this.pooled = pooled;
this.preserved = preserved;
this.maximum = maximum;
this.bufferSize = bufferSize;
}
public int getCreated() {
return created;
}
/**
* The number of buffers pooled (ready to be acquired).
*
* @return the value
*/
public int getPooled() {
return pooled;
}
/**
* The number of buffers preserved.
*
* @return the value
*/
public int getPreserved() {
return preserved;
}
public int getMaximum() {
return maximum;
}
/**
* The size of the buffers in items.
*
* @return the buffer size
*/
public int getBufferSize() {
return bufferSize;
}
}
/**
* Three views on the existing pool.
*/
class PoolInfos {
private final SortedMap<String, PoolInfo> allPools;
private final SortedMap<String, PoolInfo> nonEmptyPools;
private final SortedMap<String, PoolInfo> usedPools;
/**
* Instantiates a new pool infos.
*
* @param pools the pools
*/
public PoolInfos(Set<ManagedBufferPool<?, ?>> pools) {
allPools = new TreeMap<>();
nonEmptyPools = new TreeMap<>();
usedPools = new TreeMap<>();
@SuppressWarnings("PMD.UseConcurrentHashMap")
Map<String, Integer> dupsNext = new HashMap<>();
for (ManagedBufferPool<?, ?> mbp : pools) {
String key = mbp.name();
PoolInfo infos = new PoolInfo(
mbp.createdBufs.get(), mbp.queue.size(),
mbp.preservedBufs, mbp.maximumBufs,
mbp.bufferSize());
if (allPools.containsKey(key)
|| dupsNext.containsKey(key)) {
if (allPools.containsKey(key)) {
// Found first duplicate, rename
allPools.put(key + "#1", allPools.get(key));
allPools.remove(key);
dupsNext.put(key, 2);
}
allPools.put(key + "
+ (dupsNext.put(key, dupsNext.get(key) + 1)),
infos);
} else {
allPools.put(key, infos);
}
}
for (Map.Entry<String, PoolInfo> e : allPools.entrySet()) {
PoolInfo infos = e.getValue();
if (infos.getPooled() > 0) {
nonEmptyPools.put(e.getKey(), infos);
}
if (infos.getCreated() > 0) {
usedPools.put(e.getKey(), infos);
}
}
}
/**
* All pools.
*
* @return the all pools
*/
public SortedMap<String, PoolInfo> getAllPools() {
return allPools;
}
/**
* Pools that have at least managed buffer enqueued
* (ready to be acquired).
*
* @return the non empty pools
*/
public SortedMap<String, PoolInfo> getNonEmptyPools() {
return nonEmptyPools;
}
/**
* Pools that have at least one associated buffer
* (in pool or in use).
*
* @return the used pools
*/
public SortedMap<String, PoolInfo> getUsedPools() {
return usedPools;
}
}
/**
* Set the default drain delay.
*
* @param millis the drain delay in milli seconds
*/
void setDefaultDrainDelay(long millis);
/**
* Returns the drain delay in milli seconds.
*
* @return the value
*/
long getDefaultDrainDelay();
/**
* Set the acquire warning limit.
*
* @param millis the limit
*/
void setAcquireWarningLimit(long millis);
/**
* Returns the acquire warning limit.
*
* @return the value
*/
long getAcquireWarningLimit();
/**
* Informations about the pools.
*
* @return the map
*/
PoolInfos getPoolInfos();
/**
* Summary information about the pooled buffers.
*
* @return the values
*/
IntSummaryStatistics getPooledPerPoolStatistics();
/**
* Summary information about the created buffers.
*
* @return the values
*/
IntSummaryStatistics getCreatedPerPoolStatistics();
}
/**
* The MBean view
*/
private static class MBeanView implements ManagedBufferPoolMXBean {
private static Set<ManagedBufferPool<?, ?>> allPools
= Collections.synchronizedSet(
Collections.newSetFromMap(
new WeakHashMap<ManagedBufferPool<?, ?>, Boolean>()));
/**
* Adds the pool.
*
* @param pool the pool
*/
public static void addPool(ManagedBufferPool<?, ?> pool) {
allPools.add(pool);
}
@Override
public void setDefaultDrainDelay(long millis) {
ManagedBufferPool.setDefaultDrainDelay(millis);
}
@Override
public long getDefaultDrainDelay() {
return ManagedBufferPool.defaultDrainDelay();
}
@Override
public void setAcquireWarningLimit(long millis) {
ManagedBufferPool.acquireWarningLimit = millis;
}
@Override
public long getAcquireWarningLimit() {
return ManagedBufferPool.acquireWarningLimit;
}
@Override
public PoolInfos getPoolInfos() {
return new PoolInfos(allPools);
}
@Override
public IntSummaryStatistics getPooledPerPoolStatistics() {
return allPools.stream().collect(
Collectors.summarizingInt(mbp -> mbp.queue.size()));
}
@Override
public IntSummaryStatistics getCreatedPerPoolStatistics() {
return allPools.stream().collect(
Collectors.summarizingInt(mbp -> mbp.createdBufs.get()));
}
}
static {
try {
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
ObjectName mxbeanName = new ObjectName("org.jgrapes.io:type="
+ ManagedBufferPool.class.getSimpleName() + "s");
mbs.registerMBean(new MBeanView(), mxbeanName);
} catch (MalformedObjectNameException | InstanceAlreadyExistsException
| MBeanRegistrationException | NotCompliantMBeanException e) {
// Does not happen
}
}
} |
package org.drools.base.mvel;
import org.mvel.MVELRuntime;
import org.mvel.debug.Debugger;
import org.mvel.debug.Frame;
/**
* Debug Handler for MVEL dialect.
*
* Takes care of registering breakpoints and calling required methods
* to trigger eclipse debugger to keep breakpoints in sync etc.
*
* @author Ahti Kitsik
*
*/
public final class MVELDebugHandler {
private static int onBreakReturn = Debugger.CONTINUE;
public final static String DEBUG_LAUNCH_KEY="mvel.debugger";
private static Boolean debugMode = null;
public static final boolean verbose = true;
static {
MVELRuntime.setThreadDebugger(new MVELDebugger());
}
/**
* Notify remote debugger that runtime is ready to get latest breakpoint
* information
*
*/
public static void receiveBreakpoints() {
}
/**
* This is catched by the remote debugger
*
* @param frame
*/
private final static int onBreak(Frame frame) {
// We always fall back to Debugger.CONTINUE after each onBreak to avoid eternal step-over flag
//int oldReturn = onBreakReturn;
//onBreakReturn = Debugger.CONTINUE;
//return oldReturn;
if (verbose) {
System.out.println("Continuing with "+(onBreakReturn==Debugger.CONTINUE?"continue":"step-over"));
}
return onBreakReturn;
}
protected final static void registerBreakpoint(String sourceName, int lineNumber) {
if (verbose) {
System.out.println("Registering breakpoint for "+sourceName+":"+lineNumber);
}
MVELRuntime.registerBreakpoint( sourceName, lineNumber );
}
protected final static void clearAllBreakpoints() {
if (verbose) {
System.out.println("Clearing all breakpoints");
}
MVELRuntime.clearAllBreakpoints();
}
protected final static void removeBreakpoint(String sourceName, int lineNumber) {
if (verbose) {
System.out.println("Removing breakpoint from "+sourceName+":"+lineNumber);
}
MVELRuntime.removeBreakpoint( sourceName, lineNumber );
}
private static class MVELDebugger implements Debugger {
public MVELDebugger() {
}
public int onBreak(Frame frame) {
if (verbose) {
System.out.println("onBreak call for "+frame.getSourceName()+":"+frame.getLineNumber());
}
return MVELDebugHandler.onBreak(frame);
// This call is supposed to be catched by the remote debugger
}
}
protected final static void setOnBreakReturn(int value) {
onBreakReturn = value;
}
/**
* Do nothing for now. ensures that class is loaded prior debug handler
*/
public static void prepare() {
//do nothing
}
/**
* Returns current debug mode.<br/>
* Holds lazy initialized internal reference to improve performance.<br/>
* Therefore you can't change System property "mvel.debugger" after isDebugMode is called at least once.<br/>
* <br/>
* To update debug mode at runtime use {@link MVELDebugHandler#setDebugMode(boolean)}<br/>
* @return <code>true</code> if debug mode is enabled.
*/
public static boolean isDebugMode() {
if (debugMode==null) {
debugMode = Boolean.valueOf(System.getProperty(DEBUG_LAUNCH_KEY));
}
return debugMode.booleanValue();
}
/**
* Sets debug mode on/off.<br/>
* Updates local MVELDebugHandler property and System property "mvel.debugger"<br/>
* <br/>
* There's no need to ever call this method unless you write junit tests!<br/>
*
* @param b is Debug enabled?
*/
public static void setDebugMode(boolean b) {
debugMode = Boolean.valueOf( b );
System.setProperty( DEBUG_LAUNCH_KEY, debugMode.toString());
}
} |
package org.jgrapes.io.util;
import java.beans.ConstructorProperties;
import java.lang.management.ManagementFactory;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.nio.Buffer;
import java.time.Duration;
import java.util.AbstractMap;
import java.util.Collections;
import java.util.HashMap;
import java.util.IntSummaryStatistics;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.WeakHashMap;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiFunction;
import java.util.function.Supplier;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import javax.management.InstanceAlreadyExistsException;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;
import org.jgrapes.core.Components;
import org.jgrapes.core.Components.Timer;
import org.jgrapes.io.IOSubchannel;
import org.jgrapes.io.events.Output;
/**
* A queue based buffer pool. Using buffers from a pool is an important
* feature for limiting the computational resources for an {@link IOSubchannel}.
* A producer of {@link Output} events that simply creates its own buffers
* may produce and enqueue a large number of events that are not consumed
* as fast as they are produced.
*
* Using a buffer pool with a typical size of two synchronizes the
* producer and the consumers of events nicely. The producer
* (thread) holds one buffer and fills it, the consumer (thread) holds
* the other buffer and works with its content. If the producer finishes
* before the consumer, it has to stop until the consumer has processed
* previous event and releases the buffer. The consumer can continue
* without delay, because the data has already been prepared and enqueued
* as the next event.
*
* One of the biggest problems when using a pool can be to identify
* leaking buffers, i.e. buffers that are not properly returned to the pool.
* This implementation therefore tracks all created buffers
* (with a small overhead) and logs a warning if a buffer is no longer
* used (referenced) but has not been returned to the pool. If the
* log level for {@link ManagedBufferPool} is set to {@link Level#FINE},
* the warning also includes a stack trace of the call to {@link #acquire()}
* that handed out the buffer. Providing this information in addition
* obviously requires a larger overhead and is therefore limited to the
* finer log levels.
*
* @param <W> the type of the wrapped (managed) buffer
* @param <T> the type of the content buffer that is wrapped
*/
public class ManagedBufferPool<W extends ManagedBuffer<T>, T extends Buffer>
implements BufferCollector<W> {
protected static final Logger logger
= Logger.getLogger(ManagedBufferPool.class.getName());
private static long defaultDrainDelay = 1500;
private static long acquireWarningLimit = 1000;
private String name = Components.objectName(this);
private BiFunction<T, BufferCollector<W>,W> wrapper = null;
private Supplier<T> bufferFactory = null;
private BufferMonitor bufferMonitor;
private BlockingQueue<W> queue;
private int bufferSize = -1;
private int preservedBufs;
private int maximumBufs;
private AtomicInteger createdBufs;
private long drainDelay = -1;
private AtomicReference<Timer> idleTimer = new AtomicReference<>(null);
/**
* Sets the default delay after which buffers are removed from
* the pool. The default value is 1500ms.
*
* @param delay the delay in ms
*/
public static void setDefaultDrainDelay(long delay) {
defaultDrainDelay = delay;
}
/**
* Returns the default drain delay.
*
* @return the delay
*/
public static long defaultDrainDelay() {
return defaultDrainDelay;
}
/**
* Create a pool that contains a varying number of (wrapped) buffers.
* The pool is initially empty. When buffers are requested and none
* are left in the pool, new buffers are created up to the given
* upper limit. Recollected buffers are put in the pool until it holds
* the number specified by the lower threshold. Any additional
* recollected buffers are discarded.
*
* @param wrapper the function that converts buffers to managed buffers
* @param bufferFactory a function that creates a new buffer
* @param lowerThreshold the number of buffers kept in the pool
* @param upperLimit the maximum number of buffers
*/
public ManagedBufferPool(BiFunction<T,BufferCollector<W>, W> wrapper,
Supplier<T> bufferFactory, int lowerThreshold, int upperLimit) {
this.wrapper = wrapper;
this.bufferFactory = bufferFactory;
preservedBufs = lowerThreshold;
maximumBufs = upperLimit;
createdBufs = new AtomicInteger();
queue = new ArrayBlockingQueue<W>(lowerThreshold);
bufferMonitor = new BufferMonitor(upperLimit);
MBeanView.addPool(this);
}
/**
* Create a pool that keeps up to the given number of (wrapped) buffers
* in the pool and also uses that number as upper limit.
*
* @param wrapper the function that converts buffers to managed buffers
* @param bufferFactory a function that creates a new buffer
* @param buffers the number of buffers
*/
public ManagedBufferPool(BiFunction<T,BufferCollector<W>, W> wrapper,
Supplier<T> bufferFactory, int buffers) {
this(wrapper, bufferFactory, buffers, buffers);
}
/**
* Sets a name for this pool (to be used in status reports).
*
* @param name the name
* @return the object for easy chaining
*/
public ManagedBufferPool<W, T> setName(String name) {
this.name = name;
return this;
}
/**
* Returns the name of this pool.
*
* @return the name
*/
public String name() {
return name;
}
/**
* Sets the delay after which buffers are removed from
* the pool.
*
* @param delay the delay
* @return the object for easy chaining
*/
public ManagedBufferPool<W, T> setDrainDelay(long delay) {
this.drainDelay = delay;
return this;
}
private W createBuffer() {
createdBufs.incrementAndGet();
W buffer = wrapper.apply(this.bufferFactory.get(), this);
bufferMonitor.put(buffer, new BufferProperties());
bufferSize = buffer.capacity();
return buffer;
}
/**
* Removes the buffer from the pool.
*
* @param buffer the buffer to remove
*/
private void removeBuffer(W buffer) {
createdBufs.decrementAndGet();
if (bufferMonitor.remove(buffer) == null) {
if (logger.isLoggable(Level.FINE)) {
logger.log(Level.WARNING,
"Attempt to remove unknown buffer from pool.",
new Throwable());
} else {
logger.warning("Attempt to remove unknown buffer from pool.");
}
}
}
/**
* Returns the size of the buffers managed by this pool.
*
* @return the buffer size
*/
public int bufferSize() {
if (bufferSize < 0) {
createBuffer().unlockBuffer();
}
return bufferSize;
}
/**
* Acquires a managed buffer from the pool. If the pool is empty,
* waits for a buffer to become available. The acquired buffer has
* a lock count of one.
*
* @return the acquired buffer
* @throws InterruptedException if the current thread is interrupted
*/
public W acquire() throws InterruptedException {
// Stop draining, because we obviously need this kind of buffers
Optional.ofNullable(idleTimer.getAndSet(null)).ifPresent(
timer -> timer.cancel());
if (createdBufs.get() < maximumBufs) {
// Haven't reached maximum, so if no buffer is queued, create one.
W buffer = queue.poll();
if (buffer != null) {
buffer.lockBuffer();
return buffer;
}
return createBuffer();
}
// Wait for buffer to become available.
if (logger.isLoggable(Level.FINE)) {
// If configured, log message after waiting some time.
W buffer = queue.poll(acquireWarningLimit, TimeUnit.MILLISECONDS);
if (buffer != null) {
buffer.lockBuffer();
return buffer;
}
logger.fine("Waiting > " + acquireWarningLimit + "ms for buffer: "
+ Thread.currentThread().getName());
}
W buffer = queue.take();
buffer.lockBuffer();
return buffer;
}
/**
* Re-adds the buffer to the pool. The buffer is cleared.
*
* @see org.jgrapes.io.util.BufferCollector#recollect(org.jgrapes.io.util.ManagedBuffer)
*/
@Override
public void recollect(W buffer) {
if (queue.size() < preservedBufs) {
long effectiveDrainDelay
= drainDelay > 0 ? drainDelay : defaultDrainDelay;
if (effectiveDrainDelay > 0) {
// Enqueue
buffer.clear();
queue.add(buffer);
Timer old = idleTimer.getAndSet(Components.schedule(this::drain,
Duration.ofMillis(effectiveDrainDelay)));
if (old != null) {
old.cancel();
}
return;
}
}
// Discard
removeBuffer(buffer);
}
private void drain(Timer timer) {
idleTimer.set(null);
while(true) {
W buffer = queue.poll();
if (buffer == null) {
break;
}
removeBuffer(buffer);
}
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("ManagedBufferPool [");
if (queue != null) {
builder.append("queue=");
builder.append(queue);
}
builder.append("]");
return builder.toString();
}
private static class BufferProperties {
private StackTraceElement[] createdBy;
public BufferProperties() {
if (logger.isLoggable(Level.FINE)) {
createdBy = Thread.currentThread().getStackTrace();
}
}
public StackTraceElement[] createdBy() {
return createdBy;
}
}
private class BufferMonitor {
private List<Map.Entry<WeakReference<W>,
BufferProperties>>[] data;
private int indexMask = 0;
private ReferenceQueue<ManagedBuffer<?>> orphanedBuffers
= new ReferenceQueue<>();
/**
* @param data
*/
@SuppressWarnings("unchecked")
public BufferMonitor(int maxBuffers) {
int lists = 1;
while (lists < maxBuffers) {
lists <<= 1;
indexMask = (indexMask << 1) + 1;
}
data = (List<Map.Entry<WeakReference<W>,BufferProperties>>[])
new List[lists];
}
public BufferProperties put(W buffer, BufferProperties bufferMonitor) {
check();
int index = buffer.hashCode() & indexMask;
List<Map.Entry<WeakReference<W>,BufferProperties>> list;
synchronized(data) {
list = data[index];
if (list == null) {
list = data[index] = new LinkedList<>();
}
}
synchronized(list) {
for (Map.Entry<WeakReference<W>,BufferProperties> entry: list) {
if (entry.getKey().get() == buffer) {
BufferProperties old = entry.getValue();
entry.setValue(bufferMonitor);
return old;
}
}
list.add(new AbstractMap.SimpleEntry<>(
new WeakReference<>(buffer, orphanedBuffers), bufferMonitor));
}
return null;
}
@SuppressWarnings("unused")
public BufferProperties get(ManagedBuffer<?> buffer) {
check();
int index = buffer.hashCode() & indexMask;
List<Map.Entry<WeakReference<W>,BufferProperties>> list = data[index];
if (list == null) {
return null;
}
synchronized(list) {
for (Iterator<Map.Entry<WeakReference<W>,BufferProperties>>
itr = list.iterator(); itr.hasNext();) {
Map.Entry<WeakReference<W>,BufferProperties> entry = itr.next();
if (entry.getKey().get() == buffer) {
return entry.getValue();
}
}
}
return null;
}
public BufferProperties remove(ManagedBuffer<?> buffer) {
check();
int index = buffer.hashCode() & indexMask;
List<Map.Entry<WeakReference<W>,BufferProperties>> list = data[index];
if (list == null) {
return null;
}
synchronized(list) {
for (Iterator<Map.Entry<WeakReference<W>,BufferProperties>>
itr = list.iterator(); itr.hasNext();) {
Map.Entry<WeakReference<W>,BufferProperties> entry = itr.next();
if (entry.getKey().get() == buffer) {
BufferProperties value = entry.getValue();
itr.remove();
return value;
}
}
}
return null;
}
private void check() {
while (true) {
Reference<? extends ManagedBuffer<?>> ref = orphanedBuffers.poll();
if (ref == null) {
return;
}
ManagedBuffer<?> buffer = ref.get();
// Managed buffer has not been properly recollected, fix.
createdBufs.decrementAndGet();
BufferProperties props = remove(buffer);
// Create warning
if (logger.isLoggable(Level.WARNING)) {
final StringBuilder msg = new StringBuilder(
"Orphaned buffer from pool " + name());
StackTraceElement[] st = props.createdBy();
if (st != null) {
msg.append(", created");
for (StackTraceElement e: st) {
msg.append(System.lineSeparator());
msg.append("\tat ");
msg.append(e.toString());
}
}
logger.warning(msg.toString());
}
}
}
}
/**
* An MBean interface for getting information about the managed
* buffer pools. Note that created buffer pools are tracked using
* weak references. Therefore, the MBean may report more pools than
* are really in use.
*/
public static interface ManagedBufferPoolMXBean {
/**
* Information about a single managed pool.
*/
public static class PoolInfo {
private int created;
private int pooled;
private int bufferSize;
@ConstructorProperties({"created", "pooled", "bufferSize"})
public PoolInfo(int created, int pooled, int bufferSize) {
this.created = created;
this.pooled = pooled;
this.bufferSize = bufferSize;
}
public int getCreated() {
return created;
}
/**
* The number of buffers pooled (ready to be acquired).
*
* @return the value
*/
public int getPooled() {
return pooled;
}
/**
* The size of the buffers in items.
*
* @return the buffer size
*/
public int getBufferSize() {
return bufferSize;
}
}
/**
* Three views on the existing pool.
*/
public static class PoolInfos {
private SortedMap<String,PoolInfo> allPools;
private SortedMap<String,PoolInfo> nonEmptyPools;
private SortedMap<String,PoolInfo> usedPools;
public PoolInfos(Set<ManagedBufferPool<?, ?>> pools) {
allPools = new TreeMap<>();
nonEmptyPools = new TreeMap<>();
usedPools = new TreeMap<>();
Map<String, Integer> dupsNext = new HashMap<>();
for (ManagedBufferPool<?,?> mbp: pools) {
String key = mbp.name();
PoolInfo qi = new PoolInfo(
mbp.createdBufs.get(), mbp.queue.size(), mbp.bufferSize());
if (allPools.containsKey(key) || dupsNext.containsKey(key)) {
if (allPools.containsKey(key)) {
// Found first duplicate, rename
allPools.put(key + "#1", allPools.get(key));
allPools.remove(key);
dupsNext.put(key, 2);
}
allPools.put(key + "
+ (dupsNext.put(key, dupsNext.get(key) + 1)), qi);
} else {
allPools.put(key, qi);
}
}
for (Map.Entry<String,PoolInfo> e: allPools.entrySet()) {
PoolInfo qi = e.getValue();
if (qi.getPooled() > 0) {
nonEmptyPools.put(e.getKey(), qi);
}
if (qi.getCreated() > 0) {
usedPools.put(e.getKey(), qi);
}
}
}
/**
* All pools.
*/
public SortedMap<String, PoolInfo> getAllPools() {
return allPools;
}
/**
* Pools that have at least managed buffer enqueued
* (ready to be acquired).
*/
public SortedMap<String, PoolInfo> getNonEmptyPools() {
return nonEmptyPools;
}
/**
* Pools that have at least one associated buffer
* (in pool or in use).
*/
public SortedMap<String, PoolInfo> getUsedPools() {
return usedPools;
}
}
/**
* Set the default drain delay.
*
* @param millis the drain delay in milli seconds
*/
void setDefaultDrainDelay(long millis);
/**
* Returns the drain delay in milli seconds.
*
* @return the value
*/
long getDefaultDrainDelay();
/**
* Set the acquire warning limit.
*
* @param millis the limit
*/
void setAcquireWarningLimit(long millis);
/**
* Returns the acquire warning limit.
*
* @return the value
*/
long getAcquireWarningLimit();
/**
* Informations about the pools.
*
* @return the map
*/
PoolInfos getPoolInfos();
/**
* Summary information about the pooled buffers.
*
* @return the values
*/
IntSummaryStatistics getPooledPerPoolStatistics();
/**
* Summary information about the created buffers.
*
* @return the values
*/
IntSummaryStatistics getCreatedPerPoolStatistics();
}
private static class MBeanView implements ManagedBufferPoolMXBean {
private static Set<ManagedBufferPool<?,?>> allPools
= Collections.synchronizedSet(
Collections.newSetFromMap(
new WeakHashMap<ManagedBufferPool<?, ?>, Boolean>()));
public static void addPool(ManagedBufferPool<?, ?> pool) {
allPools.add(pool);
}
@Override
public void setDefaultDrainDelay(long millis) {
ManagedBufferPool.setDefaultDrainDelay(millis);
}
@Override
public long getDefaultDrainDelay() {
return ManagedBufferPool.defaultDrainDelay();
}
@Override
public void setAcquireWarningLimit(long millis) {
ManagedBufferPool.acquireWarningLimit = millis;
}
@Override
public long getAcquireWarningLimit() {
return ManagedBufferPool.acquireWarningLimit;
}
@Override
public PoolInfos getPoolInfos() {
return new PoolInfos(allPools);
}
@Override
public IntSummaryStatistics getPooledPerPoolStatistics() {
return allPools.stream().collect(
Collectors.summarizingInt(mbp -> mbp.queue.size()));
}
@Override
public IntSummaryStatistics getCreatedPerPoolStatistics() {
return allPools.stream().collect(
Collectors.summarizingInt(mbp -> mbp.createdBufs.get()));
}
}
static {
try {
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
ObjectName mxbeanName = new ObjectName("org.jgrapes.io:type="
+ ManagedBufferPool.class.getSimpleName());
mbs.registerMBean(new MBeanView(), mxbeanName);
} catch (MalformedObjectNameException | InstanceAlreadyExistsException
| MBeanRegistrationException | NotCompliantMBeanException e) {
// Does not happen
}
}
} |
/**
* @author Almas Baimagambetov (almaslvl@gmail.com)
*/
// module info required for customLaunch to function correctly
open module com.almasb.fxgl.nativesamples {
requires com.almasb.fxgl.all;
} |
package com.gh4a.utils;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.customtabs.CustomTabsIntent;
import android.support.v4.os.ParcelableCompat;
import android.support.v4.os.ParcelableCompatCreatorCallbacks;
import android.widget.Toast;
import com.gh4a.R;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
public class IntentUtils {
public static void launchBrowser(Context context, Uri uri) {
launchBrowser(context, uri, 0);
}
public static void launchBrowser(Context context, Uri uri, int flags) {
Intent intent = createBrowserIntent(context, uri);
if (intent != null) {
intent.addFlags(flags);
context.startActivity(intent);
} else {
Toast.makeText(context, R.string.no_browser_found, Toast.LENGTH_LONG).show();
}
}
// We want to forward the URI to a browser, but our own intent filter matches
// the browser's intent filters. We therefore resolve the intent by ourselves,
// strip our own entry from the list and pass the result to the system's
// activity chooser.
// When doing that, pass a dummy URI to the resolver and swap in our real URI
// later, as otherwise the system might return our package only if it's set
// to handle the Github URIs by default
private static Uri buildDummyUri(Uri uri) {
return uri.buildUpon().authority("www.somedummy.com").build();
}
private static Intent createBrowserIntent(Context context, Uri uri) {
final Uri dummyUri = buildDummyUri(uri);
final Intent browserIntent = new Intent(Intent.ACTION_VIEW, dummyUri)
.addCategory(Intent.CATEGORY_BROWSABLE);
return createActivityChooserIntent(context, browserIntent, uri);
}
public static Intent createViewerOrBrowserIntent(Context context, Uri uri, String mime) {
final Uri dummyUri = buildDummyUri(uri);
final Intent viewIntent = new Intent(Intent.ACTION_VIEW).setDataAndType(dummyUri, mime);
final Intent resolvedViewIntent = createActivityChooserIntent(context, viewIntent, uri);
if (resolvedViewIntent != null) {
return resolvedViewIntent;
}
return createBrowserIntent(context, uri);
}
public static void openInCustomTabOrBrowser(Activity activity, Uri uri) {
String pkg = CustomTabsHelper.getPackageNameToUse(activity);
if (pkg != null) {
int color = UiUtils.resolveColor(activity, R.attr.colorPrimary);
CustomTabsIntent i = new CustomTabsIntent.Builder()
.setToolbarColor(color)
.build();
i.intent.setPackage(pkg);
i.intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.launchUrl(activity, uri);
} else {
launchBrowser(activity, uri, Intent.FLAG_ACTIVITY_NEW_TASK);
}
}
public static void share(Context context, String subject, String url) {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
shareIntent.putExtra(Intent.EXTRA_TEXT, url);
context.startActivity(
Intent.createChooser(shareIntent, context.getString(R.string.share_title)));
}
private static Intent createActivityChooserIntent(Context context, Intent intent, Uri uri) {
final PackageManager pm = context.getPackageManager();
final List<ResolveInfo> activities = pm.queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
final ArrayList<Intent> chooserIntents = new ArrayList<>();
final String ourPackageName = context.getPackageName();
Collections.sort(activities, new ResolveInfo.DisplayNameComparator(pm));
for (ResolveInfo resInfo : activities) {
ActivityInfo info = resInfo.activityInfo;
if (!info.enabled || !info.exported) {
continue;
}
if (info.packageName.equals(ourPackageName)) {
continue;
}
Intent targetIntent = new Intent(intent);
targetIntent.setPackage(info.packageName);
targetIntent.setDataAndType(uri, intent.getType());
chooserIntents.add(targetIntent);
}
if (chooserIntents.isEmpty()) {
return null;
}
final Intent lastIntent = chooserIntents.remove(chooserIntents.size() - 1);
if (chooserIntents.isEmpty()) {
// there was only one, no need to show the chooser
return lastIntent;
}
Intent chooserIntent = Intent.createChooser(lastIntent, null);
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS,
chooserIntents.toArray(new Intent[chooserIntents.size()]));
return chooserIntent;
}
public static class InitialCommentMarker implements Parcelable {
public final long commentId;
public final Date date;
public InitialCommentMarker(long commentId) {
this(commentId, null);
}
public InitialCommentMarker(Date date) {
this(-1, date);
}
private InitialCommentMarker(long commentId, Date date) {
this.commentId = commentId;
this.date = date;
}
public boolean matches(long id, Date date) {
if (commentId >= 0 && id >= 0) {
return commentId == id;
}
if (date != null && this.date != null) {
return date.after(this.date);
}
return false;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel out, int flags) {
out.writeLong(commentId);
out.writeLong(date != null ? date.getTime() : -1);
}
public static final Parcelable.Creator<InitialCommentMarker> CREATOR =
ParcelableCompat.newCreator(new ParcelableCompatCreatorCallbacks<InitialCommentMarker>() {
@Override
public InitialCommentMarker createFromParcel(Parcel in, ClassLoader loader) {
long commentId = in.readLong();
long timeMillis = in.readLong();
return new InitialCommentMarker(commentId,
timeMillis != -1 ? new Date(timeMillis) : null);
}
@Override
public InitialCommentMarker[] newArray(int size) {
return new InitialCommentMarker[size];
}
});
}
} |
/* -*- mode: jde; c-basic-offset: 2; indent-tabs-mode: nil -*- */
package processing.app.debug;
import processing.app.Base;
import processing.app.Preferences;
import processing.app.Serial;
import processing.app.SerialException;
import java.io.*;
import java.util.*;
import java.util.zip.*;
import javax.swing.*;
import gnu.io.*;
public class AvrdudeUploader extends Uploader {
public AvrdudeUploader() {
}
public boolean uploadUsingPreferences(String buildPath, String className, boolean usingProgrammer)
throws RunnerException, SerialException {
this.verbose = verbose;
Map<String, String> boardPreferences = Base.getBoardPreferences();
// if no protocol is specified for this board, assume it lacks a
// bootloader and upload using the selected programmer.
if (usingProgrammer || boardPreferences.get("upload.protocol") == null) {
String programmer = Preferences.get("programmer");
Target target = Base.getTarget();
if (programmer.indexOf(":") != -1) {
target = Base.targetsTable.get(programmer.substring(0, programmer.indexOf(":")));
programmer = programmer.substring(programmer.indexOf(":") + 1);
}
Collection params = getProgrammerCommands(target, programmer);
params.add("-Uflash:w:" + buildPath + File.separator + className + ".hex:i");
return avrdude(params);
}
return uploadViaBootloader(buildPath, className);
}
private boolean uploadViaBootloader(String buildPath, String className)
throws RunnerException, SerialException {
Map<String, String> boardPreferences = Base.getBoardPreferences();
List commandDownloader = new ArrayList();
String protocol = boardPreferences.get("upload.protocol");
// avrdude wants "stk500v1" to distinguish it from stk500v2
if (protocol.equals("stk500"))
protocol = "stk500v1";
commandDownloader.add("-c" + protocol);
commandDownloader.add(
"-P" + (Base.isWindows() ? "\\\\.\\" : "") + Preferences.get("serial.port"));
commandDownloader.add(
"-b" + Integer.parseInt(boardPreferences.get("upload.speed")));
commandDownloader.add("-D"); // don't erase
commandDownloader.add("-Uflash:w:" + buildPath + File.separator + className + ".hex:i");
if (boardPreferences.get("upload.disable_flushing") == null ||
boardPreferences.get("upload.disable_flushing").toLowerCase().equals("false")) {
flushSerialBuffer();
}
return avrdude(commandDownloader);
}
public boolean burnBootloader() throws RunnerException {
String programmer = Preferences.get("programmer");
Target target = Base.getTarget();
if (programmer.indexOf(":") != -1) {
target = Base.targetsTable.get(programmer.substring(0, programmer.indexOf(":")));
programmer = programmer.substring(programmer.indexOf(":") + 1);
}
return burnBootloader(getProgrammerCommands(target, programmer));
}
private Collection getProgrammerCommands(Target target, String programmer) {
Map<String, String> programmerPreferences = target.getProgrammers().get(programmer);
List params = new ArrayList();
params.add("-c" + programmerPreferences.get("protocol"));
if ("usb".equals(programmerPreferences.get("communication"))) {
params.add("-Pusb");
} else if ("serial".equals(programmerPreferences.get("communication"))) {
params.add("-P" + (Base.isWindows() ? "\\\\.\\" : "") + Preferences.get("serial.port"));
if (programmerPreferences.get("speed") != null) {
params.add("-b" + Integer.parseInt(programmerPreferences.get("speed")));
}
}
// XXX: add support for specifying the port address for parallel
// programmers, although avrdude has a default that works in most cases.
if (programmerPreferences.get("force") != null &&
programmerPreferences.get("force").toLowerCase().equals("true"))
params.add("-F");
if (programmerPreferences.get("delay") != null)
params.add("-i" + programmerPreferences.get("delay"));
return params;
}
protected boolean burnBootloader(Collection params)
throws RunnerException {
Map<String, String> boardPreferences = Base.getBoardPreferences();
List fuses = new ArrayList();
fuses.add("-e"); // erase the chip
if (boardPreferences.get("bootloader.unlock_bits") != null)
fuses.add("-Ulock:w:" + boardPreferences.get("bootloader.unlock_bits") + ":m");
if (boardPreferences.get("bootloader.extended_fuses") != null)
fuses.add("-Uefuse:w:" + boardPreferences.get("bootloader.extended_fuses") + ":m");
fuses.add("-Uhfuse:w:" + boardPreferences.get("bootloader.high_fuses") + ":m");
fuses.add("-Ulfuse:w:" + boardPreferences.get("bootloader.low_fuses") + ":m");
if (!avrdude(params, fuses))
return false;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {}
Target t;
List bootloader = new ArrayList();
String bootloaderPath = boardPreferences.get("bootloader.path");
if (bootloaderPath != null) {
if (bootloaderPath.indexOf(':') == -1) {
t = Base.getTarget(); // the current target (associated with the board)
} else {
String targetName = bootloaderPath.substring(0, bootloaderPath.indexOf(':'));
t = Base.targetsTable.get(targetName);
bootloaderPath = bootloaderPath.substring(bootloaderPath.indexOf(':') + 1);
}
File bootloadersFile = new File(t.getFolder(), "bootloaders");
File bootloaderFile = new File(bootloadersFile, bootloaderPath);
bootloaderPath = bootloaderFile.getAbsolutePath();
bootloader.add("-Uflash:w:" + bootloaderPath + File.separator +
boardPreferences.get("bootloader.file") + ":i");
}
if (boardPreferences.get("bootloader.lock_bits") != null)
bootloader.add("-Ulock:w:" + boardPreferences.get("bootloader.lock_bits") + ":m");
if (bootloader.size() > 0)
return avrdude(params, bootloader);
return true;
}
public boolean avrdude(Collection p1, Collection p2) throws RunnerException {
ArrayList p = new ArrayList(p1);
p.addAll(p2);
return avrdude(p);
}
public boolean avrdude(Collection params) throws RunnerException {
List commandDownloader = new ArrayList();
if(Base.isLinux()) {
if ((new File(Base.getHardwarePath() + "/tools/" + "avrdude")).exists()) {
commandDownloader.add(Base.getHardwarePath() + "/tools/" + "avrdude");
commandDownloader.add("-C" + Base.getHardwarePath() + "/tools/avrdude.conf");
} else {
commandDownloader.add("avrdude");
}
}
else {
commandDownloader.add(Base.getHardwarePath() + "/tools/avr/bin/" + "avrdude");
commandDownloader.add("-C" + Base.getHardwarePath() + "/tools/avr/etc/avrdude.conf");
}
if (verbose || Preferences.getBoolean("upload.verbose")) {
commandDownloader.add("-v");
commandDownloader.add("-v");
commandDownloader.add("-v");
commandDownloader.add("-v");
} else {
commandDownloader.add("-q");
commandDownloader.add("-q");
}
commandDownloader.add("-p" + Base.getBoardPreferences().get("build.mcu"));
commandDownloader.addAll(params);
return executeUploadCommand(commandDownloader);
}
} |
package florian_haas.lucas.util;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.*;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.imageio.ImageIO;
import javax.validation.*;
import org.apache.shiro.ShiroException;
import org.primefaces.model.*;
public class WebUtils {
public static final String DEFAULT_MESSAGE_COMPONENT_ID = "defaultMessage";
public static final String GROWL_MESSAGE_COMPONENT_ID = "growlMessage";
public static final String STICKY_GROWL_MESSAGE_COMPONENT_ID = "stickyGrowlMessage";
public static void addDefaultInformationMessage(String message) {
addInformationMessage(message, DEFAULT_MESSAGE_COMPONENT_ID);
}
public static void addDefaultTranslatedInformationMessage(String message, Object... params) {
addTranslatedInformationMessage(message, DEFAULT_MESSAGE_COMPONENT_ID, params);
}
public static void addDefaultWarningMessage(String message) {
addWarningMessage(message, DEFAULT_MESSAGE_COMPONENT_ID);
}
public static void addDefaultTranslatedWarningMessage(String message, Object... params) {
addTranslatedWarningMessage(message, DEFAULT_MESSAGE_COMPONENT_ID, params);
}
public static void addDefaultErrorMessage(String message) {
addErrorMessage(message, DEFAULT_MESSAGE_COMPONENT_ID);
}
public static void addDefaultTranslatedErrorMessage(String message, Object... params) {
addTranslatedErrorMessage(message, DEFAULT_MESSAGE_COMPONENT_ID, params);
}
public static void addDefaultFatalMessage(String message) {
addFatalMessage(message, DEFAULT_MESSAGE_COMPONENT_ID);
}
public static void addDefaultTranslatedFatalMessage(String message, Object... params) {
addTranslatedFatalMessage(message, DEFAULT_MESSAGE_COMPONENT_ID, params);
}
public static void addGrowlInformationMessage(String message) {
addInformationMessage(message, GROWL_MESSAGE_COMPONENT_ID);
}
public static void addGrowlTranslatedInformationMessage(String message, Object... params) {
addTranslatedInformationMessage(message, GROWL_MESSAGE_COMPONENT_ID, params);
}
public static void addGrowlWarningMessage(String message) {
addWarningMessage(message, GROWL_MESSAGE_COMPONENT_ID);
}
public static void addGrowlTranslatedWarningMessage(String message, Object... params) {
addTranslatedWarningMessage(message, GROWL_MESSAGE_COMPONENT_ID, params);
}
public static void addGrowlErrorMessage(String message) {
addErrorMessage(message, GROWL_MESSAGE_COMPONENT_ID);
}
public static void addGrowlTranslatedErrorMessage(String message, Object... params) {
addTranslatedErrorMessage(message, GROWL_MESSAGE_COMPONENT_ID, params);
}
public static void addGrowlFatalMessage(String message) {
addFatalMessage(message, GROWL_MESSAGE_COMPONENT_ID);
}
public static void addGrowlTranslatedFatalMessage(String message, Object... params) {
addTranslatedFatalMessage(message, GROWL_MESSAGE_COMPONENT_ID, params);
}
public static void addStickyGrowlInformationMessage(String message) {
addInformationMessage(message, STICKY_GROWL_MESSAGE_COMPONENT_ID);
}
public static void addStickyGrowlTranslatedInformationMessage(String message, Object... params) {
addTranslatedInformationMessage(message, STICKY_GROWL_MESSAGE_COMPONENT_ID, params);
}
public static void addStickyGrowlWarningMessage(String message) {
addWarningMessage(message, STICKY_GROWL_MESSAGE_COMPONENT_ID);
}
public static void addStickyGrowlTranslatedWarningMessage(String message, Object... params) {
addTranslatedWarningMessage(message, STICKY_GROWL_MESSAGE_COMPONENT_ID, params);
}
public static void addStickyGrowlErrorMessage(String message) {
addErrorMessage(message, STICKY_GROWL_MESSAGE_COMPONENT_ID);
}
public static void addStickyGrowlTranslatedErrorMessage(String message, Object... params) {
addTranslatedErrorMessage(message, STICKY_GROWL_MESSAGE_COMPONENT_ID, params);
}
public static void addStickyGrowlFatalMessage(String message) {
addFatalMessage(message, STICKY_GROWL_MESSAGE_COMPONENT_ID);
}
public static void addStickyGrowlTranslatedFatalMessage(String message, Object... params) {
addTranslatedFatalMessage(message, STICKY_GROWL_MESSAGE_COMPONENT_ID, params);
}
public static void addInformationMessage(String message, String clientComponent) {
addMessage(FacesMessage.SEVERITY_INFO, message, clientComponent);
}
public static void addTranslatedInformationMessage(String message, String clientComponent, Object... params) {
addTranslatedMessage(FacesMessage.SEVERITY_INFO, message, clientComponent, params);
}
public static void addWarningMessage(String message, String clientComponent) {
addMessage(FacesMessage.SEVERITY_WARN, message, clientComponent);
}
public static void addTranslatedWarningMessage(String message, String clientComponent, Object... params) {
addTranslatedMessage(FacesMessage.SEVERITY_WARN, message, clientComponent, params);
}
public static void addErrorMessage(String message, String clientComponent) {
addMessage(FacesMessage.SEVERITY_ERROR, message, clientComponent);
}
public static void addTranslatedErrorMessage(String message, String clientComponent, Object... params) {
addTranslatedMessage(FacesMessage.SEVERITY_ERROR, message, clientComponent, params);
}
public static void addFatalMessage(String message, String clientComponent) {
addMessage(FacesMessage.SEVERITY_FATAL, message, clientComponent);
}
public static void addTranslatedFatalMessage(String message, String clientComponent, Object... params) {
addTranslatedMessage(FacesMessage.SEVERITY_FATAL, message, clientComponent, params);
}
private static void addTranslatedMessage(FacesMessage.Severity severity, String key, String clientComponent, Object... params) {
addMessage(severity, getTranslatedMessage(key, params), clientComponent);
}
private static void addMessage(FacesMessage.Severity severity, String message, String clientComponent) {
String titlePrefix = severity == FacesMessage.SEVERITY_WARN ? "warn"
: severity == FacesMessage.SEVERITY_ERROR ? "error" : severity == FacesMessage.SEVERITY_FATAL ? "fatal" : "info";
FacesContext.getCurrentInstance().addMessage(clientComponent,
new FacesMessage(severity, getTranslatedMessage("lucas.application.message." + titlePrefix), message));
}
public static String getTranslatedMessage(String key, Object... params) {
String message = getTranslatedMessage(key);
for (int i = 0; i < params.length; i++) {
if (params[i] != null) message = message.replaceAll("\\?" + i, params[i].toString());
}
return message;
}
public static String getTranslatedMessage(String key) {
return FacesContext.getCurrentInstance().getApplication().evaluateExpressionGet(FacesContext.getCurrentInstance(), "#{msg['" + key + "']}",
String.class);
}
public static boolean executeTask(FailableTask task, String successMessageKey, String warnMessageKey, String failMessageKey,
Object... argParams) {
boolean success = false;
List<Object> paramsList = new ArrayList<>();
paramsList.addAll(Arrays.asList(argParams));
Object[] params = paramsList.toArray();
try {
success = task.executeTask(paramsList);
params = paramsList.toArray();
if (success && successMessageKey != null) {
WebUtils.addDefaultTranslatedInformationMessage(successMessageKey, params);
} else if (warnMessageKey != null) {
WebUtils.addDefaultTranslatedInformationMessage(warnMessageKey, params);
}
}
catch (ConstraintViolationException e) {
for (ConstraintViolation<?> violation : e.getConstraintViolations()) {
WebUtils.addDefaultErrorMessage(
getTranslatedMessage(failMessageKey, params) + violation.getPropertyPath() + " " + violation.getMessage());
}
}
catch (ShiroException e2) {
WebUtils.addDefaultErrorMessage(
getTranslatedMessage(failMessageKey, params) + getTranslatedMessage("lucas.application.message.accessDenied"));
}
catch (Exception e3) {
WebUtils.addDefaultFatalMessage(getTranslatedMessage(failMessageKey, params) + e3.getLocalizedMessage());
}
return success;
}
public static final String JPEG_MIME = "image/jpeg";
public static final String JPEG_TYPE = "JPEG";
public static final String SVG_MIME = "image/svg+xml";
public static StreamedContent getJPEGImage(InputStream data) {
return getDataAsStreamedContent(data, JPEG_MIME);
}
public static StreamedContent getJPEGImage(byte[] data) {
return getDataAsStreamedContent(data, JPEG_MIME);
}
public static StreamedContent getSVGImage(byte[] data) {
return getDataAsStreamedContent(data, SVG_MIME);
}
public static StreamedContent getSVGImage(InputStream data) {
return getDataAsStreamedContent(data, SVG_MIME);
}
public static StreamedContent getDataAsStreamedContent(byte[] data, String mime) {
return getDataAsStreamedContent(data != null ? new ByteArrayInputStream(data) : null, mime);
}
public static StreamedContent getDataAsStreamedContent(InputStream data, String mime) {
if (data != null) return new DefaultStreamedContent(data, mime);
return null;
}
public static BufferedImage getBufferedImageFromBytes(byte[] data) throws Exception {
BufferedImage ret = null;
ByteArrayInputStream in = new ByteArrayInputStream(data);
ret = ImageIO.read(new ByteArrayInputStream(data));
in.close();
return ret;
}
public static byte[] convertBufferedImageToBytes(BufferedImage image, String type) throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
ImageIO.write(image, type, out);
out.close();
return out.toByteArray();
}
} |
package be.fedict.dcat.helpers;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author Bart Hanssens <bart.hanssens@fedict.be>
*/
public class Cache {
private final Logger logger = LoggerFactory.getLogger(Cache.class);
private DB db = null;
private static final String CACHE = "cache";
private static final String URLS = "urls";
private static final String PAGES = "pages";
/**
* Store list of URLs.
*
* @param urls
*/
public void storeURLList(List<URL> urls) {
ConcurrentMap<String, List<URL>> map = db.hashMap(Cache.CACHE);
map.put(Cache.URLS, urls);
db.commit();
}
/**
* Get the list of URLs in the cache.
*
* @return
*/
public List<URL> retrieveURLList() {
ConcurrentMap<String, List<URL>> map = db.hashMap(Cache.CACHE);
return map.getOrDefault(Cache.URLS, new ArrayList<>());
}
/**
* Store a web page
*
* @param id
* @param page
* @param lang
*/
public void storePage(URL id, String lang, Page page) {
logger.debug("Storing page {} with lang {} to cache", id, lang);
ConcurrentMap<URL, Map<String, Page>> map = db.hashMap(Cache.PAGES);
Map<String, Page> p = map.getOrDefault(id, new HashMap<>());
p.put(lang, page);
map.put(id, p);
db.commit();
}
/**
* Retrieve a page from the cache.
*
* @param id
* @return page object
*/
public Map<String, Page> retrievePage(URL id) {
logger.debug("Retrieving page {} from cache", id);
ConcurrentMap<URL, Map<String, Page>> map = db.hashMap(Cache.PAGES);
return map.getOrDefault(id, new HashMap<>());
}
/**
* Store a map to the cache.
*
* @param id
* @param map
*/
public void storeMap(URL id, Map<String,String> map) {
ConcurrentMap<URL, Map<String,String>> m = db.hashMap(Cache.PAGES);
m.put(id, map);
db.commit();
}
/**
* Retrieve a map from the cache.
*
* @param id
* @return
*/
public Map<String,String> retrieveMap(URL id) {
ConcurrentMap<URL, Map<String,String>> map = db.hashMap(Cache.PAGES);
return map.getOrDefault(id, new HashMap<>());
}
/**
* Close cache
*/
public void shutdown() {
logger.info("Closing cache file");
db.close();
}
public Cache(File f) {
logger.info("Opening cache file " + f.getAbsolutePath());
db = DBMaker.fileDB(f).make();
}
} |
package com.jme3.terrain.heightmap;
import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* <code>AbstractHeightMap</code> provides a base implementation of height
* data for terrain rendering. The loading of the data is dependent on the
* subclass. The abstract implementation provides a means to retrieve the height
* data and to save it.
*
* It is the general contract that any subclass provide a means of editing
* required attributes and calling <code>load</code> again to recreate a
* heightfield with these new parameters.
*
* @author Mark Powell
* @version $Id: AbstractHeightMap.java 4133 2009-03-19 20:40:11Z blaine.dev $
*/
public abstract class AbstractHeightMap implements HeightMap {
private static final Logger logger = Logger.getLogger(AbstractHeightMap.class.getName());
/** Height data information. */
protected float[] heightData = null;
/** The size of the height map's width. */
protected int size = 0;
/** Allows scaling the Y height of the map. */
protected float heightScale = 1.0f;
/** The filter is used to erode the terrain. */
protected float filter = 0.5f;
/** The range used to normalize terrain */
public static float NORMALIZE_RANGE = 255f;
/**
* <code>unloadHeightMap</code> clears the data of the height map. This
* insures it is ready for reloading.
*/
public void unloadHeightMap() {
heightData = null;
}
/**
* <code>setHeightScale</code> sets the scale of the height values.
* Typically, the height is a little too extreme and should be scaled to a
* smaller value (i.e. 0.25), to produce cleaner slopes.
*
* @param scale
* the scale to multiply height values by.
*/
public void setHeightScale(float scale) {
heightScale = scale;
}
/**
* <code>setHeightAtPoint</code> sets the height value for a given
* coordinate. It is recommended that the height value be within the 0 - 255
* range.
*
* @param height
* the new height for the coordinate.
* @param x
* the x (east/west) coordinate.
* @param z
* the z (north/south) coordinate.
*/
public void setHeightAtPoint(float height, int x, int z) {
heightData[x + (z * size)] = height;
}
/**
* <code>setSize</code> sets the size of the terrain where the area is
* size x size.
*
* @param size
* the new size of the terrain.
* @throws Exception
*
* @throws JmeException
* if the size is less than or equal to zero.
*/
public void setSize(int size) throws Exception {
if (size <= 0) {
throw new Exception("size must be greater than zero.");
}
this.size = size;
}
/**
* <code>setFilter</code> sets the erosion value for the filter. This
* value must be between 0 and 1, where 0.2 - 0.4 produces arguably the best
* results.
*
* @param filter
* the erosion value.
* @throws Exception
* @throws JmeException
* if filter is less than 0 or greater than 1.
*/
public void setMagnificationFilter(float filter) throws Exception {
if (filter < 0 || filter >= 1) {
throw new Exception("filter must be between 0 and 1");
}
this.filter = filter;
}
/**
* <code>getTrueHeightAtPoint</code> returns the non-scaled value at the
* point provided.
*
* @param x
* the x (east/west) coordinate.
* @param z
* the z (north/south) coordinate.
* @return the value at (x,z).
*/
public float getTrueHeightAtPoint(int x, int z) {
//logger.info( heightData[x + (z*size)]);
return heightData[x + (z * size)];
}
/**
* <code>getScaledHeightAtPoint</code> returns the scaled value at the
* point provided.
*
* @param x
* the x (east/west) coordinate.
* @param z
* the z (north/south) coordinate.
* @return the scaled value at (x, z).
*/
public float getScaledHeightAtPoint(int x, int z) {
return ((heightData[x + (z * size)]) * heightScale);
}
/**
* <code>getInterpolatedHeight</code> returns the height of a point that
* does not fall directly on the height posts.
*
* @param x
* the x coordinate of the point.
* @param z
* the y coordinate of the point.
* @return the interpolated height at this point.
*/
public float getInterpolatedHeight(float x, float z) {
float low, highX, highZ;
float intX, intZ;
float interpolation;
low = getScaledHeightAtPoint((int) x, (int) z);
if (x + 1 > size) {
return low;
}
highX = getScaledHeightAtPoint((int) x + 1, (int) z);
interpolation = x - (int) x;
intX = ((highX - low) * interpolation) + low;
if (z + 1 > size) {
return low;
}
highZ = getScaledHeightAtPoint((int) x, (int) z + 1);
interpolation = z - (int) z;
intZ = ((highZ - low) * interpolation) + low;
return ((intX + intZ) / 2);
}
/**
* <code>getHeightMap</code> returns the entire grid of height data.
*
* @return the grid of height data.
*/
public float[] getHeightMap() {
return heightData;
}
/**
* Build a new array of height data with the scaled values.
* @return
*/
public float[] getScaledHeightMap() {
float[] hm = new float[heightData.length];
for (int i=0; i<heightData.length; i++) {
hm[i] = heightScale * heightData[i];
}
return hm;
}
/**
* <code>getSize</code> returns the size of one side the height map. Where
* the area of the height map is size x size.
*
* @return the size of a single side.
*/
public int getSize() {
return size;
}
/**
* <code>save</code> will save the heightmap data into a new RAW file
* denoted by the supplied filename.
*
* @param filename
* the file name to save the current data as.
* @return true if the save was successful, false otherwise.
* @throws Exception
*
* @throws JmeException
* if filename is null.
*/
public boolean save(String filename) throws Exception {
if (null == filename) {
throw new Exception("Filename must not be null");
}
//open the streams and send the height data to the file.
try {
FileOutputStream fos = new FileOutputStream(filename);
DataOutputStream dos = new DataOutputStream(fos);
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
dos.write((int) heightData[j + (i * size)]);
}
}
fos.close();
dos.close();
} catch (FileNotFoundException e) {
logger.log(Level.WARNING, "Error opening file {0}", filename);
return false;
} catch (IOException e) {
logger.log(Level.WARNING, "Error writing to file {0}", filename);
return false;
}
logger.log(Level.INFO, "Saved terrain to {0}", filename);
return true;
}
/**
* <code>normalizeTerrain</code> takes the current terrain data and
* converts it to values between 0 and <code>value</code>.
*
* @param value
* the value to normalize to.
*/
public void normalizeTerrain(float value) {
float currentMin, currentMax;
float height;
currentMin = heightData[0];
currentMax = heightData[0];
//find the min/max values of the height fTemptemptempBuffer
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (heightData[i + j * size] > currentMax) {
currentMax = heightData[i + j * size];
} else if (heightData[i + j * size] < currentMin) {
currentMin = heightData[i + j * size];
}
}
}
//find the range of the altitude
if (currentMax <= currentMin) {
return;
}
height = currentMax - currentMin;
//scale the values to a range of 0-255
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
heightData[i + j * size] = ((heightData[i + j * size] - currentMin) / height) * value;
}
}
}
/**
* Find the minimum and maximum height values.
* @return a float array with two value: min height, max height
*/
public float[] findMinMaxHeights() {
float[] minmax = new float[2];
float currentMin, currentMax;
currentMin = heightData[0];
currentMax = heightData[0];
for (int i = 0; i < heightData.length; i++) {
if (heightData[i] > currentMax) {
currentMax = heightData[i];
} else if (heightData[i] < currentMin) {
currentMin = heightData[i];
}
}
minmax[0] = currentMin;
minmax[1] = currentMax;
return minmax;
}
/**
* <code>erodeTerrain</code> is a convenience method that applies the FIR
* filter to a given height map. This simulates water errosion.
*
* @see setFilter
*/
public void erodeTerrain() {
//erode left to right
float v;
for (int i = 0; i < size; i++) {
v = heightData[i];
for (int j = 1; j < size; j++) {
heightData[i + j * size] = filter * v + (1 - filter) * heightData[i + j * size];
v = heightData[i + j * size];
}
}
//erode right to left
for (int i = size - 1; i >= 0; i
v = heightData[i];
for (int j = 0; j < size; j++) {
heightData[i + j * size] = filter * v + (1 - filter) * heightData[i + j * size];
v = heightData[i + j * size];
//erodeBand(tempBuffer[size * i + size - 1], -1);
}
}
//erode top to bottom
for (int i = 0; i < size; i++) {
v = heightData[i];
for (int j = 0; j < size; j++) {
heightData[i + j * size] = filter * v + (1 - filter) * heightData[i + j * size];
v = heightData[i + j * size];
}
}
//erode from bottom to top
for (int i = size - 1; i >= 0; i
v = heightData[i];
for (int j = 0; j < size; j++) {
heightData[i + j * size] = filter * v + (1 - filter) * heightData[i + j * size];
v = heightData[i + j * size];
}
}
}
/**
* Flattens out the valleys. The flatten algorithm makes the valleys more
* prominent while keeping the hills mostly intact. This effect is based on
* what happens when values below one are squared. The terrain will be
* normalized between 0 and 1 for this function to work.
*
* @param flattening
* the power of flattening applied, 1 means none
*/
public void flatten(byte flattening) {
// If flattening is one we can skip the calculations
// since it wouldn't change anything. (e.g. 2 power 1 = 2)
if (flattening <= 1) {
return;
}
float[] minmax = findMinMaxHeights();
normalizeTerrain(1f);
for (int x = 0; x < size; x++) {
for (int y = 0; y < size; y++) {
float flat = 1.0f;
float original = heightData[x + y * size];
// Flatten as many times as desired;
for (int i = 0; i < flattening; i++) {
flat *= original;
}
heightData[x + y * size] = flat;
}
}
// re-normalize back to its oraginal height range
float height = minmax[1] - minmax[0];
normalizeTerrain(height);
}
/**
* Smooth the terrain. For each node, its 8 neighbors heights
* are averaged and will participate in the node new height
* by a factor <code>np</code> between 0 and 1
*
* @param np
* The factor to what extend the neighbors average has an influence.
* Value of 0 will ignore neighbors (no smoothing)
* Value of 1 will ignore the node old height.
*/
public void smooth(float np) {
if (np < 0 || np > 1) {
return;
}
int[] dxs = new int[]{-1, 0, 1, 1, 1, 0, -1, -1};
int[] dys = new int[]{-1, -1, -1, 0, 1, 1, 1, 0};
for (int x = 0; x < size; x++) {
for (int y = 0; y < size; y++) {
int neighNumber = 0;
float neighAverage = 0;
for (int d = 0; d < 8; d++) {
int i = x + dxs[d];
int j = y + dys[d];
if (i < 0 || i > size) {
continue;
}
if (j < 0 || j > size) {
continue;
}
neighNumber++;
neighAverage += heightData[i + j * size];
}
neighAverage /= neighNumber;
float cp = 1 - np;
heightData[x + y * size] = neighAverage * np + heightData[x + y * size] * cp;
}
}
}
} |
package org.tianocore.build.autogen;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.tools.ant.BuildException;
import org.apache.xmlbeans.XmlObject;
import org.tianocore.GuidsDocument;
import org.tianocore.LibraryClassDocument.LibraryClass;
import org.tianocore.PPIsDocument;
import org.tianocore.ProtocolsDocument;
import org.tianocore.build.exception.*;
import org.tianocore.build.global.GlobalData;
import org.tianocore.build.global.Spd;
import org.tianocore.build.global.SurfaceAreaQuery;
import org.tianocore.build.id.ModuleIdentification;
import org.tianocore.build.id.PackageIdentification;
import org.tianocore.build.pcd.action.PCDAutoGenAction;
import org.tianocore.logger.EdkLog;
/**
* This class is to generate Autogen.h and Autogen.c according to module surface
* area or library surface area.
*/
public class AutoGen {
// / The output path of Autogen.h and Autogen.c
private String outputPath;
/// The name of FV directory
private String fvDir;
// / The base name of module or library.
private ModuleIdentification moduleId;
// / The build architecture
private String arch;
// / PcdAutogen instance which is used to manage how to generate the PCD
// / information.
private PCDAutoGenAction myPcdAutogen;
// / The protocl list which records in module or library surface area and
// / it's dependence on library instance surface area.
private Set<String> mProtocolList = new HashSet<String>();
// / The Ppi list which recorded in module or library surface area and its
// / dependency on library instance surface area.
private Set<String> mPpiList = new HashSet<String>();
// / The Guid list which recoreded in module or library surface area and it's
// / dependence on library instance surface area.
private Set<String> mGuidList = new HashSet<String>();
// The dependence package list which recoreded in module or library surface
// area and it's dependence on library instance surface are.
private List<PackageIdentification> mDepPkgList = new LinkedList<PackageIdentification>();
/**
* Construct function
*
* This function mainly initialize some member variable.
*
* @param outputPath
* Output path of AutoGen file.
* @param baseName
* Module base name.
* @param arch
* Target architecture.
*/
public AutoGen(String fvDir, String outputPath, ModuleIdentification moduleId, String arch) {
this.outputPath = outputPath;
this.moduleId = moduleId;
this.arch = arch;
this.fvDir = fvDir;
}
/**
* saveFile function
*
* This function save the content in stringBuffer to file.
*
* @param fileName
* The name of file.
* @param fileBuffer
* The content of AutoGen file in buffer.
* @return "true" successful, "false" failed.
*/
private boolean saveFile(String fileName, StringBuffer fileBuffer) {
try {
File autoGenH = new File(fileName);
// if the file exists, compare their content
if (autoGenH.exists()) {
FileReader fIn = new FileReader(autoGenH);
char[] oldFileBuffer = new char[(int) autoGenH.length()];
fIn.read(oldFileBuffer, 0, (int) autoGenH.length());
fIn.close();
// if we got the same file, don't re-generate it to prevent
// sources depending on it from re-building
if (fileBuffer.toString().compareTo(new String(oldFileBuffer)) == 0) {
return true;
}
}
FileWriter fOut = new FileWriter(autoGenH);
fOut.write(fileBuffer.toString());
fOut.close();
} catch (Exception e) {
return false;
}
return true;
}
/**
* genAutogen function
*
* This function call libGenAutoGen or moduleGenAutogen function, which
* dependence on generate library autogen or module autogen.
*
* @throws BuildException
* Failed to creat AutoGen.c & AutoGen.h.
*/
public void genAutogen() throws BuildException {
try {
// If outputPath do not exist, create it.
File path = new File(outputPath);
path.mkdirs();
// Check current is library or not, then call the corresponding
// function.
if (this.moduleId.isLibrary()) {
libGenAutogen();
} else {
moduleGenAutogen();
}
} catch (Exception e) {
throw new BuildException(
"Failed to create AutoGen.c & AutoGen.h!\n"
+ e.getMessage());
}
}
/**
* moduleGenAutogen function
*
* This function generates AutoGen.c & AutoGen.h for module.
*
* @throws BuildException
* Faile to create module AutoGen.c & AutoGen.h.
*/
void moduleGenAutogen() throws BuildException {
try {
moduleGenAutogenC();
moduleGenAutogenH();
} catch (Exception e) {
throw new BuildException(
"Faile to create module AutoGen.c & AutoGen.h!\n"
+ e.getMessage());
}
}
/**
* libGenAutogen function
*
* This function generates AutoGen.c & AutoGen.h for library.
*
* @throws BuildException
* Faile to create library AutoGen.c & AutoGen.h
*/
void libGenAutogen() throws BuildException {
try {
libGenAutogenC();
libGenAutogenH();
} catch (Exception e) {
throw new BuildException(
"Faile to create library AutoGen.c & AutoGen.h!\n"
+ e.getMessage());
}
}
/**
* moduleGenAutogenH
*
* This function generates AutoGen.h for module.
*
* @throws BuildException
* Failed to generate AutoGen.h.
*/
void moduleGenAutogenH() throws AutoGenException {
Set<String> libClassIncludeH;
String moduleType;
// List<String> headerFileList;
List<String> headerFileList;
Iterator item;
StringBuffer fileBuffer = new StringBuffer(8192);
// Write Autogen.h header notation
fileBuffer.append(CommonDefinition.autogenHNotation);
// Add #ifndef ${BaseName}_AUTOGENH
// #def ${BseeName}_AUTOGENH
fileBuffer.append("#ifndef " + "_AUTOGENH_" + this.moduleId.getGuid().replaceAll("-", "_") +"\r\n");
fileBuffer.append("#define " + "_AUTOGENH_" + this.moduleId.getGuid().replaceAll("-", "_") +"\r\n\r\n");
// Write the specification version and release version at the begine
// of autogen.h file.
// Note: the specification version and release version should
// be got from module surface area instead of hard code by it's
// moduleType.
moduleType = SurfaceAreaQuery.getModuleType();
// Add "extern int __make_me_compile_correctly;" at begin of
// AutoGen.h.
fileBuffer.append(CommonDefinition.autoGenHbegin);
// Put EFI_SPECIFICATION_VERSION, and EDK_RELEASE_VERSION.
String[] specList = SurfaceAreaQuery.getExternSpecificaiton();
for (int i = 0; i < specList.length; i++) {
fileBuffer.append(CommonDefinition.marcDefineStr + specList[i]
+ "\r\n");
}
// Write consumed package's mdouleInfo related .h file to autogen.h
// PackageIdentification[] consumedPkgIdList = SurfaceAreaQuery
// .getDependencePkg(this.arch);
PackageIdentification[] consumedPkgIdList = SurfaceAreaQuery
.getDependencePkg(this.arch);
if (consumedPkgIdList != null) {
headerFileList = depPkgToAutogenH(consumedPkgIdList, moduleType);
item = headerFileList.iterator();
while (item.hasNext()) {
fileBuffer.append(item.next().toString());
}
}
// Write library class's related *.h file to autogen.h.
String[] libClassList = SurfaceAreaQuery
.getLibraryClasses(CommonDefinition.AlwaysConsumed,this.arch);
if (libClassList != null) {
libClassIncludeH = LibraryClassToAutogenH(libClassList);
item = libClassIncludeH.iterator();
while (item.hasNext()) {
fileBuffer.append(item.next().toString());
}
}
libClassList = SurfaceAreaQuery
.getLibraryClasses(CommonDefinition.AlwaysProduced, this.arch);
if (libClassList != null) {
libClassIncludeH = LibraryClassToAutogenH(libClassList);
item = libClassIncludeH.iterator();
while (item.hasNext()) {
fileBuffer.append(item.next().toString());
}
}
fileBuffer.append("\r\n");
// If is TianoR8FlashMap, copy {Fv_DIR}/FlashMap.h to
// {DEST_DIR_DRBUG}/FlashMap.h
if (SurfaceAreaQuery.isHaveTianoR8FlashMap()) {
fileBuffer.append(CommonDefinition.include);
fileBuffer.append(" <");
fileBuffer.append(CommonDefinition.tianoR8FlashMapH + ">\r\n");
copyFlashMapHToDebugDir();
}
// Write PCD autogen information to AutoGen.h.
if (this.myPcdAutogen != null) {
fileBuffer.append("\r\n");
fileBuffer.append(this.myPcdAutogen.OutputH());
}
// Append the #endif at AutoGen.h
fileBuffer.append("#endif\r\n");
// Save string buffer content in AutoGen.h.
if (!saveFile(outputPath + File.separatorChar + "AutoGen.h", fileBuffer)) {
throw new BuildException("Failed to generate AutoGen.h !!!");
}
}
/**
* moduleGenAutogenC
*
* This function generates AutoGen.c for module.
*
* @throws BuildException
* Failed to generate AutoGen.c.
*/
void moduleGenAutogenC() throws AutoGenException {
StringBuffer fileBuffer = new StringBuffer(8192);
// Write Autogen.c header notation
fileBuffer.append(CommonDefinition.autogenCNotation);
// Write #include <AutoGen.h> at beginning of AutoGen.c
fileBuffer.append(CommonDefinition.includeAutogenH);
// Get the native MSA file infomation. Since before call autogen,
// the MSA native <Externs> information were overrided. So before
// process <Externs> it should be set the DOC as the Native MSA info.
Map<String, XmlObject> doc = GlobalData.getNativeMsa(this.moduleId);
SurfaceAreaQuery.push(doc);
// Write <Extern>
// DriverBinding/ComponentName/DriverConfiguration/DriverDialog
// to AutoGen.c
ExternsDriverBindingToAutoGenC(fileBuffer);
// Write DriverExitBootServicesEvent/DriverSetVirtualAddressMapEvent
// to Autogen.c
ExternCallBackToAutoGenC(fileBuffer);
// Write EntryPoint to autgoGen.c
String[] entryPointList = SurfaceAreaQuery.getModuleEntryPointArray();
EntryPointToAutoGen(CommonDefinition.remDupString(entryPointList), fileBuffer);
// Restore the DOC which include the FPD module info.
SurfaceAreaQuery.pop();
// Write Guid to autogen.c
String guid = CommonDefinition.formatGuidName(SurfaceAreaQuery
.getModuleGuid());
fileBuffer
.append("GLOBAL_REMOVE_IF_UNREFERENCED EFI_GUID gEfiCallerIdGuid = {");
if (guid == null) {
throw new AutoGenException("Guid value must set!\n");
}
// Formate Guid as ANSI c form.Example:
// {0xd2b2b828, 0x826, 0x48a7,{0xb3, 0xdf, 0x98, 0x3c, 0x0, 0x60, 0x24,
// 0xf0}}
fileBuffer.append(guid);
fileBuffer.append("};\r\n");
// Generate library instance consumed protocol, guid, ppi, pcd list.
// Save those to this.protocolList, this.ppiList, this.pcdList,
// this.guidList. Write Consumed library constructor and desconstuct to
// autogen.c
LibInstanceToAutogenC(fileBuffer);
// Get module dependent Package identification.
PackageIdentification[] packages = SurfaceAreaQuery.getDependencePkg(this.arch);
for (int i = 0; i < packages.length; i++){
if (!this.mDepPkgList.contains(packages[i])){
this.mDepPkgList.add(packages[i]);
}
}
// Write consumed ppi, guid, protocol to autogen.c
ProtocolGuidToAutogenC(fileBuffer);
PpiGuidToAutogenC(fileBuffer);
GuidGuidToAutogenC(fileBuffer);
// Call pcd autogen. PCDAutoGenAction tool only need module name and
// isPcdEmulatedDriver as parameter. Library inherits PCD and module's
// PCD information has been collected in FPDParser task by
// CollectPCDAction.
// Note : when PCD image tool ready,
// isPCDEmulatedDriver parameter will be removed.
try {
// this.myPcdAutogen = new PCDAutoGenAction(moduleId.getName(),
// moduleId.getGuid(), moduleId.getPackage().getName(), moduleId.getPackage().getGuid(),this.arch,moduleId.getVersion(),false, null);
this.myPcdAutogen = new PCDAutoGenAction(moduleId.getName(),null,null,null, this.arch,null,false, null);
this.myPcdAutogen.execute();
} catch (Exception e) {
throw new BuildException("PCD Autogen failed:" + e.getMessage());
}
if (this.myPcdAutogen != null) {
fileBuffer.append("\r\n");
fileBuffer.append(this.myPcdAutogen.OutputC());
}
if (!saveFile(outputPath + File.separatorChar + "AutoGen.c", fileBuffer)) {
throw new BuildException("Failed to generate AutoGen.c !!!");
}
}
/**
* libGenAutogenH
*
* This function generates AutoGen.h for library.
*
* @throws BuildException
* Failed to generate AutoGen.c.
*/
void libGenAutogenH() throws AutoGenException {
Set<String> libClassIncludeH;
String moduleType;
List<String> headerFileList;
Iterator item;
StringBuffer fileBuffer = new StringBuffer(10240);
// Write Autogen.h header notation
fileBuffer.append(CommonDefinition.autogenHNotation);
// Add #ifndef ${BaseName}_AUTOGENH
// #def ${BseeName}_AUTOGENH
fileBuffer.append("#ifndef " + "_AUTOGENH_" + this.moduleId.getGuid().replaceAll("-", "_") + "\r\n");
fileBuffer.append("#define " + "_AUTOGENH_" + this.moduleId.getGuid().replaceAll("-", "_") + "\r\n\r\n");
// Write EFI_SPECIFICATION_VERSION and EDK_RELEASE_VERSION
// to autogen.h file.
// Note: the specification version and release version should
// be get from module surface area instead of hard code.
fileBuffer.append(CommonDefinition.autoGenHbegin);
String[] specList = SurfaceAreaQuery.getExternSpecificaiton();
for (int i = 0; i < specList.length; i++) {
fileBuffer.append(CommonDefinition.marcDefineStr + specList[i]
+ "\r\n");
}
// fileBuffer.append(CommonDefinition.autoGenHLine1);
// fileBuffer.append(CommonDefinition.autoGenHLine2);
// Write consumed package's mdouleInfo related *.h file to autogen.h.
moduleType = SurfaceAreaQuery.getModuleType();
PackageIdentification[] cosumedPkglist = SurfaceAreaQuery
.getDependencePkg(this.arch);
headerFileList = depPkgToAutogenH(cosumedPkglist, moduleType);
item = headerFileList.iterator();
while (item.hasNext()) {
fileBuffer.append(item.next().toString());
}
// Write library class's related *.h file to autogen.h
String[] libClassList = SurfaceAreaQuery
.getLibraryClasses(CommonDefinition.AlwaysConsumed, this.arch);
if (libClassList != null) {
libClassIncludeH = LibraryClassToAutogenH(libClassList);
item = libClassIncludeH.iterator();
while (item.hasNext()) {
fileBuffer.append(item.next().toString());
}
}
libClassList = SurfaceAreaQuery
.getLibraryClasses(CommonDefinition.AlwaysProduced, this.arch);
if (libClassList != null) {
libClassIncludeH = LibraryClassToAutogenH(libClassList);
item = libClassIncludeH.iterator();
while (item.hasNext()) {
fileBuffer.append(item.next().toString());
}
}
fileBuffer.append("\r\n");
// If is TianoR8FlashMap, copy {Fv_DIR}/FlashMap.h to
// {DEST_DIR_DRBUG}/FlashMap.h
if (SurfaceAreaQuery.isHaveTianoR8FlashMap()) {
fileBuffer.append(CommonDefinition.include);
fileBuffer.append(" <");
fileBuffer.append(CommonDefinition.tianoR8FlashMapH + ">\r\n");
copyFlashMapHToDebugDir();
}
// Write PCD information to library AutoGen.h.
if (this.myPcdAutogen != null) {
fileBuffer.append("\r\n");
fileBuffer.append(this.myPcdAutogen.OutputH());
}
// Append the #endif at AutoGen.h
fileBuffer.append("#endif\r\n");
// Save content of string buffer to AutoGen.h file.
if (!saveFile(outputPath + File.separatorChar + "AutoGen.h", fileBuffer)) {
throw new BuildException("Failed to generate AutoGen.h !!!");
}
}
/**
* libGenAutogenC
*
* This function generates AutoGen.h for library.
*
* @throws BuildException
* Failed to generate AutoGen.c.
*/
void libGenAutogenC() throws BuildException {
StringBuffer fileBuffer = new StringBuffer(10240);
// Write Autogen.c header notation
fileBuffer.append(CommonDefinition.autogenCNotation);
fileBuffer.append(CommonDefinition.autoGenCLine1);
fileBuffer.append("\r\n");
// Call pcd autogen. PCDAutoGenAction tool only need module name and
// isPcdEmulatedDriver as parameter. Library inherit PCD and module's
// PCD information has been collected in FPDParser task by
// CollectPCDAction.
// Note : when PCD image tool ready,
// isPCDEmulatedDriver parameter will be removed.
try {
// this.myPcdAutogen = new PCDAutoGenAction(this.moduleId.getName(),
// this.moduleId.getGuid(),moduleId.getPackage().getName(),moduleId.getPackage().getGuid(), this.arch, moduleId.getVersion(),true, SurfaceAreaQuery.getModulePcdEntryNameArray());
this.myPcdAutogen = new PCDAutoGenAction(this.moduleId.getName(),
null,
null,
null,
this.arch,
null,
true,
SurfaceAreaQuery.getModulePcdEntryNameArray());
this.myPcdAutogen.execute();
} catch (Exception e) {
throw new BuildException(e.getMessage());
}
if (this.myPcdAutogen != null) {
fileBuffer.append("\r\n");
fileBuffer.append(this.myPcdAutogen.OutputC());
}
if (!saveFile(outputPath + File.separatorChar + "AutoGen.c", fileBuffer)) {
throw new BuildException("Failed to generate AutoGen.c !!!");
}
}
/**
* LibraryClassToAutogenH
*
* This function returns *.h files declared by library classes which are
* consumed or produced by current build module or library.
*
* @param libClassList
* List of library class which consumed or produce by current
* build module or library.
* @return includeStrList List of *.h file.
*/
Set<String> LibraryClassToAutogenH(String[] libClassList)
throws AutoGenException {
Set<String> includStrList = new HashSet<String>();
String includerName[];
String str = "";
// Get include file from GlobalData's SPDTable according to
// library class name.
for (int i = 0; i < libClassList.length; i++) {
includerName = GlobalData.getLibraryClassHeaderFiles(
SurfaceAreaQuery.getDependencePkg(this.arch),
libClassList[i]);
if (includerName == null) {
throw new AutoGenException("Can not find library class ["
+ libClassList[i] + "] declaration in every packages. ");
}
for (int j = 0; j < includerName.length; j++) {
String includeNameStr = includerName[j];
if (includeNameStr != null) {
str = CommonDefinition.include + " " + "<";
str = str + includeNameStr + ">\r\n";
includStrList.add(str);
includeNameStr = null;
}
}
}
return includStrList;
}
/**
* IncludesToAutogenH
*
* This function add include file in AutoGen.h file.
*
* @param packageNameList
* List of module depended package.
* @param moduleType
* Module type.
* @return
*/
List<String> depPkgToAutogenH(PackageIdentification[] packageNameList,
String moduleType) throws AutoGenException {
List<String> includeStrList = new LinkedList<String>();
String pkgHeader;
String includeStr = "";
// Get include file from moduleInfo file
for (int i = 0; i < packageNameList.length; i++) {
pkgHeader = GlobalData.getPackageHeaderFiles(packageNameList[i],
moduleType);
if (pkgHeader == null) {
throw new AutoGenException("Can not find package ["
+ packageNameList[i]
+ "] declaration in every packages. ");
} else if (!pkgHeader.equalsIgnoreCase("")) {
includeStr = CommonDefinition.include + " <" + pkgHeader
+ ">\r\n";
includeStrList.add(includeStr);
}
}
return includeStrList;
}
/**
* EntryPointToAutoGen
*
* This function convert <ModuleEntryPoint> & <ModuleUnloadImage>
* information in mas to AutoGen.c
*
* @param entryPointList
* List of entry point.
* @param fileBuffer
* String buffer fo AutoGen.c.
* @throws Exception
*/
void EntryPointToAutoGen(String[] entryPointList, StringBuffer fileBuffer)
throws BuildException {
String typeStr = SurfaceAreaQuery.getModuleType();
// The parameters and return value of entryPoint is difference
// for difference module type.
switch (CommonDefinition.getModuleType(typeStr)) {
case CommonDefinition.ModuleTypePeiCore:
if (entryPointList == null ||entryPointList.length != 1 ) {
throw new BuildException(
"Module type = 'PEI_CORE', only have one module entry point!");
} else {
fileBuffer.append("EFI_STATUS\r\n");
fileBuffer.append("EFIAPI\r\n");
fileBuffer.append(entryPointList[0]);
fileBuffer.append(" (\r\n");
fileBuffer
.append(" IN EFI_PEI_STARTUP_DESCRIPTOR *PeiStartupDescriptor,\r\n");
fileBuffer
.append(" IN VOID *OldCoreData\r\n");
fileBuffer.append(" );\r\n\r\n");
fileBuffer.append("EFI_STATUS\r\n");
fileBuffer.append("EFIAPI\r\n");
fileBuffer.append("ProcessModuleEntryPointList (\r\n");
fileBuffer
.append(" IN EFI_PEI_STARTUP_DESCRIPTOR *PeiStartupDescriptor,\r\n");
fileBuffer
.append(" IN VOID *OldCoreData\r\n");
fileBuffer.append(" )\r\n\r\n");
fileBuffer.append("{\r\n");
fileBuffer.append(" return ");
fileBuffer.append(entryPointList[0]);
fileBuffer.append(" (PeiStartupDescriptor, OldCoreData);\r\n");
fileBuffer.append("}\r\n\r\n");
}
break;
case CommonDefinition.ModuleTypeDxeCore:
fileBuffer.append("const UINT32 _gUefiDriverRevision = 0;\r\n");
if (entryPointList == null || entryPointList.length != 1) {
throw new BuildException(
"Module type = 'DXE_CORE', only have one module entry point!");
} else {
fileBuffer.append("VOID\r\n");
fileBuffer.append("EFIAPI\r\n");
fileBuffer.append(entryPointList[0]);
fileBuffer.append(" (\n");
fileBuffer.append(" IN VOID *HobStart\r\n");
fileBuffer.append(" );\r\n\r\n");
fileBuffer.append("VOID\r\n");
fileBuffer.append("EFIAPI\r\n");
fileBuffer.append("ProcessModuleEntryPointList (\r\n");
fileBuffer.append(" IN VOID *HobStart\r\n");
fileBuffer.append(" )\r\n\r\n");
fileBuffer.append("{\r\n");
fileBuffer.append(" ");
fileBuffer.append(entryPointList[0]);
fileBuffer.append(" (HobStart);\r\n");
fileBuffer.append("}\r\n\r\n");
}
break;
case CommonDefinition.ModuleTypePeim:
int entryPointCount = 0;
fileBuffer
.append("GLOBAL_REMOVE_IF_UNREFERENCED const UINT32 _gPeimRevision = 0;\r\n");
if (entryPointList == null || entryPointList.length == 0) {
fileBuffer.append("EFI_STATUS\r\n");
fileBuffer.append("EFIAPI\r\n");
fileBuffer.append("ProcessModuleEntryPointList (\r\n");
fileBuffer.append(" IN EFI_FFS_FILE_HEADER *FfsHeader,\r\n");
fileBuffer.append(" IN EFI_PEI_SERVICES **PeiServices\r\n");
fileBuffer.append(" )\r\n\r\n");
fileBuffer.append("{\r\n");
fileBuffer.append(" return EFI_SUCCESS;\r\n");
fileBuffer.append("}\r\n\r\n");
break;
}
for (int i = 0; i < entryPointList.length; i++) {
fileBuffer.append("EFI_STATUS\r\n");
fileBuffer.append("EFIAPI\r\n");
fileBuffer.append(entryPointList[i]);
fileBuffer.append(" (\r\n");
fileBuffer
.append(" IN EFI_FFS_FILE_HEADER *FfsHeader,\r\n");
fileBuffer
.append(" IN EFI_PEI_SERVICES **PeiServices\r\n");
fileBuffer.append(" );\r\n");
entryPointCount++;
}
fileBuffer.append("EFI_STATUS\r\n");
fileBuffer.append("EFIAPI\r\n");
fileBuffer.append("ProcessModuleEntryPointList (\r\n");
fileBuffer.append(" IN EFI_FFS_FILE_HEADER *FfsHeader,\r\n");
fileBuffer.append(" IN EFI_PEI_SERVICES **PeiServices\r\n");
fileBuffer.append(" )\r\n\r\n");
fileBuffer.append("{\r\n");
if (entryPointCount == 1) {
fileBuffer.append(" return ");
fileBuffer.append(entryPointList[0]);
fileBuffer.append(" (FfsHeader, PeiServices);\r\n");
} else {
fileBuffer.append(" EFI_STATUS Status;\r\n");
fileBuffer.append(" EFI_STATUS CombinedStatus;\r\n\r\n");
fileBuffer.append(" CombinedStatus = EFI_LOAD_ERROR;\r\n\r\n");
for (int i = 0; i < entryPointList.length; i++) {
if (!entryPointList[i].equals("")) {
fileBuffer.append(" Status = ");
fileBuffer.append(entryPointList[i]);
fileBuffer.append(" (FfsHeader, PeiServices);\r\n");
fileBuffer
.append(" if (!EFI_ERROR (Status) || EFI_ERROR (CombinedStatus)) {\r\n");
fileBuffer.append(" CombinedStatus = Status;\r\n");
fileBuffer.append(" }\r\n\r\n");
} else {
break;
}
}
fileBuffer.append(" return CombinedStatus;\r\n");
}
fileBuffer.append("}\r\n\r\n");
break;
case CommonDefinition.ModuleTypeDxeSmmDriver:
entryPointCount = 0;
// If entryPoint is null, create an empty ProcessModuleEntryPointList
// function.
if (entryPointList == null || entryPointList.length == 0){
fileBuffer
.append("GLOBAL_REMOVE_IF_UNREFERENCED const UINT8 _gDriverEntryPointCount = ");
fileBuffer.append(Integer.toString(entryPointCount));
fileBuffer.append(";\r\n");
fileBuffer.append("EFI_STATUS\r\n");
fileBuffer.append("EFIAPI\r\n");
fileBuffer.append("ProcessModuleEntryPointList (\r\n");
fileBuffer.append(" IN EFI_HANDLE ImageHandle,\r\n");
fileBuffer.append(" IN EFI_SYSTEM_TABLE *SystemTable\r\n");
fileBuffer.append(" )\r\n\r\n");
fileBuffer.append("{\r\n");
fileBuffer.append(" return EFI_SUCCESS;\r\n");
fileBuffer.append("}\r\n\r\n");
} else {
for (int i = 0; i < entryPointList.length; i++) {
fileBuffer.append("EFI_STATUS\r\n");
fileBuffer.append("EFIAPI\r\n");
fileBuffer.append(entryPointList[i]);
fileBuffer.append(" (\r\n");
fileBuffer.append(" IN EFI_HANDLE ImageHandle,\r\n");
fileBuffer.append(" IN EFI_SYSTEM_TABLE *SystemTable\r\n");
fileBuffer.append(" );\r\n");
entryPointCount++;
}
fileBuffer
.append("GLOBAL_REMOVE_IF_UNREFERENCED const UINT8 _gDriverEntryPointCount = ");
fileBuffer.append(Integer.toString(entryPointCount));
fileBuffer.append(";\r\n");
fileBuffer
.append("static BASE_LIBRARY_JUMP_BUFFER mJumpContext;\r\n");
fileBuffer
.append("static EFI_STATUS mDriverEntryPointStatus = EFI_LOAD_ERROR;\r\n\r\n");
fileBuffer.append("EFI_STATUS\r\n");
fileBuffer.append("EFIAPI\r\n");
fileBuffer.append("ProcessModuleEntryPointList (\r\n");
fileBuffer.append(" IN EFI_HANDLE ImageHandle,\r\n");
fileBuffer.append(" IN EFI_SYSTEM_TABLE *SystemTable\r\n");
fileBuffer.append(" )\r\n\r\n");
fileBuffer.append("{\r\n");
for (int i = 0; i < entryPointList.length; i++) {
fileBuffer
.append(" if (SetJump (&mJumpContext) == 0) {\r\n");
fileBuffer.append(" ExitDriver (");
fileBuffer.append(entryPointList[i]);
fileBuffer.append(" (ImageHandle, SystemTable));\r\n");
fileBuffer.append(" ASSERT (FALSE);\r\n");
fileBuffer.append(" }\r\n");
}
fileBuffer.append(" return mDriverEntryPointStatus;\r\n");
fileBuffer.append("}\r\n\r\n");
fileBuffer.append("VOID\r\n");
fileBuffer.append("EFIAPI\r\n");
fileBuffer.append("ExitDriver (\r\n");
fileBuffer.append(" IN EFI_STATUS Status\n");
fileBuffer.append(" )\r\n\r\n");
fileBuffer.append("{\r\n");
fileBuffer
.append(" if (!EFI_ERROR (Status) || EFI_ERROR (mDriverEntryPointStatus)) {\r\n");
fileBuffer.append(" mDriverEntryPointStatus = Status;\r\n");
fileBuffer.append(" }\r\n");
fileBuffer.append(" LongJump (&mJumpContext, (UINTN)-1);\r\n");
fileBuffer.append(" ASSERT (FALSE);\r\n");
fileBuffer.append("}\r\n\r\n");
}
// Add "ModuleUnloadImage" for DxeSmmDriver module type;
entryPointList = SurfaceAreaQuery.getModuleUnloadImageArray();
entryPointList = CommonDefinition.remDupString(entryPointList);
entryPointCount = 0;
if (entryPointList != null) {
for (int i = 0; i < entryPointList.length; i++) {
fileBuffer.append("EFI_STATUS\r\n");
fileBuffer.append("EFIAPI\r\n");
fileBuffer.append(entryPointList[i]);
fileBuffer.append(" (\r\n");
fileBuffer
.append(" IN EFI_HANDLE ImageHandle\r\n");
fileBuffer.append(" );\r\n");
entryPointCount++;
}
}
fileBuffer
.append("GLOBAL_REMOVE_IF_UNREFERENCED const UINT8 _gDriverUnloadImageCount = ");
fileBuffer.append(Integer.toString(entryPointCount));
fileBuffer.append(";\r\n\r\n");
fileBuffer.append("EFI_STATUS\r\n");
fileBuffer.append("EFIAPI\r\n");
fileBuffer.append("ProcessModuleUnloadList (\r\n");
fileBuffer.append(" IN EFI_HANDLE ImageHandle\r\n");
fileBuffer.append(" )\r\n");
fileBuffer.append("{\r\n");
if (entryPointCount == 0) {
fileBuffer.append(" return EFI_SUCCESS;\r\n");
} else if (entryPointCount == 1) {
fileBuffer.append(" return ");
fileBuffer.append(entryPointList[0]);
fileBuffer.append("(ImageHandle);\r\n");
} else {
fileBuffer.append(" EFI_STATUS Status;\r\n\r\n");
fileBuffer.append(" Status = EFI_SUCCESS;\r\n\r\n");
for (int i = 0; i < entryPointList.length; i++) {
if (i == 0){
fileBuffer.append(" Status = ");
fileBuffer.append(entryPointList[i]);
fileBuffer.append("(ImageHandle);\r\n");
}else{
fileBuffer.append(" if (EFI_ERROR (Status)) {\r\n");
fileBuffer.append(" ");
fileBuffer.append(entryPointList[i]);
fileBuffer.append("(ImageHandle);\r\n");
fileBuffer.append(" } else {\r\n");
fileBuffer.append(" Status = ");
fileBuffer.append(entryPointList[i]);
fileBuffer.append("(ImageHandle);\r\n");
fileBuffer.append(" }\r\n");
}
}
fileBuffer.append(" return Status;\r\n");
}
fileBuffer.append("}\r\n\r\n");
break;
case CommonDefinition.ModuleTypeDxeRuntimeDriver:
case CommonDefinition.ModuleTypeDxeDriver:
case CommonDefinition.ModuleTypeDxeSalDriver:
case CommonDefinition.ModuleTypeUefiDriver:
case CommonDefinition.ModuleTypeUefiApplication:
entryPointCount = 0;
fileBuffer.append("const UINT32 _gUefiDriverRevision = 0;\r\n");
// If entry point is null, create a empty ProcessModuleEntryPointList function.
if (entryPointList == null || entryPointList.length == 0){
fileBuffer
.append("GLOBAL_REMOVE_IF_UNREFERENCED const UINT8 _gDriverEntryPointCount = 0;\r\n");
fileBuffer.append("EFI_STATUS\r\n");
fileBuffer.append("EFIAPI\r\n");
fileBuffer.append("ProcessModuleEntryPointList (\r\n");
fileBuffer.append(" IN EFI_HANDLE ImageHandle,\r\n");
fileBuffer.append(" IN EFI_SYSTEM_TABLE *SystemTable\r\n");
fileBuffer.append(" )\r\n\r\n");
fileBuffer.append("{\r\n");
fileBuffer.append(" return EFI_SUCCESS;\r\n");
fileBuffer.append("}\r\n");
}else {
for (int i = 0; i < entryPointList.length; i++) {
fileBuffer.append("EFI_STATUS\r\n");
fileBuffer.append("EFIAPI\r\n");
fileBuffer.append(entryPointList[i]);
fileBuffer.append(" (\r\n");
fileBuffer.append(" IN EFI_HANDLE ImageHandle,\r\n");
fileBuffer.append(" IN EFI_SYSTEM_TABLE *SystemTable\r\n");
fileBuffer.append(" );\r\n");
entryPointCount++;
}
fileBuffer
.append("GLOBAL_REMOVE_IF_UNREFERENCED const UINT8 _gDriverEntryPointCount = ");
fileBuffer.append(Integer.toString(entryPointCount));
fileBuffer.append(";\r\n");
if (entryPointCount > 1) {
fileBuffer
.append("static BASE_LIBRARY_JUMP_BUFFER mJumpContext;\r\n");
fileBuffer
.append("static EFI_STATUS mDriverEntryPointStatus = EFI_LOAD_ERROR;\r\n");
}
fileBuffer.append("\n");
fileBuffer.append("EFI_STATUS\r\n");
fileBuffer.append("EFIAPI\r\n");
fileBuffer.append("ProcessModuleEntryPointList (\r\n");
fileBuffer.append(" IN EFI_HANDLE ImageHandle,\r\n");
fileBuffer.append(" IN EFI_SYSTEM_TABLE *SystemTable\r\n");
fileBuffer.append(" )\r\n\r\n");
fileBuffer.append("{\r\n");
if (entryPointCount == 1) {
fileBuffer.append(" return (");
fileBuffer.append(entryPointList[0]);
fileBuffer.append(" (ImageHandle, SystemTable));\r\n");
} else {
for (int i = 0; i < entryPointList.length; i++) {
if (!entryPointList[i].equals("")) {
fileBuffer
.append(" if (SetJump (&mJumpContext) == 0) {\r\n");
fileBuffer.append(" ExitDriver (");
fileBuffer.append(entryPointList[i]);
fileBuffer.append(" (ImageHandle, SystemTable));\r\n");
fileBuffer.append(" ASSERT (FALSE);\r\n");
fileBuffer.append(" }\r\n");
} else {
break;
}
}
fileBuffer.append(" return mDriverEntryPointStatus;\r\n");
}
fileBuffer.append("}\r\n\r\n");
fileBuffer.append("VOID\n");
fileBuffer.append("EFIAPI\n");
fileBuffer.append("ExitDriver (\r\n");
fileBuffer.append(" IN EFI_STATUS Status\n");
fileBuffer.append(" )\r\n\r\n");
fileBuffer.append("{\r\n");
if (entryPointCount <= 1) {
fileBuffer.append(" if (EFI_ERROR (Status)) {\r\n");
fileBuffer
.append(" ProcessLibraryDestructorList (gImageHandle, gST);\r\n");
fileBuffer.append(" }\r\n");
fileBuffer
.append(" gBS->Exit (gImageHandle, Status, 0, NULL);\r\n");
} else {
fileBuffer
.append(" if (!EFI_ERROR (Status) || EFI_ERROR (mDriverEntryPointStatus)) {\r\n");
fileBuffer.append(" mDriverEntryPointStatus = Status;\r\n");
fileBuffer.append(" }\r\n");
fileBuffer.append(" LongJump (&mJumpContext, (UINTN)-1);\r\n");
fileBuffer.append(" ASSERT (FALSE);\r\n");
}
fileBuffer.append("}\r\n\r\n");
}
// Add ModuleUnloadImage for DxeDriver and UefiDriver module type.
entryPointList = SurfaceAreaQuery.getModuleUnloadImageArray();
// Remover duplicate unload entry point.
entryPointList = CommonDefinition.remDupString(entryPointList);
entryPointCount = 0;
if (entryPointList != null) {
for (int i = 0; i < entryPointList.length; i++) {
fileBuffer.append("EFI_STATUS\r\n");
fileBuffer.append("EFIAPI\r\n");
fileBuffer.append(entryPointList[i]);
fileBuffer.append(" (\r\n");
fileBuffer
.append(" IN EFI_HANDLE ImageHandle\r\n");
fileBuffer.append(" );\r\n");
entryPointCount++;
}
}
fileBuffer
.append("GLOBAL_REMOVE_IF_UNREFERENCED const UINT8 _gDriverUnloadImageCount = ");
fileBuffer.append(Integer.toString(entryPointCount));
fileBuffer.append(";\r\n\r\n");
fileBuffer.append("EFI_STATUS\n");
fileBuffer.append("EFIAPI\r\n");
fileBuffer.append("ProcessModuleUnloadList (\r\n");
fileBuffer.append(" IN EFI_HANDLE ImageHandle\r\n");
fileBuffer.append(" )\r\n");
fileBuffer.append("{\r\n");
if (entryPointCount == 0) {
fileBuffer.append(" return EFI_SUCCESS;\r\n");
} else if (entryPointCount == 1) {
fileBuffer.append(" return ");
fileBuffer.append(entryPointList[0]);
fileBuffer.append("(ImageHandle);\r\n");
} else {
fileBuffer.append(" EFI_STATUS Status;\r\n\r\n");
fileBuffer.append(" Status = EFI_SUCCESS;\r\n\r\n");
for (int i = 0; i < entryPointList.length; i++) {
if (i == 0) {
fileBuffer.append(" Status = ");
fileBuffer.append(entryPointList[i]);
fileBuffer.append("(ImageHandle);\r\n");
}else{
fileBuffer.append(" if (EFI_ERROR (Status)) {\r\n");
fileBuffer.append(" ");
fileBuffer.append(entryPointList[i]);
fileBuffer.append("(ImageHandle);\r\n");
fileBuffer.append(" } else {\r\n");
fileBuffer.append(" Status = ");
fileBuffer.append(entryPointList[i]);
fileBuffer.append("(ImageHandle);\r\n");
fileBuffer.append(" }\r\n");
}
}
fileBuffer.append(" return Status;\r\n");
}
fileBuffer.append("}\r\n\r\n");
break;
}
}
/**
* PpiGuidToAutogenc
*
* This function gets GUIDs from SPD file accrodeing to <PPIs> information
* and write those GUIDs to AutoGen.c.
*
* @param fileBuffer
* String Buffer for Autogen.c file.
* @throws BuildException
* Guid must set value!
*/
void PpiGuidToAutogenC(StringBuffer fileBuffer) throws AutoGenException {
String[] cNameGuid = null;
// Get the all PPI adn PPI Notify from MSA file,
// then add those PPI ,and PPI Notify name to list.
String[] ppiList = SurfaceAreaQuery.getPpiArray(this.arch);
for (int i = 0; i < ppiList.length; i++) {
this.mPpiList.add(ppiList[i]);
}
String[] ppiNotifyList = SurfaceAreaQuery.getPpiNotifyArray(this.arch);
for (int i = 0; i < ppiNotifyList.length; i++) {
this.mPpiList.add(ppiNotifyList[i]);
}
// Find CNAME and GUID from dependence SPD file and write to Autogen.c
Iterator ppiIterator = this.mPpiList.iterator();
String ppiKeyWord = null;
while (ppiIterator.hasNext()) {
ppiKeyWord = ppiIterator.next().toString();
cNameGuid = GlobalData.getPpiGuid(this.mDepPkgList, ppiKeyWord);
if (cNameGuid != null) {
fileBuffer
.append("\r\nGLOBAL_REMOVE_IF_UNREFERENCED EFI_GUID ");
fileBuffer.append(cNameGuid[0]);
fileBuffer.append(" = { ");
fileBuffer.append(CommonDefinition.formatGuidName(cNameGuid[1]));
fileBuffer.append(" } ;");
} else {
// If can't find Ppi GUID declaration in every package
throw new AutoGenException("Can not find Ppi GUID ["
+ ppiKeyWord + "] declaration in every packages. ");
}
}
}
/**
* ProtocolGuidToAutogenc
*
* This function gets GUIDs from SPD file accrodeing to <Protocol>
* information and write those GUIDs to AutoGen.c.
*
* @param fileBuffer
* String Buffer for Autogen.c file.
* @throws BuildException
* Protocol name must set.
*/
void ProtocolGuidToAutogenC(StringBuffer fileBuffer) throws BuildException {
String[] cNameGuid = null;
String[] protocolList = SurfaceAreaQuery.getProtocolArray(this.arch);
// Add result to Autogen global list.
for (int i = 0; i < protocolList.length; i++) {
this.mProtocolList.add(protocolList[i]);
}
String[] protocolNotifyList = SurfaceAreaQuery
.getProtocolNotifyArray(this.arch);
for (int i = 0; i < protocolNotifyList.length; i++) {
this.mProtocolList.add(protocolNotifyList[i]);
}
// Get the NAME and GUID from dependence SPD and write to Autogen.c
Iterator protocolIterator = this.mProtocolList.iterator();
String protocolKeyWord = null;
while (protocolIterator.hasNext()) {
protocolKeyWord = protocolIterator.next().toString();
cNameGuid = GlobalData.getProtocolGuid(this.mDepPkgList, protocolKeyWord);
if (cNameGuid != null) {
fileBuffer
.append("\r\nGLOBAL_REMOVE_IF_UNREFERENCED EFI_GUID ");
fileBuffer.append(cNameGuid[0]);
fileBuffer.append(" = { ");
fileBuffer.append(CommonDefinition.formatGuidName(cNameGuid[1]));
fileBuffer.append(" } ;");
} else {
// If can't find protocol GUID declaration in every package
throw new BuildException("Can not find protocol Guid ["
+ protocolKeyWord + "] declaration in every packages. ");
}
}
}
/**
* GuidGuidToAutogenc
*
* This function gets GUIDs from SPD file accrodeing to <Guids> information
* and write those GUIDs to AutoGen.c.
*
* @param fileBuffer
* String Buffer for Autogen.c file.
*
*/
void GuidGuidToAutogenC(StringBuffer fileBuffer) throws AutoGenException {
String[] cNameGuid = null;
String guidKeyWord = null;
String[] guidList = SurfaceAreaQuery.getGuidEntryArray(this.arch);
for (int i = 0; i < guidList.length; i++) {
this.mGuidList.add(guidList[i]);
}
Iterator guidIterator = this.mGuidList.iterator();
while (guidIterator.hasNext()) {
guidKeyWord = guidIterator.next().toString();
cNameGuid = GlobalData.getGuid(this.mDepPkgList, guidKeyWord);
if (cNameGuid != null) {
fileBuffer
.append("\r\nGLOBAL_REMOVE_IF_UNREFERENCED EFI_GUID ");
fileBuffer.append(cNameGuid[0]);
fileBuffer.append(" = { ");
fileBuffer.append(CommonDefinition.formatGuidName(cNameGuid[1]));
fileBuffer.append("} ;");
} else {
// If can't find GUID declaration in every package
throw new AutoGenException("Can not find Guid [" + guidKeyWord
+ "] declaration in every packages. ");
}
}
}
/**
* LibInstanceToAutogenC
*
* This function adds dependent library instance to autogen.c,which
* includeing library's constructor, destructor, and library dependent ppi,
* protocol, guid, pcd information.
*
* @param fileBuffer
* String buffer for AutoGen.c
* @throws BuildException
*/
void LibInstanceToAutogenC(StringBuffer fileBuffer) throws BuildException {
int index;
String moduleType = SurfaceAreaQuery.getModuleType();
List<String> libConstructList = new ArrayList<String>();
List<String> libDestructList = new ArrayList<String>();
String libConstructName = null;
String libDestructName = null;
ModuleIdentification[] libraryIdList = SurfaceAreaQuery
.getLibraryInstance(this.arch);
try {
if (libraryIdList != null) {
// Reorder library instance sequence.
AutogenLibOrder libOrder = new AutogenLibOrder(libraryIdList,
this.arch);
List<ModuleIdentification> orderList = libOrder
.orderLibInstance();
if (orderList != null) {
// Process library instance one by one.
for (int i = 0; i < orderList.size(); i++) {
// Get library instance basename.
ModuleIdentification libInstanceId = orderList.get(i);
// Get override map
Map<String, XmlObject> libDoc = GlobalData.getDoc(
libInstanceId, this.arch);
SurfaceAreaQuery.push(libDoc);
// Get <PPis>, <Protocols>, <Guids> list of this library
// instance.
String[] ppiList = SurfaceAreaQuery.getPpiArray(this.arch);
String[] ppiNotifyList = SurfaceAreaQuery
.getPpiNotifyArray(this.arch);
String[] protocolList = SurfaceAreaQuery
.getProtocolArray(this.arch);
String[] protocolNotifyList = SurfaceAreaQuery
.getProtocolNotifyArray(this.arch);
String[] guidList = SurfaceAreaQuery
.getGuidEntryArray(this.arch);
PackageIdentification[] pkgList = SurfaceAreaQuery.getDependencePkg(this.arch);
// Add those ppi, protocol, guid in global ppi,
// protocol, guid
// list.
for (index = 0; index < ppiList.length; index++) {
this.mPpiList.add(ppiList[index]);
}
for (index = 0; index < ppiNotifyList.length; index++) {
this.mPpiList.add(ppiNotifyList[index]);
}
for (index = 0; index < protocolList.length; index++) {
this.mProtocolList.add(protocolList[index]);
}
for (index = 0; index < protocolNotifyList.length; index++) {
this.mProtocolList.add(protocolNotifyList[index]);
}
for (index = 0; index < guidList.length; index++) {
this.mGuidList.add(guidList[index]);
}
for (index = 0; index < pkgList.length; index++){
if (!this.mDepPkgList.contains(pkgList[index])){
this.mDepPkgList.add(pkgList[index]);
}
}
// If not yet parse this library instance's constructor
// element,parse it.
libConstructName = SurfaceAreaQuery
.getLibConstructorName();
libDestructName = SurfaceAreaQuery
.getLibDestructorName();
SurfaceAreaQuery.pop();
// Add dependent library instance constructor function.
if (libConstructName != null) {
libConstructList.add(libConstructName);
}
// Add dependent library instance destructor fuction.
if (libDestructName != null) {
libDestructList.add(libDestructName);
}
}
}
// Add library constructor to AutoGen.c
LibConstructorToAutogenC(libConstructList, moduleType,
fileBuffer/* autogenC */);
// Add library destructor to AutoGen.c
LibDestructorToAutogenC(libDestructList, moduleType, fileBuffer/* autogenC */);
}
} catch (Exception e) {
throw new BuildException(e.getMessage());
}
}
/**
* LibConstructorToAutogenc
*
* This function writes library constructor list to AutoGen.c. The library
* constructor's parameter and return value depend on module type.
*
* @param libInstanceList
* List of library construct name.
* @param moduleType
* Module type.
* @param fileBuffer
* String buffer for AutoGen.c
* @throws Exception
*/
void LibConstructorToAutogenC(List<String> libInstanceList,
String moduleType, StringBuffer fileBuffer) throws Exception {
boolean isFirst = true;
// The library constructor's parameter and return value depend on
// module type.
for (int i = 0; i < libInstanceList.size(); i++) {
switch (CommonDefinition.getModuleType(moduleType)) {
case CommonDefinition.ModuleTypeBase:
fileBuffer.append("RETURN_STATUS\r\n");
fileBuffer.append(libInstanceList.get(i));
fileBuffer.append(" (\r\n");
fileBuffer.append(" VOID\r\n");
fileBuffer.append(" );\r\n");
break;
case CommonDefinition.ModuleTypePeiCore:
case CommonDefinition.ModuleTypePeim:
fileBuffer.append("EFI_STATUS\r\n");
fileBuffer.append(libInstanceList.get(i));
fileBuffer.append(" (\r\n");
fileBuffer
.append(" IN EFI_FFS_FILE_HEADER *FfsHeader,\r\n");
fileBuffer
.append(" IN EFI_PEI_SERVICES **PeiServices\r\n");
fileBuffer.append(" );\r\n");
break;
case CommonDefinition.ModuleTypeDxeCore:
case CommonDefinition.ModuleTypeDxeDriver:
case CommonDefinition.ModuleTypeDxeRuntimeDriver:
case CommonDefinition.ModuleTypeDxeSmmDriver:
case CommonDefinition.ModuleTypeDxeSalDriver:
case CommonDefinition.ModuleTypeUefiDriver:
case CommonDefinition.ModuleTypeUefiApplication:
fileBuffer.append("EFI_STATUS\r\n");
fileBuffer.append(libInstanceList.get(i));
fileBuffer.append(" (\r\n");
fileBuffer.append(" IN EFI_HANDLE ImageHandle,\r\n");
fileBuffer.append(" IN EFI_SYSTEM_TABLE *SystemTable\r\n");
fileBuffer.append(" );\r\n");
break;
}
}
// Add ProcessLibraryConstructorList in AutoGen.c
fileBuffer.append("VOID\r\n");
fileBuffer.append("ProcessLibraryConstructorList (\r\n");
switch (CommonDefinition.getModuleType(moduleType)) {
case CommonDefinition.ModuleTypeBase:
fileBuffer.append(" VOID\r\n");
break;
case CommonDefinition.ModuleTypePeiCore:
case CommonDefinition.ModuleTypePeim:
fileBuffer.append(" IN EFI_FFS_FILE_HEADER *FfsHeader,\r\n");
fileBuffer
.append(" IN EFI_PEI_SERVICES **PeiServices\r\n");
break;
case CommonDefinition.ModuleTypeDxeCore:
case CommonDefinition.ModuleTypeDxeDriver:
case CommonDefinition.ModuleTypeDxeRuntimeDriver:
case CommonDefinition.ModuleTypeDxeSmmDriver:
case CommonDefinition.ModuleTypeDxeSalDriver:
case CommonDefinition.ModuleTypeUefiDriver:
case CommonDefinition.ModuleTypeUefiApplication:
fileBuffer.append(" IN EFI_HANDLE ImageHandle,\r\n");
fileBuffer.append(" IN EFI_SYSTEM_TABLE *SystemTable\r\n");
break;
}
fileBuffer.append(" )\r\n");
fileBuffer.append("{\r\n");
// If no constructor function, return EFI_SUCCESS.
//if (libInstanceList.size() == 0){
// fileBuffer.append(" return EFI_SUCCESS;\r\n");
for (int i = 0; i < libInstanceList.size(); i++) {
if (isFirst) {
fileBuffer.append(" EFI_STATUS Status;\r\n");
fileBuffer.append(" Status = EFI_SUCCESS;\r\n");
fileBuffer.append("\r\n");
isFirst = false;
}
switch (CommonDefinition.getModuleType(moduleType)) {
case CommonDefinition.ModuleTypeBase:
fileBuffer.append(" Status = ");
fileBuffer.append(libInstanceList.get(i));
fileBuffer.append("();\r\n");
fileBuffer.append(" VOID\r\n");
break;
case CommonDefinition.ModuleTypePeiCore:
case CommonDefinition.ModuleTypePeim:
fileBuffer.append(" Status = ");
fileBuffer.append(libInstanceList.get(i));
fileBuffer.append(" (FfsHeader, PeiServices);\r\n");
break;
case CommonDefinition.ModuleTypeDxeCore:
case CommonDefinition.ModuleTypeDxeDriver:
case CommonDefinition.ModuleTypeDxeRuntimeDriver:
case CommonDefinition.ModuleTypeDxeSmmDriver:
case CommonDefinition.ModuleTypeDxeSalDriver:
case CommonDefinition.ModuleTypeUefiDriver:
case CommonDefinition.ModuleTypeUefiApplication:
fileBuffer.append(" Status = ");
fileBuffer.append(libInstanceList.get(i));
fileBuffer.append(" (ImageHandle, SystemTable);\r\n");
break;
default:
EdkLog.log(EdkLog.EDK_INFO,"Autogen don't know how to deal with module type -"+ moduleType + " !");
}
fileBuffer.append(" ASSERT_EFI_ERROR (Status);\r\n");
}
fileBuffer.append("}\r\n");
}
/**
* LibDestructorToAutogenc
*
* This function writes library destructor list to AutoGen.c. The library
* destructor's parameter and return value depend on module type.
*
* @param libInstanceList
* List of library destructor name.
* @param moduleType
* Module type.
* @param fileBuffer
* String buffer for AutoGen.c
* @throws Exception
*/
void LibDestructorToAutogenC(List<String> libInstanceList,
String moduleType, StringBuffer fileBuffer) throws Exception {
boolean isFirst = true;
for (int i = 0; i < libInstanceList.size(); i++) {
switch (CommonDefinition.getModuleType(moduleType)) {
case CommonDefinition.ModuleTypeBase:
fileBuffer.append("RETURN_STATUS\n");
fileBuffer.append(libInstanceList.get(i));
fileBuffer.append(" (\r\n");
fileBuffer.append(" VOID\r\n");
fileBuffer.append(" );\r\n");
break;
case CommonDefinition.ModuleTypePeiCore:
case CommonDefinition.ModuleTypePeim:
fileBuffer.append("EFI_STATUS\r\n");
fileBuffer.append(libInstanceList.get(i));
fileBuffer.append(" (\r\n");
fileBuffer
.append(" IN EFI_FFS_FILE_HEADER *FfsHeader,\r\n");
fileBuffer
.append(" IN EFI_PEI_SERVICES **PeiServices\r\n");
fileBuffer.append(" );\r\n");
break;
case CommonDefinition.ModuleTypeDxeCore:
case CommonDefinition.ModuleTypeDxeDriver:
case CommonDefinition.ModuleTypeDxeRuntimeDriver:
case CommonDefinition.ModuleTypeDxeSmmDriver:
case CommonDefinition.ModuleTypeDxeSalDriver:
case CommonDefinition.ModuleTypeUefiDriver:
case CommonDefinition.ModuleTypeUefiApplication:
fileBuffer.append("EFI_STATUS\r\n");
fileBuffer.append(libInstanceList.get(i));
fileBuffer.append(" (\r\n");
fileBuffer.append(" IN EFI_HANDLE ImageHandle,\r\n");
fileBuffer.append(" IN EFI_SYSTEM_TABLE *SystemTable\r\n");
fileBuffer.append(" );\r\n");
break;
}
}
// Write ProcessLibraryDestructor list to autogen.c
switch (CommonDefinition.getModuleType(moduleType)) {
case CommonDefinition.ModuleTypeBase:
case CommonDefinition.ModuleTypePeiCore:
case CommonDefinition.ModuleTypePeim:
break;
case CommonDefinition.ModuleTypeDxeCore:
case CommonDefinition.ModuleTypeDxeDriver:
case CommonDefinition.ModuleTypeDxeRuntimeDriver:
case CommonDefinition.ModuleTypeDxeSmmDriver:
case CommonDefinition.ModuleTypeDxeSalDriver:
case CommonDefinition.ModuleTypeUefiDriver:
case CommonDefinition.ModuleTypeUefiApplication:
fileBuffer.append("VOID\r\n");
fileBuffer.append("ProcessLibraryDestructorList (\r\n");
fileBuffer.append(" IN EFI_HANDLE ImageHandle,\r\n");
fileBuffer.append(" IN EFI_SYSTEM_TABLE *SystemTable\r\n");
fileBuffer.append(" )\r\n");
fileBuffer.append("{\r\n");
// If no library destructor function, return EFI_SUCCESS.
for (int i = 0; i < libInstanceList.size(); i++) {
if (isFirst) {
fileBuffer.append(" EFI_STATUS Status;\r\n");
fileBuffer.append(" Status = EFI_SUCCESS;\r\n");
fileBuffer.append("\r\n");
isFirst = false;
}
fileBuffer.append(" Status = ");
fileBuffer.append(libInstanceList.get(i));
fileBuffer.append("(ImageHandle, SystemTable);\r\n");
fileBuffer.append(" ASSERT_EFI_ERROR (Status);\r\n");
}
fileBuffer.append("}\r\n");
break;
}
}
/**
* ExternsDriverBindingToAutoGenC
*
* This function is to write DRIVER_BINDING, COMPONENT_NAME,
* DRIVER_CONFIGURATION, DRIVER_DIAGNOSTIC in AutoGen.c.
*
* @param fileBuffer
* String buffer for AutoGen.c
*/
void ExternsDriverBindingToAutoGenC(StringBuffer fileBuffer)
throws BuildException {
// Check what <extern> contains. And the number of following elements
// under <extern> should be same. 1. DRIVER_BINDING 2. COMPONENT_NAME
// 3.DRIVER_CONFIGURATION 4. DRIVER_DIAGNOSTIC
String[] drvBindList = SurfaceAreaQuery.getDriverBindingArray();
// If component name protocol,component configuration protocol,
// component diagnostic protocol is not null or empty, check
// if every one have the same number of the driver binding protocol.
if (drvBindList == null || drvBindList.length == 0) {
return;
}
String[] compNamList = SurfaceAreaQuery.getComponentNameArray();
String[] compConfList = SurfaceAreaQuery.getDriverConfigArray();
String[] compDiagList = SurfaceAreaQuery.getDriverDiagArray();
int BitMask = 0;
// Write driver binding protocol extern to autogen.c
for (int i = 0; i < drvBindList.length; i++) {
fileBuffer.append("extern EFI_DRIVER_BINDING_PROTOCOL ");
fileBuffer.append(drvBindList[i]);
fileBuffer.append(";\r\n");
}
// Write component name protocol extern to autogen.c
if (compNamList != null && compNamList.length != 0) {
if (drvBindList.length != compNamList.length) {
throw new BuildException(
"Different number of Driver Binding and Component Name protocols!");
}
BitMask |= 0x01;
for (int i = 0; i < compNamList.length; i++) {
fileBuffer.append("extern EFI_COMPONENT_NAME_PROTOCOL ");
fileBuffer.append(compNamList[i]);
fileBuffer.append(";\r\n");
}
}
// Write driver configration protocol extern to autogen.c
if (compConfList != null && compConfList.length != 0) {
if (drvBindList.length != compConfList.length) {
throw new BuildException(
"Different number of Driver Binding and Driver Configuration protocols!");
}
BitMask |= 0x02;
for (int i = 0; i < compConfList.length; i++) {
fileBuffer.append("extern EFI_DRIVER_CONFIGURATION_PROTOCOL ");
fileBuffer.append(compConfList[i]);
fileBuffer.append(";\r\n");
}
}
// Write driver dignastic protocol extern to autogen.c
if (compDiagList != null && compDiagList.length != 0) {
if (drvBindList.length != compDiagList.length) {
throw new BuildException(
"Different number of Driver Binding and Driver Diagnosis protocols!");
}
BitMask |= 0x04;
for (int i = 0; i < compDiagList.length; i++) {
fileBuffer.append("extern EFI_DRIVER_DIAGNOSTICS_PROTOCOL ");
fileBuffer.append(compDiagList[i]);
fileBuffer.append(";\r\n");
}
}
// Write driver module protocol bitmask.
fileBuffer
.append("GLOBAL_REMOVE_IF_UNREFERENCED const UINT8 _gDriverModelProtocolBitmask = ");
fileBuffer.append(Integer.toString(BitMask));
fileBuffer.append(";\r\n");
// Write driver module protocol list entry
fileBuffer
.append("GLOBAL_REMOVE_IF_UNREFERENCED const UINTN _gDriverModelProtocolListEntries = ");
fileBuffer.append(Integer.toString(drvBindList.length));
fileBuffer.append(";\r\n");
// Write drive module protocol list to autogen.c
fileBuffer
.append("GLOBAL_REMOVE_IF_UNREFERENCED const EFI_DRIVER_MODEL_PROTOCOL_LIST _gDriverModelProtocolList[] = {");
for (int i = 0; i < drvBindList.length; i++) {
if (i != 0) {
fileBuffer.append(",");
}
fileBuffer.append("\r\n {\r\n");
fileBuffer.append(" &");
fileBuffer.append(drvBindList[i]);
fileBuffer.append(", \r\n");
if (compNamList != null) {
fileBuffer.append(" &");
fileBuffer.append(compNamList[i]);
fileBuffer.append(", \r\n");
} else {
fileBuffer.append(" NULL, \r\n");
}
if (compConfList != null) {
fileBuffer.append(" &");
fileBuffer.append(compConfList[i]);
fileBuffer.append(", \r\n");
} else {
fileBuffer.append(" NULL, \r\n");
}
if (compDiagList != null) {
fileBuffer.append(" &");
fileBuffer.append(compDiagList[i]);
fileBuffer.append(", \r\n");
} else {
fileBuffer.append(" NULL, \r\n");
}
fileBuffer.append(" }");
}
fileBuffer.append("\r\n};\r\n");
}
/**
* ExternCallBackToAutoGenC
*
* This function adds <SetVirtualAddressMapCallBack> and
* <ExitBootServicesCallBack> infomation to AutoGen.c
*
* @param fileBuffer
* String buffer for AutoGen.c
* @throws BuildException
*/
void ExternCallBackToAutoGenC(StringBuffer fileBuffer)
throws BuildException {
String[] setVirtualList = SurfaceAreaQuery
.getSetVirtualAddressMapCallBackArray();
String[] exitBootList = SurfaceAreaQuery
.getExitBootServicesCallBackArray();
String moduleType = SurfaceAreaQuery.getModuleType();
boolean UefiOrDxeModule = false;
int Count = 0;
int i;
switch (CommonDefinition.getModuleType(moduleType)) {
case CommonDefinition.ModuleTypeDxeDriver:
case CommonDefinition.ModuleTypeDxeRuntimeDriver:
case CommonDefinition.ModuleTypeDxeSalDriver:
case CommonDefinition.ModuleTypeUefiDriver:
case CommonDefinition.ModuleTypeUefiApplication:
// Entry point lib for these module types needs to know the count
// of entryPoint.
UefiOrDxeModule = true;
fileBuffer
.append("\r\nGLOBAL_REMOVE_IF_UNREFERENCED const UINTN _gDriverSetVirtualAddressMapEventCount = ");
// If the list is not valid or has no entries set count to zero else
// set count to the number of valid entries
Count = 0;
if (setVirtualList != null) {
for (i = 0; i < setVirtualList.length; i++) {
if (setVirtualList[i].equalsIgnoreCase("")) {
break;
}
}
Count = i;
}
fileBuffer.append(Integer.toString(Count));
fileBuffer.append(";\r\n\r\n");
break;
default:
break;
}
if (setVirtualList == null) {
if (UefiOrDxeModule) {
// No data so make a NULL list
fileBuffer
.append("\r\nGLOBAL_REMOVE_IF_UNREFERENCED const EFI_EVENT_NOTIFY _gDriverSetVirtualAddressMapEvent[] = {\r\n");
fileBuffer.append(" NULL\r\n");
fileBuffer.append("};\r\n\r\n");
}
} else {
// Write SetVirtualAddressMap function definition.
for (i = 0; i < setVirtualList.length; i++) {
if (setVirtualList[i].equalsIgnoreCase("")) {
break;
}
fileBuffer.append("VOID\r\n");
fileBuffer.append("EFIAPI\r\n");
fileBuffer.append(setVirtualList[i]);
fileBuffer.append(" (\r\n");
fileBuffer.append(" IN EFI_EVENT Event,\r\n");
fileBuffer.append(" IN VOID *Context\r\n");
fileBuffer.append(" );\r\n\r\n");
}
// Write SetVirtualAddressMap entry point array.
fileBuffer
.append("\r\nGLOBAL_REMOVE_IF_UNREFERENCED const EFI_EVENT_NOTIFY _gDriverSetVirtualAddressMapEvent[] = {");
for (i = 0; i < setVirtualList.length; i++) {
if (setVirtualList[i].equalsIgnoreCase("")) {
break;
}
if (i == 0) {
fileBuffer.append("\r\n ");
} else {
fileBuffer.append(",\r\n ");
}
fileBuffer.append(setVirtualList[i]);
}
// If module is not DXE_DRIVER, DXE_RUNTIME_DIRVER, UEFI_DRIVER
// UEFI_APPLICATION and DXE_SAL_DRIVER add the NULL at the end of
// _gDriverSetVirtualAddressMapEvent list.
if (!UefiOrDxeModule) {
fileBuffer.append(",\r\n NULL");
}
fileBuffer.append("\r\n};\r\n\r\n");
}
if (UefiOrDxeModule) {
// Entry point lib for these module types needs to know the count.
fileBuffer
.append("\r\nGLOBAL_REMOVE_IF_UNREFERENCED const UINTN _gDriverExitBootServicesEventCount = ");
// If the list is not valid or has no entries set count to zero else
// set count to the number of valid entries.
Count = 0;
if (exitBootList != null) {
for (i = 0; i < exitBootList.length; i++) {
if (exitBootList[i].equalsIgnoreCase("")) {
break;
}
}
Count = i;
}
fileBuffer.append(Integer.toString(Count));
fileBuffer.append(";\r\n\r\n");
}
if (exitBootList == null) {
if (UefiOrDxeModule) {
// No data so make a NULL list.
fileBuffer
.append("\r\nGLOBAL_REMOVE_IF_UNREFERENCED const EFI_EVENT_NOTIFY _gDriverExitBootServicesEvent[] = {\r\n");
fileBuffer.append(" NULL\r\n");
fileBuffer.append("};\r\n\r\n");
}
} else {
// Write DriverExitBootServices function definition.
for (i = 0; i < exitBootList.length; i++) {
if (exitBootList[i].equalsIgnoreCase("")) {
break;
}
fileBuffer.append("VOID\r\n");
fileBuffer.append("EFIAPI\r\n");
fileBuffer.append(exitBootList[i]);
fileBuffer.append(" (\r\n");
fileBuffer.append(" IN EFI_EVENT Event,\r\n");
fileBuffer.append(" IN VOID *Context\r\n");
fileBuffer.append(" );\r\n\r\n");
}
// Write DriverExitBootServices entry point array.
fileBuffer
.append("\r\nGLOBAL_REMOVE_IF_UNREFERENCED const EFI_EVENT_NOTIFY _gDriverExitBootServicesEvent[] = {");
for (i = 0; i < exitBootList.length; i++) {
if (exitBootList[i].equalsIgnoreCase("")) {
break;
}
if (i == 0) {
fileBuffer.append("\r\n ");
} else {
fileBuffer.append(",\r\n ");
}
fileBuffer.append(exitBootList[i]);
}
if (!UefiOrDxeModule) {
fileBuffer.append(",\r\n NULL");
}
fileBuffer.append("\r\n};\r\n\r\n");
}
}
private void copyFlashMapHToDebugDir() throws AutoGenException{
File inFile = new File(fvDir + File.separatorChar + CommonDefinition.flashMapH);
int size = (int)inFile.length();
byte[] buffer = new byte[size];
File outFile = new File (this.outputPath + File.separatorChar + CommonDefinition.tianoR8FlashMapH);
// If TianoR8FlashMap.h existed and the flashMap.h don't change,
// do nothing.
if ((!outFile.exists()) ||(inFile.lastModified() - outFile.lastModified()) >= 0) {
try{
if (inFile.exists()) {
FileInputStream fis = new FileInputStream (inFile);
fis.read(buffer);
FileOutputStream fos = new FileOutputStream(outFile);
fos.write(buffer);
fis.close();
fos.close();
}else {
throw new AutoGenException("The flashMap.h file don't exist!!");
}
} catch (Exception e){
throw new AutoGenException(e.getMessage());
}
}
}
} |
package com.intellij.uiDesigner.compiler;
import com.intellij.uiDesigner.lw.LwRootContainer;
import com.intellij.uiDesigner.lw.PropertiesProvider;
import org.jdom.input.SAXBuilder;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import javax.swing.*;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.StringReader;
import java.lang.reflect.Constructor;
import java.lang.reflect.Member;
/**
* @author Anton Katilin
* @author Vladimir Kondratyev
*
* NOTE: the class must be compilable with JDK 1.3, so any methods and filds introduced in 1.4 or later must not be used
*
*/
public final class Utils {
public static final String FORM_NAMESPACE = "http:
private static final SAXParser SAX_PARSER = createParser();
private static SAXParser createParser() {
try {
return SAXParserFactory.newInstance().newSAXParser();
}
catch (Exception e) {
return null;
}
}
/**
* @param provider if null, no classes loaded and no properties read
*/
public static LwRootContainer getRootContainer(final String formFileContent, final PropertiesProvider provider) throws Exception{
if (formFileContent.indexOf(FORM_NAMESPACE) == -1) {
throw new AlienFormFileException();
}
final org.jdom.Document document = new SAXBuilder().build(new StringReader(formFileContent), "UTF-8");
final LwRootContainer root = new LwRootContainer();
root.read(document.getRootElement(), provider);
return root;
}
public synchronized static String getBoundClassName(final String formFileContent) throws Exception {
if (formFileContent.indexOf(FORM_NAMESPACE) == -1) {
throw new AlienFormFileException();
}
final String[] className = new String[] {null};
try {
SAX_PARSER.parse(new InputSource(new StringReader(formFileContent)), new DefaultHandler() {
public void startElement(String uri,
String localName,
String qName,
Attributes attributes)
throws SAXException {
if ("form".equals(qName)) {
className[0] = attributes.getValue("", "bind-to-class");
throw new SAXException("stop parsing");
}
}
});
}
catch (Exception e) {
// Do nothing.
}
return className[0];
}
/**
* Validates that specified class represents {@link javax.swing.JComponent} with
* empty constructor.
*
* @return descriptive human readable error message or <code>null</code> if
* no errors were detected.
*/
public static String validateJComponentClass(final ClassLoader loader, final String className){
if(loader == null){
throw new IllegalArgumentException("loader cannot be null");
}
if(className == null){
throw new IllegalArgumentException("className cannot be null");
}
// These classes are not visible for passed class loader!
if(
"com.intellij.uiDesigner.HSpacer".equals(className) ||
"com.intellij.uiDesigner.VSpacer".equals(className)
){
return null;
}
final Class aClass;
try {
aClass = Class.forName(className, true, loader);
}
catch (final ClassNotFoundException exc) {
return "Class \"" + className + "\"not found";
}
catch (NoClassDefFoundError exc) {
return "Cannot load class " + className + ": " + exc.getMessage();
}
try {
final Constructor constructor = aClass.getConstructor(new Class[0]);
if ((constructor.getModifiers() & Member.PUBLIC) != 0) {
return "Class \"" + className + "\" does not have default public constructor";
}
}
catch (final Exception exc) {
return "Class \"" + className + "\" does not have default constructor";
}
// Check that JComponent is accessible via the loader
if(!JComponent.class.isAssignableFrom(aClass)){
return "Class \"" + className + "\" is not an instance of javax.swing.JComponent";
}
return null;
}
} |
package fi.solita.botsofbf;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.*;
@RestController
public class BotController {
// The map consists of tiles with one of the following type:
private static final char WALL_TILE = 'x';
private static final char FLOOR_TILE = '_';
private static final char EXIT_TILE = 'o';
// FIXME use correct server IP address
private static final String SERVER_ADDRESS = "http://localhost:8080";
private static final String MY_REST_API_PATH = "/move";
private static final String MY_REST_API_ADDRESS = "http://%s:9080" + MY_REST_API_PATH;
private UUID myBotId;
private int botVersion = 1;
@RequestMapping(value = "/bot", method = RequestMethod.POST)
public void registerBot() throws UnknownHostException {
myBotId = registerPlayer("myUniqueBotName " + botVersion).id;
botVersion += 1;
}
@RequestMapping(value = "/chat", method = RequestMethod.POST)
public void chat(@RequestBody String message) {
sendChatMessage(myBotId, message);
}
private RegisterResponse registerPlayer(String playerName) throws UnknownHostException {
RestTemplate restTemplate = new RestTemplate();
String myRestApiAddress = String.format(MY_REST_API_ADDRESS, InetAddress.getLocalHost().getHostAddress());
Registration registration = new Registration(playerName, myRestApiAddress);
ResponseEntity<RegisterResponse> result =
restTemplate.postForEntity(SERVER_ADDRESS + "/register", registration, RegisterResponse.class);
return result.getBody();
}
@RequestMapping(value = MY_REST_API_PATH, method = RequestMethod.POST)
public @ResponseBody
Move move(@RequestBody GameStateChanged gameStateChanged) {
Player myPlayer = gameStateChanged.playerState;
Set<Item> items = gameStateChanged.gameState.items;
Map map = gameStateChanged.gameState.map;
System.out.println("My player is at " + myPlayer.position.x + ", " + myPlayer.position.y);
System.out.println("The map has " + items.size() + " items");
System.out.println("The map consists of " + map.tiles.size() + " x " + map.tiles.get(0).length() + " tiles");
Move nextMove = Arrays.asList(Move.UP, Move.LEFT, Move.DOWN, Move.RIGHT).get(new Random().nextInt(4));
return nextMove;
}
private void sendChatMessage(UUID playerId, String message) {
new RestTemplate().postForEntity(
String.format(SERVER_ADDRESS + "/%s/say", playerId),
message, Void.class);
}
public static class Map {
public int width;
public int height;
public List<String> tiles;
}
public static class Player {
public Position position;
public String name;
public String url;
public int score;
public int money;
public int health;
public List<Item> usableItems;
}
public enum Move {
UP,
DOWN,
RIGHT,
LEFT,
PICK,
USE // valid if the item is usable
}
public static class Item {
public int price;
public Position position;
public Type type;
public boolean isUsable;
public enum Type {
JUST_SOME_JUNK,
WEAPON
}
}
public static class Position {
public int x;
public int y;
}
private static class Registration {
public String playerName;
public String url;
public Registration(String playerName, String url) {
this.playerName = playerName;
this.url = url;
}
}
public static class RegisterResponse {
public UUID id;
public Player player;
public GameState gameState;
}
public static class GameStateChanged {
public GameState gameState;
public Player playerState;
}
public static class GameState {
public Map map;
public Set<Player> players;
public Set<Item> items;
}
} |
package <%=packageName%>.service;
<% if (databaseType == 'cassandra') { %>
import <%=packageName%>.AbstractCassandraTest;<% } %>
import <%=packageName%>.<%= mainClass %>;<% if ((databaseType == 'sql' || databaseType == 'mongodb') && authenticationType == 'session') { %>
import <%=packageName%>.domain.PersistentToken;<% } %>
import <%=packageName%>.domain.User;<% if ((databaseType == 'sql' || databaseType == 'mongodb') && authenticationType == 'session') { %>
import <%=packageName%>.repository.PersistentTokenRepository;<% } %>
import <%=packageName%>.config.Constants;
import <%=packageName%>.repository.UserRepository;
import <%=packageName%>.service.dto.UserDTO;
import <%=packageName%>.web.rest.UserResourceIntTest;
import java.time.ZonedDateTime;<% if (databaseType == 'sql' || databaseType == 'mongodb') { %>
import <%=packageName%>.service.util.RandomUtil;<% } %><% if ((databaseType == 'sql' || databaseType == 'mongodb') && authenticationType == 'session') { %>
import java.time.LocalDate;<% } %>
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;<% if (databaseType == 'sql') { %>
import org.springframework.transaction.annotation.Transactional;<% } %>
import org.springframework.test.context.junit4.SpringRunner;
<% if (databaseType == 'sql' || databaseType == 'mongodb') { %>
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import java.util.Optional;<%}%>
import java.util.List;
import static org.assertj.core.api.Assertions.*;
/**
* Test class for the UserResource REST controller.
*
* @see UserService
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = <%= mainClass %>.class)<% if (databaseType == 'sql') { %>
@Transactional<% } %>
public class UserServiceIntTest <% if (databaseType == 'cassandra') { %>extends AbstractCassandraTest <% } %>{<% if ((databaseType == 'sql' || databaseType == 'mongodb') && authenticationType == 'session') { %>
@Autowired
private PersistentTokenRepository persistentTokenRepository;<% } %>
@Autowired
private UserRepository userRepository;
@Autowired
private UserService userService;
private User user;
@Before
public void init() {<% if ((databaseType == 'sql' || databaseType == 'mongodb') && authenticationType == 'session') { %>
persistentTokenRepository.deleteAll();<% } %>
<%_ if (databaseType !== 'sql') { _%>
userRepository.deleteAll();
<%_ } _%>
user = UserResourceIntTest.createEntity(<% if (databaseType === 'sql') { %>null<% } %>);
}<% if ((databaseType == 'sql' || databaseType == 'mongodb') && authenticationType == 'session') { %>
@Test
<%_ if (databaseType === 'sql') { _%>
@Transactional
<%_ } _%>
public void testRemoveOldPersistentTokens() {
userRepository.save<% if (databaseType == 'sql') { %>AndFlush<% } %>(user);
int existingCount = persistentTokenRepository.findByUser(user).size();
generateUserToken(user, "1111-1111", LocalDate.now());
LocalDate now = LocalDate.now();
generateUserToken(user, "2222-2222", now.minusDays(32));
assertThat(persistentTokenRepository.findByUser(user)).hasSize(existingCount + 2);
userService.removeOldPersistentTokens();
assertThat(persistentTokenRepository.findByUser(user)).hasSize(existingCount + 1);
}<% } %><% if (databaseType == 'sql' || databaseType == 'mongodb') { %>
@Test
<%_ if (databaseType === 'sql') { _%>
@Transactional
<%_ } _%>
public void assertThatUserMustExistToResetPassword() {
userRepository.save<% if (databaseType == 'sql') { %>AndFlush<% } %>(user);
Optional<User> maybeUser = userService.requestPasswordReset("invalid.login@localhost");
assertThat(maybeUser.isPresent()).isFalse();
maybeUser = userService.requestPasswordReset(user.getEmail());
assertThat(maybeUser.isPresent()).isTrue();
assertThat(maybeUser.get().getEmail()).isEqualTo(user.getEmail());
assertThat(maybeUser.get().getResetDate()).isNotNull();
assertThat(maybeUser.get().getResetKey()).isNotNull();
}
@Test
<%_ if (databaseType === 'sql') { _%>
@Transactional
<%_ } _%>
public void assertThatOnlyActivatedUserCanRequestPasswordReset() {
user.setActivated(false);
userRepository.save<% if (databaseType == 'sql') { %>AndFlush<% } %>(user);
Optional<User> maybeUser = userService.requestPasswordReset(user.getLogin());
assertThat(maybeUser.isPresent()).isFalse();
userRepository.delete(user);
}
@Test
<%_ if (databaseType === 'sql') { _%>
@Transactional
<%_ } _%>
public void assertThatResetKeyMustNotBeOlderThan24Hours() {
ZonedDateTime daysAgo = ZonedDateTime.now().minusHours(25);
String resetKey = RandomUtil.generateResetKey();
user.setActivated(true);
user.setResetDate(daysAgo);
user.setResetKey(resetKey);
userRepository.save<% if (databaseType == 'sql') { %>AndFlush<% } %>(user);
Optional<User> maybeUser = userService.completePasswordReset("johndoe2", user.getResetKey());
assertThat(maybeUser.isPresent()).isFalse();
userRepository.delete(user);
}
@Test
<%_ if (databaseType === 'sql') { _%>
@Transactional
<%_ } _%>
public void assertThatResetKeyMustBeValid() {
ZonedDateTime daysAgo = ZonedDateTime.now().minusHours(25);
user.setActivated(true);
user.setResetDate(daysAgo);
user.setResetKey("1234");
userRepository.save<% if (databaseType == 'sql') { %>AndFlush<% } %>(user);
Optional<User> maybeUser = userService.completePasswordReset("johndoe2", user.getResetKey());
assertThat(maybeUser.isPresent()).isFalse();
userRepository.delete(user);
}
@Test
<%_ if (databaseType === 'sql') { _%>
@Transactional
<%_ } _%>
public void assertThatUserCanResetPassword() {
String oldPassword = user.getPassword();
ZonedDateTime daysAgo = ZonedDateTime.now().minusHours(2);
String resetKey = RandomUtil.generateResetKey();
user.setActivated(true);
user.setResetDate(daysAgo);
user.setResetKey(resetKey);
userRepository.save<% if (databaseType == 'sql') { %>AndFlush<% } %>(user);
Optional<User> maybeUser = userService.completePasswordReset("johndoe2", user.getResetKey());
assertThat(maybeUser.isPresent()).isTrue();
assertThat(maybeUser.get().getResetDate()).isNull();
assertThat(maybeUser.get().getResetKey()).isNull();
assertThat(maybeUser.get().getPassword()).isNotEqualTo(oldPassword);
userRepository.delete(user);
}
@Test
<%_ if (databaseType === 'sql') { _%>
@Transactional
<%_ } _%>
public void testFindNotActivatedUsersByCreationDateBefore() {
ZonedDateTime now = ZonedDateTime.now();
user.setActivated(false);
User dbUser = userRepository.save<% if (databaseType == 'sql') { %>AndFlush<% } %>(user);
dbUser.setCreatedDate(now.minusDays(4));
userRepository.save<% if (databaseType == 'sql') { %>AndFlush<% } %>(user);
List<User> users = userRepository.findAllByActivatedIsFalseAndCreatedDateBefore(now.minusDays(3));
assertThat(users).isNotEmpty();
userService.removeNotActivatedUsers();
users = userRepository.findAllByActivatedIsFalseAndCreatedDateBefore(now.minusDays(3));
assertThat(users).isEmpty();
}<% } %><% if ((databaseType == 'sql' || databaseType == 'mongodb') && authenticationType == 'session') { %>
private void generateUserToken(User user, String tokenSeries, LocalDate localDate) {
PersistentToken token = new PersistentToken();
token.setSeries(tokenSeries);
token.setUser(user);
token.setTokenValue(tokenSeries + "-data");
token.setTokenDate(localDate);
token.setIpAddress("127.0.0.1");
token.setUserAgent("Test agent");
persistentTokenRepository.save<% if (databaseType == 'sql') { %>AndFlush<% } %>(token);
}<% } %>
@Test
<%_ if (databaseType === 'sql') { _%>
@Transactional
<%_ } _%>
public void assertThatAnonymousUserIsNotGet() {
user.setLogin(Constants.ANONYMOUS_USER);
if (!userRepository.findOneByLogin(Constants.ANONYMOUS_USER).isPresent()) {
userRepository.save<% if (databaseType == 'sql') { %>AndFlush<% } %>(user);
}<% if (databaseType == 'sql' || databaseType == 'mongodb') { %>
final PageRequest pageable = new PageRequest(0, (int) userRepository.count());
final Page<UserDTO> allManagedUsers = userService.getAllManagedUsers(pageable);
assertThat(allManagedUsers.getContent().stream()<% } %><% if (databaseType == 'cassandra') { %>
final List<UserDTO> allManagedUsers = userService.getAllManagedUsers();
assertThat(allManagedUsers.stream()<% } %>
.noneMatch(user -> Constants.ANONYMOUS_USER.equals(user.getLogin())))
.isTrue();
}
} |
package com.uservoice.uservoicesdk.model;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import com.uservoice.uservoicesdk.rest.Callback;
import com.uservoice.uservoicesdk.rest.RestTask;
import com.uservoice.uservoicesdk.rest.RestTaskCallback;
public class Article extends BaseModel implements Parcelable {
private String title;
private String html;
private String topicName;
private int weight;
public Article() {
}
public static void loadAll(final Callback<List<Article>> callback) {
Map<String, String> params = new HashMap<String, String>();
params.put("sort", "ordered");
doGet(apiPath("/articles.json"), params, new RestTaskCallback(callback) {
@Override
public void onComplete(JSONObject result) throws JSONException {
callback.onModel(deserializeList(result, "articles", Article.class));
}
});
}
public static void loadForTopic(int topicId, final Callback<List<Article>> callback) {
Map<String, String> params = new HashMap<String, String>();
params.put("sort", "ordered");
doGet(apiPath("/topics/%d/articles.json", topicId), params, new RestTaskCallback(callback) {
@Override
public void onComplete(JSONObject result) throws JSONException {
callback.onModel(deserializeList(result, "articles", Article.class));
}
});
}
public static RestTask loadInstantAnswers(String query, final Callback<List<BaseModel>> callback) {
Map<String, String> params = new HashMap<String, String>();
params.put("per_page", "3");
params.put("forum_id", String.valueOf(getConfig().getForumId()));
params.put("query", query);
if (getConfig().getTopicId() != -1) {
params.put("topic_id", String.valueOf(getConfig().getTopicId()));
}
return doGet(apiPath("/instant_answers/search.json"), params, new RestTaskCallback(callback) {
@Override
public void onComplete(JSONObject result) throws JSONException {
callback.onModel(deserializeHeterogenousList(result, "instant_answers"));
}
});
}
@Override
public void load(JSONObject object) throws JSONException {
super.load(object);
title = getString(object, "question");
html = getHtml(object, "answer_html");
if (object.has("normalized_weight")) {
weight = object.getInt("normalized_weight");
}
if (!object.isNull("topic")) {
JSONObject topic = object.getJSONObject("topic");
topicName = topic.getString("name");
}
}
public String getTitle() {
return title;
}
public String getHtml() {
return html;
}
public String getTopicName() {
return topicName;
}
public int getWeight() {
return weight;
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel out, int flags) {
out.writeString(title);
out.writeString(html);
out.writeString(topicName);
out.writeInt(weight);
}
public static final Parcelable.Creator<Article> CREATOR
= new Parcelable.Creator<Article>() {
public Article createFromParcel(Parcel in) {
return new Article(in);
}
public Article[] newArray(int size) {
return new Article[size];
}
};
private Article(Parcel in) {
title = in.readString();
html = in.readString();
topicName = in.readString();
weight = in.readInt();
}
} |
// of this software and associated documentation files(the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions :
// all copies or substantial portions of the Software.
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package com.microsoft.aad.adal;
import android.content.Context;
import android.net.Uri;
import com.microsoft.identity.common.adal.internal.AuthenticationConstants;
import com.microsoft.identity.common.adal.internal.net.HttpWebResponse;
import com.microsoft.identity.common.adal.internal.net.IWebRequestHandler;
import com.microsoft.identity.common.adal.internal.net.WebRequestHandler;
import com.microsoft.identity.common.adal.internal.util.HashMapExtensions;
import com.microsoft.identity.common.adal.internal.util.StringExtensions;
import com.microsoft.identity.common.internal.providers.microsoft.azureactivedirectory.AzureActiveDirectory;
import org.json.JSONException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.locks.ReentrantLock;
/**
* Instance and Tenant discovery. It takes authorization endpoint and sends
* query to known hard coded instances to get tenant discovery endpoint. If
* instance is valid, it will return tenant discovery endpoint info. Instance
* discovery endpoint does not verify tenant info, so Discovery implementation
* sends common as a tenant name. Discovery checks only authorization endpoint.
* It does not do tenant verification. Initialize and call from UI thread.
*/
class Discovery {
private static final String TAG = "Discovery";
private static final String API_VERSION_KEY = "api-version";
private static final String API_VERSION_VALUE = "1.1";
private static final String AUTHORIZATION_ENDPOINT_KEY = "authorization_endpoint";
private static final String INSTANCE_DISCOVERY_SUFFIX = "common/discovery/instance";
private static final String AUTHORIZATION_COMMON_ENDPOINT = "/common/oauth2/authorize";
/**
* {@link ReentrantLock} for making sure there is only one instance discovery request sent out at a time.
*/
private static volatile ReentrantLock sInstanceDiscoveryNetworkRequestLock;
/**
* Sync set of valid hosts to skip query to server if host was verified
* before.
*/
private static final Set<String> AAD_WHITELISTED_HOSTS = Collections
.synchronizedSet(new HashSet<String>());
/**
* Sync map of validated AD FS authorities and domains. Skips query to server
* if already verified
*/
private static final Map<String, Set<URI>> ADFS_VALIDATED_AUTHORITIES =
Collections.synchronizedMap(new HashMap<String, Set<URI>>());
/**
* Discovery query will go to the prod only for now.
*/
private static final String TRUSTED_QUERY_INSTANCE = "login.microsoftonline.com";
private UUID mCorrelationId;
private Context mContext;
/**
* interface to use in testing.
*/
private final IWebRequestHandler mWebrequestHandler;
public Discovery(final Context context) {
initValidList();
mContext = context;
mWebrequestHandler = new WebRequestHandler();
}
void validateAuthorityADFS(final URL authorizationEndpoint, final String domain)
throws AuthenticationException {
if (StringExtensions.isNullOrBlank(domain)) {
throw new IllegalArgumentException("Cannot validate AD FS Authority with domain [null]");
}
validateADFS(authorizationEndpoint, domain);
}
public void validateAuthority(final URL authorizationEndpoint) throws AuthenticationException {
verifyAuthorityValidInstance(authorizationEndpoint);
if (AuthorityValidationMetadataCache.containsAuthorityHost(authorizationEndpoint)) {
return;
}
final String authorityHost = authorizationEndpoint.getHost().toLowerCase(Locale.US);
final String trustedHost;
if (AAD_WHITELISTED_HOSTS.contains(authorizationEndpoint.getHost().toLowerCase(Locale.US))) {
trustedHost = authorityHost;
} else {
trustedHost = TRUSTED_QUERY_INSTANCE;
}
try {
sInstanceDiscoveryNetworkRequestLock = getLock();
sInstanceDiscoveryNetworkRequestLock.lock();
performInstanceDiscovery(authorizationEndpoint, trustedHost);
} finally {
sInstanceDiscoveryNetworkRequestLock.unlock();
}
}
private static void validateADFS(final URL authorizationEndpoint, final String domain)
throws AuthenticationException {
// Maps & Sets of URLs perform domain name resolution for equals() & hashCode()
// To prevent this from happening, store/consult the cache using the URI value
final URI authorityUri;
try {
authorityUri = authorizationEndpoint.toURI();
} catch (URISyntaxException e) {
throw new AuthenticationException(
ADALError.DEVELOPER_AUTHORITY_IS_NOT_VALID_URL,
"Authority URL/URI must be RFC 2396 compliant to use AD FS validation"
);
}
// First, consult the cache
if (ADFS_VALIDATED_AUTHORITIES.get(domain) != null
&& ADFS_VALIDATED_AUTHORITIES.get(domain).contains(authorityUri)) {
// Trust has already been established, do not requery
return;
}
// Get the DRS metadata
final DRSMetadata drsMetadata = new DRSMetadataRequestor().requestMetadata(domain);
// Get the WebFinger metadata
final WebFingerMetadata webFingerMetadata =
new WebFingerMetadataRequestor() // create the requestor
.requestMetadata(// request the data
new WebFingerMetadataRequestParameters(// using these params
authorizationEndpoint,
drsMetadata
)
);
// Verify trust
if (!ADFSWebFingerValidator.realmIsTrusted(authorityUri, webFingerMetadata)) {
throw new AuthenticationException(ADALError.DEVELOPER_AUTHORITY_IS_NOT_VALID_INSTANCE);
}
// Trust established, add it to the cache
// If this authorization endpoint doesn't already have a Set, create it
if (ADFS_VALIDATED_AUTHORITIES.get(domain) == null) {
ADFS_VALIDATED_AUTHORITIES.put(domain, new HashSet<URI>());
}
// Add the entry
ADFS_VALIDATED_AUTHORITIES.get(domain).add(authorityUri);
}
/**
* Set correlation id for the tenant discovery call.
*
* @param requestCorrelationId The correlation id for the tenant discovery.
*/
public void setCorrelationId(final UUID requestCorrelationId) {
mCorrelationId = requestCorrelationId;
}
static URL constructAuthorityUrl(final URL originalAuthority, final String host) throws MalformedURLException {
final String path = originalAuthority.getPath().replaceFirst("/", "");
final Uri.Builder builder = new Uri.Builder().scheme(originalAuthority.getProtocol()).authority(host).appendPath(path);
return new URL(builder.build().toString());
}
/**
* initialize initial valid host list with known instances.
*/
private void initValidList() {
// mValidHosts is a sync set
if (AAD_WHITELISTED_HOSTS.isEmpty()) {
AAD_WHITELISTED_HOSTS.add("login.windows.net"); // Microsoft Azure Worldwide - Used in validation scenarios where host is not this list
AAD_WHITELISTED_HOSTS.add("login.microsoftonline.com"); // Microsoft Azure Worldwide
AAD_WHITELISTED_HOSTS.add("login.chinacloudapi.cn"); // Microsoft Azure China
AAD_WHITELISTED_HOSTS.add("login.microsoftonline.de"); // Microsoft Azure Germany
AAD_WHITELISTED_HOSTS.add("login-us.microsoftonline.com"); // Microsoft Azure US Government
AAD_WHITELISTED_HOSTS.add("login.microsoftonline.us"); // Microsoft Azure US
}
}
private void performInstanceDiscovery(final URL authorityUrl, final String trustedHost) throws AuthenticationException {
// Look up authority cache again. since we only allow one authority validation request goes out at one time, in case the
// map has already been filled in.
final String methodName = ":performInstanceDiscovery";
if (AuthorityValidationMetadataCache.containsAuthorityHost(authorityUrl)) {
return;
}
//Check if the network connection available
HttpWebRequest.throwIfNetworkNotAvailable(mContext);
// It will query prod instance to verify the authority
// construct query string for this instance
URL queryUrl;
final boolean result;
try {
queryUrl = buildQueryString(trustedHost, getAuthorizationCommonEndpoint(authorityUrl));
final Map<String, String> discoveryResponse = sendRequest(queryUrl);
// Set the Cloud instance discovery metadata on the AAD IdentityProvider
AzureActiveDirectory.initializeCloudMetadata(
authorityUrl.getHost().toLowerCase(Locale.US),
discoveryResponse
);
AuthorityValidationMetadataCache.processInstanceDiscoveryMetadata(authorityUrl, discoveryResponse);
if (!AuthorityValidationMetadataCache.containsAuthorityHost(authorityUrl)) {
ArrayList<String> aliases = new ArrayList<String>();
aliases.add(authorityUrl.getHost());
AuthorityValidationMetadataCache.updateInstanceDiscoveryMap(authorityUrl.getHost(),
new InstanceDiscoveryMetadata(authorityUrl.getHost(), authorityUrl.getHost(), aliases));
}
result = AuthorityValidationMetadataCache.isAuthorityValidated(authorityUrl);
} catch (JSONException e) {
Logger.e(TAG + methodName, "Error when validating authority. ", "", ADALError.DEVELOPER_AUTHORITY_IS_NOT_VALID_INSTANCE, e);
throw new AuthenticationException(ADALError.DEVELOPER_AUTHORITY_IS_NOT_VALID_INSTANCE, e.getMessage(), e);
} catch (SocketTimeoutException e){
Logger.e(TAG + methodName, "Error when validating authority. ", "", ADALError.DEVICE_CONNECTION_IS_NOT_AVAILABLE, e);
throw new AuthenticationException(ADALError.DEVICE_CONNECTION_IS_NOT_AVAILABLE, e.getMessage(), e);
} catch (IOException e){
Logger.e(TAG + methodName, "Error when validating authority. ", "", ADALError.IO_EXCEPTION, e);
throw new AuthenticationException(ADALError.IO_EXCEPTION, e.getMessage(), e);
}
if (!result) {
// throw exception in the false case
throw new AuthenticationException(ADALError.DEVELOPER_AUTHORITY_IS_NOT_VALID_INSTANCE);
}
}
private Map<String, String> sendRequest(final URL queryUrl) throws IOException, JSONException, AuthenticationException {
Logger.v(TAG, "Sending discovery request to query url. ", "queryUrl: " + queryUrl, null);
final Map<String, String> headers = new HashMap<>();
headers.put(WebRequestHandler.HEADER_ACCEPT, WebRequestHandler.HEADER_ACCEPT_JSON);
// CorrelationId is used to track the request at the Azure services
if (mCorrelationId != null) {
headers.put(AuthenticationConstants.AAD.CLIENT_REQUEST_ID, mCorrelationId.toString());
headers.put(AuthenticationConstants.AAD.RETURN_CLIENT_REQUEST_ID, "true");
}
final HttpWebResponse webResponse;
try {
ClientMetrics.INSTANCE.beginClientMetricsRecord(queryUrl, mCorrelationId, headers);
webResponse = mWebrequestHandler.sendGet(queryUrl, headers);
ClientMetrics.INSTANCE.setLastError(null);
// parse discovery response to find tenant info
final Map<String, String> discoveryResponse = parseResponse(webResponse);
if (discoveryResponse.containsKey(AuthenticationConstants.OAuth2.ERROR_CODES)) {
final String errorCodes = discoveryResponse.get(
AuthenticationConstants.OAuth2.ERROR_CODES);
ClientMetrics.INSTANCE.setLastError(errorCodes);
throw new AuthenticationException(
ADALError.DEVELOPER_AUTHORITY_IS_NOT_VALID_INSTANCE,
"Fail to valid authority with errors: " + errorCodes);
}
return discoveryResponse;
} finally {
ClientMetrics.INSTANCE.endClientMetricsRecord(
ClientMetricsEndpointType.INSTANCE_DISCOVERY, mCorrelationId);
}
}
static void verifyAuthorityValidInstance(final URL authorizationEndpoint) throws AuthenticationException {
// For comparison purposes, convert to lowercase Locale.US
// getProtocol returns scheme and it is available if it is absolute url
if (authorizationEndpoint == null || StringExtensions.isNullOrBlank(authorizationEndpoint.getHost())
|| !authorizationEndpoint.getProtocol().equals("https")
|| !StringExtensions.isNullOrBlank(authorizationEndpoint.getQuery())
|| !StringExtensions.isNullOrBlank(authorizationEndpoint.getRef())
|| StringExtensions.isNullOrBlank(authorizationEndpoint.getPath())) {
throw new AuthenticationException(ADALError.DEVELOPER_AUTHORITY_IS_NOT_VALID_INSTANCE);
}
}
/**
* get Json output from web response body. If it is well formed response, it
* will have tenant discovery endpoint.
*
* @param webResponse HttpWebResponse from which Json has to be extracted
* @return true if tenant discovery endpoint is reported. false otherwise.
* @throws JSONException
*/
private Map<String, String> parseResponse(HttpWebResponse webResponse) throws JSONException {
return HashMapExtensions.getJsonResponse(webResponse);
}
private String getAuthorizationCommonEndpoint(final URL authorizationEndpointUrl) {
return new Uri.Builder().scheme("https")
.authority(authorizationEndpointUrl.getHost())
.appendPath(AUTHORIZATION_COMMON_ENDPOINT).build().toString();
}
/**
* It will build query url to check the authorization endpoint.
*
* @param instance authority instance
* @param authorizationEndpointUrl authorization endpoint
* @return URL
* @throws MalformedURLException
*/
private URL buildQueryString(final String instance, final String authorizationEndpointUrl)
throws MalformedURLException {
Uri.Builder builder = new Uri.Builder();
builder.scheme("https").authority(instance);
// replacing tenant to common since instance validation does not check
// tenant name
builder.appendEncodedPath(INSTANCE_DISCOVERY_SUFFIX)
.appendQueryParameter(API_VERSION_KEY, API_VERSION_VALUE)
.appendQueryParameter(AUTHORIZATION_ENDPOINT_KEY, authorizationEndpointUrl);
return new URL(builder.build().toString());
}
/**
* @return {@link ReentrantLock} for locking the network request queue.
*/
private static ReentrantLock getLock() {
if (sInstanceDiscoveryNetworkRequestLock == null) {
synchronized (Discovery.class) {
if (sInstanceDiscoveryNetworkRequestLock == null) {
sInstanceDiscoveryNetworkRequestLock = new ReentrantLock();
}
}
}
return sInstanceDiscoveryNetworkRequestLock;
}
static Set<String> getValidHosts() {
return AAD_WHITELISTED_HOSTS;
}
} |
package com.carls;
import android.app.Application;
import android.net.http.HttpResponseCache;
import android.util.Log;
// keep these sorted alphabetically
import com.avishayil.rnrestart.ReactNativeRestartPackage;
import com.bugsnag.BugsnagReactNative;
import com.BV.LinearGradient.LinearGradientPackage;
import com.calendarevents.CalendarEventsPackage;
import com.facebook.react.ReactApplication;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;
import com.github.droibit.android.reactnative.customtabs.CustomTabsPackage;
import com.idehub.GoogleAnalyticsBridge.GoogleAnalyticsBridgePackage;
import com.learnium.RNDeviceInfo.RNDeviceInfo;
import com.mapbox.rctmgl.RCTMGLPackage;
import com.oblador.keychain.KeychainPackage;
import com.oblador.vectoricons.VectorIconsPackage;
import com.pusherman.networkinfo.RNNetworkInfoPackage;
import com.wix.interactable.Interactable;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
public class MainApplication extends Application implements ReactApplication {
private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
@Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(),
// please keep these sorted alphabetically
BugsnagReactNative.getPackage(),
new CalendarEventsPackage(),
new CustomTabsPackage(),
new GoogleAnalyticsBridgePackage(),
new Interactable(),
new KeychainPackage(),
new LinearGradientPackage(),
new RCTMGLPackage(),
new ReactNativeRestartPackage(),
new RNDeviceInfo(),
new RNNetworkInfoPackage(),
new VectorIconsPackage()
);
}
@Override
protected String getJSMainModuleName() {
return "index";
}
};
@Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
@Override
public void onCreate() {
super.onCreate();
SoLoader.init(this, /* native exopackage */ false);
// set up network cache
try {
File httpCacheDir = new File(getApplicationContext().getCacheDir(), "http");
long httpCacheSize = 20 * 1024 * 1024; // 20 MiB
HttpResponseCache.install(httpCacheDir, httpCacheSize);
} catch (IOException e) {
Log.i("allaboutolaf", "HTTP response cache installation failed:", e);
// Log.i(TAG, "HTTP response cache installation failed:", e);
}
}
public void onStop() {
HttpResponseCache cache = HttpResponseCache.getInstalled();
if (cache != null) {
cache.flush();
}
}
} |
package com.messagebird;
import com.messagebird.exceptions.GeneralException;
import com.messagebird.exceptions.NotFoundException;
import com.messagebird.exceptions.UnauthorizedException;
import com.messagebird.objects.Balance;
import com.messagebird.objects.Contact;
import com.messagebird.objects.ContactList;
import com.messagebird.objects.ContactRequest;
import com.messagebird.objects.ErrorReport;
import com.messagebird.objects.Group;
import com.messagebird.objects.GroupList;
import com.messagebird.objects.GroupRequest;
import com.messagebird.objects.Hlr;
import com.messagebird.objects.Lookup;
import com.messagebird.objects.LookupHlr;
import com.messagebird.objects.Message;
import com.messagebird.objects.MessageList;
import com.messagebird.objects.MessageResponse;
import com.messagebird.objects.MsgType;
import com.messagebird.objects.PagedPaging;
import com.messagebird.objects.PhoneNumbersLookup;
import com.messagebird.objects.PhoneNumbersResponse;
import com.messagebird.objects.PurchasedPhoneNumber;
import com.messagebird.objects.Verify;
import com.messagebird.objects.VerifyRequest;
import com.messagebird.objects.VoiceMessage;
import com.messagebird.objects.VoiceMessageList;
import com.messagebird.objects.VoiceMessageResponse;
import com.messagebird.objects.conversations.Conversation;
import com.messagebird.objects.conversations.ConversationList;
import com.messagebird.objects.conversations.ConversationMessage;
import com.messagebird.objects.conversations.ConversationMessageList;
import com.messagebird.objects.conversations.ConversationMessageRequest;
import com.messagebird.objects.conversations.ConversationStartRequest;
import com.messagebird.objects.conversations.ConversationStatus;
import com.messagebird.objects.conversations.ConversationWebhook;
import com.messagebird.objects.conversations.ConversationWebhookCreateRequest;
import com.messagebird.objects.conversations.ConversationWebhookList;
import com.messagebird.objects.conversations.ConversationWebhookUpdateRequest;
import com.messagebird.objects.voicecalls.RecordingResponse;
import com.messagebird.objects.voicecalls.TranscriptionResponse;
import com.messagebird.objects.voicecalls.VoiceCall;
import com.messagebird.objects.voicecalls.VoiceCallFlowList;
import com.messagebird.objects.voicecalls.VoiceCallFlowRequest;
import com.messagebird.objects.voicecalls.VoiceCallFlowResponse;
import com.messagebird.objects.voicecalls.VoiceCallLeg;
import com.messagebird.objects.voicecalls.VoiceCallLegResponse;
import com.messagebird.objects.voicecalls.VoiceCallResponse;
import com.messagebird.objects.voicecalls.VoiceCallResponseList;
import com.messagebird.objects.voicecalls.Webhook;
import com.messagebird.objects.voicecalls.WebhookList;
import com.messagebird.objects.voicecalls.WebhookResponseData;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class MessageBirdClient {
/**
* The Conversations API has a different URL scheme from the other
* APIs/endpoints. By default, the service prefixes paths with that URL. We
* can, however, override this behaviour by providing absolute URLs
* ourselves.
*/
private static final String BASE_URL_CONVERSATIONS = "https://conversations.messagebird.com/v1";
private static final String BASE_URL_CONVERSATIONS_WHATSAPP_SANDBOX = "https://whatsapp-sandbox.messagebird.com/v1";
static final String VOICE_CALLS_BASE_URL = "https://voice.messagebird.com";
static final String NUMBERS_CALLS_BASE_URL = "https://numbers.messagebird.com";
private static String[] supportedLanguages = {"de-DE", "en-AU", "en-UK", "en-US", "es-ES", "es-LA", "fr-FR", "it-IT", "nl-NL", "pt-BR"};
private static final String BALANCEPATH = "/balance";
private static final String CONTACTPATH = "/contacts";
private static final String GROUPPATH = "/groups";
private static final String HLRPATH = "/hlr";
private static final String LOOKUPHLRPATH = "/lookup/%s/hlr";
private static final String LOOKUPPATH = "/lookup";
private static final String MESSAGESPATH = "/messages";
private static final String VERIFYPATH = "/verify";
private static final String VOICEMESSAGESPATH = "/voicemessages";
private static final String CONVERSATION_PATH = "/conversations";
private static final String CONVERSATION_MESSAGE_PATH = "/messages";
private static final String CONVERSATION_WEBHOOK_PATH = "/webhooks";
static final String VOICECALLSPATH = "/calls";
static final String LEGSPATH = "/legs";
static final String RECORDINGPATH = "/recordings";
static final String TRANSCRIPTIONPATH = "/transcriptions";
static final String WEBHOOKS = "/webhooks";
static final String VOICECALLFLOWPATH = "/call-flows";
private static final String VOICELEGS_SUFFIX_PATH = "/legs";
static final String RECORDING_DOWNLOAD_FORMAT = ".wav";
static final String TRANSCRIPTION_DOWNLOAD_FORMAT = ".txt";
private static final int DEFAULT_MACHINE_TIMEOUT_VALUE = 7000;
private static final int MIN_MACHINE_TIMEOUT_VALUE = 400;
private static final int MAX_MACHINE_TIMEOUT_VALUE = 10000;
private final String DOWNLOADS = "Downloads";
private MessageBirdService messageBirdService;
private String conversationsBaseUrl;
public enum Feature {
ENABLE_CONVERSATION_API_WHATSAPP_SANDBOX
}
public MessageBirdClient(final MessageBirdService messageBirdService) {
this.messageBirdService = messageBirdService;
this.conversationsBaseUrl = BASE_URL_CONVERSATIONS;
}
public MessageBirdClient(final MessageBirdService messageBirdService, List<Feature> features) {
this(messageBirdService);
if(features.indexOf(Feature.ENABLE_CONVERSATION_API_WHATSAPP_SANDBOX) >= 0) {
this.conversationsBaseUrl = BASE_URL_CONVERSATIONS_WHATSAPP_SANDBOX;
}
}
/** Balance and HRL methods **/
/**
* MessageBird provides an API to get the balance information of your account.
*
* @return Balance object
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public Balance getBalance() throws GeneralException, UnauthorizedException, NotFoundException {
return messageBirdService.requestByID(BALANCEPATH, "", Balance.class);
}
/**
* MessageBird provides an API to send Network Queries to any mobile number across the world.
* An HLR allows you to view which mobile number (MSISDN) belongs to what operator in real time and see whether the number is active.
*
* @param msisdn The telephone number.
* @param reference A client reference
* @return Hlr Object
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public Hlr getRequestHlr(final BigInteger msisdn, final String reference) throws GeneralException, UnauthorizedException {
if (msisdn == null) {
throw new IllegalArgumentException("msisdn must be specified.");
}
if (reference == null) {
throw new IllegalArgumentException("Reference must be specified.");
}
final Map<String, Object> payload = new LinkedHashMap<String, Object>();
payload.put("msisdn", msisdn);
payload.put("reference", reference);
return messageBirdService.sendPayLoad(HLRPATH, payload, Hlr.class);
}
/**
* Retrieves the information of an existing HLR. You only need to supply the unique message id that was returned upon creation or receiving.
*
* @param hlrId ID as returned by getRequestHlr in the id variable
* @return Hlr Object
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public Hlr getViewHlr(final String hlrId) throws GeneralException, UnauthorizedException, NotFoundException {
if (hlrId == null) {
throw new IllegalArgumentException("Hrl ID must be specified.");
}
return messageBirdService.requestByID(HLRPATH, hlrId, Hlr.class);
}
/** Messaging **/
/**
* Send a message through the messagebird platform
*
* @param message Message object to be send
* @return Message Response
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public MessageResponse sendMessage(final Message message) throws UnauthorizedException, GeneralException {
return messageBirdService.sendPayLoad(MESSAGESPATH, message, MessageResponse.class);
}
/**
* Convenient function to send a simple message to a list of recipients
*
* @param originator Originator of the message, this will get truncated to 11 chars
* @param body Body of the message
* @param recipients List of recipients
* @return MessageResponse
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public MessageResponse sendMessage(final String originator, final String body, final List<BigInteger> recipients) throws UnauthorizedException, GeneralException {
return messageBirdService.sendPayLoad(MESSAGESPATH, new Message(originator, body, recipients), MessageResponse.class);
}
/**
* Convenient function to send a simple message to a list of recipients
*
* @param originator Originator of the message, this will get truncated to 11 chars
* @param body Body of the message
* @param recipients List of recipients
* @param reference your reference
* @return MessageResponse
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public MessageResponse sendMessage(final String originator, final String body, final List<BigInteger> recipients, final String reference) throws UnauthorizedException, GeneralException {
final Message message = new Message(originator, body, recipients);
message.setReference(reference);
return messageBirdService.sendPayLoad(MESSAGESPATH, message, MessageResponse.class);
}
/**
* Convenient function to send a simple flash message to a list of recipients
*
* @param originator Originator of the message, this will get truncated to 11 chars
* @param body Body of the message
* @param recipients List of recipients
* @return MessageResponse
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public MessageResponse sendFlashMessage(final String originator, final String body, final List<BigInteger> recipients) throws UnauthorizedException, GeneralException {
final Message message = new Message(originator, body, recipients);
message.setType(MsgType.flash);
return messageBirdService.sendPayLoad(MESSAGESPATH, message, MessageResponse.class);
}
/**
* Convenient function to send a simple flash message to a list of recipients
*
* @param originator Originator of the message, this will get truncated to 11 chars
* @param body Body of the message
* @param recipients List of recipients
* @param reference your reference
* @return MessageResponse
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public MessageResponse sendFlashMessage(final String originator, final String body, final List<BigInteger> recipients, final String reference) throws UnauthorizedException, GeneralException {
final Message message = new Message(originator, body, recipients);
message.setType(MsgType.flash);
message.setReference(reference);
return messageBirdService.sendPayLoad(MESSAGESPATH, message, MessageResponse.class);
}
public MessageList listMessages(final Integer offset, final Integer limit) throws UnauthorizedException, GeneralException {
verifyOffsetAndLimit(offset, limit);
return messageBirdService.requestList(MESSAGESPATH, offset, limit, MessageList.class);
}
public void deleteMessage(final String id) throws UnauthorizedException, GeneralException, NotFoundException {
if (id == null) {
throw new IllegalArgumentException("Message ID must be specified.");
}
messageBirdService.deleteByID(MESSAGESPATH, id);
}
public MessageResponse viewMessage(final String id) throws UnauthorizedException, GeneralException, NotFoundException {
if (id == null) {
throw new IllegalArgumentException("Message ID must be specified.");
}
return messageBirdService.requestByID(MESSAGESPATH, id, MessageResponse.class);
}
/** Voice Messaging **/
/**
* Convenient function to send a simple message to a list of recipients
*
* @param voiceMessage Voice message object
* @return VoiceMessageResponse
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public VoiceMessageResponse sendVoiceMessage(final VoiceMessage voiceMessage) throws UnauthorizedException, GeneralException {
addDefaultMachineTimeoutValueIfNotExists(voiceMessage);
checkMachineTimeoutValueIsInRange(voiceMessage);
return messageBirdService.sendPayLoad(VOICEMESSAGESPATH, voiceMessage, VoiceMessageResponse.class);
}
/**
* Convenient function to send a simple message to a list of recipients
*
* @param body Body of the message
* @param recipients List of recipients
* @return VoiceMessageResponse
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public VoiceMessageResponse sendVoiceMessage(final String body, final List<BigInteger> recipients) throws UnauthorizedException, GeneralException {
final VoiceMessage message = new VoiceMessage(body, recipients);
addDefaultMachineTimeoutValueIfNotExists(message);
checkMachineTimeoutValueIsInRange(message);
return messageBirdService.sendPayLoad(VOICEMESSAGESPATH, message, VoiceMessageResponse.class);
}
/**
* Convenient function to send a simple message to a list of recipients
*
* @param body Body of the message
* @param recipients List of recipients
* @param reference your reference
* @return VoiceMessageResponse
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public VoiceMessageResponse sendVoiceMessage(final String body, final List<BigInteger> recipients, final String reference) throws UnauthorizedException, GeneralException {
final VoiceMessage message = new VoiceMessage(body, recipients);
message.setReference(reference);
addDefaultMachineTimeoutValueIfNotExists(message);
checkMachineTimeoutValueIsInRange(message);
return messageBirdService.sendPayLoad(VOICEMESSAGESPATH, message, VoiceMessageResponse.class);
}
private void addDefaultMachineTimeoutValueIfNotExists(final VoiceMessage voiceMessage){
if (voiceMessage.getMachineTimeout() == 0){
voiceMessage.setMachineTimeout(DEFAULT_MACHINE_TIMEOUT_VALUE); //default machine timeout value
}
}
private void checkMachineTimeoutValueIsInRange(final VoiceMessage voiceMessage){
if (voiceMessage.getMachineTimeout() < MIN_MACHINE_TIMEOUT_VALUE || voiceMessage.getMachineTimeout() > MAX_MACHINE_TIMEOUT_VALUE){
throw new IllegalArgumentException("Please define machine timeout value between " + MIN_MACHINE_TIMEOUT_VALUE + " and " + MAX_MACHINE_TIMEOUT_VALUE);
}
}
public void deleteVoiceMessage(final String id) throws UnauthorizedException, GeneralException, NotFoundException {
if (id == null) {
throw new IllegalArgumentException("Message ID must be specified.");
}
messageBirdService.deleteByID(VOICEMESSAGESPATH, id);
}
public VoiceMessageResponse viewVoiceMessage(final String id) throws UnauthorizedException, GeneralException, NotFoundException {
if (id == null) {
throw new IllegalArgumentException("Voice Message ID must be specified.");
}
return messageBirdService.requestByID(VOICEMESSAGESPATH, id, VoiceMessageResponse.class);
}
/**
* List voice messages
*
* @param offset offset for result list
* @param limit limit for result list
* @return VoiceMessageList
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public VoiceMessageList listVoiceMessages(final Integer offset, final Integer limit) throws UnauthorizedException, GeneralException {
verifyOffsetAndLimit(offset, limit);
return messageBirdService.requestList(VOICEMESSAGESPATH, offset, limit, VoiceMessageList.class);
}
/**
* @param verifyRequest includes recipient, originator, reference, type, datacoding, template, timeout, tokenLenght, voice, language
* @return Verify object
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public Verify sendVerifyToken(VerifyRequest verifyRequest) throws UnauthorizedException, GeneralException {
if (verifyRequest == null) {
throw new IllegalArgumentException("Verify request cannot be null");
} else if (verifyRequest.getRecipient() == null || verifyRequest.getRecipient().isEmpty()) {
throw new IllegalArgumentException("Recipient cannot be empty for verify");
}
return messageBirdService.sendPayLoad(VERIFYPATH, verifyRequest, Verify.class);
}
/**
* @param recipient The telephone number that you want to verify.
* @return Verify object
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public Verify sendVerifyToken(String recipient) throws UnauthorizedException, GeneralException {
if (recipient == null || recipient.isEmpty()) {
throw new IllegalArgumentException("Recipient cannot be empty for verify");
}
VerifyRequest verifyRequest = new VerifyRequest(recipient);
return this.sendVerifyToken(verifyRequest);
}
public Verify verifyToken(String id, String token) throws NotFoundException, GeneralException, UnauthorizedException {
if (id == null || id.isEmpty()) {
throw new IllegalArgumentException("ID cannot be empty for verify");
} else if (token == null || token.isEmpty()) {
throw new IllegalArgumentException("ID cannot be empty for verify");
}
final Map<String, Object> params = new LinkedHashMap<String, Object>();
params.put("token", token);
return messageBirdService.requestByID(VERIFYPATH, id, params, Verify.class);
}
/**
* @param id id is for getting verify object
* @return Verify object
* @throws NotFoundException if id is not found
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
Verify getVerifyObject(String id) throws NotFoundException, GeneralException, UnauthorizedException {
if (id == null || id.isEmpty()) {
throw new IllegalArgumentException("ID cannot be empty for verify");
}
return messageBirdService.requestByID(VERIFYPATH, id, Verify.class);
}
/**
* @param id id for deleting verify object
* @throws NotFoundException if id is not found
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public void deleteVerifyObject(String id) throws NotFoundException, GeneralException, UnauthorizedException {
if (id == null || id.isEmpty()) {
throw new IllegalArgumentException("ID cannot be empty for verify");
}
messageBirdService.deleteByID(VERIFYPATH, id);
}
/**
* Send a Lookup request
*
* @param lookup including with country code, country prefix, phone number, type, formats, country code
* @return Lookup
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
* @throws NotFoundException if lookup not found
*/
public Lookup viewLookup(final Lookup lookup) throws UnauthorizedException, GeneralException, NotFoundException {
if (lookup.getPhoneNumber() == null) {
throw new IllegalArgumentException("PhoneNumber must be specified.");
}
final Map<String, Object> params = new LinkedHashMap<String, Object>();
if (lookup.getCountryCode() != null) {
params.put("countryCode", lookup.getCountryCode());
}
return messageBirdService.requestByID(LOOKUPPATH, String.valueOf(lookup.getPhoneNumber()), params, Lookup.class);
}
/**
* Send a Lookup request
*
* @param phoneNumber phone number is for viewing lookup
* @return Lookup
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public Lookup viewLookup(final BigInteger phoneNumber) throws UnauthorizedException, GeneralException, NotFoundException {
if (phoneNumber == null) {
throw new IllegalArgumentException("PhoneNumber must be specified.");
}
final Lookup lookup = new Lookup(phoneNumber);
return this.viewLookup(lookup);
}
/**
* Request a Lookup HLR (lookup)
*
* @param lookupHlr country code for request lookup hlr
* @return lookupHlr
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public LookupHlr requestLookupHlr(final LookupHlr lookupHlr) throws UnauthorizedException, GeneralException {
if (lookupHlr.getPhoneNumber() == null) {
throw new IllegalArgumentException("PhoneNumber must be specified.");
}
if (lookupHlr.getReference() == null) {
throw new IllegalArgumentException("Reference must be specified.");
}
final Map<String, Object> payload = new LinkedHashMap<String, Object>();
payload.put("phoneNumber", lookupHlr.getPhoneNumber());
payload.put("reference", lookupHlr.getReference());
if (lookupHlr.getCountryCode() != null) {
payload.put("countryCode", lookupHlr.getCountryCode());
}
return messageBirdService.sendPayLoad(String.format(LOOKUPHLRPATH, lookupHlr.getPhoneNumber()), payload, LookupHlr.class);
}
/**
* Request a Lookup HLR (lookup)
*
* @param phoneNumber phone number is for request hlr
* @param reference reference for request hlr
* @return lookupHlr
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public LookupHlr requestLookupHlr(final BigInteger phoneNumber, final String reference) throws UnauthorizedException, GeneralException {
if (phoneNumber == null) {
throw new IllegalArgumentException("Phonenumber must be specified.");
}
if (reference == null) {
throw new IllegalArgumentException("Reference must be specified.");
}
final LookupHlr lookupHlr = new LookupHlr();
lookupHlr.setPhoneNumber(phoneNumber);
lookupHlr.setReference(reference);
return this.requestLookupHlr(lookupHlr);
}
/**
* View a Lookup HLR (lookup)
*
* @param lookupHlr search with country code
* @return LookupHlr
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
* @throws NotFoundException if there is no lookup hlr with given country code
*/
public LookupHlr viewLookupHlr(final LookupHlr lookupHlr) throws UnauthorizedException, GeneralException, NotFoundException {
if (lookupHlr.getPhoneNumber() == null) {
throw new IllegalArgumentException("Phonenumber must be specified");
}
final Map<String, Object> params = new LinkedHashMap<String, Object>();
if (lookupHlr.getCountryCode() != null) {
params.put("countryCode", lookupHlr.getCountryCode());
}
return messageBirdService.requestByID(String.format(LOOKUPHLRPATH, lookupHlr.getPhoneNumber()), "", params, LookupHlr.class);
}
/**
* View a Lookup HLR (lookup)
*
* @param phoneNumber phone number for searching on hlr
* @return LookupHlr
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
* @throws NotFoundException phone number not found on hlr
*/
public LookupHlr viewLookupHlr(final BigInteger phoneNumber) throws UnauthorizedException, GeneralException, NotFoundException {
if (phoneNumber == null) {
throw new IllegalArgumentException("phoneNumber must be specified");
}
final LookupHlr lookupHlr = new LookupHlr();
lookupHlr.setPhoneNumber(phoneNumber);
return this.viewLookupHlr(lookupHlr);
}
/**
* Convenient function to list all call flows
*
* @param offset
* @param limit
* @return VoiceCallFlowList
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public VoiceCallFlowList listVoiceCallFlows(final Integer offset, final Integer limit)
throws UnauthorizedException, GeneralException {
verifyOffsetAndLimit(offset, limit);
String url = String.format("%s%s", VOICE_CALLS_BASE_URL, VOICECALLFLOWPATH);
return messageBirdService.requestList(url, offset, limit, VoiceCallFlowList.class);
}
/**
* Retrieves the information of an existing Call Flow. You only need to supply
* the unique call flow ID that was returned upon creation or receiving.
* @param id String
* @return VoiceCallFlowResponse
* @throws NotFoundException
* @throws GeneralException
* @throws UnauthorizedException
*/
public VoiceCallFlowResponse viewVoiceCallFlow(final String id) throws NotFoundException, GeneralException, UnauthorizedException {
if (id == null) {
throw new IllegalArgumentException("Call Flow ID must be specified.");
}
String url = String.format("%s%s", VOICE_CALLS_BASE_URL, VOICECALLFLOWPATH);
return messageBirdService.requestByID(url, id, VoiceCallFlowResponse.class);
}
/**
* Convenient function to create a call flow
*
* @param voiceCallFlowRequest VoiceCallFlowRequest
* @return VoiceCallFlowResponse
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public VoiceCallFlowResponse sendVoiceCallFlow(final VoiceCallFlowRequest voiceCallFlowRequest)
throws UnauthorizedException, GeneralException {
String url = String.format("%s%s", VOICE_CALLS_BASE_URL, VOICECALLFLOWPATH);
return messageBirdService.sendPayLoad(url, voiceCallFlowRequest, VoiceCallFlowResponse.class);
}
/**
* Updates an existing Call Flow. You only need to supply the unique id that
* was returned upon creation.
* @param id String
* @param voiceCallFlowRequest VoiceCallFlowRequest
* @return VoiceCallFlowResponse
* @throws UnauthorizedException
* @throws GeneralException
*/
public VoiceCallFlowResponse updateVoiceCallFlow(String id, VoiceCallFlowRequest voiceCallFlowRequest)
throws UnauthorizedException, GeneralException {
if (id == null) {
throw new IllegalArgumentException("Call Flow ID must be specified.");
}
String url = String.format("%s%s", VOICE_CALLS_BASE_URL, VOICECALLFLOWPATH);
String request = url + "/" + id;
return messageBirdService.sendPayLoad("PUT", request, voiceCallFlowRequest, VoiceCallFlowResponse.class);
}
/**
* Convenient function to delete call flow
*
* @param id String
* @return void
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public void deleteVoiceCallFlow(final String id) throws NotFoundException, GeneralException, UnauthorizedException {
if (id == null) {
throw new IllegalArgumentException("Voice Call Flow ID must be specified.");
}
String url = String.format("%s%s", VOICE_CALLS_BASE_URL, VOICECALLFLOWPATH);
messageBirdService.deleteByID(url, id);
}
/**
* Deletes an existing contact. You only need to supply the unique id that
* was returned upon creation.
*/
void deleteContact(final String id) throws NotFoundException, GeneralException, UnauthorizedException {
if (id == null) {
throw new IllegalArgumentException("Contact ID must be specified.");
}
messageBirdService.deleteByID(CONTACTPATH, id);
}
/**
* Gets a contact listing with specified pagination options.
*
* @return Listing of Contact objects.
*/
public ContactList listContacts(int offset, int limit) throws UnauthorizedException, GeneralException {
return messageBirdService.requestList(CONTACTPATH, offset, limit, ContactList.class);
}
/**
* Gets a contact listing with default pagination options.
*/
public ContactList listContacts() throws UnauthorizedException, GeneralException {
final int limit = 20;
final int offset = 0;
return listContacts(offset, limit);
}
/**
* Creates a new contact object. MessageBird returns the created contact
* object with each request.
*/
public Contact sendContact(final ContactRequest contactRequest) throws UnauthorizedException, GeneralException {
return messageBirdService.sendPayLoad(CONTACTPATH, contactRequest, Contact.class);
}
/**
* Updates an existing contact. You only need to supply the unique id that
* was returned upon creation.
*/
public Contact updateContact(final String id, ContactRequest contactRequest) throws UnauthorizedException, GeneralException {
if (id == null) {
throw new IllegalArgumentException("Contact ID must be specified.");
}
String request = CONTACTPATH + "/" + id;
return messageBirdService.sendPayLoad("PATCH", request, contactRequest, Contact.class);
}
/**
* Retrieves the information of an existing contact. You only need to supply
* the unique contact ID that was returned upon creation or receiving.
*/
public Contact viewContact(final String id) throws NotFoundException, GeneralException, UnauthorizedException {
if (id == null) {
throw new IllegalArgumentException("Contact ID must be specified.");
}
return messageBirdService.requestByID(CONTACTPATH, id, Contact.class);
}
/**
* Deletes an existing group. You only need to supply the unique id that
* was returned upon creation.
*/
public void deleteGroup(final String id) throws NotFoundException, GeneralException, UnauthorizedException {
if (id == null) {
throw new IllegalArgumentException("Group ID must be specified.");
}
messageBirdService.deleteByID(GROUPPATH, id);
}
/**
* Removes a contact from group. You need to supply the IDs of the group
* and contact. Does not delete the contact.
*/
public void deleteGroupContact(final String groupId, final String contactId) throws NotFoundException, GeneralException, UnauthorizedException {
if (groupId == null) {
throw new IllegalArgumentException("Group ID must be specified.");
}
if (contactId == null) {
throw new IllegalArgumentException("Contact ID must be specified.");
}
String id = String.format("%s%s/%s", groupId, CONTACTPATH, contactId);
messageBirdService.deleteByID(GROUPPATH, id);
}
/**
* Gets a contact listing with specified pagination options.
*/
public GroupList listGroups(final int offset, final int limit) throws UnauthorizedException, GeneralException {
return messageBirdService.requestList(GROUPPATH, offset, limit, GroupList.class);
}
/**
* Gets a contact listing with default pagination options.
*/
public GroupList listGroups() throws UnauthorizedException, GeneralException {
final int offset = 0;
final int limit = 20;
return listGroups(offset, limit);
}
/**
* Creates a new group object. MessageBird returns the created group object
* with each request.
*/
public Group sendGroup(final GroupRequest groupRequest) throws UnauthorizedException, GeneralException {
return messageBirdService.sendPayLoad(GROUPPATH, groupRequest, Group.class);
}
/**
* Adds contact to group. You need to supply the IDs of the group and
* contact.
*/
public void sendGroupContact(final String groupId, final String[] contactIds) throws NotFoundException, GeneralException, UnauthorizedException {
// reuestByID appends the "ID" to the base path, so this workaround
// lets us add a query string.
String path = String.format("%s%s?%s", groupId, CONTACTPATH, getQueryString(contactIds));
messageBirdService.requestByID(GROUPPATH, path, null);
}
private String getQueryString(final String[] contactIds) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("_method=PUT");
for (String groupId : contactIds) {
stringBuilder.append("&ids[]=").append(groupId);
}
return stringBuilder.toString();
}
/**
* Updates an existing group. You only need to supply the unique ID that
* was returned upon creation.
*/
public Group updateGroup(final String id, final GroupRequest groupRequest) throws UnauthorizedException, GeneralException {
if (id == null) {
throw new IllegalArgumentException("Group ID must be specified.");
}
String path = String.format("%s/%s", GROUPPATH, id);
return messageBirdService.sendPayLoad("PATCH", path, groupRequest, Group.class);
}
/**
* Retrieves the information of an existing group. You only need to supply
* the unique group ID that was returned upon creation or receiving.
*/
public Group viewGroup(final String id) throws NotFoundException, GeneralException, UnauthorizedException {
if (id == null) {
throw new IllegalArgumentException("Group ID must be specified.");
}
return messageBirdService.requestByID(GROUPPATH, id, Group.class);
}
/**
* Gets a single conversation.
*
* @param id Conversation to retrieved.
* @return The retrieved conversation.
*/
public Conversation viewConversation(final String id) throws NotFoundException, GeneralException, UnauthorizedException {
if (id == null) {
throw new IllegalArgumentException("Id must be specified");
}
String url = this.conversationsBaseUrl + CONVERSATION_PATH;
return messageBirdService.requestByID(url, id, Conversation.class);
}
/**
* Updates a conversation.
*
* @param id Conversation to update.
* @param status New status for the conversation.
* @return The updated Conversation.
*/
public Conversation updateConversation(final String id, final ConversationStatus status)
throws UnauthorizedException, GeneralException {
if (id == null) {
throw new IllegalArgumentException("Id must be specified.");
}
String url = String.format("%s%s/%s", this.conversationsBaseUrl, CONVERSATION_PATH, id);
return messageBirdService.sendPayLoad("PATCH", url, status, Conversation.class);
}
/**
* Gets a Conversation listing with specified pagination options.
*
* @param offset Number of objects to skip.
* @param limit Number of objects to take.
* @return List of conversations.
*/
public ConversationList listConversations(final int offset, final int limit)
throws UnauthorizedException, GeneralException {
String url = this.conversationsBaseUrl + CONVERSATION_PATH;
return messageBirdService.requestList(url, offset, limit, ConversationList.class);
}
/**
* Gets a contact listing with default pagination options.
*
* @return List of conversations.
*/
public ConversationList listConversations() throws UnauthorizedException, GeneralException {
final int offset = 0;
final int limit = 10;
return listConversations(offset, limit);
}
/**
* Starts a conversation by sending an initial message.
*
* @param request Data for this request.
* @return The created Conversation.
*/
public Conversation startConversation(ConversationStartRequest request)
throws UnauthorizedException, GeneralException {
String url = String.format("%s%s/start", this.conversationsBaseUrl, CONVERSATION_PATH);
return messageBirdService.sendPayLoad(url, request, Conversation.class);
}
/**
* Gets a ConversationMessage listing with specified pagination options.
*
* @param conversationId Conversation to get messages for.
* @param offset Number of objects to skip.
* @param limit Number of objects to take.
* @return List of messages.
*/
public ConversationMessageList listConversationMessages(
final String conversationId,
final int offset,
final int limit
) throws UnauthorizedException, GeneralException {
String url = String.format(
"%s%s/%s%s",
this.conversationsBaseUrl,
CONVERSATION_PATH,
conversationId,
CONVERSATION_MESSAGE_PATH
);
return messageBirdService.requestList(url, offset, limit, ConversationMessageList.class);
}
/**
* Gets a ConversationMessage listing with default pagination options.
*
* @param conversationId Conversation to get messages for.
* @return List of messages.
*/
public ConversationMessageList listConversationMessages(
final String conversationId
) throws UnauthorizedException, GeneralException {
final int offset = 0;
final int limit = 10;
return listConversationMessages(conversationId, offset, limit);
}
/**
* Gets a single message.
*
* @param messageId Message to retrieve.
* @return The retrieved message.
*/
public ConversationMessage viewConversationMessage(final String messageId)
throws NotFoundException, GeneralException, UnauthorizedException {
String url = this.conversationsBaseUrl + CONVERSATION_MESSAGE_PATH;
return messageBirdService.requestByID(url, messageId, ConversationMessage.class);
}
/**
* Sends a message to an existing Conversation.
*
* @param conversationId Conversation to send message to.
* @param request Message to send.
* @return The newly created message.
*/
public ConversationMessage sendConversationMessage(
final String conversationId,
final ConversationMessageRequest request
) throws UnauthorizedException, GeneralException {
String url = String.format(
"%s%s/%s%s",
this.conversationsBaseUrl,
CONVERSATION_PATH,
conversationId,
CONVERSATION_MESSAGE_PATH
);
return messageBirdService.sendPayLoad(url, request, ConversationMessage.class);
}
/**
* Deletes a webhook.
*
* @param webhookId Webhook to delete.
*/
public void deleteConversationWebhook(final String webhookId)
throws NotFoundException, GeneralException, UnauthorizedException {
String url = this.conversationsBaseUrl + CONVERSATION_WEBHOOK_PATH;
messageBirdService.deleteByID(url, webhookId);
}
/**
* Creates a new webhook.
*
* @param request Webhook to create.
* @return Newly created webhook.
*/
public ConversationWebhook sendConversationWebhook(final ConversationWebhookCreateRequest request)
throws UnauthorizedException, GeneralException {
String url = this.conversationsBaseUrl + CONVERSATION_WEBHOOK_PATH;
return messageBirdService.sendPayLoad(url, request, ConversationWebhook.class);
}
/**
* Update an existing webhook.
*
* @param request update request.
* @return Updated webhook.
*/
public ConversationWebhook updateConversationWebhook(final String id, final ConversationWebhookUpdateRequest request) throws UnauthorizedException, GeneralException {
if (id == null || id.isEmpty()) {
throw new IllegalArgumentException("Conversation webhook ID must be specified.");
}
String url = this.conversationsBaseUrl + CONVERSATION_WEBHOOK_PATH + "/" + id;
return messageBirdService.sendPayLoad("PATCH", url, request, ConversationWebhook.class);
}
/**
* Gets a single webhook.
*
* @param webhookId Webhook to retrieve.
* @return The retrieved webhook.
*/
public ConversationWebhook viewConversationWebhook(final String webhookId) throws NotFoundException, GeneralException, UnauthorizedException {
String url = this.conversationsBaseUrl + CONVERSATION_WEBHOOK_PATH;
return messageBirdService.requestByID(url, webhookId, ConversationWebhook.class);
}
/**
* Gets a ConversationWebhook listing with the specified pagination options.
*
* @param offset Number of objects to skip.
* @param limit Number of objects to skip.
* @return List of webhooks.
*/
public ConversationWebhookList listConversationWebhooks(final int offset, final int limit)
throws UnauthorizedException, GeneralException {
String url = this.conversationsBaseUrl + CONVERSATION_WEBHOOK_PATH;
return messageBirdService.requestList(url, offset, limit, ConversationWebhookList.class);
}
/**
* Gets a ConversationWebhook listing with default pagination options.
*
* @return List of webhooks.
*/
public ConversationWebhookList listConversationWebhooks() throws UnauthorizedException, GeneralException {
final int offset = 0;
final int limit = 10;
return listConversationWebhooks(offset, limit);
}
/**
* Function for voice call to a number
*
* @param voiceCall Voice call object
* @return VoiceCallResponse
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public VoiceCallResponse sendVoiceCall(final VoiceCall voiceCall) throws UnauthorizedException, GeneralException {
if (voiceCall.getSource() == null) {
throw new IllegalArgumentException("Source of voice call must be specified.");
}
if (voiceCall.getDestination() == null) {
throw new IllegalArgumentException("Destination of voice call must be specified.");
}
if (voiceCall.getCallFlow() == null) {
throw new IllegalArgumentException("Call flow of voice call must be specified.");
}
String url = String.format("%s%s", VOICE_CALLS_BASE_URL, VOICECALLSPATH);
return messageBirdService.sendPayLoad(url, voiceCall, VoiceCallResponse.class);
}
/**
* Function to list all voice calls
*
* @return VoiceCallResponseList
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public VoiceCallResponseList listAllVoiceCalls(Integer page, Integer pageSize) throws GeneralException, UnauthorizedException {
String url = String.format("%s%s", VOICE_CALLS_BASE_URL, VOICECALLSPATH);
return messageBirdService.requestList(url, new PagedPaging(page, pageSize), VoiceCallResponseList.class);
}
/**
* Function to view voice call by id
*
* @param id Voice call ID
* @return VoiceCallResponse
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public VoiceCallResponse viewVoiceCall(final String id) throws NotFoundException, GeneralException, UnauthorizedException {
if (id == null) {
throw new IllegalArgumentException("Voice Message ID must be specified.");
}
String url = String.format("%s%s", VOICE_CALLS_BASE_URL, VOICECALLSPATH);
return messageBirdService.requestByID(url, id, VoiceCallResponse.class);
}
/**
* Function to delete voice call by id
*
* @param id Voice call ID
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public void deleteVoiceCall(final String id) throws NotFoundException, GeneralException, UnauthorizedException {
if (id == null) {
throw new IllegalArgumentException("Voice Message ID must be specified.");
}
String url = String.format("%s%s", VOICE_CALLS_BASE_URL, VOICECALLSPATH);
messageBirdService.deleteByID(url, id);
}
/**
* Retrieves a listing of all legs.
*
* @param callId Voice call ID
* @param page page to fetch (can be null - will return first page), number of first page is 1
* @param pageSize page size
* @return VoiceCallLegResponse
* @throws UnsupportedEncodingException no UTF8 supported url
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public VoiceCallLegResponse viewCallLegsByCallId(String callId, Integer page, Integer pageSize) throws UnsupportedEncodingException, UnauthorizedException, GeneralException {
if (callId == null) {
throw new IllegalArgumentException("Voice call ID must be specified.");
}
String url = String.format(
"%s%s/%s%s",
VOICE_CALLS_BASE_URL,
VOICECALLSPATH,
urlEncode(callId),
VOICELEGS_SUFFIX_PATH);
return messageBirdService.requestList(url, new PagedPaging(page, pageSize), VoiceCallLegResponse.class);
}
/**
* Retrieves a leg resource.
* The parameters are the unique ID of the call and of the leg that were returned upon their respective creation.
*
* @param callId Voice call ID
* @param legId ID of leg of specified call {callId}
* @return VoiceCallLeg
* @throws UnsupportedEncodingException no UTF8 supported url
* @throws NotFoundException not found with callId and legId
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public VoiceCallLeg viewCallLegByCallIdAndLegId(final String callId, String legId) throws UnsupportedEncodingException, NotFoundException, GeneralException, UnauthorizedException {
if (callId == null) {
throw new IllegalArgumentException("Voice call ID must be specified.");
}
if (legId == null) {
throw new IllegalArgumentException("Leg ID must be specified.");
}
String url = String.format(
"%s%s/%s%s",
VOICE_CALLS_BASE_URL,
VOICECALLSPATH,
urlEncode(callId),
VOICELEGS_SUFFIX_PATH);
VoiceCallLegResponse response = messageBirdService.requestByID(url, legId, VoiceCallLegResponse.class);
if (response.getData().size() == 1) {
return response.getData().get(0);
} else {
throw new NotFoundException("No such leg", new LinkedList<ErrorReport>());
}
}
private String urlEncode(String s) throws UnsupportedEncodingException {
return URLEncoder.encode(s, String.valueOf(StandardCharsets.UTF_8));
}
/**
* Function to view recording by call id , leg id and recording id
*
* @param callID Voice call ID
* @param legId Leg ID
* @param recordingId Recording ID
* @return Recording
* @throws NotFoundException not found with callId and legId
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public RecordingResponse viewRecording(String callID, String legId, String recordingId) throws NotFoundException, GeneralException, UnauthorizedException {
if (callID == null) {
throw new IllegalArgumentException("Voice call ID must be specified.");
}
if (legId == null) {
throw new IllegalArgumentException("Leg ID must be specified.");
}
if (recordingId == null) {
throw new IllegalArgumentException("Recording ID must be specified.");
}
String url = String.format("%s%s", VOICE_CALLS_BASE_URL, VOICECALLSPATH);
Map<String, Object> params = new LinkedHashMap<>();
params.put("legs", legId);
params.put("recordings", recordingId);
return messageBirdService.requestByID(url, callID, params, RecordingResponse.class);
}
/**
* Downloads the record in .wav format by using callId, legId and recordId and stores to basePath. basePath is not mandatory to set.
* If basePath is not set, default download will be the /Download folder in user group.
*
* @param callID Voice call ID
* @param legId Leg ID
* @param recordingId Recording ID
* @param basePath store location. It should be directory. Property is Optional if $HOME is accessible
* @return the path that file is stored
* @throws NotFoundException if the recording does not found
* @throws GeneralException general exception
* @throws UnauthorizedException if client is unauthorized
*/
public String downloadRecording(String callID, String legId, String recordingId, String basePath) throws NotFoundException, GeneralException, UnauthorizedException {
if (callID == null) {
throw new IllegalArgumentException("Voice call ID must be specified.");
}
if (legId == null) {
throw new IllegalArgumentException("Leg ID must be specified.");
}
if (recordingId == null) {
throw new IllegalArgumentException("Recording ID must be specified.");
}
String url = String.format(
"%s%s/%s%s/%s%s/%s%s",
VOICE_CALLS_BASE_URL,
VOICECALLSPATH,
callID,
LEGSPATH,
legId,
RECORDINGPATH,
recordingId,
RECORDING_DOWNLOAD_FORMAT
);
String fileName = String.format("%s%s",recordingId, RECORDING_DOWNLOAD_FORMAT);
return messageBirdService.getBinaryData(url, basePath, fileName);
}
/**
* List the all recordings related to CallID and LegId
*
* @param callID Voice call ID
* @param legId Leg ID
* @param offset Number of objects to skip.
* @param limit Number of objects to take.
* @return Recordings for CallID and LegID
* @throws GeneralException if client is unauthorized
* @throws UnauthorizedException general exception
*/
public RecordingResponse listRecordings(String callID, String legId, final Integer offset, final Integer limit)
throws GeneralException, UnauthorizedException {
verifyOffsetAndLimit(offset, limit);
if (callID == null) {
throw new IllegalArgumentException("Voice call ID must be specified.");
}
if (legId == null) {
throw new IllegalArgumentException("Leg ID must be specified.");
}
String url = String.format(
"%s%s/%s%s/%s%s",
VOICE_CALLS_BASE_URL,
VOICECALLSPATH,
callID,
LEGSPATH,
legId,
RECORDINGPATH);
return messageBirdService.requestList(url, offset, limit, RecordingResponse.class);
}
/**
* Function to view recording by call id , leg id and recording id
*
* @param callID Voice call ID
* @param legId Leg ID
* @param recordingId Recording ID
* @param language Language
* @return TranscriptionResponseList
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public TranscriptionResponse createTranscription(String callID, String legId, String recordingId, String language)
throws UnauthorizedException, GeneralException {
if (callID == null) {
throw new IllegalArgumentException("Voice call ID must be specified.");
}
if (legId == null) {
throw new IllegalArgumentException("Leg ID must be specified.");
}
if (recordingId == null) {
throw new IllegalArgumentException("Recording ID must be specified.");
}
if (language == null) {
throw new IllegalArgumentException("Language must be specified.");
}
if (!Arrays.asList(supportedLanguages).contains(language)) {
throw new IllegalArgumentException("Your language is not allowed.");
}
String url = String.format(
"%s%s/%s%s/%s%s/%s%s",
VOICE_CALLS_BASE_URL,
VOICECALLSPATH,
callID,
LEGSPATH,
legId,
RECORDINGPATH,
recordingId,
TRANSCRIPTIONPATH);
return messageBirdService.sendPayLoad(url, language, TranscriptionResponse.class);
}
/**
* Function to view recording by call id, leg id and recording id
*
* @param callID Voice call ID
* @param legId Leg ID
* @param recordingId Recording ID
* @param transcriptionId Transcription ID
* @return Transcription
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
* @throws NotFoundException If transcription is not found
*/
public TranscriptionResponse viewTranscription(String callID, String legId, String recordingId, String transcriptionId) throws UnauthorizedException, GeneralException, NotFoundException {
if (callID == null) {
throw new IllegalArgumentException("Voice call ID must be specified.");
}
if (legId == null) {
throw new IllegalArgumentException("Leg ID must be specified.");
}
if (recordingId == null) {
throw new IllegalArgumentException("Recording ID must be specified.");
}
if(transcriptionId == null) {
throw new IllegalArgumentException("Transcription ID must be specified.");
}
String url = String.format(
"%s%s/%s%s/%s%s/%s%s",
VOICE_CALLS_BASE_URL,
VOICECALLSPATH,
callID,
LEGSPATH,
legId,
RECORDINGPATH,
recordingId,
TRANSCRIPTIONPATH);
return messageBirdService.requestByID(url, transcriptionId, TranscriptionResponse.class);
}
/**
* Lists the Transcription of callId, legId and recordId
*
* @param callID Voice call ID
* @param legId Leg ID
* @param recordingId Recording ID
* @param page page to fetch (can be null - will return first page), number of first page is 1
* @param pageSize page size
* @return List of Transcription
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public TranscriptionResponse listTranscriptions(String callID, String legId, String recordingId, Integer page, Integer pageSize) throws UnauthorizedException, GeneralException {
if (callID == null) {
throw new IllegalArgumentException("Voice call ID must be specified.");
}
if (legId == null) {
throw new IllegalArgumentException("Leg ID must be specified.");
}
if (recordingId == null) {
throw new IllegalArgumentException("Recording ID must be specified.");
}
String url = String.format(
"%s%s/%s%s/%s%s/%s%s",
VOICE_CALLS_BASE_URL,
VOICECALLSPATH,
callID,
LEGSPATH,
legId,
RECORDINGPATH,
recordingId,
TRANSCRIPTIONPATH);
return messageBirdService.requestList(url, new PagedPaging(page, pageSize), TranscriptionResponse.class);
}
/**
* Downloads the transcription in .txt format by using callId, legId, recordId and transcriptionId and stores to basePath. basePath is not mandatory to set.
* If basePath is not set, default download will be the /Download folder in user group.
*
* @param callID Voice call ID
* @param legId Leg ID
* @param recordingId Recording ID
* @param transcriptionId Transcription ID
* @param basePath store location. It should be directory. Property is Optional if $HOME is accessible
* @return the path that file is stored
* @throws NotFoundException if the recording does not found
* @throws GeneralException general exception
* @throws UnauthorizedException if client is unauthorized
*/
public String downloadTranscription(String callID, String legId, String recordingId, String transcriptionId, String basePath)
throws UnauthorizedException, GeneralException, NotFoundException {
if (callID == null) {
throw new IllegalArgumentException("Voice call ID must be specified.");
}
if (legId == null) {
throw new IllegalArgumentException("Leg ID must be specified.");
}
if (recordingId == null) {
throw new IllegalArgumentException("Recording ID must be specified.");
}
if (transcriptionId == null) {
throw new IllegalArgumentException("Transcription ID must be specified.");
}
String fileName = String.format("%s%s", transcriptionId, TRANSCRIPTION_DOWNLOAD_FORMAT);
String url = String.format(
"%s%s/%s%s/%s%s/%s%s/%s",
VOICE_CALLS_BASE_URL,
VOICECALLSPATH,
callID,
LEGSPATH,
legId,
RECORDINGPATH,
recordingId,
TRANSCRIPTIONPATH,
fileName);
return messageBirdService.getBinaryData(url, basePath, fileName);
}
/**
* Function to create a webhook
*
* @param webhook webhook to create
* @return WebhookResponseData created webhook
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public WebhookResponseData createWebhook(Webhook webhook) throws UnauthorizedException, GeneralException {
if (webhook.getUrl() == null) {
throw new IllegalArgumentException("URL of webhook must be specified.");
}
String url = String.format("%s%s", VOICE_CALLS_BASE_URL, WEBHOOKS);
return messageBirdService.sendPayLoad(url, webhook, WebhookResponseData.class);
}
/**
* Function to update a webhook
*
* @param webhook webhook fields to update
* @return WebhookResponseData updated webhook
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public WebhookResponseData updateWebhook(String id, Webhook webhook) throws UnauthorizedException, GeneralException {
if (id == null) {
throw new IllegalArgumentException("Id of webhook must be specified.");
}
String url = String.format("%s%s/%s", VOICE_CALLS_BASE_URL, WEBHOOKS, id);
return messageBirdService.sendPayLoad("PUT", url, webhook, WebhookResponseData.class);
}
/**
* Function to view a webhook
*
* @param id id of a webhook
* @return WebhookResponseData
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public WebhookResponseData viewWebhook(String id) throws NotFoundException, GeneralException, UnauthorizedException {
if (id == null) {
throw new IllegalArgumentException("Id of webhook must be specified.");
}
String url = String.format("%s%s", VOICE_CALLS_BASE_URL, WEBHOOKS);
return messageBirdService.requestByID(url, id, WebhookResponseData.class);
}
/**
* Function to list webhooks
*
* @param offset offset for result list
* @param limit limit for result list
* @return WebhookList
* @throws UnauthorizedException if client is unauthorized
* @throws GeneralException general exception
*/
public WebhookList listWebhooks(final Integer offset, final Integer limit) throws UnauthorizedException, GeneralException {
verifyOffsetAndLimit(offset, limit);
String url = String.format("%s%s", VOICE_CALLS_BASE_URL, WEBHOOKS);
return messageBirdService.requestList(url, offset, limit, WebhookList.class);
}
public void deleteWebhook(String id) throws NotFoundException, GeneralException, UnauthorizedException {
if (id == null) {
throw new IllegalArgumentException("Webhook ID must be specified.");
}
String url = String.format("%s%s", VOICE_CALLS_BASE_URL, WEBHOOKS);
messageBirdService.deleteByID(url, id);
}
private void verifyOffsetAndLimit(Integer offset, Integer limit) {
if (offset != null && offset < 0) {
throw new IllegalArgumentException("Offset must be > 0");
}
if (limit != null && limit < 0) {
throw new IllegalArgumentException("Limit must be > 0");
}
}
public PhoneNumbersResponse listNumbersForPurchase(String countryCode) throws IllegalArgumentException, GeneralException, UnauthorizedException, NotFoundException {
final String url = String.format("%s/v1/available-phone-numbers", NUMBERS_CALLS_BASE_URL);
return messageBirdService.requestByID(url, countryCode, PhoneNumbersResponse.class);
}
public PhoneNumbersResponse listNumbersForPurchase(String countryCode, PhoneNumbersLookup params) throws IllegalArgumentException, GeneralException, UnauthorizedException, NotFoundException {
final String url = String.format("%s/v1/available-phone-numbers", NUMBERS_CALLS_BASE_URL);
return messageBirdService.requestByID(url, countryCode, params.toHashMap(), PhoneNumbersResponse.class);
}
public PurchasedPhoneNumber purchaseNumber(String number, String countryCode, int billingIntervalMonths) throws UnauthorizedException, GeneralException {
final String url = String.format("%s/v1/phone-numbers", NUMBERS_CALLS_BASE_URL);
final Map<String, Object> payload = new LinkedHashMap<String, Object>();
payload.put("number", number);
payload.put("countryCode", countryCode);
payload.put("billingIntervalMonths", billingIntervalMonths);
return messageBirdService.sendPayLoad(url, payload, PurchasedPhoneNumber.class);
}
public void cancelNumber(String number) throws UnauthorizedException, GeneralException, NotFoundException {
final String url = String.format("%s/v1/phone-numbers", NUMBERS_CALLS_BASE_URL);
messageBirdService.deleteByID(url, number);
}
} |
package at.bitfire.gfxtablet;
import at.bitfire.gfxtablet.R;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
public class CanvasActivity extends Activity {
CanvasView canvas;
SharedPreferences prefs;
NetworkClient netClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
PreferenceManager.setDefaultValues(this, R.xml.network_preferences, false);
PreferenceManager.setDefaultValues(this, R.xml.drawing_preferences, false);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_canvas);
LinearLayout layout = (LinearLayout)findViewById(R.id.canvas_layout);
new Thread(netClient = new NetworkClient(PreferenceManager.getDefaultSharedPreferences(this))).start();
canvas = new CanvasView(this, netClient);
layout.addView(canvas);
}
@Override
protected void onDestroy() {
netClient.getQueue().add(new NetEvent(NetEvent.Type.TYPE_DISCONNECT));
super.onDestroy();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_canvas, menu);
return true;
}
public void showAbout(MenuItem item) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(("http://rfc2822.github.com/GfxTablet"))));
}
public void showSettings(MenuItem item) {
startActivity(new Intent(CanvasActivity.this, SettingsActivity.class));
}
} |
package grundkurs_java;
import java.net.*;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.io.*;
import java.util.*;
import java.text.*;
import javax.swing.*;
public class Chap20 {
public static void main(String[] args) {
// DateTimeServer.main(new String[] { "2222" });
// DateTimeClient.main(new String[] { "localhost", "2222" });
// DateTimeMultiServer.main(new String[] { "3333" });
// MyClient.main(new String[] { "3333" });
// CdServer.main(new String[] { "3334" });
CurrencyServer.main(new String[] { "3334" });
}
}
class TalkServer {
public static void main(String[] args) {
Socket c1;
Socket c2;
if (args.length == 1) {
// Port-Nummer bestimmen
int port = Integer.parseInt(args[0]);
// try-catch-Block beginnen
try {
ServerSocket server = new ServerSocket(port);
System.out.println("Der Server laeuft");
// Endlosschleife
while (true) {
// zwei Talk-Dienst Threads starten
c1 = server.accept();
c2 = server.accept();
new TalkDienst(c1, c2).start();
new TalkDienst(c2, c1).start();
}
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("Aufruf: java TalkServer <PortNummer>");
}
}
}
class TalkDienst extends Thread {
Socket c1, c2;
BufferedReader in;
PrintWriter out;
/**
* Eingabe- und Ausgabestroeme zu den Clients erzeugen
*
*/
TalkDienst(Socket sin, Socket sout) {
// Die Client-Sockets in den Instanzvariablen speichern
c1 = sin;
c2 = sout;
// try-catch-Block beginnen
try {
// Den Eingabe-Strom vom anderen Client erzeugen
in = new BufferedReader(new InputStreamReader(c1.getInputStream()));
// Den Ausgabe-Strom zum anderen Client erzeugen
out = new PrintWriter(c2.getOutputStream(), true);
out.println("*** " + "Chatpartner gefunden, es kann losgehen!"
+ " ***");
} catch (IOException e) {
}
}
// run-Methode ueberschreiben: Abarbeitung des eigentlichen Protokolls
public void run() {
String line;
try {
while (true) {
line = in.readLine();
if (line != null)
out.println(line);
try {
Thread.sleep(10);
} catch (InterruptedException e) {
break;
}
}
} catch (IOException e) {
System.out.println("Fehler:" + e);
}
}
}
class ChatServer {
// 20.3
public static void main(String[] args) {
if (args.length == 1) {
// Port-Nummer bestimmen
int client1Port = Integer.parseInt(args[0]);
int client2Port = Integer.parseInt(args[1]);
// Try-Catch-Block beginnen
try {
ChatDienst client1Thread;
ChatDienst client2Thread;
ServerSocket client1Socket = new ServerSocket(client1Port);
ServerSocket client2Socket = new ServerSocket(client2Port);
System.out.println("Der Server laeuft.");
// "Endlos"-Schleife
while (true) {
// einen EuroThread starten
client1Thread = new ChatDienst(client2Socket.accept());
client2Thread = new ChatDienst(client1Socket.accept());
client1Thread.start();
client2Thread.start();
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Der Server ist beendet.");
} else {
System.out.println("Aufruf: java ChatServer <PortNummer>");
}
}
}
class ChatDienst extends Thread {
// 20.3
Socket c;
BufferedReader in; // Eingabe-Strom zum Client
PrintWriter out; // Ausgabe-Strom zum Client
public ChatDienst(Socket socket) {
System.out.println("Neuer Client wird bearbeitet.");
// Den Client-Socket in der Instanzvariablen speichern
c = socket;
// Try-Catch-Block beginnen
try {
// Den Eingabe-Strom zum Client erzeugen
in = new BufferedReader(new InputStreamReader(c.getInputStream()));
// Den Ausgabe-Strom zum Client erzeugen
out = new PrintWriter(c.getOutputStream(), true);
} catch (IOException e) {
}
}
public void run() {
try {
String zeile;
double wert;
boolean toEuroDesired, nochmal;
nochmal = true;
while (nochmal) {
out.println("Welche Waehrung wollen Sie eingeben (DM oder EUR)?");
zeile = in.readLine();
if (zeile == null)
break;
toEuroDesired = zeile.toUpperCase().startsWith("DM");
out.println("Welchen Wert wollen Sie umrechnen?");
zeile = in.readLine();
if (zeile == null)
break;
wert = Double.parseDouble(zeile);
if (toEuroDesired) {
wert = EuroConverter.convertToEuro(wert, EuroConverter.DEM);
out.println("Wert in EUR: " + wert);
} else {
wert = EuroConverter.convertFromEuro(wert,
EuroConverter.DEM);
out.println("Wert in DM: " + wert);
}
out.println();
out.println("Darf's noch eine Umrechnung sein?");
zeile = in.readLine();
if (zeile == null)
break;
nochmal = zeile.startsWith("j") || zeile.startsWith("J");
}
} catch (IOException ign) {
}
}
}
class EuroServer {
// 20.2 offiziell
static boolean serverAktiv = true;
public static void main(String[] args) {
if (args.length == 1) {
// Port-Nummer bestimmen
int port = Integer.parseInt(args[0]);
// Try-Catch-Block beginnen
try {
// Server-Steuerung aktivieren
new SteuerDienst().start();
ServerSocket server = new ServerSocket(port);
System.out.println("Der Server laeuft.");
// "Endlos"-Schleife
while (serverAktiv) {
// einen EuroThread starten
new EuroThread(server.accept()).start();
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Der Server ist beendet.");
} else {
System.out.println("Aufruf: java EuroServer <PortNummer>");
}
}
}
class EuroThread extends Thread {
// 20.2 offiziell
Socket c;
BufferedReader in; // Eingabe-Strom zum Client
PrintWriter out; // Ausgabe-Strom zum Client
EuroThread(Socket sock) {
System.out.println("Neuer Client wird bearbeitet.");
// Den Client-Socket in der Instanzvariablen speichern
c = sock;
// Try-Catch-Block beginnen
try {
// Den Eingabe-Strom zum Client erzeugen
in = new BufferedReader(new InputStreamReader(c.getInputStream()));
// Den Ausgabe-Strom zum Client erzeugen
out = new PrintWriter(c.getOutputStream(), true);
} catch (IOException e) {
}
}
public void run() {
try {
String zeile;
double wert;
boolean toEuroDesired, nochmal;
nochmal = true;
while (nochmal) {
out.println("Welche Waehrung wollen Sie eingeben (DM oder EUR)?");
zeile = in.readLine();
if (zeile == null)
break;
toEuroDesired = zeile.toUpperCase().startsWith("DM");
out.println("Welchen Wert wollen Sie umrechnen?");
zeile = in.readLine();
if (zeile == null)
break;
wert = Double.parseDouble(zeile);
if (toEuroDesired) {
wert = EuroConverter.convertToEuro(wert, EuroConverter.DEM);
out.println("Wert in EUR: " + wert);
} else {
wert = EuroConverter.convertFromEuro(wert,
EuroConverter.DEM);
out.println("Wert in DM: " + wert);
}
out.println();
out.println("Darf's noch eine Umrechnung sein?");
zeile = in.readLine();
if (zeile == null)
break;
nochmal = zeile.startsWith("j") || zeile.startsWith("J");
}
} catch (IOException ign) {
}
}
}
class SteuerDienst extends Thread {
// 20.2 offiziell
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String eingabe;
public void run() {
try {
// Solange Benutzer-Eingaben anfordern, bis SHUTDOWN eingegeben wird
do {
System.out
.println("Server beenden durch Eingabe von SHUTDOWN!");
} while (!(eingabe = in.readLine()).toLowerCase().startsWith(
"shutdown"));
// EuroServer deaktivieren
EuroServer.serverAktiv = false;
System.out.println("Der Server wird nun nach Abarbeitung des");
System.out.println("naechsten Clients automatisch beendet.");
} catch (IOException e) {
}
}
}
class CurrencyServer {
// 20.2
public static void main(String[] args) {
try {
int port = Integer.parseInt(args[0]);
// Port-Nummer
ServerSocket server = new ServerSocket(port); // Server-Socket
System.out.println("CurrencyServer wartet auf Port " + port); // Statusmeldung
while (true) {
Socket s = server.accept(); // Client-Verbindung akzeptieren
new CurrencyServerDienst(s).start();
}
} catch (ArrayIndexOutOfBoundsException ae) {
System.out.println("Aufruf: java CdServer <Port>");
} catch (IOException e) {
e.printStackTrace();
}
}
}
class CurrencyServerDienst extends Thread {
// 20.2
static SimpleDateFormat time = new SimpleDateFormat(
"'Es ist gerade 'H'.'mm' Uhr.'"), date = new SimpleDateFormat(
"'Heute ist 'EEEE', der 'dd.MM.yy");
// Formate fuer den Zeitpunkt20.2 Client/Server-Programmierung
static int anzahl = 0;
// Anzahl der Clients insgesamt
int nr = 0;
// Nummer des Clients
Socket s;
// Socket in Verbindung mit dem Client
BufferedReader vomClient;
// Eingabe-Strom vom Client
PrintWriter zumClient;
// Ausgabe-Strom zum Client
public CurrencyServerDienst(Socket s) { // Konstruktor
try {
this.s = s;
nr = ++anzahl;
vomClient = new BufferedReader(new InputStreamReader(
s.getInputStream()));
zumClient = new PrintWriter(s.getOutputStream(), true);
} catch (IOException e) {
System.out.println("IO-Error bei Client " + nr);
e.printStackTrace();
}
}
public void run() { // Methode, die das Protokoll abwickelt
System.out.println("Protokoll fuer Client " + nr + " gestartet");
try {
while (true) {
zumClient
.println("Der Client laueft und kann mit 'quit' beendet werden.");
zumClient
.println("Welche Waehrung wollen Sie eingeben (DM oder EUR)?");
String wunsch = vomClient.readLine(); // vom Client empfangen
if (wunsch == null || wunsch.equalsIgnoreCase("quit"))
break;
Date jetzt = new Date();
if (wunsch.equalsIgnoreCase("date"))
zumClient.println(date.format(jetzt));
else if (wunsch.equalsIgnoreCase("time"))
zumClient.println(time.format(jetzt));
else if (wunsch.equalsIgnoreCase("dm"))
zumClient.println("Wert in Euro: " + toEuro());
else if (wunsch.equalsIgnoreCase("eur"))
zumClient.println("Wert in DM: " + toDM());
else
zumClient.println(wunsch + "ist als Kommando unzulaessig!");
}
s.close();
// Socket (und damit auch Stroeme) schliessen
} catch (IOException e) {
System.out.println("IO-Error bei Client " + nr);
}
System.out.println("Protokoll fuer Client " + nr + " beendet");
}
private double toEuro() {
zumClient.println("Bitte DM Betrag eingeben: ");
String betrag = readBetrag();
return EuroConverter.convertToEuro(Double.parseDouble(betrag),
EuroConverter.DEM);
}
private double toDM() {
zumClient.println("Bitte EUR Betrag eingeben: ");
String betrag = readBetrag();
return EuroConverter.convertFromEuro(Double.parseDouble(betrag),
EuroConverter.DEM);
}
private String readBetrag() {
String betrag = null;
try {
betrag = vomClient.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return betrag;
}
}
class CDServer {
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Aufruf: java CDServer <portnr>");
System.exit(1);
}
try {
int port = Integer.parseInt(args[0]);
ServerSocket server = new ServerSocket(port);
System.out.println("CDServer wartet auf Port " + port);
boolean neu = true;
while (neu) {
Socket sock = server.accept();
new CDVerbindung(sock).start();
}
server.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class CDVerbindung extends Thread {
Socket sock;
PrintWriter sockOut;
BufferedReader sockIn;
static final String LIST = "list", TRACKS = "tracks";
CDVerbindung(Socket sock) {
this.sock = sock;
try {
sockIn = new BufferedReader(new InputStreamReader(
sock.getInputStream()));
sockOut = new PrintWriter(sock.getOutputStream(), true);
} catch (IOException e) {
protokolliere("Ausnahme beim Verbindungsaufbau: " + e);
}
}
void protokolliere(String action) {
System.out.println("[" + sock.getInetAddress() + ":" + sock.getPort()
+ ": " + action + "]");
}
public void run() {
try {
protokolliere("neue Verbindung");
String clientAnfrage;
while ((clientAnfrage = sockIn.readLine()) != null) {
if (clientAnfrage.equalsIgnoreCase(LIST)) {
protokolliere("sende Verzeichnis der CDs");
String[] verzeichnis = new File("cdArchiv").list();
for (int i = 0; i < verzeichnis.length; i++)
sockOut.println(verzeichnis[i]);
} else if (clientAnfrage.startsWith(TRACKS)) {
String cd = clientAnfrage.substring(TRACKS.length() + 1)
.trim();
protokolliere("sende Tracks der CD " + cd);
BufferedReader fileIn;
try {
fileIn = new BufferedReader(new FileReader("cdArchiv/"
+ cd));
} catch (FileNotFoundException e) {
continue;
}
while ((cd = fileIn.readLine()) != null)
sockOut.println(cd);
fileIn.close();
}
}
sock.close();
protokolliere("Verbindung unterbrochen");
} catch (IOException e) {
}
}
}
class CdServer {
// 20.1
public static void main(String[] args) {
try {
int port = Integer.parseInt(args[0]);
// Port-Nummer
ServerSocket server = new ServerSocket(port); // Server-Socket
System.out.println("CdServer wartet auf Port " + port); // Statusmeldung
File cdArchiv = new File("cdArchiv");
if (!cdArchiv.exists()) {
try {
cdArchiv.mkdir();
} catch (SecurityException e) {
System.out
.println("Could neither find nor create cdArchive directory.");
System.exit(1);
}
}
while (true) {
Socket s = server.accept(); // Client-Verbindung akzeptieren
// Dienst starten
new CdServerDienst(s, cdArchiv).start();
}
} catch (ArrayIndexOutOfBoundsException ae) {
System.out.println("Aufruf: java CdServer <Port>");
} catch (IOException e) {
e.printStackTrace();
}
}
}
class CdServerDienst extends Thread {
// 20.1
static SimpleDateFormat time = new SimpleDateFormat(
"'Es ist gerade 'H'.'mm' Uhr.'"), date = new SimpleDateFormat(
"'Heute ist 'EEEE', der 'dd.MM.yy");
// Formate fuer den Zeitpunkt20.2 Client/Server-Programmierung
static int anzahl = 0;
// Anzahl der Clients insgesamt
int nr = 0;
// Nummer des Clients
Socket s;
// Socket in Verbindung mit dem Client
BufferedReader vomClient;
// Eingabe-Strom vom Client
PrintWriter zumClient;
File cdArchiv;
// Ausgabe-Strom zum Client
public CdServerDienst(Socket s, File cdArchiv) { // Konstruktor
try {
this.s = s;
this.cdArchiv = cdArchiv;
nr = ++anzahl;
vomClient = new BufferedReader(new InputStreamReader(
s.getInputStream()));
zumClient = new PrintWriter(s.getOutputStream(), true);
} catch (IOException e) {
System.out.println("IO-Error bei Client " + nr);
e.printStackTrace();
}
}
public void run() { // Methode, die das Protokoll abwickelt
System.out.println("Protokoll fuer Client " + nr + " gestartet");
try {
while (true) {
zumClient
.println("Mögliche Befehle: list, tracks <album>, date, time, quit");
String wunsch = vomClient.readLine(); // vom Client empfangen
if (wunsch == null || wunsch.equalsIgnoreCase("quit"))
break;
Date jetzt = new Date();
if (wunsch.equalsIgnoreCase("date"))
zumClient.println(date.format(jetzt));
else if (wunsch.equalsIgnoreCase("time"))
zumClient.println(time.format(jetzt));
else if (wunsch.equalsIgnoreCase("list"))
for (String s : cdArchiv.list())
zumClient.println(s);
else if (wunsch.toLowerCase().startsWith("tracks"))
zumClient.println(findTracks(wunsch));
else
zumClient.println(wunsch + "ist als Kommando unzulaessig!");
}
s.close();
// Socket (und damit auch Stroeme) schliessen
} catch (IOException e) {
System.out.println("IO-Error bei Client " + nr);
}
System.out.println("Protokoll fuer Client " + nr + " beendet");
}
private List<String> findTracks(String wunsch) throws IOException {
File[] matches = cdArchiv.listFiles(new FilesearchFilter(wunsch));
System.out.println(matches.length + " matches");
if (matches.length == 0)
return null;
return Files
.readAllLines(matches[0].toPath(), Charset.defaultCharset());
}
class FilesearchFilter implements FilenameFilter {
private String wunsch;
public FilesearchFilter(String wunsch) {
this.wunsch = wunsch;
}
public boolean accept(File dir, String name) {
String[] wunschSplit = wunsch.split("\\s");
for (String w : wunschSplit)
System.out.println(w);
return name.startsWith(wunsch.split("\\s")[1]);
}
}
}
class DateTimeApplet extends JApplet {
public void init() {
try {
Socket socket = new Socket(this.getCodeBase().getHost(), 7777);
BufferedReader in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
in.readLine();
out.println("date");
String s = in.readLine();
getContentPane().add(new JLabel(s, JLabel.CENTER));
} catch (IOException e) {
String s = "Verbindung zum DateTimeServer fehlgeschlagen!";
getContentPane().add(new JLabel(s, JLabel.CENTER));
}
}
}
class LiesURL {
public static void main(String[] args) {
try {
URL u = new URL(args[0]);
BufferedReader in = new BufferedReader(new InputStreamReader(
u.openStream()));
String zeile;
while ((zeile = in.readLine()) != null)
System.out.println(zeile);
in.close();
} catch (ArrayIndexOutOfBoundsException ae) {
System.out.println("Aufruf: java LiesURL <URL>");
} catch (MalformedURLException me) {
System.out.println(args[0] + " ist keine zulaessige URL");
} catch (IOException e) {
e.printStackTrace();
}
}
}
class MyClient {
// liest alle vom Server geschickten Daten
static void zeigeWasKommt(BufferedReader sin) throws IOException {
String str = null;
try {
while ((str = sin.readLine()) != null)
System.out.println(str);
} catch (SocketTimeoutException sto) {
}
}
static void zeigePrompt() {
System.out.print("> ");
System.out.flush();
}
public static void main(String[] args) {
try {
System.out.println("Client laeuft. Beenden mit QUIT");
Socket c = new Socket(args[0], Integer.parseInt(args[1]));
c.setSoTimeout(500); // setze Timeout auf eine halbe Sekunde
BufferedReader vomServer = new BufferedReader(
new InputStreamReader(c.getInputStream()));
PrintWriter zumServer = new PrintWriter(c.getOutputStream(), true);
BufferedReader vonTastatur = new BufferedReader(
new InputStreamReader(System.in));
String zeile;
do {
zeigeWasKommt(vomServer);
zeigePrompt();
zeile = vonTastatur.readLine();
zumServer.println(zeile);
} while (!zeile.equalsIgnoreCase("quit"));
c.close();
// Socket (und damit auch Stroeme) schliessen
} catch (ArrayIndexOutOfBoundsException ae) {
System.out.println("Aufruf: java MyClient <Port-Nummer>");
} catch (UnknownHostException ux) {
System.out.println("Kein DNS-Eintrag fuer " + args[0]);
} catch (IOException e) {
e.printStackTrace();
}
}
}
class DateTimeMultiServer {
public static void main(String[] args) {
try {
int port = Integer.parseInt(args[0]);
// Port-Nummer
ServerSocket server = new ServerSocket(port); // Server-Socket
System.out.println("DateTimeServer laeuft"); // Statusmeldung
while (true) {
Socket s = server.accept(); // Client-Verbindung akzeptieren
new DateTimeDienst(s).start();
// Dienst starten
}
} catch (ArrayIndexOutOfBoundsException ae) {
System.out.println("Aufruf: java DateTimeServer <Port>");
} catch (IOException e) {
e.printStackTrace();
}
}
}
class DateTimeDienst extends Thread {
static SimpleDateFormat time = new SimpleDateFormat(
"'Es ist gerade 'H'.'mm' Uhr.'"), date = new SimpleDateFormat(
"'Heute ist 'EEEE', der 'dd.MM.yy");
// Formate fuer den Zeitpunkt20.2 Client/Server-Programmierung
static int anzahl = 0;
// Anzahl der Clients insgesamt
int nr = 0;
// Nummer des Clients
Socket s;
// Socket in Verbindung mit dem Client
BufferedReader vomClient;
// Eingabe-Strom vom Client
PrintWriter zumClient;
// Ausgabe-Strom zum Client
public DateTimeDienst(Socket s) { // Konstruktor
try {
this.s = s;
nr = ++anzahl;
vomClient = new BufferedReader(new InputStreamReader(
s.getInputStream()));
zumClient = new PrintWriter(s.getOutputStream(), true);
} catch (IOException e) {
System.out.println("IO-Error bei Client " + nr);
e.printStackTrace();
}
}
public void run() { // Methode, die das Protokoll abwickelt
System.out.println("Protokoll fuer Client " + nr + " gestartet");
try {
while (true) {
zumClient.println("Geben Sie DATE, TIME oder QUIT ein");
String wunsch = vomClient.readLine(); // vom Client empfangen
if (wunsch == null || wunsch.equalsIgnoreCase("quit"))
break;
// Schleife abbrechen
Date jetzt = new Date();
// Zeitpunkt bestimmen
// vom Client empfangenes Kommando ausfuehren
if (wunsch.equalsIgnoreCase("date"))
zumClient.println(date.format(jetzt));
else if (wunsch.equalsIgnoreCase("time"))
zumClient.println(time.format(jetzt));
else
zumClient.println(wunsch + "ist als Kommando unzulaessig!");
}
s.close();
// Socket (und damit auch Stroeme) schliessen
} catch (IOException e) {
System.out.println("IO-Error bei Client " + nr);
}
System.out.println("Protokoll fuer Client " + nr + " beendet");
}
}
class DateTimeClient {
public static void main(String[] args) {
String hostName = ""; // Rechner-Name bzw. -Adresse
int port;
// Port-Nummer
Socket c = null;
// Socket fuer die Verbindung zum Server
try {
hostName = args[0];
port = Integer.parseInt(args[1]);
c = new Socket(hostName, port);
BufferedReader vomServer = new BufferedReader(
new InputStreamReader(c.getInputStream()));
PrintWriter zumServer = new PrintWriter(c.getOutputStream(), true);
BufferedReader vonTastatur = new BufferedReader(
new InputStreamReader(System.in));
// Protokoll abwickeln20.2 Client/Server-Programmierung
System.out.println("Server " + hostName + ":" + port + " sagt:");
String text = vomServer.readLine(); // vom Server empfangen
System.out.println(text);
// auf die Konsole schreiben
text = vonTastatur.readLine();
// von Tastatur lesen
zumServer.println(text);
// zum Server schicken
text = vomServer.readLine();
// vom Server empfangen
System.out.println(text);
// auf die Konsole schreiben
// Socket (und damit auch Stroeme) schliessen
c.close();
} catch (ArrayIndexOutOfBoundsException ae) {
System.out.println("Aufruf:");
System.out.println("java DateTimeClient <HostName> <PortNr>");
} catch (UnknownHostException ue) {
System.out.println("Kein DNS-Eintrag fuer " + hostName);
} catch (IOException e) {
System.out.println("IO-Error");
}
}
}
class DateTimeServer {
public static void main(String[] args) {
try {
int port = Integer.parseInt(args[0]);
// Port-Nummer
ServerSocket server = new ServerSocket(port); // Server-Socket
System.out.println("DateTimeServer laeuft");
// Statusmeldung
Socket s = server.accept();
// Client-Verbindung akzeptieren
new DateTimeProtokoll(s).transact();
// Protokoll abwickeln
} catch (ArrayIndexOutOfBoundsException ae) {
System.out.println("Aufruf: java DateTimeServer <Port-Nr>");
} catch (IOException e) {
e.printStackTrace();
}
}
}
class DateTimeProtokoll {
static SimpleDateFormat
// Formate fuer den Zeitpunkt
time = new SimpleDateFormat("'Es ist gerade 'H'.'mm' Uhr.'"),
date = new SimpleDateFormat("'Heute ist 'EEEE', der 'dd.MM.yy");
Socket s;
BufferedReader vomClient;
PrintWriter zumClient;
// Socket in Verbindung mit dem Client
// Eingabe-Strom vom Client
// Ausgabe-Strom zum Client
public DateTimeProtokoll(Socket s) { // Konstruktor
try {
this.s = s;
vomClient = new BufferedReader(new InputStreamReader(
s.getInputStream()));
zumClient = new PrintWriter(s.getOutputStream(), true);
} catch (IOException e) {
System.out.println("IO-Error");
e.printStackTrace();
}
}
public void transact() {
// Methode, die das Protokoll abwickelt
System.out.println("Protokoll gestartet");
try {
zumClient.println("Geben Sie DATE oder TIME ein");
String wunsch = vomClient.readLine();
// v. Client empfangen
Date jetzt = new Date();
// Zeitpunkt bestimmen
// vom Client empfangenes Kommando ausfuehren
if (wunsch.equalsIgnoreCase("date"))
zumClient.println(date.format(jetzt));
else if (wunsch.equalsIgnoreCase("time"))
zumClient.println(time.format(jetzt));
else
zumClient.println(wunsch + " ist als Kommando unzulaessig!");
s.close();
// Socket (und damit auch Stroeme) schliessen
} catch (IOException e) {
System.out.println("IO-Error");
}
System.out.println("Protokoll beendet");
}
}
class DNSAnfrage {
public static void main(String[] args) {
try {
InetAddress ip = InetAddress.getByName(args[0]);
System.out.println("Angefragter Name: " + args[0]);
System.out.println("IP-Adresse: " + ip.getHostAddress());
System.out.println("Host-Name: " + ip.getHostName());
} catch (ArrayIndexOutOfBoundsException aex) {
System.out.println("Aufruf: java DNSAnfrage <hostname>");
} catch (UnknownHostException uex) {
System.out.println("Kein DNS-Eintrag fuer " + args[0]);
}
}
} |
package org.exist.xquery.functions.map;
import io.lacuna.bifurcan.IMap;
import org.exist.xquery.*;
import org.exist.xquery.util.ExpressionDumper;
import org.exist.xquery.value.AtomicValue;
import org.exist.xquery.value.Item;
import org.exist.xquery.value.Sequence;
import org.exist.xquery.value.Type;
import java.util.ArrayList;
import java.util.List;
import static org.exist.xquery.functions.map.MapType.newLinearMap;
/**
* Implements the literal syntax for creating maps.
*/
public class MapExpr extends AbstractExpression {
private final List<Mapping> mappings = new ArrayList<>(13);
public MapExpr(final XQueryContext context) {
super(context);
}
public void map(final PathExpr key, final PathExpr value) {
final Mapping mapping = new Mapping(key.simplify(), value.simplify());
this.mappings.add(mapping);
}
@Override
public void analyze(final AnalyzeContextInfo contextInfo) throws XPathException {
if (getContext().getXQueryVersion() < 30) {
throw new XPathException(this, ErrorCodes.EXXQDY0003,
"Map is not available before XQuery 3.0");
}
contextInfo.setParent(this);
for (final Mapping mapping : this.mappings) {
mapping.key.analyze(contextInfo);
mapping.value.analyze(contextInfo);
}
}
@Override
public Sequence eval(Sequence contextSequence, final Item contextItem) throws XPathException {
if (contextItem != null) {
contextSequence = contextItem.toSequence();
}
final IMap<AtomicValue, Sequence> map = newLinearMap();
boolean firstType = true;
int prevType = Type.ANY_TYPE;
for (final Mapping mapping : this.mappings) {
final Sequence key = mapping.key.eval(contextSequence);
if (key.getItemCount() != 1) {
throw new XPathException(this, MapErrorCode.EXMPDY001, "Expected single value for key, got " + key.getItemCount());
}
final AtomicValue atomic = key.itemAt(0).atomize();
final Sequence value = mapping.value.eval(contextSequence);
if (map.contains(atomic)) {
throw new XPathException(this, ErrorCodes.XQDY0137, "Key \"" + atomic.getStringValue() + "\" already exists in map.");
}
map.put(atomic, value);
final int thisType = atomic.getType();
if (firstType) {
prevType = thisType;
firstType = false;
} else {
if (thisType != prevType) {
prevType = Type.ITEM;
}
}
}
return new MapType(context, map.forked(), prevType);
}
@Override
public int returnsType() {
return Type.MAP;
}
@Override
public void accept(final ExpressionVisitor visitor) {
super.accept(visitor);
for (final Mapping mapping : this.mappings) {
mapping.key.accept(visitor);
mapping.value.accept(visitor);
}
}
@Override
public void dump(final ExpressionDumper dumper) {
dumper.display("map {");
for (final Mapping mapping : this.mappings) {
mapping.key.dump(dumper);
dumper.display(" := ");
mapping.value.dump(dumper);
}
dumper.display("}");
}
@Override
public void resetState(final boolean postOptimization) {
super.resetState(postOptimization);
mappings.forEach(m -> m.resetState(postOptimization));
}
private static class Mapping {
final Expression key;
final Expression value;
public Mapping(final Expression key, final Expression value) {
this.key = key;
this.value = value;
}
private void resetState(final boolean postOptimization) {
key.resetState(postOptimization);
value.resetState(postOptimization);
}
}
} |
package org.jfree.experimental.chart.util;
import java.io.ObjectStreamException;
import java.io.Serializable;
/**
* Represents several possible interpretations for an (x, y) coordinate.
*/
public final class XYCoordinateType implements Serializable {
/** The (x, y) coordinates represent a point in the data space. */
public static final XYCoordinateType DATA
= new XYCoordinateType("XYCoordinateType.DATA");
/**
* The (x, y) coordinates represent a relative position in the data space.
* In this case, the values should be in the range (0.0 to 1.0).
*/
public static final XYCoordinateType RELATIVE
= new XYCoordinateType("XYCoordinateType.RELATIVE");
/**
* The (x, y) coordinates represent indices in a dataset.
* In this case, the values should be in the range (0.0 to 1.0).
*/
public static final XYCoordinateType INDEX
= new XYCoordinateType("XYCoordinateType.INDEX");
/** The name. */
private String name;
/**
* Private constructor.
*
* @param name the name.
*/
private XYCoordinateType(String name) {
this.name = name;
}
/**
* Returns a string representing the object.
*
* @return The string.
*/
public String toString() {
return this.name;
}
/**
* Returns <code>true</code> if this object is equal to the specified
* object, and <code>false</code> otherwise.
*
* @param obj the other object.
*
* @return A boolean.
*/
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof XYCoordinateType)) {
return false;
}
XYCoordinateType order = (XYCoordinateType) obj;
if (!this.name.equals(order.toString())) {
return false;
}
return true;
}
/**
* Ensures that serialization returns the unique instances.
*
* @return The object.
*
* @throws ObjectStreamException if there is a problem.
*/
private Object readResolve() throws ObjectStreamException {
if (this.equals(XYCoordinateType.DATA)) {
return XYCoordinateType.DATA;
}
else if (this.equals(XYCoordinateType.RELATIVE)) {
return XYCoordinateType.RELATIVE;
}
else if (this.equals(XYCoordinateType.INDEX)) {
return XYCoordinateType.INDEX;
}
return null;
}
} |
package imagej.menu;
import imagej.command.Command;
import imagej.module.Module;
import imagej.module.ModuleInfo;
import imagej.service.ImageJService;
/**
* Interface for service that tracks the application's menu structure.
*
* @author Curtis Rueden
*/
public interface MenuService extends ImageJService {
/** Gets the root node of the application menu structure. */
ShadowMenu getMenu();
/**
* Gets the root node of a menu structure.
*
* @param menuRoot the root of the desired menu structure (see
* {@link ModuleInfo#getMenuRoot()}).
*/
ShadowMenu getMenu(String menuRoot);
/**
* Populates a UI-specific application menu structure.
*
* @param creator the {@link MenuCreator} to use to populate the menus.
* @param menu the destination menu structure to populate.
*/
<T> T createMenus(MenuCreator<T> creator, T menu);
/**
* Populates a UI-specific menu structure.
*
* @param menuRoot the root of the menu structure to generate (see
* {@link ModuleInfo#getMenuRoot()}).
* @param creator the {@link MenuCreator} to use to populate the menus.
* @param menu the destination menu structure to populate.
*/
<T> T createMenus(String menuRoot, MenuCreator<T> creator, T menu);
/** Selects or deselects the given module in the menu structure. */
void setSelected(Module module, boolean selected);
/** Selects or deselects the given plugin in the menu structure. */
void setSelected(Command command, boolean selected);
/**
* Selects or deselects the plugin of the given class in the menu structure.
*/
<C extends Command> void
setSelected(Class<C> commandClass, boolean selected);
/**
* Selects or deselects the plugin of the given class in the menu structure.
*/
<C extends Command> void
setSelected(String pluginClassName, boolean selected);
/** Selects or deselects the given module in the menu structure. */
void setSelected(ModuleInfo info, boolean selected);
} |
package apps.kiosk.games;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.util.Iterator;
import java.util.Set;
import apps.kiosk.GridGameCanvas;
public class CheckersCanvas extends GridGameCanvas {
private static final long serialVersionUID = 1L;
public String getGameName() { return "Checkers"; }
protected String getGameKIF() { return "checkers"; }
protected int getGridHeight() { return 8; }
protected int getGridWidth() { return 8; }
private int selectedRow = -1;
private int selectedColumn = -1;
private String currentSelectedMove;
private Iterator<String> possibleSelectedMoves = null;
protected void handleClickOnCell(int xCell, int yCell, int xWithin, int yWithin) {
String xLetter = "" + ((char) ('a' + xCell));
xCell++;
yCell++;
if(selectedRow != yCell || selectedColumn != xCell || !possibleSelectedMoves.hasNext()) {
Set<String> theMoves = gameStateHasLegalMovesMatching("\\( move .. " + xLetter + " " + yCell + " (.*) \\)");
theMoves.addAll(gameStateHasLegalMovesMatching("\\( doublejump .. " + xLetter + " " + yCell + " (.*) \\)"));
theMoves.addAll(gameStateHasLegalMovesMatching("\\( triplejump .. " + xLetter + " " + yCell + " (.*) \\)"));
if(theMoves.size() == 0)
return;
possibleSelectedMoves = theMoves.iterator();
}
selectedRow = yCell;
selectedColumn = xCell;
currentSelectedMove = possibleSelectedMoves.next();
submitWorkingMove(stringToMove(currentSelectedMove));
}
private final Image theCrownImage = getImage("crown.png");
protected void renderCell(int xCell, int yCell, Graphics g) {
String xLetter = "" + ((char) ('a' + xCell));
xCell++;
yCell++;
int width = g.getClipBounds().width;
int height = g.getClipBounds().height;
// Alternating colors for the board
if( (xCell + yCell) % 2 == 0) {
g.setColor(Color.GRAY);
g.fillRect(0, 0, width, height);
return;
}
g.setColor(Color.BLACK);
g.drawRect(1, 1, width-2, height-2);
Set<String> theFacts = gameStateHasFactsMatching("\\( cell " + xLetter + " " + yCell + " (.*) \\)");
if(theFacts.size() > 0) {
if(theFacts.size() > 1) {
System.err.println("More than one fact for a cell? Something is weird!");
}
String[] cellFacts = theFacts.iterator().next().split(" ");
String cellType = cellFacts[4];
if(!cellType.equals("b")) {
Color theColor = ((cellType.charAt(0) == 'b') ? Color.BLACK : Color.RED);
boolean isKing = (cellType.charAt(1) == 'k');
g.setColor(Color.DARK_GRAY);
g.fillOval(4, 4, width-8, height-8);
g.setColor(theColor);
g.fillOval(6, 6, width-12, height-12);
if(isKing) {
g.setColor(Color.YELLOW);
g.drawImage(theCrownImage, width/5, 2*height/7, 3*width/5, 3*height/7, null);
}
}
}
if(selectedColumn == xCell && selectedRow == yCell) {
g.setColor(Color.GREEN);
g.drawRect(3, 3, width-6, height-6);
}
// Render move-specific graphics
if(!currentSelectedMove.isEmpty()) {
String[] moveParts = currentSelectedMove.split(" ");
String xTarget = moveParts[5];
int yTarget = Integer.parseInt(moveParts[6]);
if(xLetter.equals(xTarget) && yCell == yTarget) {
g.setColor(Color.BLUE);
g.drawRect(3, 3, width-6, height-6);
fillWithString(g, "X", 3);
}
if(moveParts.length > 8) {
xTarget = moveParts[7];
yTarget = Integer.parseInt(moveParts[8]);
if(xLetter.equals(xTarget) && yCell == yTarget) {
g.setColor(Color.BLUE);
g.drawRect(3, 3, width-6, height-6);
fillWithString(g, "Y", 3);
}
}
if(moveParts.length > 10) {
xTarget = moveParts[9];
yTarget = Integer.parseInt(moveParts[10]);
if(xLetter.equals(xTarget) && yCell == yTarget) {
g.setColor(Color.BLUE);
g.drawRect(3, 3, width-6, height-6);
fillWithString(g, "Z", 3);
}
}
}
}
public void clearMoveSelection() {
submitWorkingMove(null);
possibleSelectedMoves = null;
currentSelectedMove = "";
selectedColumn = -1;
selectedRow = -1;
repaint();
}
} |
package scal.io.liger.view;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Rect;
import android.graphics.SurfaceTexture;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.IconTextView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import com.edmodo.rangebar.RangeBar;
import com.joanzapata.android.iconify.IconDrawable;
import com.joanzapata.android.iconify.Iconify;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicInteger;
import scal.io.liger.Constants;
import scal.io.liger.MainActivity;
import scal.io.liger.MediaHelper;
import scal.io.liger.R;
import scal.io.liger.av.AudioRecorder;
import scal.io.liger.av.ClipCardsPlayer;
import scal.io.liger.model.Card;
import scal.io.liger.model.ClipCard;
import scal.io.liger.model.ClipMetadata;
import scal.io.liger.model.ExampleMediaFile;
import scal.io.liger.model.MediaFile;
public class ClipCardView extends ExampleCardView {
public static final String TAG = "ClipCardView";
public ClipCard mCardModel;
private AudioRecorder mRecorder;
private List<View> mDisplayedClipViews = new ArrayList<>(); // Views representing clips currently displayed
private int mCardFooterHeight; // The mClipsExpanded height of the card footer (e.g: Capture import buttons)
private boolean mClipsExpanded = false; // Is the clip stack expanded
private boolean mHasClips;
private final float PRIMARY_CLIP_ALPHA = 1.0f;
private final float SECONDARY_CLIP_ALPHA = .7f;
private ViewGroup mCollapsableContainer;
private ViewGroup mClipCandidatesContainer;
private TextView tvHeader;
private TextView tvBody;
private TextView tvImport;
private TextView tvCapture;
private TextView tvStop;
private ImageView ivOverflow;
private IconTextView itvClipTypeIcon;
/** Capture Media Button Click Listener */
View.OnClickListener mCaptureClickListener = new View.OnClickListener() {
@Override
public void onClick(final View v) {
Intent intent = null;
int requestId = -1;
String medium = mCardModel.getMedium();
String cardMediaId = mCardModel.getStoryPath().getId() + "::" + mCardModel.getId() + "::" + MEDIA_PATH_KEY;
if (medium.equals(Constants.VIDEO)) {
intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
requestId = Constants.REQUEST_VIDEO_CAPTURE;
} else if (medium.equals(Constants.PHOTO)) {
intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
Log.e(TAG, "Unable to make image file");
v.post(new Runnable() {
@Override
public void run() {
Toast.makeText(v.getContext(), "Unable to make image file", Toast.LENGTH_LONG).show();
}
});
return;
}
mContext.getSharedPreferences("prefs", Context.MODE_PRIVATE).edit().putString(Constants.EXTRA_FILE_LOCATION, photoFile.getAbsolutePath()).apply();
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
requestId = Constants.REQUEST_IMAGE_CAPTURE;
}
if (medium.equals(Constants.AUDIO)) {
startRecordingAudio();
} else if (null != intent && intent.resolveActivity(mContext.getPackageManager()) != null) {
mContext.getSharedPreferences("prefs", Context.MODE_PRIVATE).edit().putString(Constants.PREFS_CALLING_CARD_ID, cardMediaId).apply(); // Apply is async and fine for UI thread. commit() is synchronous
((Activity) mContext).startActivityForResult(intent, requestId);
}
}
};
/**
* Clip Stack Card Click Listener
* Handles click on primary clip (show playback / edit dialog) as well as
* secondary clips and footer (expand clip stack or collapse after new primary clip selection)
*/
View.OnClickListener mClipCardClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!mHasClips) {
// This ClipCard is displaying a single item stack with either example or
// fallback drawables. A click should expand the card footer to reveal the Capture / Import feature
toggleFooterVisibility(mCollapsableContainer, tvBody);
return;
}
ViewGroup clipContainer = (ViewGroup) v.getParent();
if (clipContainer.getTag(R.id.view_tag_clip_primary) != null &&
(boolean) clipContainer.getTag(R.id.view_tag_clip_primary)) {
// Clicked clip is primary
Log.i(TAG + "-select", "primary");
if (mClipsExpanded) {
// Collapse clip view, without change
toggleClipExpansion(mCardModel.getClips(), mClipCandidatesContainer);
toggleFooterVisibility(mCollapsableContainer, tvBody);
} else if (mCardModel.getMedium().equals(Constants.VIDEO) ||
mCardModel.getMedium().equals(Constants.AUDIO)) { //TODO : Support audio trimming
//show trim dialog
showClipPlaybackAndTrimming();
}
} else {
// Clicked clip is not primary clip
if (mClipsExpanded && clipContainer.getTag(R.id.view_tag_clip_primary) != null) {
// Clicked view is secondary clip and clips are expanded
// This indicates a new secondary clip was selected
Log.i(TAG + "-select", "new primary clip selected");
// If clips expanded, this event means we've been selected as the
// new primary clip!
setNewSelectedClip(clipContainer);
}
toggleClipExpansion(mCardModel.getClips(), mClipCandidatesContainer);
toggleFooterVisibility(mCollapsableContainer, tvBody);
}
}
};
/**
* Clip Stack Clip delete listener
* Handles user removing a clip from the Clip stack.
*/
View.OnClickListener mDeleteClipClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
ViewGroup clipContainerView = (ViewGroup) v.getParent();
ClipMetadata clipMetadata = (ClipMetadata) clipContainerView.getTag(R.id.view_tag_clip_metadata);
mCardModel.removeClip(clipMetadata);
if (mCardModel.getClips().size() > 0) {
mDisplayedClipViews = inflateClipStack(mCardModel,
mClipCandidatesContainer,
mCardModel.getClips(),
mClipCardClickListener);
} else {
mHasClips = false;
mDisplayedClipViews = inflateEmptyClipStack(mClipCandidatesContainer,
mClipCardClickListener);
}
mCardModel.getStoryPath().getStoryPathLibrary().save(true);
}
};
public ClipCardView(Context context, Card cardModel) {
super();
mContext = context;
mCardModel = (ClipCard) cardModel;
Resources r = context.getResources();
mCardFooterHeight = r.getDimensionPixelSize(R.dimen.clip_body_height) +
r.getDimensionPixelSize(R.dimen.clip_btn_height) * 2;
}
@SuppressLint("NewApi")
@Override
public View getCardView(final Context context) {
if (mCardModel == null) {
return null;
}
Log.i(TAG, "getCardView");
View view = LayoutInflater.from(context).inflate(R.layout.card_clip, null);
mCollapsableContainer = (ViewGroup) view.findViewById(R.id.collapsable);
mClipCandidatesContainer = (ViewGroup) view.findViewById(R.id.clipCandidates);
// Views only modified during initial binding
itvClipTypeIcon = (IconTextView) view.findViewById(R.id.itvClipTypeIcon);
tvHeader = (TextView) view.findViewById(R.id.tvHeader);
tvBody = (TextView) view.findViewById(R.id.tvBody);
tvImport = (TextView) view.findViewById(R.id.tvImport);
tvCapture = (TextView) view.findViewById(R.id.tvCapture);
tvStop = (TextView) view.findViewById(R.id.tvStop);
ivOverflow = (ImageView) view.findViewById(R.id.ivOverflowButton);
// mVUMeterLayout = (LinearLayout) view.findViewById(R.id.vumeter_layout);
/** Stop Button Click Listener */
View.OnClickListener stopClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
stopRecordingAudio();
}
};
// Set click listeners for actions
tvCapture.setOnClickListener(mCaptureClickListener);
tvStop.setOnClickListener(stopClickListener);
tvImport.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// ACTION_OPEN_DOCUMENT is the new API 19 action for the Android file manager
Intent intent;
int requestId = Constants.REQUEST_FILE_IMPORT;
if (Build.VERSION.SDK_INT >= 19) {
intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
} else {
intent = new Intent(Intent.ACTION_GET_CONTENT);
}
// Filter to only show results that can be "opened", such as a
// file (as opposed to a list of contacts or timezones)
intent.addCategory(Intent.CATEGORY_OPENABLE);
// TODO : Adjust based on medium?
intent.setType("*/*");
String cardMediaId = mCardModel.getStoryPath().getId() + "::" + mCardModel.getId() + "::" + MEDIA_PATH_KEY;
mContext.getSharedPreferences("prefs", Context.MODE_PRIVATE).edit().putString(Constants.PREFS_CALLING_CARD_ID, cardMediaId).apply(); // Apply is async and fine for UI thread. commit() is synchronous
((Activity) mContext).startActivityForResult(intent, requestId);
}
});
final int drawableSizeDp = 30;
Resources r = mContext.getResources();
int drawableSizePx = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, drawableSizeDp, r.getDisplayMetrics());
//set drawables for actions
Drawable drwImport = new IconDrawable(mContext, Iconify.IconValue.fa_ic_card_import).colorRes(R.color.storymaker_highlight);
drwImport.setBounds(0, 0, drawableSizePx, drawableSizePx);
Drawable drwCapture = new IconDrawable(mContext, Iconify.IconValue.fa_ic_card_capture_photo).colorRes(R.color.storymaker_highlight);
drwCapture.setBounds(0, 0, drawableSizePx, drawableSizePx);
IconDrawable iconDrawable = new IconDrawable(mContext, Iconify.IconValue.fa_ic_more_vert_48px).colorRes(R.color.storymaker_highlight);
iconDrawable.setBounds(0, 0, drawableSizePx, drawableSizePx);
ivOverflow.setImageDrawable(iconDrawable);
if (Build.VERSION.SDK_INT >= 17 &&
mContext.getResources().getConfiguration().getLayoutDirection() == View.LAYOUT_DIRECTION_RTL) {
tvCapture.setCompoundDrawables(null, null, drwCapture, null);
tvImport.setCompoundDrawables(null, null, drwImport, null);
} else {
tvCapture.setCompoundDrawables(drwCapture, null, null, null);
tvImport.setCompoundDrawables(drwImport, null, null, null);
}
//a-ic_card_capture_photo
setupOverflowMenu(ivOverflow);
// TODO: If the recycled view previously belonged to a different
// card type, tear down and rebuild the view as in onCreateViewHolder.
mHasClips = (mCardModel.getClips() != null && mCardModel.getClips().size() > 0);
/** Populate clip stack */
if (mHasClips) {
// Begin in the collapsed state
ViewGroup.LayoutParams params = mCollapsableContainer.getLayoutParams();
params.height = 0;
mCollapsableContainer.setLayoutParams(params);
mDisplayedClipViews = inflateClipStack(mCardModel,
mClipCandidatesContainer,
mCardModel.getClips(),
mClipCardClickListener);
} else {
// Begin in the expanded state
mDisplayedClipViews = inflateEmptyClipStack(mClipCandidatesContainer,
mClipCardClickListener);
}
tvHeader.setText(mCardModel.getClipTypeLocalized().toUpperCase());
tvHeader.setTextColor(getClipTypeColor(mCardModel.getClipType()));
// Expand / Collapse footer on click
tvHeader.setOnClickListener(mClipCardClickListener);
if (mCardModel.getFirstGoal() != null) {
tvBody.setText(mCardModel.getFirstGoal());
}
// supports automated testing
view.setTag(mCardModel.getId());
return view;
}
private List<View> inflateEmptyClipStack(@NonNull ViewGroup clipCandidatesContainer,
@NonNull View.OnClickListener clipThumbClickListener) {
clipCandidatesContainer.removeAllViews();
View clipThumbContainer = inflateAndAddThumbnailForClip(clipCandidatesContainer, null, 0, 0);
ImageView clipThumb = (ImageView) clipThumbContainer.findViewById(R.id.thumb);
clipThumb.setOnClickListener(clipThumbClickListener);
clipThumbContainer.setTag(R.id.view_tag_clip_primary, true);
clipThumbContainer.setTag(R.id.view_tag_clip_metadata, null);
ArrayList<View> displayedClipViews = new ArrayList<>(1);
displayedClipViews.add(clipThumbContainer);
return displayedClipViews;
}
private List<View> inflateClipStack(@NonNull ClipCard cardModel,
@NonNull ViewGroup clipCandidatesContainer,
@NonNull List<ClipMetadata> clipsToDisplay,
@NonNull View.OnClickListener clipThumbClickListener) {
clipCandidatesContainer.removeAllViews();
ArrayList<View> displayedClipViews = new ArrayList<>(clipsToDisplay.size());
Log.i(TAG + "-clip", String.format("adding %d clips for cardclip ", clipsToDisplay.size()));
// Thumbnails are added to the clip stack from back to front. This greatly simplifies producing the desired z-order
Collections.reverse(clipsToDisplay);
for (int x = 0; x < clipsToDisplay.size(); x++) {
// Create view for new clip
MediaFile mediaFile = cardModel.loadMediaFile(clipsToDisplay.get(x));
ViewGroup clipThumbContainer = inflateAndAddThumbnailForClip(clipCandidatesContainer, mediaFile, x, clipsToDisplay.size() - 1);
ImageView clipThumb = (ImageView) clipThumbContainer.findViewById(R.id.thumb);
clipThumb.setOnClickListener(clipThumbClickListener);
if (x != clipsToDisplay.size() - 1) {
// Clicking on any but the top clip triggers expansion
clipThumbContainer.setTag(R.id.view_tag_clip_primary, false);
} else {
clipThumbContainer.setTag(R.id.view_tag_clip_primary, true);
}
clipThumbContainer.setTag(R.id.view_tag_clip_metadata, clipsToDisplay.get(x));
displayedClipViews.add(clipThumbContainer);
}
// Restore order of clipsToDisplay, since it's a reference to the StoryPath model
Collections.reverse(clipsToDisplay);
return displayedClipViews;
}
/**
* Inflate and add to clipsContainer an ImageView populated with a thumbnail appropriate for the given mediaFile.
* Note: zOrder 0 is the bottom of the clip list.
* @return the view inflated and added to clipsContainer
*/
private ViewGroup inflateAndAddThumbnailForClip(@NonNull ViewGroup clipsContainer,
@Nullable MediaFile mediaFile,
int zOrder,
int zTop) {
LayoutInflater inflater = (LayoutInflater) clipsContainer.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
FrameLayout clipContainer = (FrameLayout) inflater.inflate(R.layout.clip_thumbnail,
clipsContainer,
false);
ImageButton deleteBtn = (ImageButton) clipContainer.findViewById(R.id.btn_delete);
ImageView thumbnail = (ImageView) clipContainer.findViewById(R.id.thumb);
int topMarginPerZ = clipsContainer.getContext()
.getResources()
.getDimensionPixelSize(R.dimen.clip_stack_margin_top);
FrameLayout.MarginLayoutParams params = (FrameLayout.MarginLayoutParams) clipContainer.getLayoutParams();
params.topMargin = topMarginPerZ * (zTop - zOrder);
clipContainer.setLayoutParams(params);
setThumbnailForClip(thumbnail, mediaFile);
thumbnail.setAlpha(zOrder == zTop ? PRIMARY_CLIP_ALPHA : SECONDARY_CLIP_ALPHA);
if (mediaFile != null) {
deleteBtn.setOnClickListener(mDeleteClipClickListener);
deleteBtn.setVisibility(View.VISIBLE);
}
clipsContainer.addView(clipContainer);
return clipContainer;
}
private int getClipTypeColor(String clipType) {
if (clipType.equalsIgnoreCase(Constants.CHARACTER)) {
return mContext.getResources().getColor(R.color.storymaker_blue);
} else if (clipType.equalsIgnoreCase(Constants.ACTION)) {
return mContext.getResources().getColor(R.color.storymaker_orange);
} else if (clipType.equalsIgnoreCase(Constants.RESULT)) {
return mContext.getResources().getColor(R.color.storymaker_lime);
} else if (clipType.equalsIgnoreCase(Constants.SIGNATURE)) {
return mContext.getResources().getColor(R.color.storymaker_magenta);
} else if (clipType.equalsIgnoreCase(Constants.PLACE)) {
return mContext.getResources().getColor(R.color.storymaker_slate);
}
return mContext.getResources().getColor(R.color.storymaker_highlight);
}
private void setClipExampleDrawables(String clipType, ImageView imageView) {
Drawable drawable;
if (clipType.equalsIgnoreCase(Constants.CHARACTER)) {
drawable = new IconDrawable(mContext, Iconify.IconValue.fa_clip_ex_character);
itvClipTypeIcon.setText("{fa-ic_clip_character}");
} else if (clipType.equalsIgnoreCase(Constants.ACTION)) {
drawable = new IconDrawable(mContext, Iconify.IconValue.fa_clip_ex_action);
itvClipTypeIcon.setText("{fa-ic_clip_action}");
} else if (clipType.equalsIgnoreCase(Constants.RESULT)){
drawable = new IconDrawable(mContext, Iconify.IconValue.fa_clip_ex_result);
itvClipTypeIcon.setText("{fa-ic_clip_result}");
} else if (clipType.equalsIgnoreCase(Constants.SIGNATURE)){
drawable = new IconDrawable(mContext, Iconify.IconValue.fa_clip_ex_signature);
itvClipTypeIcon.setText("{fa-ic_clip_signature}");
} else if (clipType.equalsIgnoreCase(Constants.PLACE)){
drawable = new IconDrawable(mContext, Iconify.IconValue.fa_clip_ex_place);
itvClipTypeIcon.setText("{fa-ic_clip_place}");
} else {
//TODO handle invalid clip type
Log.d(TAG, "No clipType matching '" + clipType + "' found.");
drawable = mContext.getResources().getDrawable(R.drawable.ic_launcher); // FIXME replace with a sensible placeholder image
itvClipTypeIcon.setText("{fa-card_capture_photo}");
}
imageView.setImageDrawable(drawable);
itvClipTypeIcon.setTextColor(getClipTypeColor(clipType));
}
private void setThumbnailForClip(@NonNull ImageView ivThumbnail, MediaFile media) {
final MediaFile mediaFile;
if (media != null) {
mediaFile = media;
} else {
mediaFile = mCardModel.getExampleMediaFile();
}
if ((mediaFile == null) ||
((mediaFile instanceof ExampleMediaFile) &&
((ExampleMediaFile)mediaFile).getExampleThumbnail(mCardModel) == null)) {
Log.e(this.getClass().getName(), "no media file was found");
// Clip has no attached media. Show generic drawable based on clip type
String clipType = mCardModel.getClipType();
setClipExampleDrawables(clipType, ivThumbnail);
ivThumbnail.setVisibility(View.VISIBLE);
} else {
mediaFile.loadThumbnail(ivThumbnail, new MediaHelper.ThumbnailCallback() {
@Override
public void newThumbnailGenerated(File thumbnail) {
Log.d(TAG, "Notifying StoryPath of newly generated thumbnail");
// need to update media file in model now that thumbnail is set
// being overly cautious to avoid null pointers
if ((mCardModel.getStoryPath() != null) &&
(mCardModel.getStoryPath().getStoryPathLibrary() != null)) {
HashMap<String, MediaFile> mediaFiles = mCardModel.getStoryPath()
.getStoryPathLibrary()
.getMediaFiles();
MediaFile targetMediaFile = null;
for (String key : mediaFiles.keySet()) {
MediaFile candidateMediaFile = mediaFiles.get(key);
if (candidateMediaFile.getPath().equals(mediaFile.getPath())) {
targetMediaFile = candidateMediaFile;
}
}
if (targetMediaFile != null) {
mCardModel.getStoryPath().getStoryPathLibrary().saveMediaFile(mediaFile.getPath(), mediaFile);
// set metadata too
if (mCardModel.getStoryPath().getStoryPathLibrary().getMetaThumbnail() == null) {
mCardModel.getStoryPath().getStoryPathLibrary().setMetaThumbnail(thumbnail.getPath());
}
// force save to store mediafile/metadata updates
// shouldn't need to save story path at this point
mCardModel.getStoryPath().getStoryPathLibrary().save(false);
} else {
Log.w(TAG, "Could not find MediaFile corresponding to new thumbnail");
}
}
}
});
ivThumbnail.setVisibility(View.VISIBLE);
}
}
private void showClipPlaybackAndTrimming() {
View v = ((LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE))
.inflate(R.layout.dialog_clip_playback_trim, null);
/** Trim dialog views */
final TextureView videoView = (TextureView) v.findViewById(R.id.textureView);
final ImageView thumbnailView = (ImageView) v.findViewById(R.id.thumbnail);
final TextView clipLength = (TextView) v.findViewById(R.id.clipLength);
final TextView clipStart = (TextView) v.findViewById(R.id.clipStart);
final TextView clipEnd = (TextView) v.findViewById(R.id.clipEnd);
final RangeBar rangeBar = (RangeBar) v.findViewById(R.id.rangeSeekbar);
final SeekBar playbackBar = (SeekBar) v.findViewById(R.id.playbackProgress);
final SeekBar volumeSeek = (SeekBar) v.findViewById(R.id.volumeSeekbar);
final int tickCount = mContext.getResources().getInteger(R.integer.trim_bar_tick_count);
/** Media player and media */
final MediaPlayer player = new MediaPlayer();
final ClipMetadata selectedClip = mCardModel.getSelectedClip();
final AtomicInteger clipDurationMs = new AtomicInteger();
final AtomicInteger clipStartMs = new AtomicInteger(selectedClip.getStartTime());
final AtomicInteger clipStopMs = new AtomicInteger(selectedClip.getStopTime());
/** Setup initial values that don't require media loaded */
clipStart.setText(Util.makeTimeString(selectedClip.getStartTime()));
clipEnd.setText(Util.makeTimeString(selectedClip.getStopTime()));
volumeSeek.setProgress((int) (mCardModel.getSelectedClip().getVolume() * volumeSeek.getMax()));
Log.i(TAG, String.format("Showing clip trim dialog with intial start: %d stop: %d", selectedClip.getStartTime(), selectedClip.getStopTime()));
volumeSeek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
float newVolume = progress / (float) seekBar.getMax();
mCardModel.getSelectedClip().setVolume(newVolume);
player.setVolume(newVolume, newVolume);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) { /* ignored */}
@Override
public void onStopTrackingTouch(SeekBar seekBar) { /* ignored */}
});
rangeBar.setOnRangeBarChangeListener(new RangeBar.OnRangeBarChangeListener() {
int lastLeftIdx;
int lastRightIdx;
@Override
public void onIndexChangeListener(RangeBar rangeBar, int leftIdx, int rightIdx) {
//Log.i(TAG, String.format("Seek to leftIdx %d rightIdx %d. left: %d. right: %d", leftIdx, rightIdx, rangeBar.getLeft(), rangeBar.getRight()));
if (lastLeftIdx != leftIdx) {
// Left seek was adjusted, seek to it
clipStartMs.set(getMsFromRangeBarIndex(leftIdx, tickCount, clipDurationMs.get()));
player.seekTo(clipStartMs.get());
clipStart.setText(Util.makeTimeString(clipStartMs.get()));
//Log.i(TAG, String.format("Left seek to %d ms", clipStartMs.get()));
if (playbackBar.getProgress() < leftIdx) playbackBar.setProgress(leftIdx);
} else if (lastRightIdx != rightIdx) {
// Right seek was adjusted, seek to it
clipStopMs.set(getMsFromRangeBarIndex(rightIdx, tickCount, clipDurationMs.get()));
player.seekTo(clipStopMs.get());
clipEnd.setText(Util.makeTimeString(clipStopMs.get()));
if (playbackBar.getProgress() > rightIdx) playbackBar.setProgress(rightIdx);
//Log.i(TAG, String.format("Right seek to %d ms", clipStopMs.get()));
}
lastLeftIdx = leftIdx;
lastRightIdx = rightIdx;
}
});
View.OnClickListener playbackToggleClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
thumbnailView.setVisibility(View.GONE);
if (player.isPlaying()) {
player.pause();
} else {
ClipCardsPlayer.adjustAspectRatio(videoView, player.getVideoWidth(), player.getVideoHeight());
player.seekTo(clipStartMs.get());
player.start();
}
}
};
videoView.setOnClickListener(playbackToggleClickListener);
thumbnailView.setOnClickListener(playbackToggleClickListener);
videoView.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {
@Override
public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
setThumbnailForClip(thumbnailView, mCardModel.getSelectedMediaFile());
Uri video = Uri.parse(mCardModel.getSelectedMediaFile().getPath());
Surface s = new Surface(surface);
try {
player.setDataSource(mContext, video);
player.setSurface(s);
player.prepare();
player.setVideoScalingMode(MediaPlayer.VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING);
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
player.seekTo(clipStartMs.get());
}
});
clipDurationMs.set(player.getDuration());
if (clipStopMs.get() == 0) clipStopMs.set(clipDurationMs.get()); // If no stop point set, play whole clip
// Setup initial views requiring knowledge of clip media
if (selectedClip.getStopTime() == 0) selectedClip.setStopTime(clipDurationMs.get());
player.seekTo(selectedClip.getStartTime());
rangeBar.setThumbIndices(getRangeBarIndexForMs(selectedClip.getStartTime(), tickCount, clipDurationMs.get()),
getRangeBarIndexForMs(selectedClip.getStopTime(), tickCount, clipDurationMs.get()));
clipLength.setText(mContext.getString(R.string.total) + " : " + Util.makeTimeString(clipDurationMs.get()));
clipEnd.setText(Util.makeTimeString(selectedClip.getStopTime()));
} catch (IllegalArgumentException | IllegalStateException | SecurityException | IOException e) {
e.printStackTrace();
}
}
@Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
}
@Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
return false;
}
@Override
public void onSurfaceTextureUpdated(SurfaceTexture surface) {
}
});
// Poll MediaPlayer for position, ensuring it never exceeds clipStopMs
final Timer timer = new Timer("mplayer");
timer.schedule(new TimerTask() {
@Override
public void run() {
try {
if (player.isPlaying()) {
if (player.getCurrentPosition() > clipStopMs.get()) {
player.pause();
Log.i(TAG, "stopping playback at clip end selection");
}
playbackBar.setProgress((int) (tickCount * ((float) player.getCurrentPosition()) / player.getDuration()));
}
} catch (IllegalStateException e) { /* MediaPlayer in invalid state. Ignore */}
}
}, 100, 100);
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setView(v)
.setPositiveButton(mContext.getString(R.string.trim_clip).toUpperCase(), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mCardModel.getSelectedClip().setStartTime(clipStartMs.get());
mCardModel.getSelectedClip().setStopTime(clipStopMs.get());
// need to save here
Log.d(TAG, "SAVING START/STOP TIME");
mCardModel.getStoryPath().getStoryPathLibrary().save(true);
}
})
.setNegativeButton(mContext.getString(R.string.cancel).toUpperCase(), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
Dialog dialog = builder.create();
dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
Log.d(TAG, "dialog dismissed");
if (player.isPlaying()) player.stop();
player.release();
timer.cancel();
}
});
dialog.show();
}
private int getMsFromRangeBarIndex(int tick, int max, int clipDurationMs) {
int seekMs = (int) (clipDurationMs * Math.min(1, ((float) tick / max)));
//Log.i(TAG, String.format("Seek to index %d equals %d ms. Duration: %d ms", idx, seekMs, clipDurationMs.get()));
return seekMs;
}
private int getRangeBarIndexForMs(int positionMs, int max, int clipDurationMs) {
int idx = (int) Math.min(((positionMs * max) / (float) clipDurationMs), max - 1); // Range bar goes from 0 to (max - 1)
Log.i(TAG, String.format("Converted %d ms to rangebar position %d", positionMs, idx));
return idx;
}
private final int STAGGERED_ANIMATION_GAP_MS = 70;
private void toggleClipExpansion(List<ClipMetadata> clipsToDisplay, ViewGroup clipCandidatesContainer) {
// When this method is called all clips in holder.displayedClips should be
// added to holder.clipCandidatesContainer in order (e.g: First item is highest z order)
final int clipCandidateCount = clipsToDisplay.size();
if (clipsToDisplay.size() < 2) {
// If less than 2 clips, there's no reason to expand / collapse
return;
}
// Dp to px
Resources r = clipCandidatesContainer.getContext().getResources();
int topMargin = r.getDimensionPixelSize(R.dimen.clip_stack_margin_top); // Margin between clip thumbs
int clipHeight = r.getDimensionPixelSize(R.dimen.clip_thumb_height); // Height of each clip thumb
int howtoHeight = r.getDimensionPixelSize(R.dimen.card_tap_height); // Height of howto card that appears at stack top
final View howtoCard = ((View) clipCandidatesContainer.getParent()).findViewById(R.id.tvTapToContinue);
float finalHowToOpacity = mClipsExpanded ? 0f : 1f;
ObjectAnimator howtoAnim = ObjectAnimator.ofFloat(howtoCard, "alpha", 1 - finalHowToOpacity, finalHowToOpacity);
howtoAnim.setStartDelay((long) (STAGGERED_ANIMATION_GAP_MS * (clipCandidateCount + 1) * finalHowToOpacity));
howtoAnim.start();
// Loop over all clip views except the last
for (int i = 0; i < clipCandidateCount; i ++) {
int viewIdx = i;
if (mClipsExpanded) {
// when mClipsExpanded : 0, 1
// when compressing : 1, 0
viewIdx = (clipCandidateCount - 1) - i;
}
final View child = mDisplayedClipViews.get(viewIdx);
final ViewGroup.LayoutParams params = child.getLayoutParams();
int marginPerChild = topMargin + clipHeight;
ValueAnimator animator;
//int startAnimationMargin;
int stopAnimationMargin;
int marginMultiplier = (clipCandidateCount - 1) - viewIdx;
if (mClipsExpanded) {
// compress
stopAnimationMargin = (topMargin * marginMultiplier); // howtoCard is leaving
// Remove pressable background drawables
child.setBackgroundResource(R.drawable.clip_card_unselected);
} else {
// expand
stopAnimationMargin = (marginMultiplier * marginPerChild) + (howtoHeight + topMargin);
// Add pressable background drawable
child.setBackgroundResource(R.drawable.clip_card_selectable_bg);
}
Log.i(TAG + "-anim", String.format("Animating margin from %d to %d", ((ViewGroup.MarginLayoutParams) params).topMargin, stopAnimationMargin));
animator = ValueAnimator.ofInt(((ViewGroup.MarginLayoutParams) params).topMargin, stopAnimationMargin);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
((ViewGroup.MarginLayoutParams) params).topMargin = (int) valueAnimator.getAnimatedValue();
child.setLayoutParams(params);
}
});
animator.setStartDelay((1+ i) * STAGGERED_ANIMATION_GAP_MS);
animator.start();
//Log.i("anim", "View idx " + viewIdx + " animating with delay " + (1+ i) * 400 + " to margin " + stopAnimationMargin);
}
mClipsExpanded = !mClipsExpanded;
}
private void toggleFooterVisibility(final ViewGroup collapsable, TextView body) {
final ViewGroup.LayoutParams params = collapsable.getLayoutParams();
String targetText = body.getText().toString();
Rect textRect = new Rect();
body.getPaint().getTextBounds(targetText, 0, targetText.length(), textRect);
ValueAnimator animator = null;
if (collapsable.getHeight() < mCardFooterHeight) {
// Expand
animator = ValueAnimator.ofInt(0, mCardFooterHeight);
} else {
// Collapse
animator = ValueAnimator.ofInt(mCardFooterHeight, 0);
}
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
params.height = (Integer) valueAnimator.getAnimatedValue();
collapsable.setLayoutParams(params);
}
});
animator.start();
}
//returns stored mediaPath (if exists) or exampleMediaPath (if exists)
/*
@Override
public File getValidFile(String mediaPath, String exampleMediaPath) {
File mediaFile = null;
if (mediaPath != null) {
mediaFile = MediaHelper.loadFileFromPath(mCardModel.getStoryPath().buildZipPath(mediaPath));
} else if (exampleMediaPath != null) {
mediaFile = MediaHelper.loadFileFromPath(mCardModel.getStoryPath().buildZipPath(exampleMediaPath));
}
return mediaFile;
}
*/
private void setupOverflowMenu(ImageView imageView) {
final PopupMenu popupMenu = new PopupMenu(mContext, imageView);
popupMenu.inflate(R.menu.popup_clip_card);
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
int itemId = item.getItemId(); // Can't treat Ids as constants in library modules
if (itemId == R.id.menu_edit_card) {
if (mCardModel.getSelectedClip() != null) {
showClipPlaybackAndTrimming();
} else {
Toast.makeText(mContext, mContext.getString(R.string.add_clips_generic), Toast.LENGTH_SHORT).show();
}
} else if (itemId == R.id.menu_change_goal) {
} else if (itemId == R.id.menu_duplicate_card) {
try {
int thisCardIndex = mCardModel.getStoryPath().getCardIndex(mCardModel);
if (thisCardIndex == -1) {
Log.w(TAG, "Could not find index of this card in StoryPath or StoryPathLibrary. Cannot duplicate");
return true;
}
Card newCard = (Card) mCardModel.clone();
mCardModel.getStoryPath().addCardAtPosition(newCard, thisCardIndex);
mCardModel.getStoryPath().notifyCardChanged(newCard);
// TODO Make Card#stateVisiblity true
} catch (CloneNotSupportedException e) {
Log.e(TAG, "Failed to clone this ClipCard");
e.printStackTrace();
}
} else if (itemId == R.id.menu_duplicate_clip) {
if (mCardModel.getSelectedClip() != null) {
// TODO duplicate clip
} else {
Toast.makeText(mContext, mContext.getString(R.string.add_clips_generic), Toast.LENGTH_SHORT).show();
}
} else if (itemId == R.id.menu_remove_card) {
}
Toast.makeText(mContext, "Selected " + (String) item.getTitleCondensed(), Toast.LENGTH_SHORT).show();
return true;
}
});
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
popupMenu.show();
}
});
}
private void setNewSelectedClip(View newSelectedClipContainer) {
// Put the passed clipThumbnail at the top of the stack
// The top of the stack is the end of mDisplayedClipViews
Log.i(TAG + "-swap", String.format("Swapping card %d for %d", mDisplayedClipViews.indexOf(newSelectedClipContainer), mDisplayedClipViews.size()-1));
View oldSelectedClipContainer = mDisplayedClipViews.get(mDisplayedClipViews.size()-1);
mDisplayedClipViews.remove(mDisplayedClipViews.indexOf(newSelectedClipContainer));
mDisplayedClipViews.add(newSelectedClipContainer);
newSelectedClipContainer.bringToFront();
// Swap alphas
oldSelectedClipContainer.findViewById(R.id.thumb).setAlpha(SECONDARY_CLIP_ALPHA);
newSelectedClipContainer.findViewById(R.id.thumb).setAlpha(PRIMARY_CLIP_ALPHA);
// Change view tags indicating primary / secondary status
oldSelectedClipContainer.setTag(R.id.view_tag_clip_primary, false);
newSelectedClipContainer.setTag(R.id.view_tag_clip_primary, true);
// Set new clip as selected
mCardModel.selectMediaFile((ClipMetadata) newSelectedClipContainer.getTag(R.id.view_tag_clip_metadata));
mCardModel.getStoryPath().getStoryPathLibrary().save(true);
}
private View.OnTouchListener mClipSelectionListener = new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
Log.i(TAG + "-select", "setting clip selected");
v.setBackgroundResource(R.drawable.clip_card_selected);
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
Log.i(TAG + "-select", "setting clip unselected");
v.setBackgroundResource(0);
break;
}
return false;
}// onTouch()
};
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
storageDir.mkdirs();
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
return image;
}
private void startRecordingAudio() {
// Inflate FrameLayout into clipCandidates
// Add AudioRecorder into it
FrameLayout.LayoutParams mediaViewParams =
new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
FrameLayout frame = new FrameLayout(mContext);
frame.setLayoutParams(mediaViewParams);
frame.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {
@Override
public void onViewAttachedToWindow(View v) {
// Do nothing
}
@Override
public void onViewDetachedFromWindow(View v) {
if (mRecorder != null && mRecorder.isRecording()) {
Log.w(TAG, "ClipCardView detached while recording in progress. Recording will be lost.");
mRecorder.stopRecording();
mRecorder.release();
// TODO : Can we attach this recording to the card model without :
// attaching media to ClipCardView will trigger observers in odd state. Could create separate ClipCard#saveMediaFile
// that doesn't trigger observers, but that could have its own issues...
}
}
});
try {
mRecorder = new AudioRecorder(frame);
for(int viewIdx = 0; viewIdx < mClipCandidatesContainer.getChildCount(); viewIdx++) {
mClipCandidatesContainer.getChildAt(viewIdx).setVisibility(View.GONE);
}
mClipCandidatesContainer.addView(frame);
} catch (IOException e) {
e.printStackTrace();
return;
}
mRecorder.startRecording();
tvCapture.setVisibility(View.GONE);
tvStop.setVisibility(View.VISIBLE);
}
private void stopRecordingAudio() {
MediaFile mf = mRecorder.stopRecording();
mRecorder.release();
mRecorder = null;
if (mf != null) {
mCardModel.saveMediaFile(mf);
// SEEMS LIKE A REASONABLE TIME TO SAVE
mCardModel.getStoryPath().getStoryPathLibrary().save(true);
} else {
// TODO Do something better
Toast.makeText(mContext, "Failed to save recording", Toast.LENGTH_LONG).show();
}
// Instead of manually resetting UI, just call changeCard whether or not recording succeeded
((MainActivity) mContext).mCardAdapter.changeCard(mCardModel); // FIXME this isn't pretty
}
} |
package org.yamcs;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.LogManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yamcs.utils.StringConverter;
import org.yamcs.utils.TimeEncoding;
import org.yaml.snakeyaml.LoaderOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.error.YAMLException;
/**
* A configuration object is a wrapper around a Map<String, Object> which keeps track to a parent and its original
* file (if any).
*
* This class loads yamcs configurations. There are a number of "subsystems", each using a corresponding subsystem.yaml
* file
*
* Configuration files are looked up in this order:
* <ol>
* <li>in the prefix/file.yaml via the classpath if the prefix is set in the setup method (used in the unittests)
* <li>in the userConfigDirectory .yamcs/etc/file.yaml
* <li>in the file.yaml via the classpath..
* </ol>
*
* @author nm
*/
public class YConfiguration {
public static File configDirectory; // This is used in client tools to overwrite
static YConfigurationResolver resolver = new DefaultConfigurationResolver();
private static Map<String, YConfiguration> configurations = new HashMap<>();
static Logger log = LoggerFactory.getLogger(YConfiguration.class.getName());
static String prefix = null;
// keeps track of the configuration path so meaningful error messages can be printed
// the path is something like filename.key1.subkey2[3]...
// this is used for the old style when the methods of YConfiguration were called in a static way
// Nowadays, please use Yconfiguration.getConfig() to make a child config, and then use the .path() to get the
// similar path.
private static IdentityHashMap<Object, String> staticConfPaths = new IdentityHashMap<>();
private static final YConfiguration EMPTY_CONFIG = YConfiguration.wrap(Collections.emptyMap());
/**
* The parent configuration
*/
YConfiguration parent;
// the key with which this object can be found in its parent
String parentKey;
// the root map
Map<String, Object> root;
// this is set only for the root Yconfiguration (i.e. without a parent) and indicates where (which file) it has been
// loaded from
String rootLocation;
private YConfiguration(String subsystem) throws IOException, ConfigurationException {
this(subsystem, resolver.getConfigurationStream("/" + subsystem + ".yaml"), subsystem + ".yaml");
}
/**
* Constructs a new configuration object parsing the input stream
*
* @param is
* input stream where the configuration is loaded from
* @param confpath
* configuration path - it is remembered together with the configuration in case of error to indicate
* where it is coming from (i.e. which file)
*/
@SuppressWarnings("unchecked")
public YConfiguration(String subsystem, InputStream is, String confpath) {
this.rootLocation = confpath;
Yaml yaml = getYamlParser();
try {
Object o = yaml.load(is);
if (o == null) {
o = new HashMap<String, Object>(); // config file is empty, not an error
} else if (!(o instanceof Map<?, ?>)) {
throw new ConfigurationException(confpath, "top level structure must be a map and not a " + o);
}
root = (Map<String, Object>) o;
staticConfPaths.put(root, confpath);
} catch (YAMLException e) {
throw new ConfigurationException(confpath, e.toString(), e);
}
configurations.put(subsystem, this);
}
/**
* Create a Yaml parser by taking into account some system properties.
*/
private Yaml getYamlParser() {
LoaderOptions loaderOptions = new LoaderOptions();
int maxAliases = Integer.parseInt(System.getProperty("org.yamcs.yaml.maxAliases", "200"));
loaderOptions.setMaxAliasesForCollections(maxAliases);
return new Yaml(loaderOptions);
}
/**
*
* @param parent
* @param parentKey
* @param root
*/
public YConfiguration(YConfiguration parent, String parentKey, Map<String, Object> root) {
this.root = root;
this.parent = parent;
this.parentKey = parentKey;
}
/**
* Sets up the Yamcs configuration system and loads the UTC-TAI offsets.
* <p>
* This method is intended for client tools and make store or use files from {@code ~/.yamcs}.
*/
public synchronized static void setupTool() {
File userConfigDirectory = new File(System.getProperty("user.home"), ".yamcs");
setupTool(userConfigDirectory);
}
/**
* Sets up the Yamcs configuration system and loads the UTC-TAI offsets.
* <p>
* This method is intended for client tools that wish to customize the default config directory.
*
* @param configDirectory
*/
public synchronized static void setupTool(File configDirectory) {
if (System.getProperty("java.util.logging.config.file") == null) {
try {
LogManager.getLogManager().readConfiguration(resolver.getConfigurationStream("/logging.properties"));
} catch (Exception e) {
// do nothing, the default java builtin logging is used
}
}
TimeEncoding.setUp();
YConfiguration.configDirectory = configDirectory;
File logDir = new File(configDirectory, "log");
if (!logDir.exists()) {
if (logDir.mkdirs()) {
System.err.println("Created directory: " + logDir);
} else {
System.err.println("Cannot create directory: " + logDir);
}
}
}
/**
* Sets up the Yamcs configuration system and loads the UTC-TAI offsets.
* <p>
* This method is intended for use in unit and integration tests. It allows resolving configuration files from a
* specific subdirectory of the classpath.
*
* @param configPrefix
* the name of the subdirectory where to resolve configuration files. This is resolved from the
* classpath.
*/
public static synchronized void setupTest(String configPrefix) {
prefix = configPrefix;
configurations.clear(); // forget any known config (useful in the maven unit tests called in the same VM)
resolver = new DefaultConfigurationResolver();
if (System.getProperty("java.util.logging.config.file") == null) {
try {
LogManager.getLogManager().readConfiguration(resolver.getConfigurationStream("/logging.properties"));
} catch (Exception e) {
// do nothing, the default java builtin logging is used
}
}
TimeEncoding.setUp();
}
public static synchronized void clearConfigs() {
configurations.clear();
}
/**
* Loads (if not already loaded) and returns a configuration corresponding to a file <subsystem>.yaml
*
* This method does not reload the configuration file if it has changed.
*
* @param subsystem
* @return the loaded configuration
* @throws ConfigurationException
* if the configuration file could not be found or not loaded (e.g. error in yaml formatting)
*/
public synchronized static YConfiguration getConfiguration(String subsystem) throws ConfigurationException {
if (subsystem.contains("..") || subsystem.contains("/")) {
throw new ConfigurationException("Invalid subsystem '" + subsystem + "'");
}
YConfiguration c = configurations.get(subsystem);
if (c == null) {
try {
c = new YConfiguration(subsystem);
} catch (IOException e) {
throw new ConfigurationException("Cannot load configuration for subsystem " + subsystem + ": " + e);
}
configurations.put(subsystem, c);
}
return c;
}
/**
* Loads and returns a configuration corresponding to a file <subsystem>.yaml
*
* This method reloads the configuration file always.
*
* @param subsystem
* @param reload
* @return the loaded configuration
* @throws ConfigurationException
* if the configuration file could not be found or not loaded (e.g. error in yaml formatting)
*/
public synchronized static YConfiguration getConfiguration(String subsystem, boolean reload)
throws ConfigurationException {
if (reload) {
YConfiguration c = configurations.get(subsystem);
if (c != null) {
configurations.remove(subsystem);
}
}
return getConfiguration(subsystem);
}
public static boolean isDefined(String subsystem) throws ConfigurationException {
try {
getConfiguration(subsystem);
return true;
} catch (ConfigurationNotFoundException e) {
return false;
}
}
public static boolean isNull(Map<?, ?> m, String key) {
if (!m.containsKey(key)) {
throw new ConfigurationException(staticConfPaths.get(m), "cannot find a mapping for key '" + key + "'");
}
Object o = m.get(key);
return o == null;
}
private void checkKey(String key, Class<?> cls) throws ConfigurationException {
if (!root.containsKey(key)) {
throw new ConfigurationException(getPath(), "cannot find a mapping for key '" + key + "'");
}
Object o = root.get(key);
if (o == null) {
throw new ConfigurationException(getPath(), key + " exists but is null");
}
if (!cls.isInstance(o)) {
throw new ConfigurationException(getPath(), key + " is not of the expected type " + cls.getName());
}
}
private static void checkKey(Map<String, Object> m, String key) throws ConfigurationException {
if (!m.containsKey(key)) {
throw new ConfigurationException(staticConfPaths.get(m), "cannot find a mapping for key '" + key + "'");
} else if (m.get(key) == null) {
throw new ConfigurationException(staticConfPaths.get(m), key + " exists but is null");
}
}
public boolean containsKey(String key) {
return root.containsKey(key);
}
@SuppressWarnings("unchecked")
public boolean containsKey(String key, String key1) throws ConfigurationException {
if (!root.containsKey(key)) {
return false;
}
checkKey(key, Map.class);
Map<String, Object> m = (Map<String, Object>) root.get(key);
return m.containsKey(key1);
}
/**
* returns the first entry in the config file if it's a map. Otherwise throws an error
*/
@SuppressWarnings("unchecked")
public Map<String, Object> getFirstMap() throws ConfigurationException {
Object o = root.values().iterator().next();
if (o instanceof Map) {
return (Map<String, Object>) o;
} else {
throw new ConfigurationException(
"the first entry in the config is of type " + o.getClass() + " and not Map");
}
}
/**
* returns the first entry(key) in the config file.
*
* @return
*/
public String getFirstEntry() throws ConfigurationException {
return root.keySet().iterator().next();
}
public Set<String> getKeys() {
return root.keySet();
}
private static String getUnqualfiedClassName(Object o) {
String name = o.getClass().getName();
if (name.lastIndexOf('.') > 0) {
name = name.substring(name.lastIndexOf('.') + 1); // Map$Entry
}
// The $ can be converted to a .
name = name.replace('$', '.'); // Map.Entry
return name;
}
public Map<String, Object> getRoot() {
return root;
}
/**
* If the key is pointing to a map, creates and returns a configuration object out of that map
* <p>
* The returned object will have its parent set to this object
* <p>
* If the key does not exist a ConfigurationException is thrown.
*
* @param key
* @return
*/
public YConfiguration getConfig(String key) {
Map<String, Object> m = getMap(key);
return new YConfiguration(this, key, m);
}
/**
* Same as {@link #getConfig(String)} but return an empty config if the key does not exist.
*
* @param key
* @return
*/
public YConfiguration getConfigOrEmpty(String key) {
if (root.containsKey(key)) {
return getConfig(key);
} else {
return YConfiguration.emptyConfig();
}
}
@SuppressWarnings("unchecked")
public static Map<String, Object> getMap(Map<String, Object> m, String key) throws ConfigurationException {
checkKey(m, key);
Object o = m.get(key);
if (o instanceof Map) {
Map<String, Object> m1 = (Map<String, Object>) o;
if (staticConfPaths.containsKey(m1)) {
staticConfPaths.put(m1, staticConfPaths.get(m) + "->" + key);
}
return m1;
} else {
throw new ConfigurationException(staticConfPaths.get(m),
"mapping for key '" + key + "' is of type " + o.getClass().getCanonicalName() + " and not Map");
}
}
/**
*
* Consider using {@link #getConfig} to get a child config instead of accessing the map directly
*/
@SuppressWarnings("unchecked")
public <K, V> Map<K, V> getMap(String key) throws ConfigurationException {
checkKey(key, Map.class);
return (Map<K, V>) root.get(key);
}
public Map<String, Object> getSubMap(String key, String key1) throws ConfigurationException {
Map<String, Object> m = getMap(key);
return getMap(m, key1);
}
/**
* Returns m.get(key) if it exists and is of type string, otherwise throws an exception
*
* @param m
* @param key
* @return
* @throws ConfigurationException
*/
public static String getString(Map<String, Object> m, String key) throws ConfigurationException {
checkKey(m, key);
Object o = m.get(key);
if (o instanceof String) {
return (String) o;
} else {
throw new ConfigurationException(staticConfPaths.get(m),
"mapping for key '" + key + "' is of type " + getUnqualfiedClassName(o) + " and not String");
}
}
public static String getString(Map<String, Object> m, String key, String defaultValue)
throws ConfigurationException {
if (m.containsKey(key)) {
return getString(m, key);
} else {
return defaultValue;
}
}
public String getString(String key) throws ConfigurationException {
checkKey(key, String.class);
return (String) root.get(key);
}
public String getString(String key, String defaultValue) throws ConfigurationException {
return getString(root, key, defaultValue);
}
/*
* The key has to point to a map that contains the subkey that points to a string
*/
public String getSubString(String key, String subkey) throws ConfigurationException {
Map<String, Object> m = getMap(key);
return getString(m, subkey);
}
/*
* The key has to point to a list
*/
@SuppressWarnings("unchecked")
public <T> List<T> getList(String key) throws ConfigurationException {
checkKey(key, List.class);
return (List<T>) root.get(key);
}
@SuppressWarnings("unchecked")
public List<YConfiguration> getConfigList(String key) throws ConfigurationException {
checkKey(root, key);
List<YConfiguration> r = new ArrayList<>();
Object o = root.get(key);
if (o instanceof List) {
List<?> l = (List<?>) o;
for (int i = 0; i < l.size(); i++) {
Object o1 = l.get(i);
if (o1 instanceof Map) {
r.add(new YConfiguration(this, key + "[" + i + "]", (Map<String, Object>) o1));
} else {
throw new ConfigurationException(this, "One element of the list is not a map: " + o1);
}
}
} else {
throw new ConfigurationException(staticConfPaths.get(root),
"mapping for key '" + key + "' is of type " + getUnqualfiedClassName(o) + " and not List");
}
return r;
}
public double getDouble(String key) throws ConfigurationException {
checkKey(key, Number.class);
return ((Number) root.get(key)).doubleValue();
}
public double getDouble(String key, double defaultValue) throws ConfigurationException {
if (!root.containsKey(key)) {
return defaultValue;
}
return getDouble(key);
}
/**
* This is the same like the method above but will create a {class: "string"} for strings rather than throwing an
* exception. It is to be used when loading service list which can be specified just by the class name.
*
* @param key
* @return
* @throws ConfigurationException
*/
@SuppressWarnings("unchecked")
public List<YConfiguration> getServiceConfigList(String key) throws ConfigurationException {
checkKey(root, key);
List<YConfiguration> r = new ArrayList<>();
Object o = root.get(key);
if (o instanceof List) {
List<?> l = (List<?>) o;
for (int i = 0; i < l.size(); i++) {
Object o1 = l.get(i);
if (o1 instanceof Map) {
r.add(new YConfiguration(this, key + "[" + i + "]", (Map<String, Object>) o1));
} else if (o1 instanceof String) {
Map<String, Object> m1 = new HashMap<>();
m1.put("class", o1);
r.add(new YConfiguration(this, key + "[" + i + "]", (Map<String, Object>) m1));
} else {
throw new ConfigurationException(this, "One element of the list is not a map: " + o1);
}
}
} else {
throw new ConfigurationException(staticConfPaths.get(root),
"mapping for key '" + key + "' is of type " + getUnqualfiedClassName(o) + " and not List");
}
return r;
}
@SuppressWarnings("unchecked")
public <T> List<T> getSubList(String key, String key1) throws ConfigurationException {
checkKey(key, Map.class);
Map<String, Object> m = (Map<String, Object>) root.get(key);
return getList(m, key1);
}
/**
* Returns m.get(key) if it exists and is of type boolean, if m.get(key) exists and is not boolean, throw an
* exception. if m.get(key) does not exist, return the default value.
*
* @param m
* @param key
* @param defaultValue
* - the default value to return if m.get(key) does not exist.
* @return the boolean config value
* @throws ConfigurationException
*/
public static boolean getBoolean(Map<String, Object> m, String key, boolean defaultValue)
throws ConfigurationException {
Object o = m.get(key);
if (o != null) {
if (o instanceof Boolean) {
return (Boolean) o;
} else {
throw new ConfigurationException(staticConfPaths.get(m), "mapping for key '" + key + "' is of type "
+ getUnqualfiedClassName(o) + " and not Boolean (use true or false without quotes)");
}
} else {
return defaultValue;
}
}
public static boolean getBoolean(Map<String, Object> m, String key) throws ConfigurationException {
checkKey(m, key);
Object o = m.get(key);
if (o instanceof Boolean) {
return (Boolean) o;
} else {
throw new ConfigurationException(staticConfPaths.get(m), "mapping for key '" + key + "' is of type "
+ getUnqualfiedClassName(o) + " and not Boolean (use true or false without quotes)");
}
}
public boolean getBoolean(String key) throws ConfigurationException {
checkKey(key, Boolean.class);
return (Boolean) root.get(key);
}
public boolean getBoolean(String key, String key1) throws ConfigurationException {
Map<String, Object> m = getMap(key);
return getBoolean(m, key1);
}
public boolean getBoolean(String key, boolean defaultValue) {
return getBoolean(root, key, defaultValue);
}
public int getInt(String key) throws ConfigurationException {
checkKey(key, Integer.class);
return (Integer) root.get(key);
}
public int getInt(String key, int defaultValue) throws ConfigurationException {
if (root.containsKey(key)) {
return getInt(key);
} else {
return defaultValue;
}
}
public int getInt(String key, String key1) throws ConfigurationException {
Map<String, Object> m = getMap(key);
return getInt(m, key1);
}
public int getInt(String key, String key1, int defaultValue) throws ConfigurationException {
if (!root.containsKey(key)) {
return defaultValue;
}
Map<String, Object> m = getMap(key);
return getInt(m, key1, defaultValue);
}
public static int getInt(Map<String, Object> m, String key) throws ConfigurationException {
checkKey(m, key);
Object o = m.get(key);
if (o instanceof Integer) {
return (Integer) o;
} else {
throw new ConfigurationException(staticConfPaths.get(m),
"mapping for key '" + key + "' is of type " + getUnqualfiedClassName(o) + " and not Integer");
}
}
/**
* return the m.get(key) as an int if it's present or v if it is not.
*
* If the key is present but the value is not an integer, a ConfigurationException is thrown.
*
* @param m
* @param key
* @param defaultValue
* @return the value from the map or the passed value if the map does not contain the key
* @throws ConfigurationException
* if the key is present but it's not an int
*/
public static int getInt(Map<String, Object> m, String key, int defaultValue) throws ConfigurationException {
if (!m.containsKey(key)) {
return defaultValue;
}
Object o = m.get(key);
if (o instanceof Integer) {
return (Integer) o;
} else {
throw new ConfigurationException(staticConfPaths.get(m),
"mapping for key '" + key + "' is of type " + getUnqualfiedClassName(o) + " and not Integer");
}
}
public long getLong(String key) {
return getLong(root, key);
}
public long getLong(String key, long defaultValue) {
return getLong(root, key, defaultValue);
}
public static long getLong(Map<String, Object> m, String key) throws ConfigurationException {
checkKey(m, key);
Object o = m.get(key);
if (o instanceof Integer) {
return (Integer) o;
} else if (o instanceof Long) {
return (Long) o;
} else {
throw new ConfigurationException(staticConfPaths.get(m), "mapping for key '" + key + "' is of type "
+ getUnqualfiedClassName(o) + " and not Integer or Long");
}
}
public byte[] getBinary(String key) {
return getBinary(root, key);
}
public byte[] getBinary(String key, byte[] defaultValue) {
if (root.containsKey(key)) {
return getBinary(root, key);
} else {
return defaultValue;
}
}
public static byte[] getBinary(Map<String, Object> m, String key) throws ConfigurationException {
checkKey(m, key);
Object o = m.get(key);
if (o instanceof byte[]) {
return (byte[]) o;
} else if (o instanceof String) {
String s = (String) o;
try {
return StringConverter.hexStringToArray((String) o);
} catch (IllegalArgumentException e) {
throw new ConfigurationException("'" + s + "' is not an hexadecimal string");
}
} else {
throw new ConfigurationException(staticConfPaths.get(m), "mapping for key '" + key + "' is of type "
+ getUnqualfiedClassName(o) + " and not binary or hexadecimal string");
}
}
/**
* return the m.get(key) as an long if it's present or v if it is not.
*
* @param m
* @param key
* @param v
* @return the value from the map or the passed value if the map does not contain the key
* @throws ConfigurationException
* if the key is present but it's not an long
*/
public static long getLong(Map<String, Object> m, String key, long v) throws ConfigurationException {
if (!m.containsKey(key)) {
return v;
}
Object o = m.get(key);
if (o instanceof Integer) {
return (Integer) o;
} else if (o instanceof Long) {
return (Long) o;
} else {
throw new ConfigurationException(staticConfPaths.get(m), "mapping for key '" + key + "' is of type "
+ getUnqualfiedClassName(o) + " and not Integer or Long");
}
}
public static double getDouble(Map<String, Object> m, String key, double v) throws ConfigurationException {
if (!m.containsKey(key)) {
return v;
}
Object o = m.get(key);
if (o instanceof Number) {
return ((Number) o).doubleValue();
} else {
throw new ConfigurationException(staticConfPaths.get(m), "mapping for key '" + key + "' is of type "
+ getUnqualfiedClassName(o) + " and not Integer or Long");
}
}
public boolean isList(String key) {
return isList(root, key);
}
public static boolean isList(Map<String, Object> m, String key) {
checkKey(m, key);
Object o = m.get(key);
return (o instanceof List);
}
public static void setResolver(YConfigurationResolver resolver) {
YConfiguration.resolver = resolver;
}
public static YConfigurationResolver getResolver() {
return YConfiguration.resolver;
}
/**
* Default config file resolver. Looks for configuration files in the classpath and in the user config directory
* (~/.yamcs/).
*/
public static class DefaultConfigurationResolver implements YConfigurationResolver {
@Override
public InputStream getConfigurationStream(String name) throws ConfigurationException {
InputStream is;
if (prefix != null) {
if ((is = YConfiguration.class.getResourceAsStream("/" + prefix + name)) != null) {
log.debug("Reading {}", new File(YConfiguration.class.getResource("/" + prefix + name).getFile())
.getAbsolutePath());
return is;
}
}
// see if the users has an own version of the file
if (configDirectory != null) {
File f = new File(configDirectory, name);
if (f.exists()) {
try {
is = new FileInputStream(f);
log.debug("Reading {}", f.getAbsolutePath());
return is;
} catch (FileNotFoundException e) {
throw new ConfigurationException("Cannot read file " + f, e);
}
}
}
is = YConfiguration.class.getResourceAsStream(name);
if (is == null) {
throw new ConfigurationNotFoundException("Cannot find resource " + name);
}
log.debug("Reading {}", new File(YConfiguration.class.getResource(name).getFile()).getAbsolutePath());
return is;
}
}
/**
* Introduced to be able to detect when a configuration file was not specified (as opposed to when there's a
* validation error inside). The current default behaviour of Yamcs is to throw an error when
* getConfiguration(String subystem) is called and the resource does not exist.
*/
public static class ConfigurationNotFoundException extends ConfigurationException {
private static final long serialVersionUID = 1L;
public ConfigurationNotFoundException(String message) {
super(message);
}
public ConfigurationNotFoundException(String message, Throwable t) {
super(message, t);
}
}
public <T extends Enum<T>> T getEnum(String key, Class<T> enumClass) {
return getEnum(root, key, enumClass);
}
public <T extends Enum<T>> T getEnum(String key, Class<T> enumClass, T defaultValue) {
if (root.containsKey(key)) {
return getEnum(root, key, enumClass);
} else {
return defaultValue;
}
}
/**
* Returns a value of an enumeration that matches ignoring case the string obtained from the config with the given
* key. Throws an Configurationexception if the key does not exist in config or if it does not map to a valid
* enumeration value
*
* @param config
* @param key
* @param enumClass
* @return
*/
public static <T extends Enum<T>> T getEnum(Map<String, Object> config, String key, Class<T> enumClass) {
String sk = getString(config, key);
T[] values = enumClass.getEnumConstants();
for (T v : values) {
if (v.toString().equalsIgnoreCase(sk)) {
return v;
}
}
throw new ConfigurationException("Invalid value '" + sk + "'. Valid values are: " + Arrays.toString(values));
}
/**
*
* @param key
* @return root.get(key)
*/
public Object get(String key) {
return root.get(key);
}
/**
* Create a new configuration wrapping around a map The resulting config will have no parent
*
* @param m
* @return
*/
public static YConfiguration wrap(Map<String, Object> m) {
return new YConfiguration(null, null, m);
}
public static YConfiguration emptyConfig() {
return EMPTY_CONFIG;
}
public Map<String, Object> toMap() {
return getRoot();
}
public String getPath() {
if (parent == null) {
return rootLocation;
}
StringBuilder sb = new StringBuilder();
buildPath(this, sb);
return sb.toString();
}
private static void buildPath(YConfiguration c, StringBuilder sb) {
if (c.parent != null) {
buildPath(c.parent, sb);
if (c.parent.parent != null) {
sb.append(".");
}
sb.append(c.parentKey);
} else {
sb.append(c.rootLocation).append(": ");
}
}
@SuppressWarnings("unchecked")
public static <T> List<T> getList(Map<String, Object> m, String key) throws ConfigurationException {
checkKey(m, key);
Object o = m.get(key);
if (o instanceof List) {
List<T> l = (List<T>) o;
String parentPath = staticConfPaths.get(m);
for (int i = 0; i < l.size(); i++) {
Object o1 = l.get(i);
if (!staticConfPaths.containsKey(o1)) {
staticConfPaths.put(o1, parentPath + "->" + key + "[" + i + "]");
}
}
return l;
} else {
throw new ConfigurationException(staticConfPaths.get(m),
"mapping for key '" + key + "' is of type " + getUnqualfiedClassName(o) + " and not List");
}
}
@Override
public String toString() {
return root.toString();
}
/**
* If config.get(key) exists and is a list, and the list has the element idx and is a map, then return a
* configuration wrapper around that map.
* <p>
* Otherwise throw a ConfigurationException
*
* @param key
* @param idx
* @return
*/
@SuppressWarnings("unchecked")
public YConfiguration getConfigListIdx(String key, int idx) {
checkKey(root, key);
Object o = root.get(key);
if (!(o instanceof List)) {
throw new ConfigurationException(staticConfPaths.get(root),
"mapping for key '" + key + "' is of type " + getUnqualfiedClassName(o) + " and not List");
}
List<?> l = (List<?>) o;
if (idx >= l.size()) {
throw new ConfigurationException(staticConfPaths.get(root),
"mapping for key '" + key + "' is a list but the requested index " + idx
+ " is outside of the list");
}
Object o1 = l.get(idx);
if (!(o1 instanceof Map)) {
throw new ConfigurationException(this,
"The element " + idx + " in the list is not a map but " + getUnqualfiedClassName(o1));
}
return new YConfiguration(this, key + "[" + idx + "]", (Map<String, Object>) o1);
}
} |
package hm.binkley.util;
import hm.binkley.util.YamlHelper.Builder;
import lombok.EqualsAndHashCode;
import org.intellij.lang.annotations.Language;
import org.jetbrains.annotations.Nullable;
import org.junit.Test;
import org.yaml.snakeyaml.Yaml;
import javax.annotation.Nonnull;
import java.util.Random;
import static java.util.stream.IntStream.rangeClosed;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
/**
* {@code YamlHelperTest} tests {@link YamlHelper}.
*
* @author <a href="mailto:binkley@alumni.rice.edu">B. K. Oxley</a>
*/
public class YamlHelperTest {
@Test
public void shouldLoadWithImplicit() {
final Yaml yaml = YamlHelper.builder().
then(Foo::registerWith).
build();
final Object o = yaml.load("3x12");
assertThat(o, is(instanceOf(Foo.class)));
final Foo foo = (Foo) o;
assertThat(foo.bar, is(equalTo(3)));
assertThat(foo.none, is(equalTo(12)));
}
@Test
public void shouldDumpWithImplicit() {
final Yaml yaml = YamlHelper.builder().
then(Foo::registerWith).
build();
final Foo foo = new Foo(3, 12);
final String doc = yaml.dump(foo);
assertThat(doc, is(equalTo("--- 3x12\n...\n")));
}
@Test
public void shouldLoadWithExtraImplicit() {
final Yaml yaml = YamlHelper.builder().
then(FancyFoo::registerWith).
build();
final Object o = yaml.load("x20");
assertThat(o, is(instanceOf(FancyFoo.class)));
final FancyFoo foo = (FancyFoo) o;
assertThat(foo.number(), is(equalTo(1)));
assertThat(foo.sides(), is(equalTo(20)));
}
@Test
public void shouldLoadithValueOf() {
assertThat(FancyFoo.valueOf("3x6"), is(equalTo(new FancyFoo(3, 6))));
}
@Test
public void shouldLoadWithExplicit() {
final Yaml yaml = YamlHelper.builder().
then(Bar::registerWith).
build();
final Object o = yaml.load("!* howard jones");
assertThat(o, is(instanceOf(Bar.class)));
final Bar bar = (Bar) o;
assertThat(bar.value(), is(equalTo("howard jones")));
}
public static final class Foo {
@Language("RegExp")
private static final String match
= "^([123456789]\\d*)x(4|6|8|10|12|20|100)$";
private static final YamlHelper<Foo> helper = YamlHelper
.from("123456789", match, Integer::valueOf, Integer::valueOf,
Foo::new, "'%s' is not the foo you are looking for");
public static void registerWith(final YamlHelper.Builder builder) {
builder.addImplicit(Foo.class, helper);
}
public final int bar;
public final int none;
public Foo(final int bar, final int none) {
this.bar = bar;
this.none = none;
}
@Override
public String toString() {
return bar + "x" + none;
}
}
@EqualsAndHashCode
public static final class FancyFoo {
@Language("RegExp")
private static final String match
= "^([123456789]\\d*)?x(4|6|8|10|12|20|100)$";
private static final YamlHelper<FancyFoo> helper = YamlHelper
.from("x123456789", match, FancyFoo::nullableIntegerValueOf,
Integer::valueOf, FancyFoo::new,
"'%s' is not the *fancy* foo you are looking for");
private static final Random random = new Random();
public static void registerWith(final YamlHelper.Builder builder) {
builder.addImplicit(FancyFoo.class, helper);
}
@Nullable
private final Integer number;
private final int sides;
@Nonnull
public static FancyFoo valueOf(@Nonnull final String val) {
return helper.valueOf().apply(val);
}
public FancyFoo(@Nullable final Integer number, final int sides) {
this.number = number;
this.sides = sides;
}
public int number() {
return null == number ? 1 : number;
}
public int sides() {
return sides;
}
public int roll() {
return rangeClosed(1, number()).
map(n -> random.nextInt(sides()) + 1).
sum();
}
@Override
public String toString() {
return null == number ? "x" + sides : number + "x" + sides;
}
private static Integer nullableIntegerValueOf(final String n) {
return null == n ? null : Integer.valueOf(n);
}
}
public static final class Bar {
public static void registerWith(final Builder builder) {
// not permitted by SnakeYAML. In fact, SnakeYAML does not like
// anyone not using ASCII.
builder.addExplicit(Bar.class, "*");
}
@Nonnull
public static Bar valueOf(final String val) {
return new Bar(val);
}
public Bar(@Nonnull final String value) {
this.value = value;
}
private final String value;
@Nonnull
public String value() {
return value;
}
}
} |
package com.exedio.cope.instrument;
import java.io.*;
import java.util.*;
import java.lang.reflect.Modifier;
/**
* Implements a modifying java parser.
* This means, the input stream is continuesly written
* into an output stream, and may be modified before writing.
*
* The parser recognizes java meta information only,
* which is anything outside method bodies and attribute
* inizializers.
*
* To use the parser, provide an implemention of the
* InjectionConsumer interface to the constructor.
* @see InjectionConsumer
*/
public final class Injector
{
private final Reader input;
private final Writer output;
private final InjectionConsumer consumer;
private final StringBuffer buf = new StringBuffer();
private boolean do_block = false;
private boolean start_block = false;
private boolean collect_when_blocking = false;
private final StringBuffer collector = new StringBuffer();
private String doccomment = null;
private final JavaFile javafile = new JavaFile();
/**
* Constructs a new java parser.
* @parameter input
* the input stream to be parsed.
* @parameter output
* the target, where the modified input stream is written to.
* May be null, if only reading is desired.
* @parameter consumer
* an implementation of InjectionConsumer,
* listening to parsed elements of the input stream.
* @see InjectionConsumer
*/
public Injector(Reader input, Writer output, InjectionConsumer consumer)
{
this.input = input;
this.output = output;
this.consumer = consumer;
}
private char outbuf;
private boolean outbufvalid = false;
/**
* The line number in the current file.
*/
private int linenumber = 1;
/**
* The character in the current line.
*/
private int lineposition = 0;
public final char read() throws IOException, EndException
{
int c = input.read();
if (output != null && !do_block && outbufvalid)
output.write(outbuf);
if (c >= 0)
{
if (c == '\n')
{
linenumber++;
lineposition = -1;
}
else
{
lineposition++;
}
if (do_block && collect_when_blocking)
collector.append(outbuf);
outbuf = (char)c;
outbufvalid = true;
//System.out.print((char)c);
return (char)c;
}
else
throw new EndException();
}
private void scheduleBlock(boolean collect_when_blocking)
{
if (do_block || collector.length() > 0)
throw new IllegalArgumentException();
start_block = true;
this.collect_when_blocking = collect_when_blocking;
}
private String getCollector()
{
do_block = false;
start_block = false;
String s = collector.toString();
collector.setLength(0);
//System.out.println(" collector: >"+s+"<");
return s;
}
private void flushOutbuf() throws IOException
{
if (outbufvalid)
{
if (do_block)
{
if (collect_when_blocking)
collector.append(outbuf);
}
else
{
if (output != null)
output.write(outbuf);
}
outbufvalid = false;
}
}
private void write(String s) throws IOException
{
if (output != null)
output.write(s);
}
/**
* Reads a comment.
* Is started after the initial '/' character.
* If the next character is either '/' or '*',
* the rest of the comment is read, and a value of -1 is returned.
* If not, there is no comment,
* and this next character is returned, casted to int.
*/
private int readComment() throws IOException, EndException
{
char x;
switch (x = read())
{
case '*' :
if (read() == '*')
{
// definitly a doc comment, see Java Lang. Spec. 3.7.
//System.out.println("this is a '' doc-comment");
}
//System.out.println("this is a '' comment");
while (true)
{
if (read() != '*')
continue;
char c;
while ((c = read()) == '*');
if (c == '/')
break;
}
break;
case '/' :
//System.out.println("this is a '//' comment");
do;
while (read() != '\n');
break;
default :
return (int)x;
}
return -1;
}
private char tokenBuf = '\0';
private String commentBuf = null;
private String comment = null;
/**
* Splits the character stream into tokens.
* This tokenizer works only outside of method bodys.
* @return '\0' for multiple character token in buf,
* 'c' for comment token in comment,
* else for single character token.
*/
private char readToken() throws IOException, EndException
{
char c;
if (tokenBuf != '\0')
{
c = tokenBuf;
tokenBuf = '\0';
//System.out.println("<<"+c+">>");
return c;
}
if (commentBuf != null)
{
comment = commentBuf;
commentBuf = null;
//System.out.println("<<"+comment+">>");
return 'c';
}
buf.setLength(0);
while (true)
{
switch (c = read())
{
case '/' :
boolean commentcollector = false;
if (!do_block && start_block)
{
do_block = true;
commentcollector = true;
}
readComment();
if (commentcollector)
flushOutbuf();
if (buf.length() > 0)
{
if (commentcollector)
commentBuf = getCollector();
//System.out.println("<"+buf+">");
return '\0';
}
if (commentcollector)
{
comment = getCollector();
//System.out.println("<<"+comment+">>");
return 'c';
}
break;
case ' ' :
case '\t' :
case '\n' :
case '\r' :
if (buf.length() > 0)
{
//System.out.println("<"+buf+">");
return '\0';
}
break;
case '{' :
case '}' :
case '(' :
case ')' :
case ';' :
case '=' :
case ',' :
if (buf.length() > 0)
{
tokenBuf = c;
//System.out.println("<"+buf+">");
return '\0';
}
//System.out.println("<<"+c+">>");
return c;
default :
if (!do_block && start_block)
do_block = true;
buf.append(c);
break;
}
}
}
/**
* Parses a method body or an attribute initializer,
* depending on the parameter.
* For method bodys, the input stream must be directly behind
* the first opening curly bracket of the body.
* For attribute initializers, the input stream must be directly
* behind the '='.
* @return
* the delimiter, which terminated the attribute initializer
* (';' or ',') or '}' for methods.
*/
private char parseBody(boolean attribute)
throws IOException, EndException, ParseException
{
//System.out.println(" body("+(attribute?"attribute":"method")+")");
int bracketdepth = (attribute ? 0 : 1);
char c = read();
while (true)
{
switch (c)
{
case '/' :
int i = readComment();
if (i >= 0)
c = (char)i;
else
c = read();
break;
case '{' :
case '(' :
bracketdepth++;
//System.out.print("<("+bracketdepth+")>");
c = read();
break;
case '}' :
case ')' :
bracketdepth
//System.out.print("<("+bracketdepth+")>");
if (bracketdepth == 0 && !attribute)
return '}';
if (bracketdepth < 0)
throw new ParseException("';' expected.");
c = read();
break;
case ';' :
// dont have to test for "attribute" here
// since then the test in the '}' branch would have
// already terminated the loop
if (bracketdepth == 0)
return ';';
c = read();
break;
case ',' :
if (bracketdepth == 0)
return ',';
c = read();
break;
// ignore brackets inside of literal String's
case '"' :
il : while (true)
{
switch (read())
{
case '"' :
break il;
case '\\' :
read();
break; // ignore escaped characters
}
}
c = read();
break;
// ignore brackets inside of literal characters
case '\'' :
il : while (true)
{
switch (read())
{
case '\'' :
break il;
case '\\' :
read();
break; // ignore escaped characters
}
}
c = read();
break;
default :
c = read();
break;
}
}
}
/**
* Parses a class feature. May be an attribute, a method or a inner
* class. May even be a normal class, in this case parent==null.
* @parameter parent the class that contains the class feature
* if null, there is no containing class, and
* the feature must be a class itself.
*/
private JavaFeature[] parseFeature(JavaClass parent)
throws IOException, EndException, InjectorParseException
{
return parseFeature(parent, buf.toString());
}
/**
* The same as parseFeature(JavaClass) but the first token has
* already been fetched from the input stream.
* @parameter bufs the first token of the class feature.
* @see #parseFeature(JavaClass)
*/
private JavaFeature[] parseFeature(JavaClass parent, String bufs)
throws IOException, EndException, InjectorParseException
{
int modifiers = 0;
while (true)
{
//System.out.println("bufs >"+bufs+"<");
if ("public".equals(bufs))
modifiers |= Modifier.PUBLIC;
else if ("protected".equals(bufs))
modifiers |= Modifier.PROTECTED;
else if ("private".equals(bufs))
modifiers |= Modifier.PRIVATE;
else if ("static".equals(bufs))
modifiers |= Modifier.STATIC;
else if ("final".equals(bufs))
modifiers |= Modifier.FINAL;
else if ("synchronized".equals(bufs))
modifiers |= Modifier.SYNCHRONIZED;
else if ("volatile".equals(bufs))
modifiers |= Modifier.VOLATILE;
else if ("transient".equals(bufs))
modifiers |= Modifier.TRANSIENT;
else if ("native".equals(bufs))
modifiers |= Modifier.NATIVE;
else if ("abstract".equals(bufs))
modifiers |= Modifier.ABSTRACT;
else if ("interface".equals(bufs))
{
modifiers |= Modifier.INTERFACE;
JavaClass[] jcarray = { parseClass(parent, modifiers)};
return jcarray;
}
else if ("class".equals(bufs))
{
JavaClass[] jcarray = { parseClass(parent, modifiers)};
return jcarray;
}
else
{
if (parent == null)
throw new ParseException("'class' or 'interface' expected.");
break;
}
char c = readToken();
if (c != '\0')
{
if (parent == null)
throw new ParseException("'class' or 'interface' expected.");
else
{
if (c == '{' && modifiers == Modifier.STATIC)
{
// this is a static initializer
if (collect_when_blocking)
write(getCollector());
flushOutbuf();
parseBody(false);
scheduleBlock(true);
doccomment = null;
return new JavaClass[0];
}
else
{
throw new ParseException("modifier expected.");
}
}
}
bufs = buf.toString();
}
String featuretype = buf.toString();
String featurename;
int position_name_end = collector.length();
char c = readToken();
if (c != '\0')
{
if (c == '(') // it's a constructor !
{
featurename = featuretype;
featuretype = null;
if (!parent.getName().equals(featurename))
throw new ParseException(
"constructor '"
+ featurename
+ " must have the classes name '"
+ parent.getName()
+ '\'');
}
else
throw new ParseException("'(' expected.");
}
else
{
featurename = buf.toString();
position_name_end = collector.length();
c = readToken();
}
if (c == '(') // it's a method/constructor
{
JavaBehaviour jb =
(featuretype == null)
? (JavaBehaviour)new JavaConstructor(parent,
modifiers,
featurename)
: new JavaMethod(parent, modifiers, featuretype, featurename);
parseBehaviour(jb);
JavaFeature[] jbarray = { jb };
return jbarray;
}
else // it's an attribute
{
JavaAttribute ja =
new JavaAttribute(parent, modifiers, featuretype, featurename);
return parseAttribute(ja, c);
}
}
private void parseBehaviour(JavaBehaviour jb)
throws IOException, EndException, ParseException
{
char c = readToken();
// parsing parameter list
while (true)
{
String parametertype;
if (c == ')')
{
break;
}
else if (c == '\0')
{
parametertype = buf.toString();
if ("final".equals(parametertype))
{
c = readToken();
if (c == '\0')
parametertype = buf.toString();
else
throw new ParseException("parameter type expected.");
}
}
else
throw new ParseException("')' expected.");
c = readToken();
if (c != '\0')
throw new ParseException("parameter name expected.");
//System.out.println("addParameter("+parametertype+", "+buf.toString()+")");
jb.addParameter(parametertype, buf.toString());
c = readToken();
if (c == ',')
{
c = readToken();
continue;
}
else if (c == ')')
{
break;
}
else
throw new ParseException("')' expected.");
}
// parsing throws clauses
c = readToken();
ti : while (true)
{
switch (c)
{
case '{' :
if (collect_when_blocking)
{
output.write(getCollector());
consumer.onBehaviourHeader(jb);
}
parseBody(false);
flushOutbuf();
break ti;
case ';' :
if (collect_when_blocking)
{
output.write(getCollector());
consumer.onBehaviourHeader(jb);
}
flushOutbuf();
break ti;
case '\0' :
if (buf.toString().equals("throws"))
{
do
{
c = readToken();
if (c == '\0')
jb.addThrowable(buf.toString());
else
throw new ParseException("class name expected.");
c = readToken();
}
while (c == ',');
}
else
throw new ParseException("'throws' expected.");
break;
default :
throw new ParseException("'{' expected.");
}
}
if (do_block)
getCollector();
else
{
//jb.print(System.out);
}
}
private JavaAttribute[] parseAttribute(JavaAttribute ja, char c)
throws IOException, EndException, InjectorParseException
{
consumer.onAttributeHeader(ja);
final ArrayList commaSeparatedAttributes = new ArrayList();
commaSeparatedAttributes.add(ja);
//if(!do_block) ja.print(System.out);
while (true)
{
switch (c)
{
case ';' :
if (collect_when_blocking)
write(getCollector());
flushOutbuf();
if (do_block)
getCollector();
JavaAttribute[] jaarray =
new JavaAttribute[commaSeparatedAttributes.size()];
commaSeparatedAttributes.toArray(jaarray);
return jaarray;
case ',' :
c = readToken();
if (c != '\0')
throw new ParseException("attribute name expected.");
ja = new JavaAttribute(ja, buf.toString());
commaSeparatedAttributes.add(ja);
//if(!do_block) ja.print(System.out);
c = readToken();
break;
case '=' :
if (collect_when_blocking)
write(getCollector());
c = parseBody(true);
flushOutbuf();
break;
default :
throw new ParseException("';', '=' or ',' expected.");
}
}
}
private JavaClass parseClass(JavaClass parent, int modifiers)
throws IOException, EndException, InjectorParseException
{
if (readToken() != '\0')
throw new ParseException("class name expected.");
String classname = buf.toString();
//System.out.println("class ("+Modifier.toString(modifiers)+") >"+classname+"<");
JavaClass jc = new JavaClass(javafile, parent, modifiers, classname);
//cc.print(System.out);
consumer.onClass(jc);
if (collect_when_blocking)
write(getCollector());
if (do_block)
getCollector();
while (readToken() != '{');
scheduleBlock(true);
ml : while (true)
{
switch (readToken())
{
case '}' :
getCollector();
break ml;
case 'c' :
/**
* @parameter tagname the tag name without the '@' prefix
* @return the first word following the tag
*/
public final static String findDocTag(String doccomment, String tagname)
{
String s = '@' + tagname + ' ';
int start = doccomment.indexOf(s);
if (start < 0)
return null;
start += s.length();
int end;
li : for (end = start; end < doccomment.length(); end++)
{
switch (doccomment.charAt(end))
{
case ' ' :
case '\n' :
case '\r' :
case '*' :
break li;
}
}
String result = doccomment.substring(start, end).trim();
//System.out.println("doctag:>"+tagname+"< >"+doccomment.substring(start, end)+"<");
return result;
}
/**
* @parameter tagname the tag name without the '@' prefix
* @return the whole string following the tag without ending whitespaces
*/
public final static String findWholeDocTag(
String doccomment,
String tagname)
{
String s = '@' + tagname + ' ';
int start = doccomment.indexOf(s);
if (start < 0)
return null;
start += s.length();
final int end = doccomment.indexOf('\n', start);
if (end > 0)
return doccomment.substring(start, end).trim();
else
return doccomment.substring(start).trim();
}
private final static Map makeResult(
Map result,
final String tagname,
final StringBuffer buf)
{
if (tagname != null)
{
if (result == Collections.EMPTY_MAP)
result = new HashMap();
Object o = result.get(tagname);
if (o == null)
result.put(tagname, buf.toString().trim());
// TODO: trim should not be neccesasary
else if (o instanceof String)
{
final ArrayList list = new ArrayList();
list.add(o);
list.add(buf.toString().trim());
// TODO: trim should not be neccesasary
result.put(tagname, list);
}
else
{
((ArrayList)o).add(buf.toString());
}
}
return result;
}
public final static Map extractDocParagraphs(String doccomment)
{
Map result = Collections.EMPTY_MAP;
StringBuffer buf = null;
if (!doccomment.regionMatches(0, "/**", 0, 3))
throw new RuntimeException();
int pos = 3;
final int length = doccomment.length() - 2;
if (!doccomment.regionMatches(length, "*/", 0, 2))
throw new RuntimeException();
findfirsttag : while (true)
{
//System.out.print("1");
skipwhitespace : while (true)
{
//System.out.print("2");
switch (doccomment.charAt(pos))
{
case ' ' :
case '\t' :
case '\n' :
case '\r' :
break;
default :
break skipwhitespace;
}
if ((++pos) >= length)
return result;
}
// we are either at the first significant character of line
// or the leading askeriks
if (doccomment.charAt(pos) == '*')
{
// we are at the leading askeriks
if ((++pos) >= length)
return result;
skipwhitespace : while (true)
{
//System.out.print("3");
switch (doccomment.charAt(pos))
{
case ' ' :
case '\t' :
case '\n' :
case '\r' :
break;
default :
break skipwhitespace;
}
if ((++pos) >= length)
return result;
}
}
// we are at the first significant character of line
if (doccomment.charAt(pos) == '@')
break findfirsttag;
pos = doccomment.indexOf('\n', pos);
if (pos < 0)
return result;
}
tagloop : while (true)
{
//System.out.print("4");
// we are at the '@' of the first tag
if ((++pos) >= length)
return result;
// we are at the first tag name
if (buf == null)
buf = new StringBuffer();
collecttagname : while (true)
{
//System.out.print("5");
switch (doccomment.charAt(pos))
{
case ' ' :
break collecttagname;
case ':' :
throw new RuntimeException();
default :
buf.append(doccomment.charAt(pos));
break;
}
if ((++pos) >= length)
return result;
}
// we are at the space following the tagname
if ((++pos) >= length)
return result;
// we are at the start of the tag body
final String tagname = buf.toString();
buf.setLength(0);
lineloop : while (true)
{
//System.out.print("6");
// we are at the start of a new line of a tag body
collecttagline : while (true)
{
//System.out.print("7");
switch (doccomment.charAt(pos))
{
case '\n' :
case '\r' :
break collecttagline;
default :
buf.append(doccomment.charAt(pos));
break;
}
if ((++pos) >= length)
return makeResult(result, tagname, buf);
}
// we are at the beginning of a new line
skipwhitespace : while (true)
{
//System.out.print("8");
switch (doccomment.charAt(pos))
{
case ' ' :
case '\t' :
case '\n' :
case '\r' :
break;
default :
break skipwhitespace;
}
if ((++pos) >= length)
return makeResult(result, tagname, buf);
}
// we are either at the first significant character of line
// or the leading askeriks
if (doccomment.charAt(pos) == '*')
{
// we are at the leading askeriks
if ((++pos) >= length)
return makeResult(result, tagname, buf);
skipwhitespace : while (true)
{
//System.out.print("9");
switch (doccomment.charAt(pos))
{
case ' ' :
case '\t' :
buf.append(doccomment.charAt(pos));
break;
case '\n' :
case '\r' :
continue lineloop;
default :
break skipwhitespace;
}
if ((++pos) >= length)
return makeResult(result, tagname, buf);
}
}
// we are either at the start of significant characters of a new
// line of this paragraph, or at the start of a new tag
if (doccomment.charAt(pos) == '@')
{
// we are at the start of a new tag
result = makeResult(result, tagname, buf);
buf.setLength(0);
continue tagloop;
}
// add a separator beetween line of tag bodies
buf.append(' ');
}
}
}
public static final void main(final String[] args)
{
final String source =
"/**\n"
+ "\t * Hallo Du!\n"
+ "\t * @zapp zooppell mappel\n"
+ "\t * @bipp flap\n"
+ "\t * @soli\n"
+ "\t * @bipp flppp\n"
+ "\t * @schnopp blubb\n"
+ "\t */";
System.out.println(source);
final Map map = extractDocParagraphs(source);
for (Iterator i = map.keySet().iterator(); i.hasNext();)
{
final String tag = (String)i.next();
final Object value = map.get(tag);
if (value instanceof String)
System.out.println("@>" + tag + "< >" + value + "<");
else
{
for (Iterator j = ((List)value).iterator(); j.hasNext();)
System.out.println(
"@>" + tag + "< >" + ((String)j.next()) + "<");
}
}
}
} |
package com.crashinvaders.texturepackergui;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.GdxRuntimeException;
import com.badlogic.gdx.utils.I18NBundle;
import com.crashinvaders.common.PrioritizedInputMultiplexer;
import com.crashinvaders.texturepackergui.services.model.ModelService;
import com.crashinvaders.texturepackergui.services.shortcuts.GlobalShortcutHandler;
import com.crashinvaders.texturepackergui.utils.LmlUtils;
import com.github.czyzby.autumn.annotation.Component;
import com.github.czyzby.autumn.annotation.Initiate;
import com.github.czyzby.autumn.annotation.Inject;
import com.github.czyzby.autumn.context.Context;
import com.github.czyzby.autumn.context.ContextDestroyer;
import com.github.czyzby.autumn.context.ContextInitializer;
import com.github.czyzby.autumn.mvc.component.asset.AssetService;
import com.github.czyzby.autumn.mvc.component.i18n.LocaleService;
import com.github.czyzby.autumn.mvc.component.i18n.processor.AvailableLocalesAnnotationProcessor;
import com.github.czyzby.autumn.mvc.component.i18n.processor.I18nBundleAnnotationProcessor;
import com.github.czyzby.autumn.mvc.component.preferences.PreferencesService;
import com.github.czyzby.autumn.mvc.component.ui.InterfaceService;
import com.github.czyzby.autumn.mvc.component.ui.SkinService;
import com.github.czyzby.autumn.mvc.component.ui.processor.*;
import com.github.czyzby.autumn.mvc.stereotype.View;
import com.github.czyzby.autumn.mvc.stereotype.ViewActionContainer;
import com.github.czyzby.autumn.mvc.stereotype.ViewDialog;
import com.github.czyzby.autumn.mvc.stereotype.preference.Property;
import com.github.czyzby.autumn.mvc.stereotype.preference.StageViewport;
import com.github.czyzby.autumn.processor.event.EventDispatcher;
import com.github.czyzby.autumn.processor.event.MessageDispatcher;
import com.github.czyzby.autumn.scanner.ClassScanner;
import com.github.czyzby.kiwi.util.gdx.GdxUtilities;
import com.github.czyzby.kiwi.util.gdx.asset.Disposables;
import com.github.czyzby.kiwi.util.gdx.collection.GdxArrays;
import com.github.czyzby.kiwi.util.tuple.immutable.Pair;
import com.github.czyzby.lml.parser.LmlParser;
import com.github.czyzby.lml.parser.impl.tag.Dtd;
import com.kotcrab.vis.ui.VisUI;
import com.kotcrab.vis.ui.widget.file.FileChooser;
import java.io.Writer;
public class App implements ApplicationListener {
private static App instance;
private final ClassScanner componentScanner;
private final AppParams params;
private final PrioritizedInputMultiplexer inputMultiplexer;
private final DragDropManager dragDropManager = new DragDropManager();
private ContextDestroyer contextDestroyer;
private InterfaceService interfaceService;
private ModelService modelService;
private LocaleService localeService;
private GlobalShortcutHandler shortcutHandler;
private ComponentExtractor componentExtractor;
private EventDispatcher eventDispatcher;
private MessageDispatcher messageDispatcher;
/** Manually set inside {@link #pause()} and {@link #resume()} */
private boolean paused;
/** Singleton accessor */
public static App inst() {
if (instance == null) {
throw new NullPointerException("App is not initialized yet");
}
return instance;
}
public App(ClassScanner componentScanner, AppParams params) {
this.componentScanner = componentScanner;
this.params = params;
inputMultiplexer = new PrioritizedInputMultiplexer();
inputMultiplexer.setMaxPointers(1);
instance = this;
}
@Override
public void create() {
Gdx.input.setInputProcessor(inputMultiplexer);
initiateContext();
FileChooser.setDefaultPrefsName("file_chooser.xml");
// Uncomment to update project's LML DTD schema
// LmlUtils.saveDtdSchema(interfaceService.getParser(), Gdx.files.local("../lml.dtd"));
}
private void initiateContext() {
final ContextInitializer initializer = new ContextInitializer();
registerDefaultComponentAnnotations(initializer);
addDefaultComponents(initializer);
initializer.scan(this.getClass(), componentScanner);
contextDestroyer = initializer.initiate();
interfaceService.getParser().getData().addArgument("currentVersionCode", AppConstants.version.toString());
}
/** Invoked before context initiation.
* @param initializer should be used to register component annotations to scan for. */
@SuppressWarnings("unchecked")
protected void registerDefaultComponentAnnotations(final ContextInitializer initializer) {
initializer.scanFor(ViewActionContainer.class, ViewDialog.class, View.class, StageViewport.class, Property.class);
}
/** Invoked before context initiation.
* @param initializer should be used to registered default components, created with plain old Java. */
protected void addDefaultComponents(final ContextInitializer initializer) {
initializer.addComponents(
// PROCESSORS
// Assets:
new AssetService(), new SkinAssetAnnotationProcessor(),
// Locale:
localeService = new LocaleService(),
// Settings:
new I18nBundleAnnotationProcessor(), new PreferenceAnnotationProcessor(), new SkinAnnotationProcessor(),
new StageViewportAnnotationProcessor(), new PreferencesService(),
// Interface:
new ViewAnnotationProcessor(), new ViewDialogAnnotationProcessor(),
new ViewActionContainerAnnotationProcessor(), new ViewStageAnnotationProcessor(),
new LmlMacroAnnotationProcessor(), new LmlParserSyntaxAnnotationProcessor(),
new AvailableLocalesAnnotationProcessor(),
// COMPONENTS
// Interface:
interfaceService = new InterfaceService(),
new SkinService(),
// Custom
modelService = new ModelService(),
shortcutHandler = new GlobalShortcutHandler(),
componentExtractor = new ComponentExtractor());
}
@Override
public void resize(final int width, final int height) {
interfaceService.resize(width, height);
}
@Override
public void render() {
if (paused) return;
GdxUtilities.clearScreen();
interfaceService.render(Gdx.graphics.getDeltaTime());
}
@Override
public void resume() {
paused = false;
interfaceService.resume();
Gdx.input.setInputProcessor(inputMultiplexer);
}
@Override
public void pause() {
paused = true;
interfaceService.pause();
Gdx.input.setInputProcessor(null);
}
@Override
public void dispose() {
Disposables.disposeOf(contextDestroyer);
VisUI.dispose(false);
}
public void restart() {
inputMultiplexer.clear();
dispose();
create();
}
//region Accessors
public DragDropManager getDragDropManager() { return dragDropManager; }
public InterfaceService getInterfaceService() { return interfaceService; }
public ModelService getModelService() { return modelService; }
public EventDispatcher getEventDispatcher() { return eventDispatcher; }
public MessageDispatcher getMessageDispatcher() { return messageDispatcher; }
public AppParams getParams() { return params; }
public PrioritizedInputMultiplexer getInput() { return inputMultiplexer; }
public GlobalShortcutHandler getShortcuts() { return shortcutHandler; }
public I18NBundle getI18n() { return localeService.getI18nBundle(); }
//endregion
/** This is utility component class that helps to get access to some system components for App class */
@SuppressWarnings("WeakerAccess")
private class ComponentExtractor {
@Initiate() void extractComponents(EventDispatcher eventDispatcher, MessageDispatcher messageDispatcher) {
App.this.eventDispatcher = eventDispatcher;
App.this.messageDispatcher = messageDispatcher;
}
}
} |
package com.onelogin.saml2.util;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.security.GeneralSecurityException;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Key;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.SignatureException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Calendar;
import java.util.Iterator;
import java.util.Locale;
import java.util.TimeZone;
import java.util.UUID;
import java.util.zip.Deflater;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.Inflater;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.xml.namespace.NamespaceContext;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;
import javax.xml.validation.Schema;
import javax.xml.validation.Validator;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import javax.xml.XMLConstants;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.xml.security.encryption.EncryptedData;
import org.apache.xml.security.encryption.EncryptedKey;
import org.apache.xml.security.encryption.XMLCipher;
import org.apache.xml.security.exceptions.XMLSecurityException;
import org.apache.xml.security.keys.KeyInfo;
import org.apache.xml.security.signature.XMLSignature;
import org.apache.xml.security.transforms.Transforms;
import org.apache.xml.security.utils.XMLUtils;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.Period;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISOPeriodFormat;
import org.joda.time.format.PeriodFormatter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import com.onelogin.saml2.exception.ValidationError;
import com.onelogin.saml2.exception.XMLEntityException;
/**
* Util class of OneLogin's Java Toolkit.
*
* A class that contains several auxiliary methods related to the SAML protocol
*/
public final class Util {
/**
* Private property to construct a logger for this class.
*/
private static final Logger LOGGER = LoggerFactory.getLogger(Util.class);
private static final DateTimeFormatter DATE_TIME_FORMAT = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss'Z'").withZone(DateTimeZone.UTC);
private static final DateTimeFormatter DATE_TIME_FORMAT_MILLS = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(DateTimeZone.UTC);
public static final String UNIQUE_ID_PREFIX = "ONELOGIN_";
public static final String RESPONSE_SIGNATURE_XPATH = "/samlp:Response/ds:Signature";
public static final String ASSERTION_SIGNATURE_XPATH = "/samlp:Response/saml:Assertion/ds:Signature";
private Util() {
//not called
}
/**
* This function load an XML string in a save way. Prevent XEE/XXE Attacks
*
* @param xml
* String. The XML string to be loaded.
*
* @return The result of load the XML at the Document or null if any error occurs
*/
public static Document loadXML(String xml) {
try {
if (xml.contains("<!ENTITY")) {
throw new XMLEntityException("Detected use of ENTITY in XML, disabled to prevent XXE/XEE attacks");
}
return convertStringToDocument(xml);
} catch (XMLEntityException e) {
LOGGER.debug("Load XML error due XMLEntityException.", e);
} catch (Exception e) {
LOGGER.debug("Load XML error: " + e.getMessage(), e);
}
return null;
}
/**
* Extracts a node from the DOMDocument
*
* @param dom
* The DOMDocument
* @param query
* Xpath Expression
* @param context
* Context Node (DomElement)
*
* @return DOMNodeList The queried node
*
* @throws XPathExpressionException
*/
public static NodeList query(Document dom, String query, Node context) throws XPathExpressionException {
NodeList nodeList;
XPath xpath = XPathFactory.newInstance().newXPath();
xpath.setNamespaceContext(new NamespaceContext() {
@Override
public String getNamespaceURI(String prefix) {
String result = null;
if (prefix.equals("samlp") || prefix.equals("samlp2")) {
result = Constants.NS_SAMLP;
} else if (prefix.equals("saml") || prefix.equals("saml2")) {
result = Constants.NS_SAML;
} else if (prefix.equals("ds")) {
result = Constants.NS_DS;
} else if (prefix.equals("xenc")) {
result = Constants.NS_XENC;
} else if (prefix.equals("md")) {
result = Constants.NS_MD;
}
return result;
}
@Override
public String getPrefix(String namespaceURI) {
return null;
}
@SuppressWarnings("rawtypes")
@Override
public Iterator getPrefixes(String namespaceURI) {
return null;
}
});
if (context == null) {
nodeList = (NodeList) xpath.evaluate(query, dom, XPathConstants.NODESET);
} else {
nodeList = (NodeList) xpath.evaluate(query, context, XPathConstants.NODESET);
}
return nodeList;
}
/**
* Extracts a node from the DOMDocument
*
* @param dom
* The DOMDocument
* @param query
* Xpath Expression
*
* @return DOMNodeList The queried node
*
* @throws XPathExpressionException
*/
public static NodeList query(Document dom, String query) throws XPathExpressionException {
return query(dom, query, null);
}
/**
* This function attempts to validate an XML against the specified schema.
*
* @param xmlDocument
* The XML document which should be validated
* @param schemaUrl
* The schema filename which should be used
*
* @return found errors after validation
*/
public static boolean validateXML(Document xmlDocument, URL schemaUrl) {
try {
if (xmlDocument == null) {
throw new IllegalArgumentException("xmlDocument was null");
}
Schema schema = SchemaFactory.loadFromUrl(schemaUrl);
Validator validator = schema.newValidator();
// Prevent XXE attacks
validator.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, "");
validator.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
XMLErrorAccumulatorHandler errorAcumulator = new XMLErrorAccumulatorHandler();
validator.setErrorHandler(errorAcumulator);
Source xmlSource = new DOMSource(xmlDocument);
validator.validate(xmlSource);
final boolean isValid = !errorAcumulator.hasError();
if (!isValid) {
LOGGER.warn("Errors found when validating SAML response with schema: " + errorAcumulator.getErrorXML());
}
return isValid;
} catch (Exception e) {
LOGGER.warn("Error executing validateXML: " + e.getMessage(), e);
return false;
}
}
/**
* Converts an XML in string format in a Document object
*
* @param xmlStr
* The XML string which should be converted
*
* @return the Document object
*
* @throws ParserConfigurationException
* @throws SAXException
* @throws IOException
*/
public static Document convertStringToDocument(String xmlStr) throws ParserConfigurationException, SAXException, IOException {
DocumentBuilderFactory docfactory = DocumentBuilderFactory.newInstance();
docfactory.setNamespaceAware(true);
// do not expand entity reference nodes
docfactory.setExpandEntityReferences(false);
docfactory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage", XMLConstants.W3C_XML_SCHEMA_NS_URI);
// Add various options explicitly to prevent XXE attacks.
// (adding try/catch around every setAttribute just in case a specific parser does not support it.
try {
// do not include external general entities
docfactory.setAttribute("http://xml.org/sax/features/external-general-entities", Boolean.FALSE);
} catch (Exception e) {}
try {
// do not include external parameter entities or the external DTD subset
docfactory.setAttribute("http://xml.org/sax/features/external-parameter-entities", Boolean.FALSE);
} catch (Exception e) {}
try {
docfactory.setAttribute("http://apache.org/xml/features/disallow-doctype-decl", Boolean.TRUE);
} catch (Exception e) {}
try {
docfactory.setAttribute("http://javax.xml.XMLConstants/feature/secure-processing", Boolean.TRUE);
} catch (Exception e) {}
try {
// ignore the external DTD completely
docfactory.setAttribute("http://apache.org/xml/features/nonvalidating/load-external-dtd", Boolean.FALSE);
} catch (Exception e) {}
try {
// build the grammar but do not use the default attributes and attribute types information it contains
docfactory.setAttribute("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", Boolean.FALSE);
} catch (Exception e) {}
try {
docfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
} catch (Exception e) {}
DocumentBuilder builder = docfactory.newDocumentBuilder();
Document doc = builder.parse(new InputSource(new StringReader(xmlStr)));
// Loop through the doc and tag every element with an ID attribute
// as an XML ID node.
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expr;
try {
/**
* Converts an XML in Document format in a String
*
* @param doc
* The Document object
* @param c14n
* If c14n transformation should be applied
*
* @return the Document object
*/
public static String convertDocumentToString(Document doc, Boolean c14n) {
org.apache.xml.security.Init.init();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (c14n) {
XMLUtils.outputDOMc14nWithComments(doc, baos);
} else {
XMLUtils.outputDOM(doc, baos);
}
return Util.toUtf8String(baos.toByteArray());
}
private static String toUtf8String(byte[] bytes) {
try {
return new String(bytes, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException(e);
}
}
/**
* Converts an XML in Document format in a String without applying the c14n transformation
*
* @param doc
* The Document object
*
* @return the Document object
*/
public static String convertDocumentToString(Document doc) {
return convertDocumentToString(doc, false);
}
/**
* Returns a certificate in String format (adding header and footer if required)
*
* @param cert
* A x509 unformatted cert
* @param heads
* True if we want to include head and footer
*
* @return X509Certificate $x509 Formated cert
*/
public static String formatCert(String cert, Boolean heads) {
String x509cert = StringUtils.EMPTY;
if (cert != null) {
x509cert = cert.replace("\\x0D", "").replace("\r", "").replace("\n", "").replace(" ", "");
if (!StringUtils.isEmpty(x509cert)) {
x509cert = x509cert.replace("
if (heads) {
x509cert = "
}
}
}
return x509cert;
}
/**
* Returns a private key (adding header and footer if required).
*
* @param key
* A private key
* @param heads
* True if we want to include head and footer
*
* @return Formated private key
*/
public static String formatPrivateKey(String key, boolean heads) {
String xKey = StringUtils.EMPTY;
if (key != null) {
xKey = key.replace("\\x0D", "").replace("\r", "").replace("\n", "").replace(" ", "");
if (!StringUtils.isEmpty(xKey)) {
if (xKey.startsWith("
xKey = xKey.replace("
if (heads) {
xKey = "
}
} else {
xKey = xKey.replace("
if (heads) {
xKey = "
}
}
}
}
return xKey;
}
/**
* chunk a string
*
* @param str
* The string to be chunked
* @param chunkSize
* The chunk size
*
* @return the chunked string
*/
private static String chunkString(String str, int chunkSize) {
String newStr = StringUtils.EMPTY;
int stringLength = str.length();
for (int i = 0; i < stringLength; i += chunkSize) {
if (i + chunkSize > stringLength) {
chunkSize = stringLength - i;
}
newStr += str.substring(i, chunkSize + i) + '\n';
}
return newStr;
}
/**
* Load X.509 certificate
*
* @param certString
* certificate in string format
*
* @return Loaded Certificate. X509Certificate object
*
* @throws UnsupportedEncodingException
* @throws CertificateException
*
*/
public static X509Certificate loadCert(String certString) throws CertificateException, UnsupportedEncodingException {
certString = formatCert(certString, true);
X509Certificate cert;
try {
cert = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(
new ByteArrayInputStream(certString.getBytes("utf-8")));
} catch (IllegalArgumentException e){
cert = null;
}
return cert;
}
/**
* Load private key
*
* @param keyString
* private key in string format
*
* @return Loaded private key. PrivateKey object
*
* @throws GeneralSecurityException
* @throws IOException
*/
public static PrivateKey loadPrivateKey(String keyString) throws GeneralSecurityException, IOException {
org.apache.xml.security.Init.init();
keyString = formatPrivateKey(keyString, false);
keyString = chunkString(keyString, 64);
KeyFactory kf = KeyFactory.getInstance("RSA");
PrivateKey privKey;
try {
byte[] encoded = Base64.decodeBase64(keyString);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded);
privKey = (PrivateKey) kf.generatePrivate(keySpec);
}
catch(IllegalArgumentException e) {
privKey = null;
}
return privKey;
}
/**
* Calculates the fingerprint of a x509cert
*
* @param x509cert
* x509 certificate
* @param alg
* Digest Algorithm
*
* @return the formated fingerprint
*/
public static String calculateX509Fingerprint(X509Certificate x509cert, String alg) {
String fingerprint = StringUtils.EMPTY;
try {
byte[] dataBytes = x509cert.getEncoded();
if (alg == null || alg.isEmpty() || alg.equals("SHA-1")|| alg.equals("sha1")) {
fingerprint = DigestUtils.sha1Hex(dataBytes);
} else if (alg.equals("SHA-256") || alg .equals("sha256")) {
fingerprint = DigestUtils.sha256Hex(dataBytes);
} else if (alg.equals("SHA-384") || alg .equals("sha384")) {
fingerprint = DigestUtils.sha384Hex(dataBytes);
} else if (alg.equals("SHA-512") || alg.equals("sha512")) {
fingerprint = DigestUtils.sha512Hex(dataBytes);
} else {
LOGGER.debug("Error executing calculateX509Fingerprint. alg " + alg + " not supported");
}
} catch (Exception e) {
LOGGER.debug("Error executing calculateX509Fingerprint: "+ e.getMessage(), e);
}
return fingerprint.toLowerCase();
}
/**
* Calculates the SHA-1 fingerprint of a x509cert
*
* @param x509cert
* x509 certificate
*
* @return the SHA-1 formated fingerprint
*/
public static String calculateX509Fingerprint(X509Certificate x509cert) {
return calculateX509Fingerprint(x509cert, "SHA-1");
}
/**
* Converts an X509Certificate in a well formated PEM string
*
* @param certificate
* The public certificate
*
* @return the formated PEM string
*/
public static String convertToPem(X509Certificate certificate) {
String pemCert = "";
try {
Base64 encoder = new Base64(64);
String cert_begin = "
String end_cert = "
byte[] derCert = certificate.getEncoded();
String pemCertPre = new String(encoder.encode(derCert));
pemCert = cert_begin + pemCertPre + end_cert;
} catch (Exception e) {
LOGGER.debug("Error converting certificate on PEM format: "+ e.getMessage(), e);
}
return pemCert;
}
/**
* Loads a resource located at a relative path
*
* @param relativeResourcePath
* Relative path of the resource
*
* @return the loaded resource in String format
*
* @throws IOException
*/
public static String getFileAsString(String relativeResourcePath) throws IOException {
InputStream is = Util.class.getResourceAsStream("/" + relativeResourcePath);
if (is == null) {
throw new FileNotFoundException(relativeResourcePath);
}
try {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
copyBytes(new BufferedInputStream(is), bytes);
return bytes.toString("utf-8");
} finally {
is.close();
}
}
private static void copyBytes(InputStream is, OutputStream bytes) throws IOException {
int res = is.read();
while (res != -1) {
bytes.write(res);
res = is.read();
}
}
/**
* Returns String Base64 decoded and inflated
*
* @param input
* String input
*
* @return the base64 decoded and inflated string
*/
public static String base64decodedInflated(String input) {
// Base64 decoder
byte[] decoded = Base64.decodeBase64(input);
// Inflater
try {
Inflater decompresser = new Inflater(true);
decompresser.setInput(decoded);
byte[] result = new byte[2048];
int resultLength = decompresser.inflate(result);
decompresser.end();
String inflated = new String(result, 0, resultLength, "UTF-8");
return inflated;
} catch (Exception e) {
return new String(decoded);
}
}
/**
* Returns String Deflated and base64 encoded
*
* @param input
* String input
*
* @return the deflated and base64 encoded string
* @throws IOException
*/
public static String deflatedBase64encoded(String input) throws IOException {
// Deflater
ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
Deflater deflater = new Deflater(Deflater.DEFLATED, true);
DeflaterOutputStream deflaterStream = new DeflaterOutputStream(bytesOut, deflater);
deflaterStream.write(input.getBytes(Charset.forName("UTF-8")));
deflaterStream.finish();
// Base64 encoder
return new String(Base64.encodeBase64(bytesOut.toByteArray()));
}
/**
* Returns String base64 encoded
*
* @param input
* Stream input
*
* @return the base64 encoded string
*/
public static String base64encoder(byte [] input) {
return new String(Base64.encodeBase64(input));
}
/**
* Returns String base64 encoded
*
* @param input
* String input
*
* @return the base64 encoded string
*/
public static String base64encoder(String input) {
return base64encoder(input.getBytes());
}
/**
* Returns String base64 decoded
*
* @param input
* Stream input
*
* @return the base64 decoded bytes
*/
public static byte[] base64decoder(byte [] input) {
return Base64.decodeBase64(input);
}
/**
* Returns String base64 decoded
*
* @param input
* String input
*
* @return the base64 decoded bytes
*/
public static byte[] base64decoder(String input) {
return base64decoder(input.getBytes());
}
/**
* Returns String URL encoded
*
* @param input
* String input
*
* @return the URL encoded string
*/
public static String urlEncoder(String input) {
if (input != null) {
try {
return URLEncoder.encode(input, "UTF-8");
} catch (UnsupportedEncodingException e) {
LOGGER.error("URL encoder error.", e);
throw new IllegalArgumentException();
}
} else {
return null;
}
}
/**
* Returns String URL decoded
*
* @param input
* URL encoded input
*
* @return the URL decoded string
*/
public static String urlDecoder(String input) {
if (input != null) {
try {
return URLDecoder.decode(input, "UTF-8");
} catch (UnsupportedEncodingException e) {
LOGGER.error("URL decoder error.", e);
throw new IllegalArgumentException();
}
} else {
return null;
}
}
/**
* Generates a signature from a string
*
* @param text
* The string we should sign
* @param key
* The private key to sign the string
* @param signAlgorithm
* Signature algorithm method
*
* @return the signature
*
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
* @throws SignatureException
*/
public static byte[] sign(String text, PrivateKey key, String signAlgorithm) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException {
org.apache.xml.security.Init.init();
if (signAlgorithm == null) {
signAlgorithm = Constants.RSA_SHA1;
}
Signature instance = Signature.getInstance(signatureAlgConversion(signAlgorithm));
instance.initSign(key);
instance.update(text.getBytes());
byte[] signature = instance.sign();
return signature;
}
/**
* Converts Signature algorithm method name
*
* @param sign
* signature algorithm method
*
* @return the converted signature name
*/
public static String signatureAlgConversion(String sign) {
String convertedSignatureAlg = "";
if (sign == null) {
convertedSignatureAlg = "SHA1withRSA";
} else if (sign.equals(Constants.DSA_SHA1)) {
convertedSignatureAlg = "SHA1withDSA";
} else if (sign.equals(Constants.RSA_SHA256)) {
convertedSignatureAlg = "SHA256withRSA";
} else if (sign.equals(Constants.RSA_SHA384)) {
convertedSignatureAlg = "SHA384withRSA";
} else if (sign.equals(Constants.RSA_SHA512)) {
convertedSignatureAlg = "SHA512withRSA";
} else {
convertedSignatureAlg = "SHA1withRSA";
}
return convertedSignatureAlg;
}
/**
* Validate the signature pointed to by the xpath
*
* @param doc The document we should validate
* @param cert The public certificate
* @param fingerprint The fingerprint of the public certificate
* @param alg The signature algorithm method
* @param xpath the xpath of the ds:Signture node to validate
*
* @return True if the signature exists and is valid, false otherwise.
*/
public static boolean validateSign(final Document doc, final X509Certificate cert, final String fingerprint,
final String alg, final String xpath) {
try {
final NodeList signatures = query(doc, xpath);
return signatures.getLength() == 1 && validateSignNode(signatures.item(0), cert, fingerprint, alg);
} catch (XPathExpressionException e) {
LOGGER.warn("Failed to find signature nodes", e);
}
return false;
}
/**
* Validate signature (Metadata).
*
* @param doc
* The document we should validate
* @param cert
* The public certificate
* @param fingerprint
* The fingerprint of the public certificate
* @param alg
* The signature algorithm method
*
* @return True if the sign is valid, false otherwise.
*/
public static Boolean validateMetadataSign(Document doc, X509Certificate cert, String fingerprint, String alg) {
NodeList signNodesToValidate;
try {
signNodesToValidate = query(doc, "/md:EntitiesDescriptor/ds:Signature");
if (signNodesToValidate.getLength() == 0) {
signNodesToValidate = query(doc, "/md:EntityDescriptor/ds:Signature");
if (signNodesToValidate.getLength() == 0) {
signNodesToValidate = query(doc, "/md:EntityDescriptor/md:SPSSODescriptor/ds:Signature|/md:EntityDescriptor/IDPSSODescriptor/ds:Signature");
}
}
if (signNodesToValidate.getLength() > 0) {
for (int i = 0; i < signNodesToValidate.getLength(); i++) {
Node signNode = signNodesToValidate.item(i);
if (!validateSignNode(signNode, cert, fingerprint, alg)) {
return false;
}
}
return true;
}
} catch (XPathExpressionException e) {
LOGGER.warn("Failed to find signature nodes", e);
}
return false;
}
/**
* Validate signature of the Node.
*
* @param signNode
* The document we should validate
* @param cert
* The public certificate
* @param fingerprint
* The fingerprint of the public certificate
* @param alg
* The signature algorithm method
*
* @return True if the sign is valid, false otherwise.
*/
public static Boolean validateSignNode(Node signNode, X509Certificate cert, String fingerprint, String alg) {
Boolean res = false;
try {
org.apache.xml.security.Init.init();
Element sigElement = (Element) signNode;
XMLSignature signature = new XMLSignature(sigElement, "", true);
if (cert != null) {
res = signature.checkSignatureValue(cert);
} else {
KeyInfo keyInfo = signature.getKeyInfo();
if (keyInfo != null && keyInfo.containsX509Data()) {
X509Certificate providedCert = keyInfo.getX509Certificate();
if (fingerprint.equals(calculateX509Fingerprint(providedCert, alg))) {
res = signature.checkSignatureValue(providedCert);
}
}
}
} catch (Exception e) {
LOGGER.warn("Error executing validateSignNode: " + e.getMessage(), e);
}
return res;
}
/**
* Decrypt an encrypted element.
*
* @param encryptedDataElement
* The encrypted element.
* @param inputKey
* The private key to decrypt.
*/
public static void decryptElement(Element encryptedDataElement, PrivateKey inputKey) {
try {
org.apache.xml.security.Init.init();
XMLCipher xmlCipher = XMLCipher.getInstance();
xmlCipher.init(XMLCipher.DECRYPT_MODE, null);
/* Check if we have encryptedData with a KeyInfo that contains a RetrievalMethod to obtain the EncryptedKey.
xmlCipher is not able to handle that so we move the EncryptedKey inside the KeyInfo element and
replacing the RetrievalMethod.
*/
NodeList keyInfoInEncData = encryptedDataElement.getElementsByTagNameNS(Constants.NS_DS, "KeyInfo");
if (keyInfoInEncData.getLength() == 0) {
throw new ValidationError("No KeyInfo inside EncryptedData element", ValidationError.KEYINFO_NOT_FOUND_IN_ENCRYPTED_DATA);
}
NodeList childs = keyInfoInEncData.item(0).getChildNodes();
for (int i=0; i < childs.getLength(); i++) {
if (childs.item(i).getLocalName() != null && childs.item(i).getLocalName().equals("RetrievalMethod")) {
Element retrievalMethodElem = (Element)childs.item(i);
if (!retrievalMethodElem.getAttribute("Type").equals("http://www.w3.org/2001/04/xmlenc#EncryptedKey")) {
throw new ValidationError("Unsupported Retrieval Method found", ValidationError.UNSUPPORTED_RETRIEVAL_METHOD);
}
String uri = retrievalMethodElem.getAttribute("URI").substring(1);
NodeList encryptedKeyNodes = ((Element) encryptedDataElement.getParentNode()).getElementsByTagNameNS(Constants.NS_XENC, "EncryptedKey");
for (int j=0; j < encryptedKeyNodes.getLength(); j++) {
if (((Element)encryptedKeyNodes.item(j)).getAttribute("Id").equals(uri)) {
keyInfoInEncData.item(0).replaceChild(encryptedKeyNodes.item(j), childs.item(i));
}
}
}
}
xmlCipher.setKEK(inputKey);
xmlCipher.doFinal(encryptedDataElement.getOwnerDocument(), encryptedDataElement, false);
} catch (Exception e) {
LOGGER.warn("Error executing decryption: " + e.getMessage(), e);
}
}
/**
* Clone a Document object.
*
* @param source
* The Document object to be cloned.
*
* @return the clone of the Document object
*
* @throws ParserConfigurationException
*/
public static Document copyDocument(Document source) throws ParserConfigurationException
{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
Node originalRoot = source.getDocumentElement();
Document copiedDocument = db.newDocument();
Node copiedRoot = copiedDocument.importNode(originalRoot, true);
copiedDocument.appendChild(copiedRoot);
return copiedDocument;
}
/**
* Signs the Document using the specified signature algorithm with the private key and the public certificate.
*
* @param document
* The document to be signed
* @param key
* The private key
* @param certificate
* The public certificate
* @param signAlgorithm
* Signature Algorithm
*
* @return the signed document in string format
*
* @throws XMLSecurityException
* @throws XPathExpressionException
*/
public static String addSign(Document document, PrivateKey key, X509Certificate certificate, String signAlgorithm) throws XMLSecurityException, XPathExpressionException {
org.apache.xml.security.Init.init();
// Check arguments.
if (document == null) {
throw new IllegalArgumentException("Provided document was null");
}
if (document.getDocumentElement() == null) {
throw new IllegalArgumentException("The Xml Document has no root element.");
}
if (key == null) {
throw new IllegalArgumentException("Provided key was null");
}
if (certificate == null) {
throw new IllegalArgumentException("Provided certificate was null");
}
if (signAlgorithm == null || signAlgorithm.isEmpty()) {
signAlgorithm = Constants.RSA_SHA1;
}
// document.normalizeDocument();
String c14nMethod = Constants.C14N_WC;
// Signature object
XMLSignature sig = new XMLSignature(document, null, signAlgorithm, c14nMethod);
// Including the signature into the document before sign, because
// this is an envelop signature
Element root = document.getDocumentElement();
document.setXmlStandalone(false);
// If Issuer, locate Signature after Issuer, Otherwise as first child.
NodeList issuerNodes = Util.query(document, "//saml:Issuer", null);
if (issuerNodes.getLength() > 0) {
Node issuer = issuerNodes.item(0);
root.insertBefore(sig.getElement(), issuer.getNextSibling());
} else {
root.insertBefore(sig.getElement(), root.getFirstChild());
}
String id = root.getAttribute("ID");
String reference = id;
if (!id.isEmpty()) {
root.setIdAttributeNS(null, "ID", true);
reference = "
}
// Create the transform for the document
Transforms transforms = new Transforms(document);
transforms.addTransform(Constants.ENVSIG);
//transforms.addTransform(Transforms.TRANSFORM_C14N_OMIT_COMMENTS);
transforms.addTransform(c14nMethod);
sig.addDocument(reference, transforms, Constants.SHA1);
// Add the certification info
sig.addKeyInfo(certificate);
// Sign the document
sig.sign(key);
return convertDocumentToString(document, true);
}
/**
* Signs a Node using the specified signature algorithm with the private key and the public certificate.
*
* @param node
* The Node to be signed
* @param key
* The private key
* @param certificate
* The public certificate
* @param signAlgorithm
* Signature Algorithm
*
* @return the signed document in string format
*
* @throws ParserConfigurationException
* @throws XMLSecurityException
* @throws XPathExpressionException
*/
public static String addSign(Node node, PrivateKey key, X509Certificate certificate, String signAlgorithm) throws ParserConfigurationException, XPathExpressionException, XMLSecurityException {
// Check arguments.
if (node == null) {
throw new IllegalArgumentException("Provided node was null");
}
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
Document doc = dbf.newDocumentBuilder().newDocument();
Node newNode = doc.importNode(node, true);
doc.appendChild(newNode);
return addSign(doc, key, certificate, signAlgorithm);
}
/**
* Validates signed binary data (Used to validate GET Signature).
*
* @param signedQuery
* The element we should validate
* @param signature
* The signature that will be validate
* @param cert
* The public certificate
* @param signAlg
* Signature Algorithm
*
* @return the signed document in string format
*
* @throws NoSuchAlgorithmException
* @throws NoSuchProviderException
* @throws InvalidKeyException
* @throws SignatureException
*/
public static Boolean validateBinarySignature(String signedQuery, byte[] signature, X509Certificate cert, String signAlg) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, SignatureException {
Boolean valid = false;
try {
org.apache.xml.security.Init.init();
String convertedSigAlg = signatureAlgConversion(signAlg);
Signature sig = Signature.getInstance(convertedSigAlg); //, provider);
sig.initVerify(cert.getPublicKey());
sig.update(signedQuery.getBytes());
valid = sig.verify(signature);
} catch (Exception e) {
LOGGER.warn("Error executing validateSign: " + e.getMessage(), e);
}
return valid;
}
/**
* Generates a nameID.
*
* @param value
* The value
* @param spnq
* SP Name Qualifier
* @param format
* SP Format
* @param cert
* IdP Public certificate to encrypt the nameID
*
* @return Xml contained in the document.
*/
public static String generateNameId(String value, String spnq, String format, X509Certificate cert) {
String res = null;
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
Document doc = dbf.newDocumentBuilder().newDocument();
Element nameId = doc.createElement("saml:NameID");
if (spnq != null && !spnq.isEmpty()) {
nameId.setAttribute("SPNameQualifier", spnq);
}
if (format != null && !format.isEmpty()) {
nameId.setAttribute("Format", format);
}
nameId.appendChild(doc.createTextNode(value));
doc.appendChild(nameId);
if (cert != null) {
// We generate a symmetric key
Key symmetricKey = generateSymmetricKey();
// cipher for encrypt the data
XMLCipher xmlCipher = XMLCipher.getInstance(Constants.AES128_CBC);
xmlCipher.init(XMLCipher.ENCRYPT_MODE, symmetricKey);
// cipher for encrypt the symmetric key
XMLCipher keyCipher = XMLCipher.getInstance(Constants.RSA_1_5);
keyCipher.init(XMLCipher.WRAP_MODE, cert.getPublicKey());
// encrypt the symmetric key
EncryptedKey encryptedKey = keyCipher.encryptKey(doc, symmetricKey);
// Add keyinfo inside the encrypted data
EncryptedData encryptedData = xmlCipher.getEncryptedData();
KeyInfo keyInfo = new KeyInfo(doc);
keyInfo.add(encryptedKey);
encryptedData.setKeyInfo(keyInfo);
// Encrypt the actual data
xmlCipher.doFinal(doc, nameId, false);
// Building the result
res = "<saml:EncryptedID>" + convertDocumentToString(doc) + "</saml:EncryptedID>";
} else {
res = convertDocumentToString(doc);
}
} catch (Exception e) {
LOGGER.error("Error executing generateNameId: " + e.getMessage(), e);
}
return res;
}
/**
* Generates a nameID.
*
* @param value
* The value
* @param spnq
* SP Name Qualifier
* @param format
* SP Format
*
* @return Xml contained in the document.
*/
public static String generateNameId(String value, String spnq, String format) {
return generateNameId(value, spnq, format, null);
}
/**
* Method to generate a symmetric key for encryption
*
* @return the symmetric key
*
* @throws Exception
*/
private static SecretKey generateSymmetricKey() throws Exception {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(128);
return keyGenerator.generateKey();
}
/**
* Generates a unique string (used for example as ID of assertions)
*
* @return A unique string
*/
public static String generateUniqueID() {
return UNIQUE_ID_PREFIX + UUID.randomUUID();
}
public static long parseDuration(String duration) throws IllegalArgumentException {
TimeZone timeZone = DateTimeZone.UTC.toTimeZone();
return parseDuration(duration, Calendar.getInstance(timeZone).getTimeInMillis() / 1000);
}
public static long parseDuration(String durationString, long timestamp) throws IllegalArgumentException {
boolean haveMinus = false;
if (durationString.startsWith("-")) {
durationString = durationString.substring(1);
haveMinus = true;
}
PeriodFormatter periodFormatter = ISOPeriodFormat.standard().withLocale(new Locale("UTC"));
Period period = periodFormatter.parsePeriod(durationString);
DateTime dt = new DateTime(timestamp * 1000, DateTimeZone.UTC);
DateTime result = null;
if (haveMinus) {
result = dt.minus(period);
} else {
result = dt.plus(period);
}
return result.getMillis() / 1000;
}
/**
* @return the unix timestamp that matches the current time.
*/
public static Long getCurrentTimeStamp() {
DateTime currentDate = new DateTime(DateTimeZone.UTC);
return currentDate.getMillis() / 1000;
}
/**
* Compare 2 dates and return the the earliest
*
* @param cacheDuration
* The duration, as a string.
* @param validUntil
* The valid until date, as a string
*
* @return the expiration time (timestamp format).
*/
public static long getExpireTime(String cacheDuration, String validUntil) {
long expireTime = 0;
try {
if (cacheDuration != null && !StringUtils.isEmpty(cacheDuration)) {
expireTime = parseDuration(cacheDuration);
}
if (validUntil != null && !StringUtils.isEmpty(validUntil)) {
DateTime dt = Util.parseDateTime(validUntil);
long validUntilTimeInt = dt.getMillis() / 1000;
if (expireTime == 0 || expireTime > validUntilTimeInt) {
expireTime = validUntilTimeInt;
}
}
} catch (Exception e) {
LOGGER.error("Error executing getExpireTime: " + e.getMessage(), e);
}
return expireTime;
}
/**
* Compare 2 dates and return the the earliest
*
* @param cacheDuration
* The duration, as a string.
* @param validUntil
* The valid until date, as a timestamp
*
* @return the expiration time (timestamp format).
*/
public static long getExpireTime(String cacheDuration, long validUntil) {
long expireTime = 0;
try {
if (cacheDuration != null && !StringUtils.isEmpty(cacheDuration)) {
expireTime = parseDuration(cacheDuration);
}
if (expireTime == 0 || expireTime > validUntil) {
expireTime = validUntil;
}
} catch (Exception e) {
LOGGER.error("Error executing getExpireTime: " + e.getMessage(), e);
}
return expireTime;
}
/**
* Create string form time In Millis with format yyyy-MM-ddTHH:mm:ssZ
*
* @param timeInMillis
* The time in Millis
*
* @return string with format yyyy-MM-ddTHH:mm:ssZ
*/
public static String formatDateTime(long timeInMillis) {
return DATE_TIME_FORMAT.print(timeInMillis);
}
/**
* Create string form time In Millis with format yyyy-MM-ddTHH:mm:ssZ
*
* @param time
* The time
* @param millis
* Defines if the time is in Millis
*
* @return string with format yyyy-MM-ddTHH:mm:ssZ
*/
public static String formatDateTime(long time, boolean millis) {
if (millis) {
return DATE_TIME_FORMAT_MILLS.print(time);
} else {
return formatDateTime(time);
}
}
/**
* Create calendar form string with format yyyy-MM-ddTHH:mm:ssZ // yyyy-MM-ddTHH:mm:ss.SSSZ
*
* @param dateTime
* string with format yyyy-MM-ddTHH:mm:ssZ // yyyy-MM-ddTHH:mm:ss.SSSZ
*
* @return datetime
*/
public static DateTime parseDateTime(String dateTime) {
DateTime parsedData = null;
try {
parsedData = DATE_TIME_FORMAT.parseDateTime(dateTime);
} catch(Exception e) {
return DATE_TIME_FORMAT_MILLS.parseDateTime(dateTime);
}
return parsedData;
}
} |
package hudson.tasks;
import hudson.FilePath;
import hudson.Launcher;
import hudson.Util;
import hudson.Extension;
import hudson.EnvVars;
import hudson.model.*;
import hudson.util.FormValidation;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.AncestorInPath;
import javax.servlet.ServletException;
import java.io.File;
import java.io.IOException;
/**
* Saves Javadoc for the project and publish them.
*
* @author Kohsuke Kawaguchi
*/
public class JavadocArchiver extends Recorder {
/**
* Path to the Javadoc directory in the workspace.
*/
private final String javadocDir;
/**
* If true, retain javadoc for all the successful builds.
*/
private final boolean keepAll;
@DataBoundConstructor
public JavadocArchiver(String javadoc_dir, boolean keep_all) {
this.javadocDir = javadoc_dir;
this.keepAll = keep_all;
}
public String getJavadocDir() {
return javadocDir;
}
public boolean isKeepAll() {
return keepAll;
}
/**
* Gets the directory where the Javadoc is stored for the given project.
*/
private static File getJavadocDir(AbstractItem project) {
return new File(project.getRootDir(),"javadoc");
}
/**
* Gets the directory where the Javadoc is stored for the given build.
*/
private static File getJavadocDir(Run run) {
return new File(run.getRootDir(),"javadoc");
}
public boolean perform(AbstractBuild<?,?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
listener.getLogger().println(Messages.JavadocArchiver_Publishing());
EnvVars env = build.getEnvironment(listener);
FilePath javadoc = build.getWorkspace().child(env.expand(javadocDir));
FilePath target = new FilePath(keepAll ? getJavadocDir(build) : getJavadocDir(build.getProject()));
try {
if (javadoc.copyRecursiveTo("**/*",target)==0) {
if(build.getResult().isBetterOrEqualTo(Result.UNSTABLE)) {
// If the build failed, don't complain that there was no javadoc.
// The build probably didn't even get to the point where it produces javadoc.
listener.error(Messages.JavadocArchiver_NoMatchFound(javadoc,javadoc.validateAntFileMask("**/*")));
}
build.setResult(Result.FAILURE);
return true;
}
} catch (IOException e) {
Util.displayIOException(e,listener);
e.printStackTrace(listener.fatalError(Messages.JavadocArchiver_UnableToCopy(javadoc,target)));
build.setResult(Result.FAILURE);
return true;
}
// add build action, if javadoc is recorded for each build
if(keepAll)
build.addAction(new JavadocBuildAction(build));
return true;
}
@Override
public Action getProjectAction(AbstractProject project) {
return new JavadocAction(project);
}
public BuildStepMonitor getRequiredMonitorService() {
return BuildStepMonitor.NONE;
}
protected static abstract class BaseJavadocAction implements Action {
public String getUrlName() {
return "javadoc";
}
public String getDisplayName() {
if (new File(dir(), "help-doc.html").exists())
return Messages.JavadocArchiver_DisplayName_Javadoc();
else
return Messages.JavadocArchiver_DisplayName_Generic();
}
public String getIconFileName() {
if(dir().exists())
return "help.gif";
else
// hide it since we don't have javadoc yet.
return null;
}
/**
* Serves javadoc.
*/
public void doDynamic(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
new DirectoryBrowserSupport(this, new FilePath(dir()), getTitle(), "help.gif", false).generateResponse(req,rsp,this);
}
protected abstract String getTitle();
protected abstract File dir();
}
public static class JavadocAction extends BaseJavadocAction implements ProminentProjectAction {
private final AbstractItem project;
public JavadocAction(AbstractItem project) {
this.project = project;
}
protected File dir() {
// Would like to change AbstractItem to AbstractProject, but is
// that a backwards compatible change?
if (project instanceof AbstractProject) {
AbstractProject abstractProject = (AbstractProject) project;
Run run = abstractProject.getLastSuccessfulBuild();
if (run != null) {
File javadocDir = getJavadocDir(run);
if (javadocDir.exists())
return javadocDir;
}
}
return getJavadocDir(project);
}
protected String getTitle() {
return project.getDisplayName()+" javadoc";
}
}
public static class JavadocBuildAction extends BaseJavadocAction {
private final AbstractBuild<?,?> build;
public JavadocBuildAction(AbstractBuild<?,?> build) {
this.build = build;
}
protected String getTitle() {
return build.getDisplayName()+" javadoc";
}
protected File dir() {
return getJavadocDir(build);
}
}
@Extension
public static class DescriptorImpl extends BuildStepDescriptor<Publisher> {
public String getDisplayName() {
return Messages.JavadocArchiver_DisplayName();
}
/**
* Performs on-the-fly validation on the file mask wildcard.
*/
public FormValidation doCheck(@AncestorInPath AbstractProject project, @QueryParameter String value) throws IOException, ServletException {
FilePath ws = project.getSomeWorkspace();
return ws != null ? ws.validateRelativeDirectory(value) : FormValidation.ok();
}
public boolean isApplicable(Class<? extends AbstractProject> jobType) {
return true;
}
}
} |
package com.db.gui;
import java.awt.Component;
import java.awt.FontMetrics;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.HashMap;
import java.util.Vector;
import javax.swing.JComponent;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableColumnModel;
import com.db.event.EventObject;
import com.db.logging.LoggerManager;
/**
* This is a simple table model that can be easily extended.
*
* @author Dave Longley
* @author Mike Johnson
*/
public abstract class JComponentTableModel
extends AbstractTableModel
implements SortableTableModel, ComponentListener
{
/**
* Column names for any table model.
*/
protected String[] mColumnNames;
/**
* Column classes for any table model.
*/
protected Class[] mColumnClasses;
/**
* The row data.
*/
protected Vector mRows;
/**
* Table that is to be resized.
*/
protected JTable mResizeTable;
/**
* The old table width.
*/
protected int mOldWidth = -1;
/**
* The old table height.
*/
protected int mOldHeight = -1;
/**
* The column widths of the table.
*/
protected HashMap mColWidths;
/**
* The total preferred width of the table.
*/
protected int mTotalPrefWidth;
/**
* The column sorter for this table.
*/
protected ColumnSorter mColumnSorter;
/**
* Creates a default simple table model.
*/
public JComponentTableModel()
{
super();
mRows = new Vector();
// create the column sorter for this table
mColumnSorter = createColumnSorter();
}
/**
* Sets the row data.
*
* @param rowData the row data to use.
*/
protected void setRowData(Vector rowData)
{
mRows = rowData;
Iterator rowIndex = rowData.iterator();
while(rowIndex.hasNext())
{
Object row = rowIndex.next();
if(row instanceof ChangeReporter)
{
ChangeReporter cr = (ChangeReporter)row;
cr.getChangeDelegate().addListener(this, "stateChanged");
}
}
// resort column
getColumnSorter().resort();
}
/**
* Gets all of the rows as a vector.
*
* @return the row data as a vector.
*/
protected Vector getRowData()
{
return mRows;
}
/**
* Creates the column sorter for this model.
*
* @return the column sorter for this model.
*/
protected ColumnSorter createColumnSorter()
{
return new ColumnSorter(this);
}
/**
* Gets the column sorter for this model.
*
* @return the column sorter for this model.
*/
protected ColumnSorter getColumnSorter()
{
return mColumnSorter;
}
/**
* Gets the preferred width for components in a column.
*
* @param table the table the column is in.
* @param col the column to get the preferred width for.
* @return the preferred width for the column.
*/
protected int getPreferredColumnWidth(JTable table, int col)
{
int rval = 0;
try
{
// check actual data for preferred widths
int width = 0;
int rows = getRowCount();
for(int i = 0; i < rows; i++)
{
Object obj = getValueAt(i, col);
if(obj instanceof JComponent)
{
JComponent component = (JComponent)obj;
width = component.getPreferredSize().width;
}
else
{
FontMetrics fm = table.getFontMetrics(table.getFont());
width = fm.stringWidth(obj.toString());
}
if(width > rval)
{
rval = width;
}
}
// check column classes for preferred widths
if(col < mColumnClasses.length)
{
Class c = mColumnClasses[col];
Object obj = c.newInstance();
if(obj instanceof JComponent)
{
JComponent component = (JComponent)obj;
width = component.getPreferredSize().width;
}
else
{
FontMetrics fm = table.getFontMetrics(table.getFont());
width = fm.stringWidth(obj.toString());
}
if(width > rval)
{
rval = width;
}
}
}
catch(Throwable t)
{
//LoggerManager.debug("dbgui", LoggerManager.getStackTrace(t));
}
LoggerManager.getLogger("dbdata").debug(getClass(),
"col=" + col + ",preferred width=" + rval);
return rval;
}
/**
* Sets the column names for this model.
*
* @param colNames the column names for this model.
*/
public void setColumnNames(String[] colNames)
{
mColumnNames = colNames;
}
/**
* Gets the column names for this model.
*
* @return the column names for this model.
*/
public String[] getColumnNames()
{
return mColumnNames;
}
/**
* Gets a column name.
*
* @param column the column index.
* @return the name of the column.
*/
public String getColumnName(int column)
{
String colName = "NONE";
if(column >= 0 && column < getColumnCount())
{
colName = mColumnNames[column];
}
return colName;
}
/**
* Sets the column classes for this model.
*
* @param colClasses the column classes for this model.
*/
public void setColumnClasses(Class[] colClasses)
{
mColumnClasses = colClasses;
}
/**
* Gets the column classes for this model.
*
* @return the column classes for this model.
*/
public Class[] getColumnClasses()
{
return mColumnClasses;
}
/**
* Gets the column class for a column.
*
* @param column the column index.
* @return the class for the column.
*/
public Class getColumnClass(int column)
{
Class c = Object.class;
if(column >= 0 && column < mColumnClasses.length)
{
c = mColumnClasses[column];
}
return c;
}
/**
* Allows cells to be edited so that components can be inserted
* into the table.
*
* @param row the row of the cell.
* @param column the column of the cell.
* @return return true if the class is JComponent for the cell.
*/
public boolean isCellEditable(int row, int column)
{
boolean rval = false;
if(getColumnClass(column) == JComponent.class)
{
rval = true;
}
return rval;
}
/**
* Returns the column count for this model.
*
* @return the column count for this model.
*/
public int getColumnCount()
{
return mColumnClasses.length;
}
/**
* Sets up the table column header renderers for the table header.
*
* @param table the table to alter.
* @param header the table's header.
*/
public void setTableColumnHeaderRenderers(
JComponentTable table, JComponentTableHeader header)
{
// do nothing by default
}
/**
* Sets the preferred table dimensions for rows and columns.
*
* @param table the table to alter.
*/
public void setTableDimensions(JTable table)
{
// setup the preferred column widths
TableColumnModel tcm = table.getColumnModel();
int count = getColumnCount();
for(int i = 0; i < count; i++)
{
int width = getPreferredColumnWidth(table, i);
tcm.getColumn(i).setPreferredWidth(width);
}
}
/**
* Call this function after adding a table to a scrolling container
* if you want the table to be resized according to the parent
* container's dimensions.
*
* @param table the table you want to modify.
* @param on true if you want to turn column resizing on, false if not.
*/
public void setScrollResizingOn(JTable table, boolean on)
{
Component parent = table.getParent();
if(on)
{
if(parent != null)
{
mResizeTable = table;
parent.getParent().addComponentListener(this);
mColWidths = new HashMap();
mTotalPrefWidth = 0;
TableColumnModel tcm = mResizeTable.getColumnModel();
for(int i = 0; i < tcm.getColumnCount(); i++)
{
int width = tcm.getColumn(i).getPreferredWidth();
mTotalPrefWidth += width;
mColWidths.put(new Integer(i), new Integer(width));
}
}
}
else if(parent != null)
{
mResizeTable = null;
parent.getParent().removeComponentListener(this);
}
}
/**
* Notifies all listeners that a value has been updated.
*
* @param obj the value that has been updated.
*/
public void fireTableValueUpdated(Object obj)
{
int row = getRow(obj);
if(row != -1)
{
fireTableRowsUpdated(row, row);
}
}
/**
* Inserts an object at the given row.
*
* @param obj the object to insert.
* @param row the row to insert at.
*/
public void insertValueAt(Object obj, int row)
{
mRows.insertElementAt(obj, row);
if(obj instanceof ChangeReporter)
{
ChangeReporter cr = (ChangeReporter)obj;
cr.getChangeDelegate().addListener(this, "stateChanged");
}
fireTableRowsInserted(row, row);
}
/**
* Sets the object at a certain row.
*
* @param obj the object to insert.
* @param row the row to set.
*/
public void setValueAt(Object obj, int row)
{
if(row < mRows.size())
{
mRows.removeElementAt(row);
fireTableRowsDeleted(row, row);
}
if(row <= mRows.size())
{
mRows.insertElementAt(obj, row);
if(obj instanceof ChangeReporter)
{
ChangeReporter cr = (ChangeReporter)obj;
cr.getChangeDelegate().addListener(this, "stateChanged");
}
fireTableRowsInserted(row, row);
}
}
/**
* Gets the object for a particular row.
*
* @param row the row to get the object for.
* @return the object retrieved or null.
*/
public synchronized Object getValueAt(int row)
{
Object obj = null;
if(mRows.size() > row)
{
obj = mRows.get(row);
}
return obj;
}
/**
* Gets the row the passed object is at.
*
* @param obj the value to look for.
* @return the row the passed object is at or -1.
*/
public int getRow(Object obj)
{
int row = -1;
Iterator i = mRows.iterator();
for(int count = 0; i.hasNext(); count++)
{
Object o = i.next();
if(o.equals(obj))
{
row = count;
break;
}
}
return row;
}
/**
* Adds a new row to the table using the passed object.
*
* @param obj the object to add.
* @return true if successfully added, false if not.
*/
public boolean addValue(Object obj)
{
boolean rval = false;
if(mRows.add(obj))
{
if(obj instanceof ChangeReporter)
{
ChangeReporter cr = (ChangeReporter)obj;
cr.getChangeDelegate().addListener(this, "stateChanged");
}
// resort column
getColumnSorter().resort();
rval = true;
fireTableDataChanged();
}
return rval;
}
/**
* Removes a row from the table where the row matches
* the object.
*
* @param obj the object to remove.
* @return true if a row was removed, false if not.
*/
public boolean removeValue(Object obj)
{
boolean rval = false;
if(mRows.remove(obj))
{
rval = true;
fireTableDataChanged();
}
return rval;
}
/**
* Removes the passed rows from the table.
*
* @param rows the rows to remove.
*/
public void removeRows(int[] rows)
{
boolean changed = false;
Vector objects = new Vector();
for(int i = 0; i < rows.length; i++)
{
objects.add(getValueAt(rows[i]));
}
Iterator i = objects.iterator();
while(i.hasNext())
{
if(mRows.remove(i.next()))
{
changed = true;
}
}
if(changed)
{
fireTableDataChanged();
}
}
/**
* Removes a row from the table.
*
* @param row the row to remove.
* @return true if a row was removed, false if not.
*/
public boolean removeRow(int row)
{
boolean rval = false;
Object obj = getValueAt(row);
rval = removeValue(obj);
return rval;
}
/**
* Gets a row from the table.
*
* Same as getValueAt(row).
*
* @param row the row to get.
*
* @return the row.
*/
public Object getRow(int row)
{
return getValueAt(row);
}
/**
* Removes all of the rows from the table.
*/
public void clear()
{
mRows.clear();
fireTableDataChanged();
}
/**
* Gets the row count for this model.
*
* @return the number of rows currently represented by this model.
*/
public int getRowCount()
{
return mRows.size();
}
/*
* Methods for component listener.
*/
public void componentHidden(ComponentEvent e) {}
public void componentMoved(ComponentEvent e) {}
public void componentShown(ComponentEvent e)
{
resizeColumns();
}
public void componentResized(ComponentEvent e)
{
resizeColumns();
}
/**
* Forces a resize of the columns. This method will only work if
* the table the model is for is in a scrollable pane and scroll
* resizing has been turned on.
*/
public void resizeColumns()
{
Component parent = mResizeTable.getParent();
// if height has changed
if(parent != null &&
(mOldWidth != parent.getWidth() || mOldHeight != parent.getHeight()))
{
mOldWidth = parent.getWidth();
mOldHeight = parent.getHeight();
TableColumnModel tcm = mResizeTable.getColumnModel();
// get the average amount to add to each column
double avg = 0;
if(mTotalPrefWidth < mOldWidth)
{
avg = ((double)(mOldWidth - mTotalPrefWidth)) /
tcm.getColumnCount();
}
int add = (int)avg;
int totalWidth = 0;
int resizable = -1;
for(int i = 0; i < tcm.getColumnCount(); i++)
{
if(tcm.getColumn(i).getResizable())
{
Integer width = (Integer)mColWidths.get(new Integer(i));
if(width != null)
{
tcm.getColumn(i).setPreferredWidth(width.intValue() + add);
totalWidth += width.intValue() + add;
}
else
{
int w = tcm.getColumn(i).getPreferredWidth();
mColWidths.put(new Integer(i), new Integer(w));
tcm.getColumn(i).setPreferredWidth(w + add);
totalWidth += w + add;
}
if(resizable == -1)
{
resizable = i;
}
}
else
{
totalWidth += tcm.getColumn(i).getPreferredWidth();
}
}
// add the remaining width to the first resizable column
if(totalWidth != mOldWidth && resizable != -1)
{
add = mOldWidth - totalWidth;
int w = tcm.getColumn(resizable).getPreferredWidth();
tcm.getColumn(resizable).setPreferredWidth(w + add);
}
}
fireTableDataChanged();
}
/**
* Called when row data changes.
*
* @param event the event identifying the row that changed.
*/
public void stateChanged(EventObject event)
{
// get the index of the changed row
int index = getRowData().indexOf(event.getData("source"));
if(index != -1)
{
// fire rows updated message
fireTableRowsUpdated(index, index);
}
}
/**
* Sorts a column.
*
* @param column the column to sort.
* @param ascending true to sort ascending, false to sort descending.
*/
public void sortColumn(int column, boolean ascending)
{
// sort the row data
getColumnSorter().sort(column, ascending);
if(getRowCount() > 0)
{
// all rows have been updated
fireTableRowsUpdated(0, getRowCount());
}
}
/**
* Compares two row objects on a column. Returns -1 if the first object
* is less than the second, 0 if they are equal, and 1 if the first
* object is greater than the second.
*
* This is the method you should overload if you want to do
* special comparisons.
*
* @param column the column to compare data in.
* @param row1 the first row.
* @param row2 the second row.
* @return -1 if the first object is less than the second, 0 if the
* first is equal to the second, and 1 if the first is greater.
*/
public int compareColumnData(int column, int row1, int row2)
{
int rval = 0;
Object obj1 = getValueAt(row1, column);
Object obj2 = getValueAt(row2, column);
if(obj1.equals(obj2))
{
rval = 0;
}
else if(obj1 instanceof Comparable)
{
Comparable c1 = (Comparable)obj1;
rval = c1.compareTo(obj2);
}
else if(obj1 instanceof Comparator)
{
Comparator c1 = (Comparator)obj1;
rval = c1.compare(obj1, obj2);
}
else if(obj1 instanceof Number)
{
Number number1 = (Number)obj1;
Number number2 = (Number)obj2;
rval = (number1.doubleValue() < number2.doubleValue()) ? -1 : 1;
}
else
{
String s1 = "" + obj1;
String s2 = "" + obj2;
rval = s1.compareTo(s2);
}
if(rval != 0)
{
rval = (rval < 0) ? -1 : 1;
}
return rval;
}
/**
* The column sorter.
*/
public class ColumnSorter implements Comparator
{
/**
* The table model being sorted.
*/
protected JComponentTableModel mTableModel;
/**
* The column to sort.
*/
protected int mColumn;
/**
* Whether or not to use ascending sorting.
*/
protected boolean mAscending;
/**
* Creates a new ColumnSorter.
*
* @param model the model to sort.
*/
public ColumnSorter(JComponentTableModel model)
{
// store model
mTableModel = model;
// column -1 by default
mColumn = -1;
// ascending by default
mAscending = true;
}
/**
* Sorts row data in a given column.
*
* @param column the column to sort according to.
* @param ascending true to sort ascending, false to sort descending.
*/
public void sort(int column, boolean ascending)
{
mColumn = column;
mAscending = ascending;
Collections.sort(mTableModel.getRowData(), this);
}
/**
* Resorts using the last sort parameters. If no column was previously
* sorted than no sorting will take place.
*/
public void resort()
{
if(mColumn != -1)
{
sort(mColumn, mAscending);
}
}
/**
* Compares two objects. Returns -1 if the first object
* is less than the second, 0 if they are equal, and 1 if the first
* object is greater than the second.
*
* @param o1 the first object to compare.
* @param o2 the second object to compare.
* @return -1 if the first object is less than the second, 0 if the
* first is equal to the second, and 1 if the first is greater.
*/
public int compare(Object o1, Object o2)
{
int rval = 0;
int index1 = getRowData().indexOf(o1);
int index2 = getRowData().indexOf(o2);
rval = mTableModel.compareColumnData(mColumn, index1, index2);
if(!mAscending)
{
// swap values
if(rval != 0)
{
rval = (rval < 0) ? 1 : -1;
}
}
return rval;
}
/**
* Gets the column that was last sorted.
*
* @return the column that was last sorted.
*/
public int getSortedColumn()
{
return mColumn;
}
}
} |
package de.triplet.simpleprovider;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import android.provider.BaseColumns;
import android.text.TextUtils;
import android.util.Log;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
public abstract class AbstractProvider extends ContentProvider {
protected final String mTag;
protected SQLiteDatabase mDatabase;
protected AbstractProvider() {
this("AbstractProvider");
}
protected AbstractProvider(String tag) {
mTag = tag;
}
@Override
public final boolean onCreate() {
SQLiteOpenHelper dbHelper = new SQLHelper(getContext());
try {
mDatabase = dbHelper.getWritableDatabase();
} catch (SQLiteException e) {
mDatabase = null;
Log.w(mTag, "Database Opening exception", e);
}
return mDatabase != null;
}
protected abstract String getAuthority();
protected String getDatabaseFileName() {
return getClass().getName().toLowerCase() + ".db";
}
/**
* Return the schema version of the database (starting at 1).<br>
* <br>
* This number is used to announce changes to the database schema. If the
* database is older, {@link #onUpgrade(SQLiteDatabase, int, int)} will be
* used to upgrade the database. If the database is newer,
* {@link #onDowngrade(SQLiteDatabase, int, int)} will be used to downgrade
* the database.
*/
protected int getSchemaVersion() {
/* Override in derived classes */
return 1;
}
@Override
public String getType(Uri uri) {
return null;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
final SelectionBuilder builder = buildBaseQuery(uri);
return builder.where(selection, selectionArgs).query(mDatabase, projection, sortOrder);
}
private final SelectionBuilder buildBaseQuery(Uri uri) {
SelectionBuilder builder = new SelectionBuilder(uri.getPathSegments().get(0));
if (uri.getPathSegments().size() == 2) {
builder.whereEquals(BaseColumns._ID, uri.getLastPathSegment());
}
return builder;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
List<String> segments = uri.getPathSegments();
if (segments.size() != 1) {
return null;
}
long rowId = mDatabase.insert(segments.get(0), null, values);
if (rowId > -1) {
getContext().getContentResolver().notifyChange(uri, null);
return Uri.withAppendedPath(uri, String.valueOf(rowId));
}
return null;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
final SelectionBuilder builder = buildBaseQuery(uri);
return builder.where(selection, selectionArgs).delete(mDatabase);
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
final SelectionBuilder builder = buildBaseQuery(uri);
return builder.where(selection, selectionArgs).update(mDatabase, values);
}
private class SQLHelper extends SQLiteOpenHelper {
public SQLHelper(Context context) {
super(context, getDatabaseFileName(), null, getSchemaVersion());
}
@Override
public void onCreate(SQLiteDatabase db) {
createTables(db);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
AbstractProvider.this.onUpgrade(db, oldVersion, newVersion);
}
@Override
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
AbstractProvider.this.onDowngrade(db, oldVersion, newVersion);
}
}
protected void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
/* Override in derived classes */
}
/**
* Called when the database needs to be downgraded. This is strictly similar
* to {@link #onUpgrade} method, but is called whenever current version is
* newer than requested one. However, this method is not abstract, so it is
* not mandatory for a customer to implement it. If not overridden, default
* implementation will reject downgrade and throws SQLiteException
* <p>
* This method executes within a transaction. If an exception is thrown, all
* changes will automatically be rolled back.
* </p>
*
* @param db The database.
* @param oldVersion The old database version.
* @param newVersion The new database version.
*/
protected void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
/* Override in derived classes */
}
private void createTables(SQLiteDatabase db) {
for (Class<?> clazz : getClass().getClasses()) {
Table table = clazz.getAnnotation(Table.class);
if (table != null) {
createTable(db, table.value(), clazz);
}
}
}
private void createTable(SQLiteDatabase db, String tableName, Class<?> tableClass) {
ArrayList<String> columns = new ArrayList<String>();
for (Field field : tableClass.getFields()) {
Column column = field.getAnnotation(Column.class);
if (column != null) {
try {
columns.add(field.get(null) + " " + column.value());
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
StringBuilder sql = new StringBuilder();
sql.append("CREATE TABLE ").append(tableName).append(" (");
sql.append(TextUtils.join(", ", columns));
sql.append(");");
db.execSQL(sql.toString());
}
} |
package donnu.zolotarev.SpaceShip.Scenes;
import android.graphics.Point;
import android.opengl.GLES20;
import android.view.KeyEvent;
import android.widget.Toast;
import donnu.zolotarev.SpaceShip.Bullets.BulletBase;
import donnu.zolotarev.SpaceShip.*;
import donnu.zolotarev.SpaceShip.Textures.TextureLoader;
import donnu.zolotarev.SpaceShip.Units.BaseUnit;
import donnu.zolotarev.SpaceShip.Units.Enemy1;
import donnu.zolotarev.SpaceShip.Units.Hero;
import donnu.zolotarev.SpaceShip.Waves.IAddedEnemy;
import donnu.zolotarev.SpaceShip.Waves.UnitWave;
import donnu.zolotarev.SpaceShip.Waves.WaveController;
import org.andengine.engine.Engine;
import org.andengine.engine.camera.hud.controls.AnalogOnScreenControl;
import org.andengine.entity.primitive.Rectangle;
import org.andengine.entity.scene.Scene;
import org.andengine.entity.scene.background.Background;
import org.andengine.entity.scene.menu.MenuScene;
import org.andengine.entity.scene.menu.item.IMenuItem;
import org.andengine.entity.scene.menu.item.SpriteMenuItem;
import org.andengine.entity.text.Text;
import org.andengine.entity.text.TextOptions;
import org.andengine.input.touch.TouchEvent;
import org.andengine.util.HorizontalAlign;
import org.andengine.util.color.Color;
import java.util.Random;
public class MainScene extends Scene implements IAddedEnemy {
private static final int MENU_RESUME = 0;
private static final int MENU_BACK_TO_MAIN = MENU_RESUME + 1;
private final Hero hero;
private static MainScene acitveScene;
private static Engine engine;
private final ObjectController enemyController;
private final ObjectController bulletController;
private final IParentScene parrentScene;
private SpaceShipActivity shipActivity;
private Text healthBar;
private MenuScene menuScene;
private AnalogOnScreenControl analogOnScreenControl;
private boolean isShowMenuScene = false;
private WaveController waveController;
private boolean isVictory = false;
public ObjectController getBulletController() {
return bulletController;
}
public MainScene(IParentScene self) {
//super();
parrentScene = self;
// BulletBase.initPool();
acitveScene = this;
shipActivity = SpaceShipActivity.getInstance();
engine = shipActivity.getEngine();
setBackground(new Background(0.9f, 0.9f, 0.9f));
createHealthBar();
hero = new Hero(new IHealthBar() {
@Override
public void updateHealthBar(int health) {
healthBar.setText(String.valueOf(health));
}
});
hero.setStartPosition(new Point(0,250));
addHeroMoveControl();
enemyController = new ObjectController<BaseUnit>();
initWave();
bulletController = new ObjectController<BulletBase>();
BulletBase.setDieListener(new IHeroDieListener() {
@Override
public void heroDie() {
shipActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(shipActivity,"ТЫ ПРОИГРАЛ!",Toast.LENGTH_SHORT).show();
acitveScene.setIgnoreUpdate(true);
bulletController.cleer();
}
});
}
});
createMenuScene();
}
@Override
protected void onManagedUpdate(float pSecondsElapsed) {
updateWave(pSecondsElapsed);
super.onManagedUpdate(pSecondsElapsed);
}
UnitWave _currentWave = null;
private void updateWave(float pSecondsElapsed) {
if (!waveController.isEmpty()){
if (_currentWave == null ){
if ( BaseUnit.getEnemiesOnMap() < 3){
_currentWave = waveController.getNextWave();
_currentWave.startWave();
// _game.changeWaveInfo(_waveIndex,_waves.length);
}
} else {
_currentWave.update(pSecondsElapsed);
if (_currentWave.isFinished()){
waveController.waveEnds();
_currentWave = null;
}
}
} else {
if (BaseUnit.getEnemiesOnMap() == 0 && !isVictory){
isVictory = true;
shipActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(shipActivity,"ТЫ выиграл!",Toast.LENGTH_SHORT).show();
// acitveScene.setIgnoreUpdate(true);
// bulletController.cleer();
}
});
}
}
}
private void initWave() {
waveController = new WaveController();
UnitWave unitWave = new UnitWave(this);
unitWave.addEnemy(0,10,1);
unitWave.addDelay(5);
unitWave.addEnemy(0,5,0.1f);
unitWave.addDelay(5);
unitWave.addEnemy(0,10,1);
unitWave.addDelay(5);
unitWave.addEnemy(0,5,0.2f);
unitWave.addDelay(5);
unitWave.addEnemy(0,15,0.4f);
unitWave.addDelay(5);
unitWave.addEnemy(0,40,0.9f);
waveController.addWave(unitWave);
}
public void addEnemy(int kind){
Enemy1 enemy1 = new Enemy1();
Random random = new Random();
enemy1.setStartPosition(new Point(1300, random.nextInt(65)*10));
enemyController.add(enemy1);
}
public static MainScene getAcitveScene() {
return acitveScene;
}
public static Engine getEngine() {
return engine;
}
public ObjectController getEnemyController() {
return enemyController;
}
public Hero getHero() {
return hero;
}
private void createHealthBar(){
try {
int y = SpaceShipActivity.getCameraHeight() - 32;
int x = (int)TextureLoader.getScreenControlBaseTextureRegion().getWidth() + 30 +100;
Text text = new Text(x,y,TextureLoader.getFont(),"Прочность: ",new TextOptions(HorizontalAlign.LEFT),engine.getVertexBufferObjectManager());
attachChild(text);
x += text.getWidth();
healthBar = new Text(x,y,TextureLoader.getFont(),"1234567890/",new TextOptions(HorizontalAlign.LEFT),engine.getVertexBufferObjectManager());
attachChild(healthBar);
} catch (Exception e) {
e.printStackTrace();
}
}
private void addHeroMoveControl() {
analogOnScreenControl = new AnalogOnScreenControl(30,
SpaceShipActivity.getCameraHeight() - TextureLoader.getScreenControlBaseTextureRegion().getHeight() - 30,
shipActivity.getCamera(), TextureLoader.getScreenControlBaseTextureRegion(),
TextureLoader.getScreenControlKnobTextureRegion(), 0.1f, 200,
shipActivity.getEngine().getVertexBufferObjectManager(),
hero.getCallback());
analogOnScreenControl.getControlBase().setBlendFunction(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA);
analogOnScreenControl.getControlBase().setAlpha(0.5f);
analogOnScreenControl.getControlBase().setScaleCenter(0, 128);
analogOnScreenControl.getControlBase().setScale(1.25f);
analogOnScreenControl.getControlKnob().setScale(1.25f);
analogOnScreenControl.refreshControlKnobPosition();
setChildScene(analogOnScreenControl);
Rectangle btnFire = new Rectangle(SpaceShipActivity.getCameraWidth()-130,SpaceShipActivity.getCameraHeight()-230,
100,100,shipActivity.getEngine().getVertexBufferObjectManager()){
@Override
public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, float pTouchAreaLocalX, float pTouchAreaLocalY) {
shipActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
if(pSceneTouchEvent.isActionDown()){
hero.canFire(true);
} else if(pSceneTouchEvent.isActionUp()){
hero.canFire(false);
}
}
});
return true;
}
};
Rectangle btnFire2 = new Rectangle(SpaceShipActivity.getCameraWidth()-230,SpaceShipActivity.getCameraHeight()-130,
100,100,shipActivity.getEngine().getVertexBufferObjectManager()){
@Override
public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, float pTouchAreaLocalX, float pTouchAreaLocalY) {
shipActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
if(pSceneTouchEvent.isActionDown()){
Toast.makeText(shipActivity,"БУ!!",Toast.LENGTH_SHORT).show();
}
}
});
return true;
}
};
btnFire.setColor(Color.BLACK);
btnFire.setAlpha(0.5f);
btnFire2.setColor(Color.BLACK);
btnFire2.setAlpha(0.5f);
analogOnScreenControl.attachChild(btnFire);
analogOnScreenControl.attachChild(btnFire2);
analogOnScreenControl.registerTouchArea(btnFire);
analogOnScreenControl.registerTouchArea(btnFire2);
}
protected void createMenuScene() {
this.menuScene = new MenuScene(shipActivity.getCamera());
final SpriteMenuItem resetMenuItem = new SpriteMenuItem(MENU_RESUME, TextureLoader.getMenuResumeTextureRegion(),
engine.getVertexBufferObjectManager());
resetMenuItem.setBlendFunction(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA);
this.menuScene.addMenuItem(resetMenuItem);
final SpriteMenuItem quitMenuItem = new SpriteMenuItem(MENU_BACK_TO_MAIN, TextureLoader.getMenuBackToMainMenuTextureRegion(),
engine.getVertexBufferObjectManager());
quitMenuItem.setBlendFunction(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA);
this.menuScene.addMenuItem(quitMenuItem);
this.menuScene.buildAnimations();
this.menuScene.setBackgroundEnabled(false);
this.menuScene.setOnMenuItemClickListener(new MenuScene.IOnMenuItemClickListener() {
@Override
public boolean onMenuItemClicked(MenuScene pMenuScene, IMenuItem pMenuItem, float pMenuItemLocalX,
float pMenuItemLocalY) {
switch (pMenuItem.getID()) {
case MENU_RESUME:
/* Restart the animation. */
//acitveScene.reset();
acitveScene.detachChild(menuScene);
acitveScene.setChildScene(analogOnScreenControl);
isShowMenuScene = false;
//menuScene = null;
break;
case MENU_BACK_TO_MAIN:
returnToParentScene();
break;
}
return true;
}
});
}
private void returnToParentScene(){
enemyController.cleer();
bulletController.cleer();
parrentScene.returnToParentScene();
}
public void onKeyPressed(int keyCode, KeyEvent event) {
if (!isShowMenuScene){
isShowMenuScene = true;
setChildScene(menuScene, false, true, true);
}else{
isShowMenuScene = false;
acitveScene.detachChild(menuScene);
acitveScene.setChildScene(analogOnScreenControl);
}
}
} |
/*
* PriorDialog.java
*
* @author Marc A. Suchard
*/
package dr.app.beauti.priorsPanel;
import dr.app.beauti.ComboBoxRenderer;
import dr.app.beauti.components.hpm.HierarchicalModelComponentOptions;
import dr.app.beauti.components.linkedparameters.LinkedParameter;
import dr.app.beauti.options.BeautiOptions;
import dr.app.beauti.options.Parameter;
import dr.app.beauti.options.TraitData;
import dr.app.beauti.traitspanel.CreateTraitDialog;
import dr.app.beauti.types.PriorType;
import dr.app.gui.components.RealNumberField;
import dr.app.gui.table.TableEditorStopper;
import dr.app.util.OSType;
import jam.panels.ActionPanel;
import jam.panels.OptionsPanel;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.plaf.BorderUIResource;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableColumn;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.*;
import java.util.List;
/**
* A dialog which acts as a base for linking parameters together under joint priors such
* as hierarchical models.
*
* @author Andrew Rambaut
* @author Marc A. Suchard
*/
public class JointPriorDialog implements AbstractPriorDialog {
private static final int MINIMUM_TABLE_WIDTH = 120;
private JFrame frame;
private final JTable parametersTable;
private final ParametersTableModel parametersTableModel;
private JTextField nameField = new JTextField();
private JPanel panel;
private final PriorSettingsPanel priorSettingsPanel;
private java.util.List<Parameter> parameterList;
private Parameter parameter;
final private BeautiOptions options;
public JointPriorDialog(JFrame frame, BeautiOptions options) {
this.frame = frame;
this.options = options;
priorSettingsPanel = new PriorSettingsPanel(frame);
nameField.setColumns(30);
nameField.setText("Untitled");
parametersTableModel = new ParametersTableModel();
// TableSorter sorter = new TableSorter(traitsTableModel);
// traitsTable = new JTable(sorter);
// sorter.setTableHeader(traitsTable.getTableHeader());
parametersTable = new JTable(parametersTableModel);
parametersTable.getTableHeader().setReorderingAllowed(false);
parametersTable.getTableHeader().setResizingAllowed(false);
// traitsTable.getTableHeader().setDefaultRenderer(
// new HeaderRenderer(SwingConstants.LEFT, new Insets(0, 4, 0, 4)));
parametersTable.getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
parametersTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent evt) {
parametersSelectionChanged();
}
});
}
private void parametersSelectionChanged() {
int selRow = parametersTable.getSelectedRow();
if (selRow >= 0) {
removeParameterAction.setEnabled(true);
}
if (parameterList.size() <= 0) {
removeParameterAction.setEnabled(false);
}
}
public void addParameters(java.util.List<Parameter> parameterList) {
}
public boolean validateModelName() {
return validateModelName(nameField.getText());
}
private boolean validateModelName(String modelName) {
// System.err.println("Validating: " + modelName);
// check that the name is valid
if (modelName.trim().length() == 0) {
Toolkit.getDefaultToolkit().beep();
return false;
}
// check that the trait name doesn't exist
if (modelExists(modelName)) {
JOptionPane.showMessageDialog(frame,
"A model with this name already exists.",
"HPM name error",
// JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE);
// System.err.println("Model name exists");
return false;
// if (option == JOptionPane.NO_OPTION) {
// return false;
}
return true;
}
private boolean modelExists(String modelName) {
HierarchicalModelComponentOptions comp = (HierarchicalModelComponentOptions)
options.getComponentOptions(HierarchicalModelComponentOptions.class);
return comp.modelExists(modelName);
}
public int showDialog() {
panel = new JPanel(new GridBagLayout());
double lower = Double.NEGATIVE_INFINITY;
double upper = Double.POSITIVE_INFINITY;
if (parameter.isZeroOne) {
lower = 0.0;
upper = 1.0;
} else if (parameter.isNonNegative) {
lower = 0.0;
}
panel = new JPanel(new GridBagLayout());
setupComponents();
JOptionPane optionPane = new JOptionPane(panel,
JOptionPane.PLAIN_MESSAGE,
JOptionPane.OK_CANCEL_OPTION,
null,
null,
null);
optionPane.setBorder(new EmptyBorder(12, 12, 12, 12));
final JDialog dialog = optionPane.createDialog(frame, "Linked Parameter Setup");
priorSettingsPanel.setDialog(dialog);
priorSettingsPanel.setParameter(parameter);
if (OSType.isMac()) {
dialog.setMinimumSize(new Dimension(dialog.getBounds().width, 300));
} else {
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension d = tk.getScreenSize();
if (d.height < 700 && panel.getHeight() > 450) {
dialog.setSize(new Dimension(panel.getWidth() + 100, 550));
} else {
// setSize because optionsPanel is shrunk in dialog
dialog.setSize(new Dimension(panel.getWidth() + 100, panel.getHeight() + 100));
}
// System.out.println("panel width = " + panel.getWidth());
// System.out.println("panel height = " + panel.getHeight());
}
dialog.pack();
dialog.setResizable(true);
dialog.setVisible(true);
int result = JOptionPane.CANCEL_OPTION;
Integer value = (Integer) optionPane.getValue();
if (value != null && value != -1) {
result = value;
}
return result;
}
public String getName() {
return nameField.getText();
}
public List<Parameter> getParameterList() {
return parameterList;
}
private void setupComponents() {
panel.removeAll();
JScrollPane scrollPane1 = new JScrollPane(parametersTable,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane1.setOpaque(false);
ActionPanel actionPanel1 = new ActionPanel(false);
actionPanel1.setAddAction(addParameterAction);
actionPanel1.setRemoveAction(removeParameterAction);
actionPanel1.setAddToolTipText("Use this button to add an existing parameter to the prior");
actionPanel1.setRemoveToolTipText("Use this button to remove a parameter from the prior");
removeParameterAction.setEnabled(false);
JPanel controlPanel1 = new JPanel(new FlowLayout(FlowLayout.LEFT));
controlPanel1.setOpaque(false);
controlPanel1.add(actionPanel1);
JPanel panel1 = new JPanel(new BorderLayout(0, 0));
panel1.setOpaque(false);
panel1.add(scrollPane1, BorderLayout.CENTER);
panel1.add(controlPanel1, BorderLayout.SOUTH);
panel1.setPreferredSize(new Dimension(MINIMUM_TABLE_WIDTH, 0));
panel1.setMinimumSize(new Dimension(MINIMUM_TABLE_WIDTH, 0));
OptionsPanel optionsPanel = new OptionsPanel(0,6);
optionsPanel.addComponentWithLabel("Unique Name: ", nameField);
// optionsPanel.addComponentWithLabel("Initial Value: ", initialField);
panel.setOpaque(false);
panel.setBorder(new BorderUIResource.EmptyBorderUIResource(new Insets(12, 12, 12, 12)));
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.fill = GridBagConstraints.BOTH;
c.gridwidth = 2;
panel.add(optionsPanel, c);
c.gridx = 0;
c.gridy = 1;
c.gridwidth = 1;
panel.add(panel1, c);
c.gridx = 1;
c.gridy = 1;
c.anchor = GridBagConstraints.PAGE_START;
c.gridwidth = GridBagConstraints.REMAINDER;
panel.add(priorSettingsPanel, c);
}
protected JPanel createPriorPanel() {
return new JPanel();
}
public void getArguments(Parameter parameter) {
priorSettingsPanel.getArguments(parameter);
}
public boolean hasInvalidInput(boolean showError) {
return priorSettingsPanel.hasInvalidInput(showError);
}
public boolean addParameter() {
// if (addParametersDialog == null) {
// addParametersDialog = new AddParametersDialog(frame);
// addParametersDialog.setSpeciesTrait(isSpeciesTrait);
// addParametersDialog.setTraitName(traitName);
// addParametersDialog.setMessage(message);
// int result = addParametersDialog.showDialog();
// if (result == JOptionPane.OK_OPTION) {
// fireParametersChanged();
// updateButtons();
// } else if (result == JOptionPane.CANCEL_OPTION) {
// return false;
return true;
}
private void removeParameter() {
int selRow = parametersTable.getSelectedRow();
removeParameter((Parameter)parametersTable.getValueAt(selRow, 0));
}
private void removeParameter(Parameter parameter) {
}
private AddParameterAction addParameterAction = new AddParameterAction();
public void setLinkedParameter(LinkedParameter linkedParameter) {
parameter = linkedParameter.getArgumentParameterList().get(0);
}
public void setParameterList(List<Parameter> parameterList) {
this.parameterList = parameterList;
}
public class AddParameterAction extends AbstractAction {
public AddParameterAction() {
super("Add parameter");
}
public void actionPerformed(ActionEvent ae) {
addParameter();
}
}
AbstractAction removeParameterAction = new AbstractAction() {
public void actionPerformed(ActionEvent ae) {
removeParameter();
}
};
class ParametersTableModel extends AbstractTableModel {
private static final long serialVersionUID = -6707994233020715574L;
String[] columnNames = {"Parameter"};
public ParametersTableModel() {
}
public int getColumnCount() {
return columnNames.length;
}
public int getRowCount() {
if (parameterList == null) {
return 0;
}
return parameterList.size();
}
public Object getValueAt(int row, int col) {
switch (col) {
case 0:
return parameterList.get(row).getName();
}
return null;
}
public String getColumnName(int column) {
return columnNames[column];
}
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append(getColumnName(0));
for (int j = 1; j < getColumnCount(); j++) {
buffer.append("\t");
buffer.append(getColumnName(j));
}
buffer.append("\n");
for (int i = 0; i < getRowCount(); i++) {
buffer.append(getValueAt(i, 0));
for (int j = 1; j < getColumnCount(); j++) {
buffer.append("\t");
buffer.append(getValueAt(i, j));
}
buffer.append("\n");
}
return buffer.toString();
}
}
} |
package dr.inference.operators;
import dr.evomodel.continuous.LatentFactorModel;
import dr.inference.model.DiagonalMatrix;
import dr.inference.model.MatrixParameter;
import dr.math.matrixAlgebra.IllegalDimension;
import dr.math.matrixAlgebra.Matrix;
import dr.math.distributions.MultivariateNormalDistribution;
import dr.inference.model.Parameter;
public class FactorGibbsOperator extends SimpleMCMCOperator implements GibbsOperator{
private static final String FACTOR_GIBBS_OPERATOR="factorGibbsOperator";
private LatentFactorModel LFM;
private int numFactors=0;
private Matrix idMat;
public FactorGibbsOperator(LatentFactorModel LFM, double weight){
this.LFM=LFM;
setWeight(weight);
}
private Matrix getPrecision(){
if(numFactors!=LFM.getFactors().getRowDimension()){
numFactors=LFM.getFactors().getRowDimension();
idMat=Matrix.buildIdentity(numFactors);
}
Matrix LoadMat=new Matrix(LFM.getLoadings().getParameterAsMatrix());
Matrix colPrec=new Matrix(LFM.getColumnPrecision().getParameterAsMatrix());
Matrix answer= null;
try {
answer = LoadMat.transpose().product(colPrec).product(LoadMat).add(idMat);
} catch (IllegalDimension illegalDimension) {
illegalDimension.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
return answer;
}
private Matrix getMean(){
Matrix answer=null;
try {
answer=getPrecision().inverse().productWithTransposed(new Matrix(LFM.getLoadings().getParameterAsMatrix())).product(new Matrix(LFM.getColumnPrecision().getParameterAsMatrix())).product(LFM.getScaledData());
} catch (IllegalDimension illegalDimension) {
illegalDimension.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
return answer;
}
private void copy(double[] put, int i){
Parameter working=LFM.getFactors().getParameter(i);
for (int j = 0; j < working.getSize(); j++) {
working.setParameterValueQuietly(j, put[j]);
}
working.fireParameterChangedEvent();
}
public int getStepCount() {
return 0; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public String getPerformanceSuggestion() {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public String getOperatorName() {
return FACTOR_GIBBS_OPERATOR; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public double doOperation() throws OperatorFailedException {
Matrix mean=getMean();
double[][] meanFull=mean.transpose().toComponents();
double[][] precFull=getPrecision().toComponents();
double[] nextList=null;
double[] nextValue=null;
for (int i = 0; i <mean.columns() ; i++) {
nextList=meanFull[i];
nextValue=MultivariateNormalDistribution.nextMultivariateNormalPrecision(nextList, precFull);
copy(nextValue, i);
}
LFM.getFactors().fireParameterChangedEvent();
return 0; //To change body of implemented methods use File | Settings | File Templates.
}
} |
package music_thing;
import java.io.File;
import java.net.URL;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Iterator;
import java.util.List;
import java.util.ResourceBundle;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.MenuItem;
import javafx.scene.control.Slider;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.DragEvent;
import javafx.scene.input.Dragboard;
import javafx.scene.input.TransferMode;
import javafx.stage.DirectoryChooser;
import javafx.stage.FileChooser;
import javafx.stage.FileChooser.ExtensionFilter;
/**
*
* @author csstudent
*/
public class FXMLDocumentController implements Initializable {
@FXML
private Button play;
@FXML
private TableView<Track> songList;
@FXML
private MenuItem fileImport;
@FXML
private MenuItem quit;
@FXML
private Label songTime;
@FXML
private Slider songTimeBar;
@FXML
private TableColumn<Track,String> songCol;
@FXML
private TableColumn<Track,String> artistCol;
@FXML
private TableColumn<Track,String> albumCol;
@FXML
private TableColumn<Track,String> genreCol;
@FXML
private TableColumn<Track,Double> ratingCol;
@FXML
private void play(ActionEvent event) {
if(MusicLibrary.size()>0){
if(!MusicController.getPlaying()){
MusicController.play(MusicLibrary.getSelectedTrack(songList));
}else if(MusicController.getPlaying() && MusicLibrary.getSelectedTrack(songList)!=MusicController.getCurrentTrack()){
MusicController.play(MusicLibrary.getSelectedTrack(songList));
}else{
MusicController.pause();
}
songList.getSelectionModel().select(MusicLibrary.getTrackNumber());
songList.requestFocus();
}
}
@FXML
private void quit(ActionEvent event){
Platform.exit();
}
@FXML
private void deleteFile(ActionEvent event){
try{
Track toDelete = MusicLibrary.getSelectedTrack(songList);
if(MusicController.getCurrentTrack()==toDelete){
MusicController.stop();
}
Files.delete(Paths.get("music/"+toDelete.getPath()));
MusicLibrary.removeTrack(toDelete);
MusicLibrary.setTrack(songList.getFocusModel().getFocusedCell().getRow());
}catch(Exception e){}
MusicLibrary.save();
}
@FXML
private void fileDragged(DragEvent event) {
Dragboard db = event.getDragboard();
if (db.hasFiles()) {
event.acceptTransferModes(TransferMode.COPY);
} else {
event.consume();
}
}
@FXML
private void importFromDrag(DragEvent event){
Dragboard db = event.getDragboard();
boolean success = false;
if (db.hasFiles()) {
success = true;
for (File file : db.getFiles()) {
importFile(file);
}
}
event.setDropCompleted(success);
event.consume();
}
@FXML
private void importFromMenu(ActionEvent event){
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Open A Music File");
fileChooser.getExtensionFilters().addAll(
new ExtensionFilter("Supported Audio Files", "*.mp3", "*.mid", "*.m4a", "*.wav", "*.aiff"),
new ExtensionFilter("All Files", "*.*")
);
List<File> files = fileChooser.showOpenMultipleDialog(Music_Thing.getMainWindow());
if(files!=null){
for(File file: files) importFile(file);
}
}
@FXML
private void importDirectory(ActionEvent event){
DirectoryChooser directoryChooser = new DirectoryChooser();
directoryChooser.setTitle("Choose a folder for import");
File file = directoryChooser.showDialog(Music_Thing.getMainWindow());
if(file!=null)importFile(file);
}
private void importFile(File file){
if(file.isFile()){
File copyTo = new File("music/"+file.getName());
try{
if(!copyTo.exists()){
if(file.getName().toLowerCase().endsWith("mp3")){
Files.copy(file.toPath(), copyTo.toPath());
MusicLibrary.addSong(new Track(SongType.MP3, file.getName()));
}else if(file.getName().toLowerCase().endsWith("mid")){
Files.copy(file.toPath(), copyTo.toPath());
MusicLibrary.addSong(new Track(SongType.MIDI, file.getName()));
}else if(file.getName().toLowerCase().endsWith("m4a")){
Files.copy(file.toPath(), copyTo.toPath());
MusicLibrary.addSong(new Track(SongType.AAC, file.getName()));
}else if(file.getName().toLowerCase().endsWith("aiff")){
Files.copy(file.toPath(), copyTo.toPath());
MusicLibrary.addSong(new Track(SongType.AIFF, file.getName()));
}else if(file.getName().toLowerCase().endsWith("wav")){
Files.copy(file.toPath(), copyTo.toPath());
MusicLibrary.addSong(new Track(SongType.WAV, file.getName()));
}//else{
//add alert file not supported
}
}catch (Exception e){}
}else if(file.isDirectory()){
for(File thing : file.listFiles()) importFile(thing);
}
MusicLibrary.save();
}
@Override
public void initialize(URL url, ResourceBundle rb) {
MusicLibrary.load();
File music = new File("music");
if(!music.exists())music.mkdir();
songCol.setCellValueFactory(
new PropertyValueFactory("name"));
artistCol.setCellValueFactory(
new PropertyValueFactory("artist"));
albumCol.setCellValueFactory(
new PropertyValueFactory("album"));
genreCol.setCellValueFactory(
new PropertyValueFactory("genre"));
ratingCol.setCellValueFactory(
new PropertyValueFactory("rating"));
songList.setItems(MusicLibrary.getLibrary());
}
} |
import java.io.*;
import java.net.*;
import java.util.*;
class Clientes{
private String nickname;
private InetAddress dir;
private int puerto;
public Clientes(){
}
public void setNickname(String s){
nickname = s;
}
public void setInetAddress(InetAddress d){
dir = d;
}
public void setPuerto(int d){
puerto = d;
}
public String getNickname(){
return nickname;
}
public InetAddress getDir(){
return dir;
}
public int getPuerto(){
return puerto;
}
}
public class Servidor{
public static ArrayList<Clientes> usuarios = new ArrayList<Clientes>();
static String parseMessage(String s , String ip){
String message;
String messageData;
String nickname;
String[] parts = s.split("π");
nickname = parts[0];
messageData = parts[1];
//Nickname(ipaddress): mensaje
message = nickname + "(" + ip + "): " + messageData;
return message;
}
public static void sendMessage(DatagramSocket yo, String aMandar){
DatagramPacket paquete;
byte[] buffer;
buffer = new byte[80];
buffer = aMandar.getBytes(); // Transformamos el string a arreglo de bytes
for(int i = 0; i < usuarios.size(); i++){
Clientes userARecibir = (Clientes)usuarios.get(i);
paquete = new DatagramPacket(buffer,buffer.length, userARecibir.getDir(), userARecibir.getPuerto());
try{
yo.send(paquete);
}catch(IOException e){
System.out.println(e.getMessage());
System.exit(1);
}
}
}
public static void main(String[] args){
DatagramSocket yo = null; // Socket del servidor para recibir datagramas
DatagramPacket paquete; // Paquete para recibir los datos
InetAddress dirCliente = null;
int puertoCliente; // Puerto del cliente que manda los datos
byte[] buffer = new byte[80];
String recibido; // String para guardar los bytes recibidos transformados a caracteres
String aMandar;
final int PUERTO = 5000;
boolean viejo = false; //usuario ya creado
try{
yo = new DatagramSocket(PUERTO);
}catch(SocketException e){
System.out.println(e.getMessage());
System.exit(1);
}
System.out.println("Socket escuchando en el puerto "+PUERTO);
while(true){
//reiniciar variable viejo
viejo = false;
buffer = new byte[80]; // Crear el buffer para almacenar el string recibido como arreglo de bytes
paquete = new DatagramPacket(buffer, buffer.length); // Crear paquete para recibir el datagrama
try{
yo.receive(paquete);
}catch(IOException e){
System.out.println(e.getMessage());
System.exit(1);
}
recibido = new String(paquete.getData()).trim(); // Extraer los datos recibidos y transformalos a String
dirCliente = paquete.getAddress();
puertoCliente = paquete.getPort(); // Obtener el puerto del cliente
//checarcliente haber si es cliente nuevo
for(int i = 0; i < usuarios.size(); i++){
Clientes checar = (Clientes) usuarios.get(i);
if(dirCliente == checar.getDir()){
viejo = true;
break;
}
}
if(!viejo){
Clientes c = new Clientes();
c.setInetAddress(dirCliente);
c.setPuerto(puertoCliente);
String[] partes = recibido.split("π");
String nick = partes[0];
c.setNickname(nick);
usuarios.add(c);
sendMessage(yo, "Usuario " + nick + " inicio sesion");
}
//System.out.println(dirCliente.toString()+"("+puertoCliente+") >>"+recibido);
aMandar = parseMessage(recibido, dirCliente.toString());
//un for para enviar paquete a todos los usuarios conectados
sendMessage(yo, aMandar);
}
//yo.close();
}
} |
package hex.tree.drf;
import hex.ModelMetricsBinomial;
import org.junit.*;
import static org.junit.Assert.assertEquals;
import water.*;
import water.exceptions.H2OModelBuilderIllegalArgumentException;
import water.fvec.Frame;
import water.fvec.RebalanceDataSet;
import water.fvec.Vec;
import water.util.Log;
import java.util.Arrays;
import java.util.Random;
public class DRFTest extends TestUtil {
@BeforeClass public static void stall() { stall_till_cloudsize(1); }
abstract static class PrepData { abstract int prep(Frame fr); }
static String[] s(String...arr) { return arr; }
static long[] a(long ...arr) { return arr; }
static long[][] a(long[] ...arr) { return arr; }
@Test public void testClassIris1() throws Throwable {
// iris ntree=1
// the DRF should use only subset of rows since it is using oob validation
basicDRFTestOOBE_Classification(
"./smalldata/iris/iris.csv", "iris.hex",
new PrepData() {
@Override
int prep(Frame fr) {
return fr.numCols() - 1;
}
},
1,
20,
1,
20,
ard(ard(25, 0, 0),
ard(0, 17, 1),
ard(2, 1, 15)),
s("Iris-setosa", "Iris-versicolor", "Iris-virginica"));
}
@Test public void testClassIris5() throws Throwable {
// iris ntree=50
basicDRFTestOOBE_Classification(
"./smalldata/iris/iris.csv", "iris5.hex",
new PrepData() {
@Override
int prep(Frame fr) {
return fr.numCols() - 1;
}
},
5,
20,
1,
20,
ard(ard(41, 0, 0),
ard(1, 39, 2),
ard(1, 3, 41)),
s("Iris-setosa", "Iris-versicolor", "Iris-virginica"));
}
@Test public void testClassCars1() throws Throwable {
// cars ntree=1
basicDRFTestOOBE_Classification(
"./smalldata/junit/cars.csv", "cars.hex",
new PrepData() {
@Override
int prep(Frame fr) {
fr.remove("name").remove();
return fr.find("cylinders");
}
},
1,
20,
1,
20,
ard(ard(0, 0, 0, 0, 0),
ard(3, 65, 0, 1, 0),
ard(0, 1, 0, 0, 0),
ard(0, 0, 1, 30, 0),
ard(0, 0, 0, 1, 39)),
s("3", "4", "5", "6", "8"));
}
@Test public void testClassCars5() throws Throwable {
basicDRFTestOOBE_Classification(
"./smalldata/junit/cars.csv", "cars5.hex",
new PrepData() {
@Override
int prep(Frame fr) {
fr.remove("name").remove();
return fr.find("cylinders");
}
},
5,
20,
1,
20,
ard(ard(3, 0, 0, 0, 0),
ard(2, 177, 1, 4, 0),
ard(0, 1, 1, 0, 0),
ard(0, 2, 2, 69, 1),
ard(0, 0, 0, 3, 87)),
s("3", "4", "5", "6", "8"));
}
@Test public void testConstantCols() throws Throwable {
try {
basicDRFTestOOBE_Classification(
"./smalldata/poker/poker100", "poker.hex",
new PrepData() {
@Override
int prep(Frame fr) {
for (int i = 0; i < 7; i++) {
fr.remove(3).remove();
}
return 3;
}
},
1,
20,
1,
20,
null,
null);
Assert.fail();
} catch( H2OModelBuilderIllegalArgumentException iae ) {
/*pass*/
}
}
@Ignore @Test public void testBadData() throws Throwable {
basicDRFTestOOBE_Classification(
"./smalldata/junit/drf_infinities.csv", "infinitys.hex",
new PrepData() { @Override int prep(Frame fr) { return fr.find("DateofBirth"); } },
1,
20,
1,
20,
ard(ard(6, 0),
ard(9, 1)),
s("0", "1"));
}
//@Test
public void testCreditSample1() throws Throwable {
basicDRFTestOOBE_Classification(
"./smalldata/kaggle/creditsample-training.csv.gz", "credit.hex",
new PrepData() {
@Override
int prep(Frame fr) {
fr.remove("MonthlyIncome").remove();
return fr.find("SeriousDlqin2yrs");
}
},
1,
20,
1,
20,
ard(ard(46294, 202),
ard(3187, 107)),
s("0", "1"));
}
@Test public void testCreditProstate1() throws Throwable {
basicDRFTestOOBE_Classification(
"./smalldata/logreg/prostate.csv", "prostate.hex",
new PrepData() {
@Override
int prep(Frame fr) {
fr.remove("ID").remove();
return fr.find("CAPSULE");
}
},
1,
20,
1,
20,
ard(ard(0, 81),
ard(0, 53)),
s("0", "1"));
}
@Test public void testCreditProstateRegression1() throws Throwable {
basicDRFTestOOBE_Regression(
"./smalldata/logreg/prostate.csv", "prostateRegression.hex",
new PrepData() {
@Override
int prep(Frame fr) {
fr.remove("ID").remove();
return fr.find("AGE");
}
},
1,
20,
1,
10,
84.83960821204235
);
}
@Test public void testCreditProstateRegression5() throws Throwable {
basicDRFTestOOBE_Regression(
"./smalldata/logreg/prostate.csv", "prostateRegression5.hex",
new PrepData() {
@Override
int prep(Frame fr) {
fr.remove("ID").remove();
return fr.find("AGE");
}
},
5,
20,
1,
10,
62.34506879389341
);
}
@Test public void testCreditProstateRegression50() throws Throwable {
basicDRFTestOOBE_Regression(
"./smalldata/logreg/prostate.csv", "prostateRegression50.hex",
new PrepData() {
@Override
int prep(Frame fr) {
fr.remove("ID").remove();
return fr.find("AGE");
}
},
50,
20,
1,
10,
48.16452593965962
);
}
@Test public void testCzechboard() throws Throwable {
basicDRFTestOOBE_Classification(
"./smalldata/gbm_test/czechboard_300x300.csv", "czechboard_300x300.hex",
new PrepData() {
@Override
int prep(Frame fr) {
Vec resp = fr.remove("C2");
fr.add("C2", resp.toEnum());
resp.remove();
return fr.find("C3");
}
},
50,
20,
1,
20,
ard(ard(0, 45000),
ard(0, 45000)),
s("0", "1"));
}
@Test public void testProstate() throws Throwable {
basicDRFTestOOBE_Classification(
"./smalldata/prostate/prostate.csv.zip", "prostate2.zip.hex",
new PrepData() {
@Override
int prep(Frame fr) {
String[] names = fr.names().clone();
Vec[] en = fr.remove(new int[]{1,4,5,8});
fr.add(names[1], en[0].toEnum()); //CAPSULE
fr.add(names[4], en[1].toEnum()); //DPROS
fr.add(names[5], en[2].toEnum()); //DCAPS
fr.add(names[8], en[3].toEnum()); //GLEASON
for (Vec v : en) v.remove();
fr.remove(0).remove(); //drop ID
return 4; //CAPSULE
}
},
4, //ntrees
2, //bins
1, //min_rows
1, //max_depth
null,
s("0", "1"));
}
@Test public void testAlphabet() throws Throwable {
basicDRFTestOOBE_Classification(
"./smalldata/gbm_test/alphabet_cattest.csv", "alphabetClassification.hex",
new PrepData() {
@Override
int prep(Frame fr) {
return fr.find("y");
}
},
1,
20,
1,
20,
ard(ard(664, 0),
ard(0, 702)),
s("0", "1"));
}
@Test public void testAlphabetRegression() throws Throwable {
basicDRFTestOOBE_Regression(
"./smalldata/gbm_test/alphabet_cattest.csv", "alphabetRegression.hex",
new PrepData() {
@Override
int prep(Frame fr) {
return fr.find("y");
}
},
1,
20,
1,
10,
0.0);
}
@Ignore //1-vs-5 node discrepancy (parsing into different number of chunks?)
@Test public void testAirlines() throws Throwable {
basicDRFTestOOBE_Classification(
"./smalldata/airlines/allyears2k_headers.zip", "airlines.hex",
new PrepData() {
@Override
int prep(Frame fr) {
for (String s : new String[]{
"DepTime", "ArrTime", "ActualElapsedTime",
"AirTime", "ArrDelay", "DepDelay", "Cancelled",
"CancellationCode", "CarrierDelay", "WeatherDelay",
"NASDelay", "SecurityDelay", "LateAircraftDelay", "IsArrDelayed"
}) {
fr.remove(s).remove();
}
return fr.find("IsDepDelayed");
}
},
7,
20, 1, 20, ard(ard(7958, 11707), //1-node
ard(2709, 19024)),
// a(a(7841, 11822), //5-node
// a(2666, 19053)),
s("NO", "YES"));
}
// Put response as the last vector in the frame and return possible frames to clean up later
// Also fill DRF.
static Vec unifyFrame(DRFModel.DRFParameters drf, Frame fr, PrepData prep, boolean classification) {
int idx = prep.prep(fr);
if( idx < 0 ) { idx = ~idx; }
String rname = fr._names[idx];
drf._response_column = fr.names()[idx];
Vec resp = fr.vecs()[idx];
Vec ret = null;
if (classification) {
ret = fr.remove(idx);
fr.add(rname,resp.toEnum());
} else {
fr.remove(idx);
fr.add(rname,resp);
}
return ret;
}
public void basicDRFTestOOBE_Classification(String fnametrain, String hexnametrain, PrepData prep, int ntree, int nbins, int min_rows, int max_depth, double[][] expCM, String[] expRespDom) throws Throwable {
basicDRF(fnametrain, hexnametrain, null, prep, ntree, max_depth, nbins, true, min_rows, expCM, -1, expRespDom);
}
public void basicDRFTestOOBE_Regression(String fnametrain, String hexnametrain, PrepData prep, int ntree, int nbins, int min_rows, int max_depth, double expMSE) throws Throwable {
basicDRF(fnametrain, hexnametrain, null, prep, ntree, max_depth, nbins, false, min_rows, null, expMSE, null);
}
public void basicDRF(String fnametrain, String hexnametrain, String fnametest, PrepData prep, int ntree, int max_depth, int nbins, boolean classification, int min_rows, double[][] expCM, double expMSE, String[] expRespDom) throws Throwable {
Scope.enter();
DRFModel.DRFParameters drf = new DRFModel.DRFParameters();
Frame frTest = null, pred = null;
Frame frTrain = null;
Frame test = null, res = null;
DRFModel model = null;
try {
frTrain = parse_test_file(fnametrain);
Vec removeme = unifyFrame(drf, frTrain, prep, classification);
if (removeme != null) Scope.track(removeme._key);
DKV.put(frTrain._key, frTrain);
// Configure DRF
drf._train = frTrain._key;
drf._response_column = ((Frame)DKV.getGet(drf._train)).lastVecName();
drf._ntrees = ntree;
drf._max_depth = max_depth;
drf._min_rows = min_rows;
// drf._binomial_double_trees = new Random().nextBoolean();
drf._nbins = nbins;
drf._nbins_cats = nbins;
drf._mtries = -1;
drf._sample_rate = 0.66667f; // Simulated sampling with replacement
drf._seed = (1L<<32)|2;
drf._model_id = Key.make("DRF_model_4_" + hexnametrain);
// Invoke DRF and block till the end
DRF job = null;
try {
job = new DRF(drf);
// Get the model
model = job.trainModel().get();
Log.info(model._output);
} finally {
if (job != null) job.remove();
}
Assert.assertTrue(job._state == water.Job.JobState.DONE); //HEX-1817
hex.ModelMetrics mm;
if (fnametest != null) {
frTest = parse_test_file(fnametest);
pred = model.score(frTest);
mm = hex.ModelMetrics.getFromDKV(model, frTest);
// Check test set CM
} else {
mm = hex.ModelMetrics.getFromDKV(model, frTrain);
}
Assert.assertEquals("Number of trees differs!", ntree, model._output._ntrees);
test = parse_test_file(fnametrain);
res = model.score(test);
// Build a POJO, validate same results
Assert.assertTrue(model.testJavaScoring(test,res,1e-15));
if (classification && expCM != null) {
Assert.assertTrue("Expected: " + Arrays.deepToString(expCM) + ", Got: " + Arrays.deepToString(mm.cm()._cm),
Arrays.deepEquals(mm.cm()._cm, expCM));
String[] cmDom = model._output._domains[model._output._domains.length - 1];
Assert.assertArrayEquals("CM domain differs!", expRespDom, cmDom);
Log.info("\nOOB Training CM:\n" + mm.cm().toASCII());
Log.info("\nTraining CM:\n" + hex.ModelMetrics.getFromDKV(model, test).cm().toASCII());
} else if (!classification) {
Assert.assertTrue("Expected: " + expMSE + ", Got: " + mm.mse(), expMSE == mm.mse());
Log.info("\nOOB Training MSE: " + mm.mse());
Log.info("\nTraining MSE: " + hex.ModelMetrics.getFromDKV(model, test).mse());
}
hex.ModelMetrics.getFromDKV(model, test);
} finally {
if (frTrain!=null) frTrain.remove();
if (frTest!=null) frTest.remove();
if( model != null ) model.delete(); // Remove the model
if( pred != null ) pred.delete();
if( test != null ) test.delete();
if( res != null ) res.delete();
Scope.exit();
}
}
// HEXDEV-194 Check reproducibility for the same # of chunks (i.e., same # of nodes) and same parameters
@Test public void testReproducibility() {
Frame tfr=null;
final int N = 5;
double[] mses = new double[N];
Scope.enter();
try {
// Load data, hack frames
tfr = parse_test_file("smalldata/covtype/covtype.20k.data");
// rebalance to 256 chunks
Key dest = Key.make("df.rebalanced.hex");
RebalanceDataSet rb = new RebalanceDataSet(tfr, dest, 256);
H2O.submitTask(rb);
rb.join();
tfr.delete();
tfr = DKV.get(dest).get();
// Scope.track(tfr.replace(54, tfr.vecs()[54].toEnum())._key);
// DKV.put(tfr);
for (int i=0; i<N; ++i) {
DRFModel.DRFParameters parms = new DRFModel.DRFParameters();
parms._train = tfr._key;
parms._response_column = "C55";
parms._nbins = 1000;
parms._ntrees = 1;
parms._max_depth = 8;
parms._mtries = -1;
parms._min_rows = 10;
parms._seed = 1234;
// Build a first model; all remaining models should be equal
DRF job = new DRF(parms);
DRFModel drf = job.trainModel().get();
assertEquals(drf._output._ntrees, parms._ntrees);
mses[i] = drf._output._scored_train[drf._output._scored_train.length-1]._mse;
job.remove();
drf.delete();
}
} finally{
if (tfr != null) tfr.remove();
}
Scope.exit();
for (int i=0; i<mses.length; ++i) {
Log.info("trial: " + i + " -> MSE: " + mses[i]);
}
for(double mse : mses)
assertEquals(mse, mses[0], 1e-15);
}
// PUBDEV-557 Test dependency on # nodes (for small number of bins, but fixed number of chunks)
@Test public void testReprodubilityAirline() {
Frame tfr=null;
final int N = 1;
double[] mses = new double[N];
Scope.enter();
try {
// Load data, hack frames
tfr = parse_test_file("./smalldata/airlines/allyears2k_headers.zip");
// rebalance to fixed number of chunks
Key dest = Key.make("df.rebalanced.hex");
RebalanceDataSet rb = new RebalanceDataSet(tfr, dest, 256);
H2O.submitTask(rb);
rb.join();
tfr.delete();
tfr = DKV.get(dest).get();
// Scope.track(tfr.replace(54, tfr.vecs()[54].toEnum())._key);
// DKV.put(tfr);
for (String s : new String[]{
"DepTime", "ArrTime", "ActualElapsedTime",
"AirTime", "ArrDelay", "DepDelay", "Cancelled",
"CancellationCode", "CarrierDelay", "WeatherDelay",
"NASDelay", "SecurityDelay", "LateAircraftDelay", "IsArrDelayed"
}) {
tfr.remove(s).remove();
}
DKV.put(tfr);
for (int i=0; i<N; ++i) {
DRFModel.DRFParameters parms = new DRFModel.DRFParameters();
parms._train = tfr._key;
parms._response_column = "IsDepDelayed";
parms._nbins = 10;
parms._nbins_cats = 1024;
parms._ntrees = 7;
parms._max_depth = 10;
parms._binomial_double_trees = false;
parms._mtries = -1;
parms._min_rows = 1;
parms._sample_rate = 0.632f; // Simulated sampling with replacement
parms._balance_classes = true;
parms._seed = (1L<<32)|2;
// Build a first model; all remaining models should be equal
DRF job = new DRF(parms);
DRFModel drf = job.trainModel().get();
assertEquals(drf._output._ntrees, parms._ntrees);
mses[i] = drf._output._training_metrics.mse();
job.remove();
drf.delete();
}
} finally{
if (tfr != null) tfr.remove();
}
Scope.exit();
for (int i=0; i<mses.length; ++i) {
Log.info("trial: " + i + " -> MSE: " + mses[i]);
}
for (int i=0; i<mses.length; ++i) {
assertEquals(0.20934191392060025, mses[i], 1e-4); //check for the same result on 1 nodes and 5 nodes
}
}
// HEXDEV-319
@Ignore
@Test public void testAirline() {
Frame tfr=null;
Frame test=null;
Scope.enter();
try {
// Load data, hack frames
tfr = parse_test_file(Key.make("air.hex"), "/users/arno/sz_bench_data/train-1m.csv");
test = parse_test_file(Key.make("airt.hex"), "/users/arno/sz_bench_data/test.csv");
// for (int i : new int[]{0,1,2}) {
// tfr.vecs()[i] = tfr.vecs()[i].toEnum();
// test.vecs()[i] = test.vecs()[i].toEnum();
DRFModel.DRFParameters parms = new DRFModel.DRFParameters();
parms._train = tfr._key;
parms._valid = test._key;
parms._ignored_columns = new String[]{"Origin","Dest"};
// parms._ignored_columns = new String[]{"UniqueCarrier","Origin","Dest"};
// parms._ignored_columns = new String[]{"UniqueCarrier","Origin"};
// parms._ignored_columns = new String[]{"Month","DayofMonth","DayOfWeek","DepTime","UniqueCarrier","Origin","Distance"};
parms._response_column = "dep_delayed_15min";
parms._nbins = 20;
parms._nbins_cats = 1024;
parms._binomial_double_trees = new Random().nextBoolean(); //doesn't matter!
parms._ntrees = 1;
parms._max_depth = 3;
parms._mtries = -1;
parms._sample_rate = 0.632f;
parms._min_rows = 10;
parms._seed = 12;
// Build a first model; all remaining models should be equal
DRF job = new DRF(parms);
DRFModel drf = job.trainModel().get();
Log.info("Training set AUC: " + drf._output._training_metrics.auc()._auc);
Log.info("Validation set AUC: " + drf._output._validation_metrics.auc()._auc);
// all numerical
assertEquals(drf._output._training_metrics.auc()._auc, 0.6498819479528417, 1e-8);
assertEquals(drf._output._validation_metrics.auc()._auc, 0.6479974533672835, 1e-8);
job.remove();
drf.delete();
} finally{
if (tfr != null) tfr.remove();
if (test != null) test.remove();
}
Scope.exit();
}
static double _AUC = 0.9285714285714285;
static double _MSE = 0.07692307692307693;
static double _R2 = 0.6904761904761905;
static double _LogLoss = 2.656828953454668;
@Test
public void testNoRowWeights() {
Frame tfr = null, vfr = null;
DRFModel drf = null;
Scope.enter();
try {
tfr = parse_test_file("smalldata/junit/no_weights.csv");
DKV.put(tfr);
DRFModel.DRFParameters parms = new DRFModel.DRFParameters();
parms._train = tfr._key;
parms._response_column = "response";
parms._seed = 234;
parms._min_rows = 1;
parms._max_depth = 2;
parms._ntrees = 3;
// Build a first model; all remaining models should be equal
DRF job = new DRF(parms);
drf = job.trainModel().get();
// OOB
ModelMetricsBinomial mm = (ModelMetricsBinomial)drf._output._training_metrics;
assertEquals(_AUC, mm.auc()._auc, 1e-8);
assertEquals(_MSE, mm.mse(), 1e-8);
assertEquals(_R2, mm.r2(), 1e-6);
assertEquals(_LogLoss, mm.logloss(), 1e-6);
job.remove();
} finally {
if (tfr != null) tfr.remove();
if (vfr != null) vfr.remove();
if (drf != null) drf.remove();
Scope.exit();
}
}
@Test
public void testRowWeightsOne() {
Frame tfr = null, vfr = null;
DRFModel drf = null;
Scope.enter();
try {
tfr = parse_test_file("smalldata/junit/weights_all_ones.csv");
DKV.put(tfr);
DRFModel.DRFParameters parms = new DRFModel.DRFParameters();
parms._train = tfr._key;
parms._response_column = "response";
parms._weights_column = "weight";
parms._seed = 234;
parms._min_rows = 1;
parms._max_depth = 2;
parms._ntrees = 3;
// Build a first model; all remaining models should be equal
DRF job = new DRF(parms);
drf = job.trainModel().get();
// OOB
ModelMetricsBinomial mm = (ModelMetricsBinomial)drf._output._training_metrics;
assertEquals(_AUC, mm.auc()._auc, 1e-8);
assertEquals(_MSE, mm.mse(), 1e-8);
assertEquals(_R2, mm.r2(), 1e-6);
assertEquals(_LogLoss, mm.logloss(), 1e-6);
job.remove();
} finally {
if (tfr != null) tfr.remove();
if (vfr != null) vfr.remove();
if (drf != null) drf.delete();
Scope.exit();
}
}
@Test
public void testRowWeightsTwo() {
Frame tfr = null, vfr = null;
DRFModel drf = null;
Scope.enter();
try {
tfr = parse_test_file("smalldata/junit/weights_all_twos.csv");
DKV.put(tfr);
DRFModel.DRFParameters parms = new DRFModel.DRFParameters();
parms._train = tfr._key;
parms._response_column = "response";
parms._weights_column = "weight";
parms._seed = 234;
parms._min_rows = 2; //in terms of weighted rows
parms._max_depth = 2;
parms._ntrees = 3;
// Build a first model; all remaining models should be equal
DRF job = new DRF(parms);
drf = job.trainModel().get();
// OOB
ModelMetricsBinomial mm = (ModelMetricsBinomial)drf._output._training_metrics;
assertEquals(_AUC, mm.auc()._auc, 1e-8);
assertEquals(_MSE, mm.mse(), 1e-8);
assertEquals(_R2, mm.r2(), 1e-6);
assertEquals(_LogLoss, mm.logloss(), 1e-6);
job.remove();
} finally {
if (tfr != null) tfr.remove();
if (vfr != null) vfr.remove();
if (drf != null) drf.delete();
Scope.exit();
}
}
@Ignore
@Test
public void testRowWeightsTiny() {
Frame tfr = null, vfr = null;
DRFModel drf = null;
Scope.enter();
try {
tfr = parse_test_file("smalldata/junit/weights_all_tiny.csv");
DKV.put(tfr);
DRFModel.DRFParameters parms = new DRFModel.DRFParameters();
parms._train = tfr._key;
parms._response_column = "response";
parms._weights_column = "weight";
parms._seed = 234;
parms._min_rows = 0.01242; // in terms of weighted rows
parms._max_depth = 2;
parms._ntrees = 3;
// Build a first model; all remaining models should be equal
DRF job = new DRF(parms);
drf = job.trainModel().get();
// OOB
ModelMetricsBinomial mm = (ModelMetricsBinomial)drf._output._training_metrics;
assertEquals(_AUC, mm.auc()._auc, 1e-8);
assertEquals(_MSE, mm.mse(), 1e-8);
assertEquals(_R2, mm.r2(), 1e-6);
assertEquals(_LogLoss, mm.logloss(), 1e-6);
job.remove();
} finally {
if (tfr != null) tfr.remove();
if (vfr != null) vfr.remove();
if (drf != null) drf.delete();
Scope.exit();
}
}
@Test
public void testNoRowWeightsShuffled() {
Frame tfr = null, vfr = null;
DRFModel drf = null;
Scope.enter();
try {
tfr = parse_test_file("smalldata/junit/no_weights_shuffled.csv");
DKV.put(tfr);
DRFModel.DRFParameters parms = new DRFModel.DRFParameters();
parms._train = tfr._key;
parms._response_column = "response";
parms._seed = 234;
parms._min_rows = 1;
parms._max_depth = 2;
parms._ntrees = 3;
// Build a first model; all remaining models should be equal
DRF job = new DRF(parms);
drf = job.trainModel().get();
// OOB
// Shuffling changes the row sampling -> results differ
ModelMetricsBinomial mm = (ModelMetricsBinomial)drf._output._training_metrics;
assertEquals(0.975, mm.auc()._auc, 1e-8);
assertEquals(0.09254807692307693, mm.mse(), 1e-8);
assertEquals(0.6089843749999999, mm.r2(), 1e-6);
assertEquals(0.24567709133200652, mm.logloss(), 1e-6);
job.remove();
} finally {
if (tfr != null) tfr.remove();
if (vfr != null) vfr.remove();
if (drf != null) drf.delete();
Scope.exit();
}
}
@Test
public void testRowWeights() {
Frame tfr = null, vfr = null;
DRFModel drf = null;
Scope.enter();
try {
tfr = parse_test_file("smalldata/junit/weights.csv");
DKV.put(tfr);
DRFModel.DRFParameters parms = new DRFModel.DRFParameters();
parms._train = tfr._key;
parms._response_column = "response";
parms._weights_column = "weight";
parms._seed = 234;
parms._min_rows = 1;
parms._max_depth = 2;
parms._ntrees = 3;
// Build a first model; all remaining models should be equal
DRF job = new DRF(parms);
drf = job.trainModel().get();
// OOB
// Reduced number of rows changes the row sampling -> results differ
ModelMetricsBinomial mm = (ModelMetricsBinomial)drf._output._training_metrics;
assertEquals(0.9, mm.auc()._auc, 1e-8);
assertEquals(0.09090909090909091, mm.mse(), 1e-8);
assertEquals(0.6333333333333333, mm.r2(), 1e-6);
assertEquals(3.1398887631736985, mm.logloss(), 1e-6);
// test set scoring (on the same dataset, but without normalizing the weights)
drf.score(parms.train());
hex.ModelMetricsBinomial mm2 = hex.ModelMetricsBinomial.getFromDKV(drf, parms.train());
// Non-OOB
assertEquals(1, mm2.auc()._auc, 1e-8);
assertEquals(0.006172839506172841, mm2.mse(), 1e-8);
assertEquals(0.9753086419753086, mm2.r2(), 1e-8);
assertEquals(0.02252583933934247, mm2.logloss(), 1e-8);
job.remove();
} finally {
if (tfr != null) tfr.remove();
if (vfr != null) vfr.remove();
if (drf != null) drf.delete();
Scope.exit();
}
}
@Ignore
@Test
public void testNFold() {
Frame tfr = null, vfr = null;
DRFModel drf = null;
Scope.enter();
try {
tfr = parse_test_file("./smalldata/airlines/allyears2k_headers.zip");
for (String s : new String[]{
"DepTime", "ArrTime", "ActualElapsedTime",
"AirTime", "ArrDelay", "DepDelay", "Cancelled",
"CancellationCode", "CarrierDelay", "WeatherDelay",
"NASDelay", "SecurityDelay", "LateAircraftDelay", "IsArrDelayed"
}) {
tfr.remove(s).remove();
}
DKV.put(tfr);
DRFModel.DRFParameters parms = new DRFModel.DRFParameters();
parms._train = tfr._key;
parms._response_column = "IsDepDelayed";
parms._seed = 234;
parms._min_rows = 2;
parms._nfolds = 3;
parms._max_depth = 5;
parms._ntrees = 5;
// Build a first model; all remaining models should be equal
DRF job = new DRF(parms);
drf = job.trainModel().get();
ModelMetricsBinomial mm = (ModelMetricsBinomial)drf._output._validation_metrics;
assertEquals(0.7252305790568023, mm.auc()._auc, 1e-8); // 1 node
assertEquals(0.7330846346541204, mm.auc()._auc, 1e-8); // 5 nodes
assertEquals(0.21258514360090627, mm.mse(), 1e-8);
assertEquals(0.14751832396119646, mm.r2(), 1e-6);
assertEquals(0.6133063511996262, mm.logloss(), 1e-6);
job.remove();
} finally {
if (tfr != null) tfr.remove();
if (vfr != null) vfr.remove();
if (drf != null) drf.delete();
Scope.exit();
}
}
} |
package water.rapids;
import water.H2O;
import water.MRTask;
import water.fvec.Chunk;
import water.fvec.Frame;
import water.fvec.NewChunk;
import water.fvec.Vec;
import water.parser.BufferedString;
import water.util.ArrayUtils;
import water.util.MathUtils;
import java.util.Arrays;
/**
* Subclasses auto-widen between scalars and Frames, and have exactly two arguments
*/
abstract class ASTBinOp extends ASTPrim {
@Override
public String[] args() { return new String[]{"leftArg", "rightArg"}; }
@Override int nargs() { return 1+2; }
@Override Val apply( Env env, Env.StackHelp stk, AST asts[] ) {
Val left = stk.track(asts[1].exec(env));
Val rite = stk.track(asts[2].exec(env));
return prim_apply(left,rite);
}
Val prim_apply( Val left, Val rite ) {
switch( left.type() ) {
case Val.NUM:
final double dlf = left.getNum();
switch( rite.type() ) {
case Val.NUM: return new ValNum( op (dlf,rite.getNum()));
case Val.FRM: return scalar_op_frame(dlf,rite.getFrame());
case Val.STR: throw H2O.unimpl();
default: throw H2O.fail();
}
case Val.FRM:
Frame flf = left.getFrame();
switch( rite.type() ) {
case Val.NUM: return frame_op_scalar(flf,rite.getNum());
case Val.STR: return frame_op_scalar(flf,rite.getStr());
case Val.FRM: return frame_op_frame (flf,rite.getFrame());
default: throw H2O.fail();
}
case Val.STR:
String slf = left.getStr();
switch( rite.type() ) {
case Val.NUM: throw H2O.unimpl();
case Val.STR: throw H2O.unimpl();
case Val.FRM: return scalar_op_frame(slf,rite.getFrame());
default: throw H2O.fail();
}
case Val.ROW:
double dslf[] = left.getRow();
switch( rite.type() ) {
case Val.NUM:
double[] right = new double[dslf.length];
Arrays.fill(right, rite.getNum());
return row_op_row(dslf,right,left.getNames());
case Val.ROW: return row_op_row(dslf,rite.getRow(),rite.getNames());
default: throw H2O.fail();
}
default: throw H2O.fail();
}
}
/** Override to express a basic math primitive */
abstract double op( double l, double r );
double str_op( BufferedString l, BufferedString r ) { throw H2O.fail(); }
/** Auto-widen the scalar to every element of the frame */
private ValFrame scalar_op_frame( final double d, Frame fr ) {
Frame res = new MRTask() {
@Override public void map( Chunk[] chks, NewChunk[] cress ) {
for( int c=0; c<chks.length; c++ ) {
Chunk chk = chks[c];
NewChunk cres = cress[c];
for( int i=0; i<chk._len; i++ )
cres.addNum(op(d,chk.atd(i)));
}
}
}.doAll(fr.numCols(),fr).outputFrame(fr._names,null);
return cleanCategorical(fr, res); // Cleanup categorical misuse
}
/** Auto-widen the scalar to every element of the frame */
ValFrame frame_op_scalar( Frame fr, final double d ) {
Frame res = new MRTask() {
@Override public void map( Chunk[] chks, NewChunk[] cress ) {
for( int c=0; c<chks.length; c++ ) {
Chunk chk = chks[c];
NewChunk cres = cress[c];
for( int i=0; i<chk._len; i++ )
cres.addNum(op(chk.atd(i),d));
}
}
}.doAll(fr.numCols(),fr).outputFrame(fr._names,null);
return cleanCategorical(fr, res); // Cleanup categorical misuse
}
// Ops do not make sense on categoricals, except EQ/NE; flip such ops to NAs
private ValFrame cleanCategorical(Frame oldfr, Frame newfr) {
final boolean categoricalOK = categoricalOK();
final Vec oldvecs[] = oldfr.vecs();
final Vec newvecs[] = newfr.vecs();
for( int i=0; i<oldvecs.length; i++ )
if( !oldvecs[i].isNumeric() && // Must be numeric OR
!oldvecs[i].isTime() && // time OR
!(oldvecs[i].isCategorical() && categoricalOK) ) // categorical are OK (op is EQ/NE)
newvecs[i] = newvecs[i].makeCon(Double.NaN);
return new ValFrame(newfr);
}
/** Auto-widen the scalar to every element of the frame */
private ValFrame frame_op_scalar( Frame fr, final String str ) {
Frame res = new MRTask() {
@Override public void map( Chunk[] chks, NewChunk[] cress ) {
BufferedString vstr = new BufferedString();
for( int c=0; c<chks.length; c++ ) {
Chunk chk = chks[c];
NewChunk cres = cress[c];
Vec vec = chk.vec();
// String Vectors: apply str_op as BufferedStrings to all elements
if( vec.isString() ) {
final BufferedString conStr = new BufferedString(str);
for( int i=0; i<chk._len; i++ )
cres.addNum(str_op(chk.atStr(vstr,i),conStr));
} else if( vec.isCategorical() ) {
// categorical Vectors: convert string to domain value; apply op (not
// str_op). Not sure what the "right" behavior here is, can
// easily argue that should instead apply str_op to the categorical
// string domain value - except that this whole operation only
// makes sense for EQ/NE, and is much faster when just comparing
// doubles vs comparing strings. Note that if the string is not
// part of the categorical domain, the find op returns -1 which is never
// equal to any categorical dense integer (which are always 0+).
final double d = (double)ArrayUtils.find(vec.domain(),str);
for( int i=0; i<chk._len; i++ )
cres.addNum(op(chk.atd(i),d));
} else { // mixing string and numeric
final double d = op(1,2); // false or true only
for( int i=0; i<chk._len; i++ )
cres.addNum(d);
}
}
}
}.doAll(fr.numCols(),fr).outputFrame(fr._names,null);
return new ValFrame(res);
}
/** Auto-widen the scalar to every element of the frame */
private ValFrame scalar_op_frame( final String str, Frame fr ) {
Frame res = new MRTask() {
@Override public void map( Chunk[] chks, NewChunk[] cress ) {
BufferedString vstr = new BufferedString();
for( int c=0; c<chks.length; c++ ) {
Chunk chk = chks[c];
NewChunk cres = cress[c];
Vec vec = chk.vec();
// String Vectors: apply str_op as BufferedStrings to all elements
if( vec.isString() ) {
final BufferedString conStr = new BufferedString(str);
for( int i=0; i<chk._len; i++ )
cres.addNum(str_op(conStr,chk.atStr(vstr,i)));
} else if( vec.isCategorical() ) {
// categorical Vectors: convert string to domain value; apply op (not
// str_op). Not sure what the "right" behavior here is, can
// easily argue that should instead apply str_op to the categorical
// string domain value - except that this whole operation only
// makes sense for EQ/NE, and is much faster when just comparing
// doubles vs comparing strings.
final double d = (double)ArrayUtils.find(vec.domain(),str);
for( int i=0; i<chk._len; i++ )
cres.addNum(op(d,chk.atd(i)));
} else { // mixing string and numeric
final double d = op(1,2); // false or true only
for( int i=0; i<chk._len; i++ )
cres.addNum(d);
}
}
}
}.doAll(fr.numCols(),fr).outputFrame(fr._names,null);
return new ValFrame(res);
}
/** Auto-widen: If one frame has only 1 column, auto-widen that 1 column to
* the rest. Otherwise the frames must have the same column count, and
* auto-widen element-by-element. Short-cut if one frame has zero
* columns. */
private ValFrame frame_op_frame( Frame lf, Frame rt ) {
if( lf.numRows() != rt.numRows() )
throw new IllegalArgumentException("Frames must have same rows, found "+lf.numRows()+" rows and "+rt.numRows()+" rows.");
if( lf.numCols() == 0 ) return new ValFrame(lf);
if( rt.numCols() == 0 ) return new ValFrame(rt);
if( lf.numCols() == 1 && rt.numCols() > 1 ) return vec_op_frame(lf.vecs()[0],rt);
if( rt.numCols() == 1 && lf.numCols() > 1 ) return frame_op_vec(lf,rt.vecs()[0]);
if( lf.numCols() != rt.numCols() )
throw new IllegalArgumentException("Frames must have same columns, found "+lf.numCols()+" columns and "+rt.numCols()+" columns.");
return new ValFrame(new MRTask() {
@Override public void map( Chunk[] chks, NewChunk[] cress ) {
assert (cress.length<<1) == chks.length;
for( int c=0; c<cress.length; c++ ) {
Chunk clf = chks[c];
Chunk crt = chks[c+cress.length];
NewChunk cres = cress[c];
for( int i=0; i<clf._len; i++ )
cres.addNum(op(clf.atd(i),crt.atd(i)));
}
}
}.doAll(lf.numCols(),new Frame(lf).add(rt)).outputFrame(lf._names,null));
}
private ValRow row_op_row( double[] lf, double[] rt, String[] names ) {
double[] res = new double[lf.length];
for( int i=0; i<lf.length; i++ )
res[i] = op(lf[i],rt[i]);
return new ValRow(res,names);
}
private ValFrame vec_op_frame( Vec vec, Frame fr ) {
throw H2O.unimpl();
}
private ValFrame frame_op_vec( Frame fr, Vec vec ) {
throw H2O.unimpl();
}
// Make sense to run this OP on an enm?
boolean categoricalOK() { return false; }
}
// Expressions that auto-widen between NUM and FRM
class ASTAnd extends ASTBinOp { public String str() { return "&" ; } double op( double l, double r ) { return ASTLAnd.and_op(l,r); } }
class ASTDiv extends ASTBinOp { public String str() { return "/" ; } double op( double l, double r ) { return l/r;}}
class ASTMod extends ASTBinOp { public String str() { return "mod";} double op( double l, double r ) { return l%r;}}
class ASTModR extends ASTBinOp { public String str() { return "%%"; } double op( double l, double r ) { return l%r;}} // Language R mod operator
class ASTMul extends ASTBinOp { public String str() { return "*" ; } double op( double l, double r ) { return l*r;}}
class ASTOr extends ASTBinOp { public String str() { return "|" ; } double op( double l, double r ) { return ASTLOr . or_op(l,r); } }
class ASTPlus extends ASTBinOp { public String str() { return "+" ; } double op( double l, double r ) { return l+ r; } }
class ASTPow extends ASTBinOp { public String str() { return "^" ; } double op( double l, double r ) { return Math.pow(l,r); } }
class ASTSub extends ASTBinOp { public String str() { return "-" ; } double op( double l, double r ) { return l- r; } }
class ASTIntDiv extends ASTBinOp { public String str() { return "intDiv"; } double op(double l, double r) { return (int)l/(int)r;}}
class ASTIntDivR extends ASTBinOp { public String str() { return "%/%"; } double op(double l, double r) { return (int)(l/r);}} // Language R intdiv op
class ASTRound extends ASTBinOp {
public String str() { return "round"; }
double op(double x, double digits) {
// e.g.: floor(2.676*100 + 0.5) / 100 => 2.68
if(Double.isNaN(x)) return x;
double sgn = x < 0 ? -1 : 1;
x = Math.abs(x);
double power_of_10 = (int)Math.pow(10, (int)digits);
return sgn*(digits == 0
// go to the even digit
? (x % 1 >= 0.5 && !(Math.floor(x)%2==0))
? Math.ceil(x)
: Math.floor(x)
: Math.floor(x * power_of_10 + 0.5) / power_of_10);
}
}
class ASTSignif extends ASTBinOp {
public String str() { return "signif"; }
double op(double x, double digits) {
if(Double.isNaN(x)) return x;
java.math.BigDecimal bd = new java.math.BigDecimal(x);
bd = bd.round(new java.math.MathContext((int)digits, java.math.RoundingMode.HALF_EVEN));
return bd.doubleValue();
}
}
class ASTGE extends ASTBinOp { public String str() { return ">="; } double op( double l, double r ) { return l>=r?1:0; } }
class ASTGT extends ASTBinOp { public String str() { return ">" ; } double op( double l, double r ) { return l> r?1:0; } }
class ASTLE extends ASTBinOp { public String str() { return "<="; } double op( double l, double r ) { return l<=r?1:0; } }
class ASTLT extends ASTBinOp { public String str() { return "<" ; } double op( double l, double r ) { return l< r?1:0; } }
class ASTEQ extends ASTBinOp { public String str() { return "=="; } double op( double l, double r ) { return MathUtils.equalsWithinOneSmallUlp(l,r)?1:0; }
double str_op( BufferedString l, BufferedString r ) { return l==null ? (r==null?1:0) : (l.equals(r) ? 1 : 0); }
@Override ValFrame frame_op_scalar( Frame fr, final double d ) {
return new ValFrame(new MRTask() {
@Override public void map( Chunk[] chks, NewChunk[] cress ) {
for( int c=0; c<chks.length; c++ ) {
Chunk chk = chks[c];
NewChunk cres = cress[c];
if( !chk.vec().isNumeric() ) cres.addZeros(chk._len);
else
for( int i=0; i<chk._len; i++ )
cres.addNum(op(chk.atd(i),d));
}
}
}.doAll(fr.numCols(),fr).outputFrame());
}
@Override boolean categoricalOK() { return true; } // Make sense to run this OP on an enm?
}
class ASTNE extends ASTBinOp { public String str() { return "!="; } double op( double l, double r ) { return MathUtils.equalsWithinOneSmallUlp(l,r)?0:1; }
double str_op( BufferedString l, BufferedString r ) { return l==null ? (r==null?0:1) : (l.equals(r) ? 0 : 1); }
@Override boolean categoricalOK() { return true; } // Make sense to run this OP on an enm?
}
// Logical-AND. If the first arg is false, do not execute the 2nd arg.
class ASTLAnd extends ASTBinOp {
public String str() { return "&&"; }
@Override Val apply( Env env, Env.StackHelp stk, AST asts[] ) {
Val left = stk.track(asts[1].exec(env));
// If the left is zero or NA, do not evaluate the right, just return the left
if( left.isNum() ) {
double d = ((ValNum)left)._d;
if( d==0 || Double.isNaN(d) ) return left;
}
Val rite = stk.track(asts[2].exec(env));
return prim_apply(left,rite);
}
// Weird R semantics, zero trumps NA
double op( double l, double r ) { return and_op(l,r); }
static double and_op( double l, double r ) {
return (l==0||r==0) ? 0 : (Double.isNaN(l) || Double.isNaN(r) ? Double.NaN : 1);
}
}
// Logical-OR. If the first arg is true, do not execute the 2nd arg.
class ASTLOr extends ASTBinOp {
public String str() { return "||"; }
@Override Val apply( Env env, Env.StackHelp stk, AST asts[] ) {
Val left = stk.track(asts[1].exec(env));
// If the left is non-zero or NA, do not evaluate the right, just return the left
if( left.isNum() ) {
double d = ((ValNum)left)._d;
if( d!=0 || Double.isNaN(d) ) return left;
}
Val rite = stk.track(asts[2].exec(env));
return prim_apply(left,rite);
}
// Weird R semantics, zero trumps NA
double op( double l, double r ) { return or_op(l, r); }
static double or_op( double l, double r ) {
return (l!=0||r!=0) ? 1 : (Double.isNaN(l) || Double.isNaN(r) ? Double.NaN : 0);
}
}
// IfElse.
// "NaNs poison". If the test is a NaN, evaluate neither side and return a NaN
// "Frames poison". If the test is a Frame, both sides are evaluated and
// selected between according to the test. The result is a Frame. All Frames
// must be compatible, and scalars and 1-column Frames are widened to match the
// widest frame. NaN test values produce NaN results.
// If the test is a scalar, then only the returned side is evaluated. If both
// sides are scalars or frames, then the evaluated result is returned. The
// unevaluated side is not checked for being a compatible frame. It is an
// error if one side is typed as a scalar and the other as a Frame.
class ASTIfElse extends ASTPrim {
@Override
public String[] args() { return new String[]{"test","true","false"}; }
@Override int nargs() { return 1+3; } // (ifelse test true false)
public String str() { return "ifelse"; }
@Override Val apply( Env env, Env.StackHelp stk, AST asts[] ) {
Val val = stk.track(asts[1].exec(env));
if( val.isNum() ) { // Scalar test, scalar result
double d = val.getNum();
if( Double.isNaN(d) ) return new ValNum(Double.NaN);
Val res = stk.track(asts[d==0 ? 3 : 2].exec(env)); // exec only 1 of false and true
return res.isFrame() ? new ValNum(res.getFrame().vec(0).at(0)) : res;
}
// Frame test. Frame result.
if( val.type() == Val.ROW)
return row_ifelse((ValRow)val,asts[2].exec(env), asts[3].exec(env));
Frame tst = val.getFrame();
// If all zero's, return false and never execute true.
Frame fr = new Frame(tst);
Val tval = null;
for( Vec vec : tst.vecs() )
if( vec.min()!=0 || vec.max()!= 0 ) {
tval = exec_check(env,stk,tst,asts[2],fr);
break;
}
final boolean has_tfr = tval != null && tval.isFrame();
final String ts = (tval != null && tval.isStr() ) ? tval.getStr() : null;
final double td = (tval != null && tval.isNum()) ? tval.getNum() : Double.NaN;
final int[] tsIntMap = new int[tst.numCols()];
// If all nonzero's (or NA's), then never execute false.
Val fval = null;
for( Vec vec : tst.vecs() )
if( vec.nzCnt()+vec.naCnt() < vec.length() ) {
fval = exec_check(env,stk,tst,asts[3],fr);
break;
}
final boolean has_ffr = fval != null && fval.isFrame();
final String fs = (fval != null && fval.isStr() ) ? fval.getStr() : null;
final double fd = (fval != null && fval.isNum()) ? fval.getNum() : Double.NaN;
final int[] fsIntMap = new int[tst.numCols()];
String[][] domains = null;
final int[][] maps = new int[tst.numCols()][];
if( fs!=null || ts!=null ) { // time to build domains...
domains = new String[tst.numCols()][];
String s;
if( fs!=null && ts!=null ) {
for( int i=0;i<tst.numCols(); ++i ) {
domains[i] = new String[]{fs, ts}; // false => 0; truth => 1
fsIntMap[i] = 0;
tsIntMap[i] = 1;
}
} else if( ts!=null ) {
for(int i=0;i<tst.numCols();++i) {
if( has_ffr ) {
Vec v = fr.vec(i+tst.numCols()+(has_tfr ? tst.numCols() : 0));
if( !v.isCategorical() )
throw H2O.unimpl("Column is not categorical.");
String[] dom = Arrays.copyOf(v.domain(),v.domain().length+1);
dom[dom.length-1] = ts;
Arrays.sort(dom);
maps[i] = computeMap(v.domain(),dom);
tsIntMap[i] = ArrayUtils.find(dom,ts);
domains[i] = dom;
} else throw H2O.unimpl();
}
} else { // fs!=null
for(int i=0;i<tst.numCols();++i) {
if( has_tfr ) {
Vec v = fr.vec(i+tst.numCols()+(has_ffr ? tst.numCols() : 0));
if( !v.isCategorical() )
throw H2O.unimpl("Column is not categorical.");
String[] dom = Arrays.copyOf(v.domain(),v.domain().length+1);
dom[dom.length-1] = fs;
Arrays.sort(dom);
maps[i] = computeMap(v.domain(),dom);
fsIntMap[i] = ArrayUtils.find(dom,fs);
domains[i] = dom;
} else throw H2O.unimpl();
}
}
}
// Now pick from left-or-right in the new frame
Frame res = new MRTask() {
@Override public void map( Chunk chks[], NewChunk nchks[] ) {
assert nchks.length+(has_tfr ? nchks.length : 0)+(has_ffr ? nchks.length : 0) == chks.length;
for( int i=0; i<nchks.length; i++ ) {
Chunk ctst = chks[i];
NewChunk res = nchks[i];
for( int row=0; row<ctst._len; row++ ) {
double d;
if( ctst.isNA(row) ) d = Double.NaN;
else if( ctst.atd(row)==0 ) d = has_ffr
? domainMap(chks[i+nchks.length+(has_tfr ? nchks.length : 0)].atd(row), maps[i])
: fs!=null ? fsIntMap[i] : fd;
else d = has_tfr
? domainMap(chks[i+nchks.length ].atd(row), maps[i])
: ts!=null ? tsIntMap[i] : td;
res.addNum(d);
}
}
}
}.doAll(tst.numCols(),fr).outputFrame(null,domains);
// flatten domains since they may be larger than needed
if( domains!=null ) {
for (int i = 0; i < res.numCols(); ++i) {
if (res.vec(i).domain() != null) {
final long[] dom = new Vec.CollectDomainFast((int) res.vec(i).max()).doAll(res.vec(i)).domain();
String[] newDomain = new String[dom.length];
for (int l = 0; l < dom.length; ++l)
newDomain[l] = res.vec(i).domain()[(int) dom[l]];
new MRTask() {
@Override
public void map(Chunk c) {
for (int i = 0; i < c._len; ++i)
c.set(i, ArrayUtils.find(dom, c.at8(i)));
}
}.doAll(res.vec(i));
res.vec(i).setDomain(newDomain); // needs a DKVput?
}
}
}
return new ValFrame(res);
}
private static double domainMap(double d, int[] maps) {
if( maps!=null && d==(int)d && ( 0 <= d && d < maps.length) ) return maps[(int)d];
return d;
}
private static int[] computeMap(String[] from, String[] to) {
int[] map = new int[from.length];
for(int i=0;i<from.length;++i)
map[i] = ArrayUtils.find(to, from[i]);
return map;
}
Val exec_check( Env env, Env.StackHelp stk, Frame tst, AST ast, Frame xfr ) {
Val val = ast.exec(env);
if( val.isFrame() ) {
Frame fr = stk.track(val).getFrame();
if( tst.numCols() != fr.numCols() || tst.numRows() != fr.numRows() )
throw new IllegalArgumentException("ifelse test frame and other frames must match dimensions, found "+tst+" and "+fr);
xfr.add(fr);
}
return val;
}
ValRow row_ifelse(ValRow tst, Val yes, Val no) {
if( !yes.isRow() || !no.isRow() ) throw H2O.unimpl();
double[] test = tst.getRow();
double[] True = yes.getRow();
double[] False = no.getRow();
double[] ds = new double[test.length];
String[] ns = new String[test.length];
for(int i=0;i<test.length;++i) {
ns[i] = "C"+(i+1);
if( Double.isNaN(test[i])) ds[i] = Double.NaN;
else ds[i] = test[i]==0 ? False[i] : True[i];
}
return new ValRow(ds,ns);
}
}
// Center and scale a frame. Can be passed in the centers and scales (one per
// column in an number list), or a TRUE/FALSE.
class ASTScale extends ASTPrim {
@Override
public String[] args() { return new String[]{"ary", "center", "scale"}; }
@Override int nargs() { return 1+3; } // (scale x center scale)
@Override
public String str() { return "scale"; }
@Override Val apply( Env env, Env.StackHelp stk, AST asts[] ) {
Frame fr = stk.track(asts[1].exec(env)).getFrame();
int ncols = fr.numCols();
// Peel out the bias/shift/mean
double[] means;
if( asts[2] instanceof ASTNumList ) {
means = ((ASTNumList)asts[2]).expand();
if( means.length != ncols )
throw new IllegalArgumentException("Numlist must be the same length as the columns of the Frame");
} else {
double d = asts[2].exec(env).getNum();
if( d==0 ) means = new double[ncols]; // No change on means, so zero-filled
else if( d==1 ) means = fr.means();
else throw new IllegalArgumentException("Only true or false allowed");
}
// Peel out the scale/stddev
double[] mults;
if( asts[3] instanceof ASTNumList ) {
mults = ((ASTNumList)asts[3]).expand();
if( mults.length != ncols )
throw new IllegalArgumentException("Numlist must be the same length as the columns of the Frame");
} else {
Val v = asts[3].exec(env);
if( v instanceof ValFrame ) {
mults = toArray(v.getFrame().anyVec());
} else {
double d = v.getNum();
if (d == 0)
Arrays.fill(mults = new double[ncols], 1.0); // No change on mults, so one-filled
else if (d == 1) mults = fr.mults();
else throw new IllegalArgumentException("Only true or false allowed");
}
}
// Update in-place.
final double[] fmeans = means; // Make final copy for closure
final double[] fmults = mults; // Make final copy for closure
new MRTask() {
@Override public void map( Chunk[] cs ) {
for( int i=0; i<cs.length; i++ )
for( int row=0; row<cs[i]._len; row++ )
cs[i].set(row,(cs[i].atd(row)-fmeans[i])*fmults[i]);
}
}.doAll(fr);
return new ValFrame(fr);
}
private static double[] toArray(Vec v) {
double[] res = new double[(int)v.length()];
for(int i=0;i<res.length;++i)
res[i] = v.at(i);
return res;
}
} |
package edu.umd.cs.findbugs;
import java.io.File;
import java.net.URL;
import java.util.*;
/**
* The DetectorFactoryCollection stores all of the DetectorFactory objects
* used to create the Detectors which implement the various analyses.
* It is a singleton class.
*
* @author David Hovemeyer
* @see DetectorFactory
*/
public class DetectorFactoryCollection {
private ArrayList<DetectorFactory> factoryList = new ArrayList<DetectorFactory>();
private HashMap<String, DetectorFactory> factoriesByName = new HashMap<String, DetectorFactory>();
private HashMap<String, DetectorFactory> factoriesByDetectorClassName =
new HashMap<String, DetectorFactory>();
private static DetectorFactoryCollection theInstance;
private static final Object lock = new Object();
private static File[] pluginList;
/**
* Constructor.
*/
private DetectorFactoryCollection() {
loadPlugins();
}
/**
* Set the list of plugins to load explicitly.
* This must be done before the instance of DetectorFactoryCollection
* is created.
*
* @param pluginList list of plugin Jar files to load
*/
public static void setPluginList(File[] pluginList) {
DetectorFactoryCollection.pluginList = new File[pluginList.length];
System.arraycopy(pluginList, 0, DetectorFactoryCollection.pluginList, 0, pluginList.length);
}
/**
* Get the single instance of DetectorFactoryCollection.
*/
public static DetectorFactoryCollection instance() {
synchronized (lock) {
if (theInstance == null)
theInstance = new DetectorFactoryCollection();
return theInstance;
}
}
/**
* Return an Iterator over the DetectorFactory objects for all
* registered Detectors.
*/
public Iterator<DetectorFactory> factoryIterator() {
return factoryList.iterator();
}
/**
* Look up a DetectorFactory by its short name.
*
* @param name the short name
* @return the DetectorFactory, or null if there is no factory with that short name
*/
public DetectorFactory getFactory(String name) {
return factoriesByName.get(name);
}
/**
* Look up a DetectorFactory by its class name.
*
* @param className the class name
* @return the DetectoryFactory, or null if there is no factory with
* that class name
*/
public DetectorFactory getFactoryByClassName(String className) {
return factoriesByDetectorClassName.get(className);
}
/**
* Disable all detectors.
*/
public void disableAll() {
enableAll(false);
}
/**
* Enable all detectors.
*/
public void enableAll() {
enableAll(true);
}
private void enableAll(boolean enabled) {
Iterator<DetectorFactory> i = DetectorFactoryCollection.instance().factoryIterator();
while (i.hasNext()) {
DetectorFactory factory = i.next();
factory.setEnabled(enabled);
}
}
/**
* Register a DetectorFactory.
*/
private void registerDetector(DetectorFactory factory) {
String detectorName = factory.getShortName();
factoryList.add(factory);
factoriesByName.put(detectorName, factory);
factoriesByDetectorClassName.put(factory.getFullName(), factory);
}
/**
* Load all plugins.
* If a setPluginList() has been called, then those plugins
* are loaded. Otherwise, the "findbugs.home" property is checked
* to determine where FindBugs is installed, and the plugin files
* are dynamically loaded from the plugin directory.
*/
private void loadPlugins() {
// Load all detector plugins.
if (pluginList == null) {
String homeDir = FindBugs.getHome();
File pluginDir = new File(homeDir + File.separator + "plugin");
File[] contentList = pluginDir.listFiles();
if (contentList == null) {
System.err.println("Error: The path " + pluginDir.getPath() + " does not seem to be a directory!");
System.err.println("No FindBugs plugins could be loaded");
pluginList = new File[0];
return;
}
ArrayList<File> arr = new ArrayList<File>();
for (int i = 0; i < contentList.length; ++i) {
if (contentList[i].getName().endsWith(".jar"))
arr.add(contentList[i]);
}
pluginList = (File[]) arr.toArray(new File[arr.size()]);
}
int numLoaded = 0;
for (int i = 0; i < pluginList.length; ++i) {
File file = pluginList[i];
try {
URL url = file.toURL();
PluginLoader pluginLoader = new PluginLoader(url, this.getClass().getClassLoader());
// Register all of the detectors that this plugin contains
DetectorFactory[] detectorFactoryList = pluginLoader.getDetectorFactoryList();
for (int j = 0; j < detectorFactoryList.length; ++j)
registerDetector(detectorFactoryList[j]);
I18N i18n = I18N.instance();
// Register the BugPatterns
BugPattern[] bugPatternList = pluginLoader.getBugPatternList();
for (int j = 0; j < bugPatternList.length; ++j)
i18n.registerBugPattern(bugPatternList[j]);
// Register the BugCodes
BugCode[] bugCodeList = pluginLoader.getBugCodeList();
for (int j = 0; j < bugCodeList.length; ++j)
i18n.registerBugCode(bugCodeList[j]);
++numLoaded;
} catch (Exception e) {
System.err.println("Warning: could not load plugin " + file.getPath() + ": " + e.toString());
}
}
//System.out.println("Loaded " + numLoaded + " plugins");
}
}
// vim:ts=4 |
package edu.umd.cs.findbugs.ba.obl;
import java.util.Iterator;
import java.util.Map;
import org.apache.bcel.generic.InstructionHandle;
import org.apache.bcel.generic.MethodGen;
import edu.umd.cs.findbugs.SystemProperties;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.ba.BasicBlock;
import edu.umd.cs.findbugs.ba.DataflowAnalysisException;
import edu.umd.cs.findbugs.ba.DepthFirstSearch;
import edu.umd.cs.findbugs.ba.Edge;
import edu.umd.cs.findbugs.ba.ForwardDataflowAnalysis;
import edu.umd.cs.findbugs.classfile.Global;
import edu.umd.cs.findbugs.classfile.IErrorLogger;
import java.util.HashSet;
import java.util.Set;
public class ObligationAnalysis
extends ForwardDataflowAnalysis<StateSet> {
private static final boolean DEBUG = SystemProperties.getBoolean("oa.debug");
private MethodGen methodGen;
private ObligationFactory factory;
private ObligationPolicyDatabase database;
private IErrorLogger errorLogger;
/**
* Constructor.
*
* @param dfs a DepthFirstSearch on the method to be analyzed
* @param methodGen the MethodGen of the method being analyzed
* @param factory the ObligationFactory defining the obligation types
* @param database the PolicyDatabase defining the methods which
* add and delete obligations
* @param errorLogger callback to use when reporting
* missing classes
*/
public ObligationAnalysis(
DepthFirstSearch dfs,
MethodGen methodGen,
ObligationFactory factory,
ObligationPolicyDatabase database,
IErrorLogger errorLogger) {
super(dfs);
this.methodGen = methodGen;
this.factory = factory;
this.database = database;
this.errorLogger = errorLogger;
}
public StateSet createFact() {
return new StateSet(factory);
}
@Override
public boolean isFactValid(StateSet fact) {
return fact.isValid();
}
@Override
public void transferInstruction(InstructionHandle handle, BasicBlock basicBlock, StateSet fact)
throws DataflowAnalysisException {
Obligation obligation;
try {
if ((obligation = database.addsObligation(handle, methodGen.getConstantPool())) != null) {
// Add obligation to all states
if (DEBUG) { System.out.println("Adding obligation " + obligation.toString()); }
fact.addObligation(obligation, basicBlock.getLabel());
} else if ((obligation = database.deletesObligation(handle, methodGen.getConstantPool())) != null) {
// Delete obligation from all states
if (DEBUG) { System.out.println("Deleting obligation " + obligation.toString()); }
fact.deleteObligation(obligation, basicBlock.getLabel());
}
} catch (ClassNotFoundException e) {
Global.getAnalysisCache().getErrorLogger().reportMissingClass(e);
}
}
/* (non-Javadoc)
* @see edu.umd.cs.findbugs.ba.AbstractDataflowAnalysis#transfer(edu.umd.cs.findbugs.ba.BasicBlock, org.apache.bcel.generic.InstructionHandle, java.lang.Object, java.lang.Object)
*/
@Override
public void transfer(BasicBlock basicBlock, @CheckForNull InstructionHandle end, StateSet start, StateSet result) throws DataflowAnalysisException {
super.transfer(basicBlock, end, start, result);
endTransfer(basicBlock, end, result);
}
private void endTransfer(BasicBlock basicBlock, @CheckForNull InstructionHandle end, StateSet result)
throws DataflowAnalysisException {
// Append this block id to the Paths of all States
for (Iterator<State> i = result.stateIterator(); i.hasNext(); ) {
State state = i.next();
state.getPath().append(basicBlock.getLabel());
}
}
/* (non-Javadoc)
* @see edu.umd.cs.findbugs.ba.DataflowAnalysis#copy(edu.umd.cs.findbugs.ba.obl.StateSet, edu.umd.cs.findbugs.ba.obl.StateSet)
*/
public void copy(StateSet src, StateSet dest) {
dest.copyFrom(src);
}
/* (non-Javadoc)
* @see edu.umd.cs.findbugs.ba.DataflowAnalysis#initEntryFact(edu.umd.cs.findbugs.ba.obl.StateSet)
*/
public void initEntryFact(StateSet fact) throws DataflowAnalysisException {
fact.initEntryFact(factory);
}
/* (non-Javadoc)
* @see edu.umd.cs.findbugs.ba.DataflowAnalysis#makeFactTop(edu.umd.cs.findbugs.ba.obl.StateSet)
*/
public void makeFactTop(StateSet fact) {
fact.setTop();
}
public boolean isTop(StateSet fact) {
return fact.isTop();
}
/* (non-Javadoc)
* @see edu.umd.cs.findbugs.ba.DataflowAnalysis#same(edu.umd.cs.findbugs.ba.obl.StateSet, edu.umd.cs.findbugs.ba.obl.StateSet)
*/
public boolean same(StateSet a, StateSet b) {
return a.equals(b);
}
/* (non-Javadoc)
* @see edu.umd.cs.findbugs.ba.DataflowAnalysis#meetInto(edu.umd.cs.findbugs.ba.obl.StateSet, edu.umd.cs.findbugs.ba.Edge, edu.umd.cs.findbugs.ba.obl.StateSet)
*/
public void meetInto(StateSet fact, Edge edge, StateSet result)
throws DataflowAnalysisException {
final StateSet inputFact = fact;
// Handle easy top and bottom cases
if (inputFact.isTop() || result.isBottom()) {
// Nothing to do
} else if (inputFact.isBottom() || result.isTop()) {
copy(inputFact, result);
} else {
// We will destructively replace the state map of the result fact
// we're building.
final Map<ObligationSet, State> updatedStateMap = result.createEmptyMap();
// Build a Set of all ObligationSets.
Set<ObligationSet> allObligationSets = new HashSet<ObligationSet>();
allObligationSets.addAll(inputFact.getAllObligationSets());
allObligationSets.addAll(result.getAllObligationSets());
// Go through set of all ObligationsSets.
// When both inputFact and result fact have a State
// with a common ObligationSet, we combine them into
// a single State.
for (Iterator<ObligationSet> i = allObligationSets.iterator(); i.hasNext(); ) {
ObligationSet obligationSet = i.next();
State stateInInputFact = inputFact.getStateWithObligationSet(obligationSet);
State stateInResultFact = result.getStateWithObligationSet(obligationSet);
State stateToAdd;
if (stateInInputFact != null && stateInResultFact != null) {
// Combine the two states,
// using the shorter path as the basis
// of the new state's path.
// If both paths are the same length, we arbitrarily choose
// the path from the result fact.
Path path = stateInResultFact.getPath();
if (stateInInputFact.getPath().getLength() < path.getLength()) {
path = stateInInputFact.getPath();
}
stateToAdd = new State(factory);
stateToAdd.getObligationSet().copyFrom(obligationSet);
stateToAdd.getPath().copyFrom(path);
} else if (stateInInputFact != null) {
stateToAdd = stateInInputFact.duplicate();
} else {
// if (stateInResultFact == null ) {
// System.out.println("Missing ObligationSet : " + obligationSet);
// System.out.println(" input fact : " + inputFact);
// System.out.println(" result fact: " + result);
stateToAdd = stateInResultFact.duplicate();
}
updatedStateMap.put(stateToAdd.getObligationSet(), stateToAdd);
}
result.replaceMap(updatedStateMap);
}
}
}
// vim:ts=4 |
package edu.umd.cs.findbugs.classfile;
/**
* An engine for analyzing classes or methods.
*
* @author David Hovemeyer
*/
public interface IAnalysisEngine<DescriptorType> {
/**
* Perform an analysis on class or method named by given descriptor.
*
* @param analysisCache the analysis cache
* @param descriptor the descriptor of the class or method to be analyzed
* @return the result of the analysis of the class or method
*/
public Object analyze(IAnalysisCache analysisCache, DescriptorType descriptor)
throws CheckedAnalysisException;
/**
* Register the analysis engine with given analysis cache.
*
* @param analysisCache the analysis cache
*/
public void registerWith(IAnalysisCache analysisCache);
/**
* Return true if analysis results produced by this
* analysis engine can be recomputed.
* Unless some correctness criterion prevents analysis results
* from being recomputed, analysis engines should
* return true (allowing the cache to be kept to a manageable size).
*
* @return true if analysis results produced by this engine
* can be recomputed, false if for some reason the
* analysis results must be retained indefinitely
*/
public boolean canRecompute();
} |
package edu.umd.cs.findbugs.detect;
import org.apache.bcel.classfile.Code;
import edu.umd.cs.findbugs.BugAccumulator;
import edu.umd.cs.findbugs.BugInstance;
import edu.umd.cs.findbugs.BugReporter;
import edu.umd.cs.findbugs.LocalVariableAnnotation;
import edu.umd.cs.findbugs.OpcodeStack;
import edu.umd.cs.findbugs.ba.SignatureParser;
import edu.umd.cs.findbugs.ba.XField;
import edu.umd.cs.findbugs.bcel.OpcodeStackDetector;
public class FindSelfComparison extends OpcodeStackDetector {
final BugAccumulator bugAccumulator;
public FindSelfComparison(BugReporter bugReporter) {
this.bugAccumulator = new BugAccumulator(bugReporter);
}
String f;
String className;
int state;
int putFieldRegister;
int putFieldPC = Integer.MIN_VALUE;
OpcodeStack.Item putFieldObj;
OpcodeStack.Item putFieldValue;
XField putFieldXField;
@Override
public void visit(Code obj) {
whichRegister = -1;
registerLoadCount = 0;
state = 0;
resetDoubleAssignmentState();
super.visit(obj);
resetDoubleAssignmentState();
bugAccumulator.reportAccumulatedBugs();
}
private void resetDoubleAssignmentState() {
putFieldPC = Integer.MIN_VALUE;
putFieldXField = null;
putFieldValue = null;
putFieldObj = null;
}
@Override
public void sawBranchTo(int target) {
resetDoubleAssignmentState();
}
@Override
public void sawOpcode(int seen) {
// System.out.println(getPC() + " " + OPCODE_NAMES[seen] + " " + whichRegister + " " + registerLoadCount);
if (seen == PUTFIELD) {
OpcodeStack.Item obj = stack.getStackItem(1);
OpcodeStack.Item value = stack.getStackItem(0);
XField f = getXFieldOperand();
if (putFieldPC + 10 > getPC()
&& f.equals(putFieldXField)
&& obj.equals(putFieldObj)) {
int priority = value.equals(putFieldValue) ? NORMAL_PRIORITY : HIGH_PRIORITY;
bugAccumulator.accumulateBug(new BugInstance(this, "SA_FIELD_DOUBLE_ASSIGNMENT", priority)
.addClassAndMethod(this)
.addReferencedField(this), this);
}
putFieldPC = getPC();
putFieldXField = f;
putFieldObj = obj;
putFieldValue = value;
} else if (isReturn(seen))
resetDoubleAssignmentState();
if (false) switch (state) {
case 0:
if (seen == DUP_X1) state = 4;
break;
case 4:
if (seen == PUTFIELD) {
f = getRefConstantOperand();
className = getClassConstantOperand();
OpcodeStack.Item item1 = stack.getStackItem(1);
putFieldRegister = item1.getRegisterNumber();
if (putFieldRegister >= 0)
state = 5;
else state = 0;
} else
state = 0;
break;
case 5:
if (seen == PUTFIELD && getRefConstantOperand().equals(f) && getClassConstantOperand().equals(className)) {
OpcodeStack.Item item1 = stack.getStackItem(1);
if (putFieldRegister == item1.getRegisterNumber())
bugAccumulator.accumulateBug(new BugInstance(this, "SA_FIELD_DOUBLE_ASSIGNMENT", NORMAL_PRIORITY)
.addClassAndMethod(this)
.addReferencedField(this), this);
}
state = 0;
break;
}
switch (seen) {
case INVOKEVIRTUAL:
case INVOKEINTERFACE:
if (getClassName().toLowerCase().indexOf("test") >= 0)
break;
if (getMethodName().toLowerCase().indexOf("test") >= 0)
break;
if (getSuperclassName().toLowerCase().indexOf("test") >= 0)
break;
if (getNextOpcode() == POP)
break;
String name = getNameConstantOperand();
if (name.equals("equals") || name.equals("compareTo")) {
String sig = getSigConstantOperand();
SignatureParser parser = new SignatureParser(sig);
if (parser.getNumParameters() == 1
&& (name.equals("equals") && sig.endsWith(";)Z") || name.equals("compareTo") && sig.endsWith(";)I")))
checkForSelfOperation(seen, "COMPARISON");
}
break;
case LOR:
case LAND:
case LXOR:
case LSUB:
case IOR:
case IAND:
case IXOR:
case ISUB:
checkForSelfOperation(seen, "COMPUTATION");
break;
case FCMPG:
case DCMPG:
case DCMPL:
case FCMPL:
break;
case LCMP:
case IF_ACMPEQ:
case IF_ACMPNE:
case IF_ICMPNE:
case IF_ICMPEQ:
case IF_ICMPGT:
case IF_ICMPLE:
case IF_ICMPLT:
case IF_ICMPGE:
checkForSelfOperation(seen, "COMPARISON");
}
if (isRegisterLoad() && seen != IINC) {
if (getRegisterOperand() == whichRegister) registerLoadCount++;
else {
whichRegister = getRegisterOperand();
registerLoadCount = 1;
}
} else {
whichRegister = -1;
registerLoadCount = 0;
}
}
int whichRegister;
int registerLoadCount;
private void checkForSelfOperation(int opCode, String op) {
{
OpcodeStack.Item item0 = stack.getStackItem(0);
OpcodeStack.Item item1 = stack.getStackItem(1);
if (item0.getSignature().equals("D")
|| item0.getSignature().equals("F"))
return;
if (item1.getSignature().equals("D")
|| item1.getSignature().equals("F"))
return;
XField field0 = item0.getXField();
XField field1 = item1.getXField();
int fr0 = item0.getFieldLoadedFromRegister();
int fr1 = item1.getFieldLoadedFromRegister();
if (field0 != null && field0.equals(field1) && fr0 != -1 && fr0 == fr1)
bugAccumulator.accumulateBug(new BugInstance(this,
"SA_FIELD_SELF_" + op, NORMAL_PRIORITY)
.addClassAndMethod(this).addField(field0), this);
else if (opCode == IXOR && item0.equals(item1)) {
LocalVariableAnnotation localVariableAnnotation = LocalVariableAnnotation
.getLocalVariableAnnotation(this, item0);
if (localVariableAnnotation != null)
bugAccumulator.accumulateBug(new BugInstance(this,
"SA_LOCAL_SELF_" + op, HIGH_PRIORITY)
.addClassAndMethod(this).add(
localVariableAnnotation),this);
} else if (opCode == ISUB && registerLoadCount >= 2) { // let FindSelfComparison2 report this; more accurate
bugAccumulator.accumulateBug(new BugInstance(this,
"SA_LOCAL_SELF_" + op, (opCode == ISUB || opCode == LSUB || opCode == INVOKEINTERFACE || opCode == INVOKEVIRTUAL) ? NORMAL_PRIORITY : HIGH_PRIORITY)
.addClassAndMethod(this).add(
LocalVariableAnnotation
.getLocalVariableAnnotation(
getMethod(), whichRegister, getPC(),
getPC() - 1)),this);
}
}
}
} |
package edu.umd.cs.findbugs.detect;
import static org.apache.bcel.Constants.*;
import java.util.BitSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NoSuchElementException;
import java.util.Set;
import org.apache.bcel.classfile.LocalVariable;
import org.apache.bcel.classfile.LocalVariableTable;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.generic.ANEWARRAY;
import org.apache.bcel.generic.ConstantPoolGen;
import org.apache.bcel.generic.IINC;
import org.apache.bcel.generic.INVOKESPECIAL;
import org.apache.bcel.generic.Instruction;
import org.apache.bcel.generic.InstructionHandle;
import org.apache.bcel.generic.InvokeInstruction;
import org.apache.bcel.generic.MULTIANEWARRAY;
import org.apache.bcel.generic.NEWARRAY;
import org.apache.bcel.generic.POP;
import org.apache.bcel.generic.POP2;
import org.apache.bcel.generic.StoreInstruction;
import org.apache.bcel.generic.Type;
import edu.umd.cs.findbugs.BugInstance;
import edu.umd.cs.findbugs.BugReporter;
import edu.umd.cs.findbugs.Detector;
import edu.umd.cs.findbugs.StringAnnotation;
import edu.umd.cs.findbugs.ba.BasicBlock;
import edu.umd.cs.findbugs.ba.CFG;
import edu.umd.cs.findbugs.ba.ClassContext;
import edu.umd.cs.findbugs.ba.DataflowAnalysisException;
import edu.umd.cs.findbugs.ba.EdgeTypes;
import edu.umd.cs.findbugs.ba.Location;
import edu.umd.cs.findbugs.ba.XClass;
import edu.umd.cs.findbugs.ba.XMethod;
import edu.umd.cs.findbugs.ba.type.TypeAnalysis;
import edu.umd.cs.findbugs.ba.type.TypeFrame;
import edu.umd.cs.findbugs.ba.vna.ValueNumber;
import edu.umd.cs.findbugs.ba.vna.ValueNumberAnalysis;
import edu.umd.cs.findbugs.ba.vna.ValueNumberFrame;
import edu.umd.cs.findbugs.classfile.CheckedAnalysisException;
import edu.umd.cs.findbugs.classfile.DescriptorFactory;
import edu.umd.cs.findbugs.classfile.Global;
import edu.umd.cs.findbugs.classfile.MethodDescriptor;
import edu.umd.cs.findbugs.detect.FindNoSideEffectMethods.MethodSideEffectStatus;
import edu.umd.cs.findbugs.detect.FindNoSideEffectMethods.NoSideEffectMethodsDatabase;
/**
* @author Tagir Valeev
*/
public class FindUselessObjects implements Detector {
private final BugReporter reporter;
private final NoSideEffectMethodsDatabase noSideEffectMethods;
private static class ValueInfo {
Location created;
String var;
int origValue;
boolean hasObjectOnlyCall;
boolean escaped;
boolean used;
boolean derivedEscaped;
public BitSet origValues;
public BitSet derivedValues = new BitSet();
Type type;
public ValueInfo(int origValue, Location location, Type type) {
this.created = location;
this.origValue = origValue;
this.type = type;
}
@Override
public String toString() {
return "[" + (escaped ? "E" : "-") + (hasObjectOnlyCall ? "O" : "-") + (used ? "U" : "-")
+ (derivedEscaped ? "D" : "-") + "] " + (var == null ? "" : var + " ") + type + " " + created;
}
}
private class UselessValuesContext {
ValueNumberAnalysis vna;
TypeAnalysis ta;
CFG cfg;
int count;
Map<Integer, ValueInfo> observedValues = new HashMap<>();
ConstantPoolGen cpg;
Map<Integer, Set<ValueInfo>> values;
ValueNumber thisValue;
ClassContext classContext;
Method method;
UselessValuesContext(ClassContext classContext, Method method) throws CheckedAnalysisException {
this.classContext = classContext;
this.method = method;
cfg = classContext.getCFG(method);
cpg = cfg.getMethodGen().getConstantPool();
ta = classContext.getTypeDataflow(method).getAnalysis();
vna = classContext.getValueNumberDataflow(method).getAnalysis();
}
void initObservedValues() throws DataflowAnalysisException {
for(Iterator<Location> iterator = cfg.locationIterator(); iterator.hasNext(); ) {
Location location = iterator.next();
Instruction instruction = location.getHandle().getInstruction();
if(instruction instanceof ANEWARRAY || instruction instanceof NEWARRAY || instruction instanceof MULTIANEWARRAY) {
int number = vna.getFactAfterLocation(location).getTopValue().getNumber();
TypeFrame typeFrame = ta.getFactAfterLocation(location);
if(typeFrame.isValid()) {
Type type = typeFrame.getTopValue();
observedValues.put(number, new ValueInfo(number, location, type));
}
} else if(instruction instanceof INVOKESPECIAL) {
InvokeInstruction inv = (InvokeInstruction) instruction;
if (inv.getMethodName(cpg).equals("<init>")
&& noSideEffectMethods.hasNoSideEffect(new MethodDescriptor(inv, cpg))) {
int number = vna.getFactAtLocation(location).getStackValue(inv.consumeStack(cpg)-1).getNumber();
TypeFrame typeFrame = ta.getFactAtLocation(location);
if(typeFrame.isValid()) {
Type type = typeFrame.getStackValue(inv.consumeStack(cpg)-1);
observedValues.put(number, new ValueInfo(number, location, type));
}
}
}
}
thisValue = vna.getThisValue();
if(thisValue != null) {
observedValues.remove(thisValue.getNumber());
}
count = observedValues.size();
}
void enhanceViaMergeTree() {
values = new HashMap<>();
for (Entry<Integer, ValueInfo> entry : observedValues.entrySet()) {
BitSet outputSet = vna.getMergeTree().getTransitiveOutputSet(entry.getKey());
outputSet.set(entry.getKey());
entry.getValue().origValues = outputSet;
for (int i = outputSet.nextSetBit(0); i >= 0; i = outputSet.nextSetBit(i+1)) {
Set<ValueInfo> list = values.get(i);
if(list == null) {
list = new HashSet<>();
values.put(i, list);
}
list.add(entry.getValue());
}
}
}
boolean setEscape(Set<ValueInfo> vals) {
boolean result = false;
for(ValueInfo vi : vals) {
result |= !vi.escaped;
vi.escaped = true;
count
}
return result;
}
boolean setDerivedEscape(Set<ValueInfo> vals, ValueNumber vn) {
boolean result = false;
for(ValueInfo vi : vals) {
if(vi.origValues.get(vn.getNumber())) {
result |= !vi.derivedEscaped;
vi.derivedEscaped = true;
}
}
return result;
}
boolean setUsed(Set<ValueInfo> vals) {
boolean result = false;
for(ValueInfo vi : vals) {
result |= !vi.used;
vi.used = true;
}
return result;
}
boolean setObjectOnly(Set<ValueInfo> vals, ValueNumber vn) {
boolean result = false;
for(ValueInfo vi : vals) {
if(vi.origValues.get(vn.getNumber()) || (!vi.derivedEscaped && vi.derivedValues.get(vn.getNumber()))) {
result |= !vi.hasObjectOnlyCall;
vi.hasObjectOnlyCall = true;
} else {
result |= !vi.escaped;
vi.escaped = true;
count
}
}
return result;
}
boolean propagateValues(Set<ValueInfo> vals, ValueNumber origNumber, ValueNumber vn) {
int number = vn.getNumber();
if(vals.size() == 1 && vals.iterator().next().origValue == number) {
return false;
}
boolean result = setUsed(vals);
if(origNumber != null) {
for(ValueInfo vi : vals) {
if(vi.origValues.get(origNumber.getNumber()) && !vi.derivedValues.get(number)) {
vi.derivedValues.set(number);
result = true;
}
}
}
Set<ValueInfo> list = values.get(number);
if(list == null) {
list = new HashSet<>();
values.put(number, list);
}
result |= list.addAll(vals);
BitSet outputSet = vna.getMergeTree().getTransitiveOutputSet(number);
for (int i = outputSet.nextSetBit(0); i >= 0; i = outputSet.nextSetBit(i+1)) {
list = values.get(i);
if(list == null) {
list = new HashSet<>();
values.put(i, list);
}
result |= list.addAll(vals);
}
return result;
}
boolean propagateToReturnValue(Set<ValueInfo> vals, ValueNumber vn, GenLocation location, MethodDescriptor m)
throws DataflowAnalysisException {
for(ValueInfo vi : vals) {
if(vi.type.getSignature().startsWith("[") && vi.hasObjectOnlyCall && vi.var == null && vn.getNumber() == vi.origValue) {
// Ignore initialized arrays passed to methods
vi.escaped = true;
count
}
}
if (Type.getReturnType(m.getSignature()) == Type.VOID || location instanceof ExceptionLocation) {
return false;
}
InstructionHandle nextHandle = location.getHandle().getNext();
if (nextHandle == null || (nextHandle.getInstruction() instanceof POP || nextHandle.getInstruction() instanceof POP2)) {
return false;
}
return propagateValues(vals, null, location.frameAfter().getTopValue());
}
boolean isEmpty() {
return count == 0;
}
Iterator<GenLocation> genIterator() {
return new Iterator<FindUselessObjects.GenLocation>() {
Iterator<Location> locIterator = cfg.locationIterator();
Iterator<BasicBlock> blockIterator = cfg.blockIterator();
GenLocation next = advance();
private GenLocation advance() {
if(locIterator.hasNext()) {
return new RegularLocation(ta, vna, locIterator.next());
}
while(blockIterator.hasNext()) {
BasicBlock block = blockIterator.next();
if(block.isExceptionThrower() && cfg.getOutgoingEdgeWithType(block, EdgeTypes.FALL_THROUGH_EDGE) == null) {
return new ExceptionLocation(ta, vna, block);
}
}
return null;
}
@Override
public boolean hasNext() {
return next != null;
}
@Override
public GenLocation next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
GenLocation cur = next;
next = advance();
return cur;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
boolean escaped(ValueNumber vn) {
Set<ValueInfo> vals = values.get(vn.getNumber());
if(vals == null) {
return true;
}
for(ValueInfo vi : vals) {
if(vi.escaped) {
return true;
}
}
return false;
}
Set<ValueInfo> getLiveVals(ValueNumber vn) {
Set<ValueInfo> vals = this.values.get(vn.getNumber());
if(vals == null) {
return null;
}
if(vals.size() == 1) {
return vals.iterator().next().escaped ? null : vals;
}
Set<ValueInfo> result = new HashSet<>();
for(ValueInfo vi : vals) {
if(!vi.escaped) {
result.add(vi);
}
}
return result.isEmpty() ? null : result;
}
void report() {
for(ValueInfo vi : observedValues.values()) {
if(!vi.escaped) {
if(vi.hasObjectOnlyCall && vi.used && vi.var == null) {
continue;
}
if(vi.hasObjectOnlyCall || (vi.used && vi.var != null)) {
BugInstance bug = new BugInstance(vi.var == null ? "UC_USELESS_OBJECT_STACK" : "UC_USELESS_OBJECT",
NORMAL_PRIORITY).addClassAndMethod(classContext.getJavaClass(), method);
if(vi.var != null) {
bug.add(new StringAnnotation(vi.var));
}
reporter.reportBug(bug.addType(vi.type).addSourceLine(classContext, method, vi.created));
}
}
}
}
}
private static interface GenLocation {
InstructionHandle getHandle();
TypeFrame typeFrameBefore() throws DataflowAnalysisException;
ValueNumberFrame frameBefore();
ValueNumberFrame frameAfter();
}
private static class RegularLocation implements GenLocation {
Location loc;
ValueNumberAnalysis vna;
TypeAnalysis ta;
public RegularLocation(TypeAnalysis ta, ValueNumberAnalysis vna, Location loc) {
this.ta = ta;
this.vna = vna;
this.loc = loc;
}
@Override
public InstructionHandle getHandle() {
return loc.getHandle();
}
@Override
public ValueNumberFrame frameBefore() {
return vna.getFactAtLocation(loc);
}
@Override
public ValueNumberFrame frameAfter() {
return vna.getFactAfterLocation(loc);
}
@Override
public TypeFrame typeFrameBefore() throws DataflowAnalysisException {
return ta.getFactAtLocation(loc);
}
@Override
public String toString() {
return loc.toString();
}
}
private static class ExceptionLocation implements GenLocation {
BasicBlock b;
ValueNumberAnalysis vna;
TypeAnalysis ta;
public ExceptionLocation(TypeAnalysis ta, ValueNumberAnalysis vna, BasicBlock block) {
this.vna = vna;
this.ta = ta;
this.b = block;
}
@Override
public InstructionHandle getHandle() {
return b.getExceptionThrower();
}
@Override
public ValueNumberFrame frameBefore() {
return vna.getStartFact(b);
}
@Override
public ValueNumberFrame frameAfter() {
return vna.getResultFact(b);
}
@Override
public TypeFrame typeFrameBefore() {
return ta.getStartFact(b);
}
@Override
public String toString() {
return "ex: "+b.getExceptionThrower()+" at "+b;
}
}
public FindUselessObjects(BugReporter reporter) {
this.reporter = reporter;
this.noSideEffectMethods = Global.getAnalysisCache().getDatabase(NoSideEffectMethodsDatabase.class);
}
@Override
public void visitClassContext(ClassContext classContext) {
for(Method method : classContext.getMethodsInCallOrder()) {
if(method.isAbstract() || method.isNative()) {
continue;
}
try {
analyzeMethod(classContext, method);
} catch (CheckedAnalysisException e) {
reporter.logError("Error analyzing "+method+" (class: "+classContext.getJavaClass().getClassName()+")", e);
}
}
}
private void analyzeMethod(ClassContext classContext, Method method) throws CheckedAnalysisException {
LocalVariableTable lvt = method.getLocalVariableTable();
UselessValuesContext context = new UselessValuesContext(classContext, method);
context.initObservedValues();
if(context.isEmpty()) {
return;
}
context.enhanceViaMergeTree();
boolean changed;
do {
changed = false;
for(Iterator<GenLocation> iterator = context.genIterator(); iterator.hasNext() && !context.isEmpty(); ) {
GenLocation location = iterator.next();
Instruction inst = location.getHandle().getInstruction();
ValueNumberFrame before = location.frameBefore();
if(inst instanceof IINC) {
int index = ((IINC)inst).getIndex();
Set<ValueInfo> vals = context.getLiveVals(before.getValue(index));
if(vals != null) {
changed |= context.propagateValues(vals, null, location.frameAfter().getValue(index));
}
continue;
}
int nconsumed = inst.consumeStack(context.cpg);
if(nconsumed > 0) {
ValueNumber[] vns = new ValueNumber[nconsumed];
before.getTopStackWords(vns);
for(int i=0; i<nconsumed; i++) {
ValueNumber vn = vns[i];
Set<ValueInfo> vals = context.getLiveVals(vn);
if(vals != null) {
switch(inst.getOpcode()) {
case ASTORE:
case ASTORE_0:
case ASTORE_1:
case ASTORE_2:
case ASTORE_3:
for(ValueInfo vi : vals) {
if(vi.var == null && vi.origValue == vn.getNumber()) {
int index = ((StoreInstruction)inst).getIndex();
LocalVariable lv = lvt == null ? null : lvt.getLocalVariable(index, location.getHandle().getNext().getPosition());
vi.var = lv == null ? "var$"+index : lv.getName();
vi.hasObjectOnlyCall = false;
changed = true;
}
}
break;
case POP:
case POP2:
case DUP:
case DUP2:
case DUP_X1:
case DUP2_X1:
case ISTORE:
case ISTORE_0:
case ISTORE_1:
case ISTORE_2:
case ISTORE_3:
case LSTORE:
case LSTORE_0:
case LSTORE_1:
case LSTORE_2:
case LSTORE_3:
case FSTORE:
case FSTORE_0:
case FSTORE_1:
case FSTORE_2:
case FSTORE_3:
case DSTORE:
case DSTORE_0:
case DSTORE_1:
case DSTORE_2:
case DSTORE_3:
case SWAP:
case IMPDEP1:
case IMPDEP2:
case CHECKCAST:
case MONITORENTER:
break;
case IADD:
case LADD:
case FADD:
case DADD:
case ISUB:
case LSUB:
case FSUB:
case DSUB:
case IMUL:
case DMUL:
case LMUL:
case FMUL:
case IDIV:
case DDIV:
case LDIV:
case FDIV:
case INEG:
case LNEG:
case FNEG:
case DNEG:
case IREM:
case LREM:
case FREM:
case DREM:
case ISHL:
case LSHL:
case ISHR:
case LSHR:
case IUSHR:
case LUSHR:
case IAND:
case LAND:
case IOR:
case LOR:
case IXOR:
case LXOR:
case I2L:
case I2F:
case I2D:
case L2I:
case L2F:
case L2D:
case F2I:
case F2L:
case F2D:
case D2I:
case D2L:
case D2F:
case I2B:
case I2C:
case I2S:
case LCMP:
case FCMPL:
case FCMPG:
case DCMPL:
case DCMPG:
case ARRAYLENGTH:
changed |= context.propagateValues(vals, null, location.frameAfter().getTopValue());
break;
case GETFIELD:
case AALOAD:
case DALOAD:
case BALOAD:
case CALOAD:
case LALOAD:
case SALOAD:
case IALOAD:
changed |= context.propagateValues(vals, vn, location.frameAfter().getTopValue());
break;
case AASTORE:
case DASTORE:
case BASTORE:
case CASTORE:
case LASTORE:
case SASTORE:
case IASTORE:
case PUTFIELD:
if(i == 0) {
ValueNumber value = vns[vns.length-1];
if(!value.hasFlag(ValueNumber.CONSTANT_VALUE) && !value.hasFlag(ValueNumber.CONSTANT_CLASS_OBJECT) &&
!context.observedValues.containsKey(value.getNumber())) {
changed |= context.setDerivedEscape(vals, vn);
}
changed |= context.setObjectOnly(vals, vn);
} else {
if(context.escaped(vns[0])) {
changed |= context.setEscape(vals);
} else {
changed |= context.propagateValues(vals, null, vns[0]);
}
}
break;
case INVOKESTATIC:
case INVOKESPECIAL:
case INVOKEINTERFACE:
case INVOKEVIRTUAL:
MethodDescriptor m = new MethodDescriptor((InvokeInstruction) inst, context.cpg);
XMethod xMethod = null;
try {
Type type = location.typeFrameBefore().getStackValue(nconsumed-1);
xMethod = Global
.getAnalysisCache()
.getClassAnalysis(XClass.class,
DescriptorFactory.createClassDescriptorFromSignature(type.getSignature()))
.findMatchingMethod(m);
} catch (CheckedAnalysisException e) {
// ignore
}
if(xMethod != null) {
m = xMethod.getMethodDescriptor();
}
MethodSideEffectStatus status = noSideEffectMethods.status(m);
if(status == MethodSideEffectStatus.NSE || status == MethodSideEffectStatus.SE_CLINIT) {
if(m.getName().equals("<init>")) {
if(vns[0].equals(context.thisValue)) {
changed |= context.setEscape(vals);
} else {
changed |= context.propagateValues(vals, null, vns[0]);
}
} else {
changed |= context.propagateToReturnValue(vals, vn, location, m);
}
break;
}
if(status == MethodSideEffectStatus.OBJ) {
if(i == 0) {
changed |= context.setDerivedEscape(vals, vn);
changed |= context.propagateToReturnValue(vals, vn, location, m);
changed |= context.setObjectOnly(vals, vn);
break;
} else {
if(!context.escaped(vns[0])) {
changed |= context.propagateValues(vals, null, vns[0]);
changed |= context.propagateToReturnValue(vals, vn, location, m);
break;
}
}
}
changed |= context.setEscape(vals);
break;
default:
changed |= context.setEscape(vals);
break;
}
}
}
}
}
} while(changed);
context.report();
}
@Override
public void report() {
}
} |
package com.firefly.client.http2;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import com.firefly.codec.http2.model.BadMessageException;
import com.firefly.codec.http2.model.Cookie;
import com.firefly.codec.http2.model.CookieGenerator;
import com.firefly.codec.http2.model.CookieParser;
import com.firefly.codec.http2.model.HttpField;
import com.firefly.codec.http2.model.HttpFields;
import com.firefly.codec.http2.model.HttpHeader;
import com.firefly.codec.http2.model.HttpMethod;
import com.firefly.codec.http2.model.HttpURI;
import com.firefly.codec.http2.model.HttpVersion;
import com.firefly.codec.http2.model.MetaData;
import com.firefly.codec.http2.model.MetaData.Response;
import com.firefly.codec.http2.model.MimeTypes;
import com.firefly.codec.http2.stream.HTTPOutputStream;
import com.firefly.utils.concurrent.FuturePromise;
import com.firefly.utils.concurrent.Promise;
import com.firefly.utils.concurrent.Scheduler;
import com.firefly.utils.concurrent.Schedulers;
import com.firefly.utils.function.Action1;
import com.firefly.utils.function.Action3;
import com.firefly.utils.io.BufferUtils;
import com.firefly.utils.io.EofException;
import com.firefly.utils.json.Json;
import com.firefly.utils.json.JsonArray;
import com.firefly.utils.json.JsonObject;
import com.firefly.utils.lang.AbstractLifeCycle;
import com.firefly.utils.lang.pool.BlockingPool;
import com.firefly.utils.lang.pool.BoundedBlockingPool;
import com.firefly.utils.log.Log;
import com.firefly.utils.log.LogFactory;
public class SimpleHTTPClient extends AbstractLifeCycle {
private static Log log = LogFactory.getInstance().getLog("firefly-system");
protected final HTTP2Client http2Client;
protected final Scheduler scheduler;
private final Map<RequestBuilder, BlockingPool<HTTPClientConnection>> poolMap = new ConcurrentHashMap<>();
public SimpleHTTPClient() {
this(new SimpleHTTPClientConfiguration());
}
public SimpleHTTPClient(SimpleHTTPClientConfiguration http2Configuration) {
http2Client = new HTTP2Client(http2Configuration);
scheduler = Schedulers.createScheduler();
start();
}
public class SimpleResponse {
Response response;
List<ByteBuffer> responseBody = new ArrayList<>();
public Response getResponse() {
return response;
}
public void setResponse(Response response) {
this.response = response;
}
public List<ByteBuffer> getResponseBody() {
return responseBody;
}
public void setResponseBody(List<ByteBuffer> responseBody) {
this.responseBody = responseBody;
}
public String getStringBody() {
StringBuilder builder = new StringBuilder();
responseBody.stream().map(BufferUtils::toUTF8String).forEach(builder::append);
return builder.toString();
}
public <T> T getJsonBody(Class<T> clazz) {
return Json.toObject(getStringBody(), clazz);
}
public JsonObject getJsonObjectBody() {
return Json.toJsonObject(getStringBody());
}
public JsonArray getJsonArrayBody() {
return Json.toJsonArray(getStringBody());
}
public List<Cookie> getCookies() {
return response.getFields().getValuesList(HttpHeader.SET_COOKIE.asString()).stream()
.map(CookieParser::parseSetCookie).collect(Collectors.toList());
}
}
public class RequestBuilder {
String host;
int port;
MetaData.Request request;
List<ByteBuffer> requestBody = new ArrayList<>();
Action1<Response> messageComplete;
Action1<ByteBuffer> content;
Action3<Integer, String, Response> badMessage;
Action1<Response> earlyEof;
Promise<HTTPOutputStream> promise;
Action1<HTTPOutputStream> output;
FuturePromise<SimpleResponse> future;
SimpleResponse simpleResponse;
public RequestBuilder cookies(List<Cookie> cookies) {
request.getFields().put(HttpHeader.COOKIE, CookieGenerator.generateCookies(cookies));
return this;
}
public RequestBuilder put(String name, List<String> list) {
request.getFields().put(name, list);
return this;
}
public RequestBuilder put(HttpHeader header, String value) {
request.getFields().put(header, value);
return this;
}
public RequestBuilder put(String name, String value) {
request.getFields().put(name, value);
return this;
}
public RequestBuilder put(HttpField field) {
request.getFields().put(field);
return this;
}
public RequestBuilder addAll(HttpFields fields) {
request.getFields().addAll(fields);
return this;
}
public RequestBuilder add(HttpField field) {
request.getFields().add(field);
return this;
}
public RequestBuilder jsonBody(Object obj) {
return put(HttpHeader.CONTENT_TYPE, MimeTypes.Type.APPLICATION_JSON.asString()).body(Json.toJson(obj));
}
public RequestBuilder body(String content) {
return body(content, StandardCharsets.UTF_8);
}
public RequestBuilder body(String content, Charset charset) {
return write(BufferUtils.toBuffer(content, charset));
}
public RequestBuilder write(ByteBuffer buffer) {
requestBody.add(buffer);
return this;
}
public RequestBuilder output(Action1<HTTPOutputStream> output) {
this.output = output;
return this;
}
public RequestBuilder output(Promise<HTTPOutputStream> promise) {
this.promise = promise;
return this;
}
public RequestBuilder messageComplete(Action1<Response> messageComplete) {
this.messageComplete = messageComplete;
return this;
}
public RequestBuilder content(Action1<ByteBuffer> content) {
this.content = content;
return this;
}
public RequestBuilder badMessage(Action3<Integer, String, Response> badMessage) {
this.badMessage = badMessage;
return this;
}
public RequestBuilder earlyEof(Action1<Response> earlyEof) {
this.earlyEof = earlyEof;
return this;
}
public FuturePromise<SimpleResponse> submit() {
submit(new FuturePromise<>());
return future;
}
public void submit(FuturePromise<SimpleResponse> future) {
this.future = future;
simpleResponse = new SimpleResponse();
send(this);
}
public void submit(Action1<SimpleResponse> action) {
FuturePromise<SimpleResponse> future = new FuturePromise<SimpleResponse>() {
public void succeeded(SimpleResponse t) {
action.call(t);
}
public void failed(Throwable c) {
log.error("http request exception", c);
}
};
submit(future);
}
public void end() {
send(this);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + getOuterType().hashCode();
result = prime * result + ((host == null) ? 0 : host.hashCode());
result = prime * result + port;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
RequestBuilder other = (RequestBuilder) obj;
if (!getOuterType().equals(other.getOuterType()))
return false;
if (host == null) {
if (other.host != null)
return false;
} else if (!host.equals(other.host))
return false;
if (port != other.port)
return false;
return true;
}
private SimpleHTTPClient getOuterType() {
return SimpleHTTPClient.this;
}
}
public RequestBuilder get(String url) {
return request(HttpMethod.GET.asString(), url);
}
public RequestBuilder post(String url) {
return request(HttpMethod.POST.asString(), url);
}
public RequestBuilder head(String url) {
return request(HttpMethod.HEAD.asString(), url);
}
public RequestBuilder put(String url) {
return request(HttpMethod.PUT.asString(), url);
}
public RequestBuilder delete(String url) {
return request(HttpMethod.DELETE.asString(), url);
}
public RequestBuilder request(HttpMethod method, String url) {
return request(method.asString(), url);
}
public RequestBuilder request(String method, String url) {
try {
return request(method, new URL(url));
} catch (MalformedURLException e) {
log.error("url exception", e);
throw new IllegalArgumentException(e);
}
}
public RequestBuilder request(String method, URL url) {
try {
RequestBuilder req = new RequestBuilder();
req.host = url.getHost();
req.port = url.getPort() < 0 ? url.getDefaultPort() : url.getPort();
req.request = new MetaData.Request(method, new HttpURI(url.toURI()), HttpVersion.HTTP_1_1,
new HttpFields());
return req;
} catch (URISyntaxException e) {
log.error("url exception", e);
throw new IllegalArgumentException(e);
}
}
private void release(HTTPClientConnection connection, BlockingPool<HTTPClientConnection> pool) {
boolean released = (Boolean) connection.getAttachment();
if (released == false) {
connection.setAttachment(true);
pool.release(connection);
}
}
protected void send(RequestBuilder r) {
SimpleHTTPClientConfiguration config = (SimpleHTTPClientConfiguration) http2Client.getHttp2Configuration();
BlockingPool<HTTPClientConnection> pool = getPool(r);
try {
HTTPClientConnection connection = pool.take(config.getTakeConnectionTimeout(), TimeUnit.MILLISECONDS);
connection.setAttachment(false);
if (connection.getHttpVersion() == HttpVersion.HTTP_2) {
release(connection, pool);
}
log.debug("take the connection {} from pool, released: {}", connection.getSessionId(),
connection.getAttachment());
ClientHTTPHandler handler = new ClientHTTPHandler.Adapter()
.messageComplete((req, resp, outputStream, conn) -> {
release(connection, pool);
log.debug("complete request of the connection {} , released: {}", connection.getSessionId(),
connection.getAttachment());
if (r.messageComplete != null) {
r.messageComplete.call(resp);
}
if (r.future != null) {
r.simpleResponse.response = resp;
r.future.succeeded(r.simpleResponse);
}
return true;
}).content((buffer, req, resp, outputStream, conn) -> {
if (r.content != null) {
r.content.call(buffer);
}
if (r.future != null && r.simpleResponse != null) {
r.simpleResponse.responseBody.add(buffer);
}
return false;
}).badMessage((errCode, reason, req, resp, outputStream, conn) -> {
release(connection, pool);
log.debug("bad message of the connection {} , released: {}", connection.getSessionId(),
connection.getAttachment());
if (r.badMessage != null) {
r.badMessage.call(errCode, reason, resp);
}
if (r.future != null) {
r.simpleResponse.response = resp;
r.future.failed(new BadMessageException(errCode, reason));
}
}).earlyEOF((req, resp, outputStream, conn) -> {
release(connection, pool);
log.debug("eafly EOF of the connection {} , released: {}", connection.getSessionId(),
connection.getAttachment());
if (r.earlyEof != null) {
r.earlyEof.call(resp);
}
if (r.future != null) {
r.simpleResponse.response = resp;
r.future.failed(new EofException("early eof"));
}
});
if (r.requestBody != null && r.requestBody.isEmpty() == false) {
connection.send(r.request, r.requestBody.toArray(BufferUtils.EMPTY_BYTE_BUFFER_ARRAY), handler);
} else if (r.promise != null) {
connection.send(r.request, r.promise, handler);
} else if (r.output != null) {
Promise<HTTPOutputStream> p = new Promise<HTTPOutputStream>() {
public void succeeded(HTTPOutputStream out) {
r.output.call(out);
}
};
connection.send(r.request, p, handler);
} else {
connection.send(r.request, handler);
}
} catch (InterruptedException e) {
log.error("take connection exception", e);
}
}
private BlockingPool<HTTPClientConnection> getPool(RequestBuilder request) {
BlockingPool<HTTPClientConnection> pool = poolMap.get(request);
if (pool == null) {
synchronized (this) {
if (pool == null) {
SimpleHTTPClientConfiguration config = (SimpleHTTPClientConfiguration) http2Client
.getHttp2Configuration();
pool = new BoundedBlockingPool<>(config.getInitPoolSize(), config.getMaxPoolSize(), () -> {
FuturePromise<HTTPClientConnection> promise = new FuturePromise<>();
http2Client.connect(request.host, request.port, promise);
try {
return promise.get();
} catch (InterruptedException | ExecutionException e) {
log.error("create http connection exception", e);
throw new IllegalStateException(e);
}
}, (conn) -> {
return conn.isOpen();
}, (conn) -> {
try {
conn.close();
} catch (IOException e) {
log.error("close http connection exception", e);
}
});
poolMap.put(request, pool);
return pool;
}
}
}
return pool;
}
@Override
protected void init() {
SimpleHTTPClientConfiguration config = (SimpleHTTPClientConfiguration) http2Client.getHttp2Configuration();
scheduler.scheduleAtFixedRate(() -> {
Iterator<Map.Entry<RequestBuilder, BlockingPool<HTTPClientConnection>>> iterator = poolMap.entrySet()
.iterator();
while (iterator.hasNext()) {
Map.Entry<RequestBuilder, BlockingPool<HTTPClientConnection>> entry = iterator.next();
entry.getValue().cleanup();
if (log.isDebugEnabled()) {
log.debug("clean up connection pool [{}:{}], current pool size is {}", entry.getKey().host,
entry.getKey().port, entry.getValue().size());
}
}
}, config.getCleanupInitialDelay(), config.getCleanupInterval(), TimeUnit.MILLISECONDS);
}
@Override
protected void destroy() {
http2Client.stop();
scheduler.stop();
}
} |
package org.apache.flume.node;
import org.apache.flume.LogicalNode;
import org.apache.flume.lifecycle.LifecycleController;
import org.apache.flume.lifecycle.LifecycleException;
import org.apache.flume.lifecycle.LifecycleState;
import org.apache.flume.node.nodemanager.AbstractLogicalNodeManager;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
public class TestFlumeNode {
private FlumeNode node;
@Before
public void setUp() {
node = new FlumeNode();
node.setName("test-node");
node.setNodeManager(new EmptyLogicalNodeManager());
}
@Ignore("Fails given recent changes to configuration system")
@Test
public void testLifecycle() throws InterruptedException, LifecycleException {
node.start();
boolean reached = LifecycleController.waitForOneOf(node,
LifecycleState.START_OR_ERROR, 5000);
Assert.assertTrue("Matched a known state", reached);
Assert.assertEquals(LifecycleState.START, node.getLifecycleState());
node.stop();
reached = LifecycleController.waitForOneOf(node,
LifecycleState.STOP_OR_ERROR, 5000);
Assert.assertTrue("Matched a known state", reached);
Assert.assertEquals(LifecycleState.STOP, node.getLifecycleState());
}
@Ignore("Fails given recent changes to configuration system")
@Test
public void testAddNodes() throws InterruptedException, LifecycleException {
node.start();
boolean reached = LifecycleController.waitForOneOf(node,
LifecycleState.START_OR_ERROR, 5000);
Assert.assertTrue("Matched a known state", reached);
Assert.assertEquals(LifecycleState.START, node.getLifecycleState());
LogicalNode n1 = new LogicalNode();
node.getNodeManager().add(n1);
node.stop();
reached = LifecycleController.waitForOneOf(node,
LifecycleState.STOP_OR_ERROR, 5000);
Assert.assertTrue("Matched a known state", reached);
Assert.assertEquals(LifecycleState.STOP, node.getLifecycleState());
}
public static class EmptyLogicalNodeManager extends
AbstractLogicalNodeManager {
private LifecycleState lifecycleState;
public EmptyLogicalNodeManager() {
lifecycleState = LifecycleState.IDLE;
}
@Override
public void start() {
lifecycleState = LifecycleState.START;
}
@Override
public void stop() {
lifecycleState = LifecycleState.STOP;
}
@Override
public LifecycleState getLifecycleState() {
return lifecycleState;
}
}
} |
package tachyon.conf;
import java.util.LinkedHashMap;
import java.util.Map;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import tachyon.Constants;
import tachyon.client.RemoteBlockReader;
import tachyon.client.WriteType;
import tachyon.util.NetworkUtils;
import tachyon.worker.DataServer;
import tachyon.worker.netty.ChannelType;
import tachyon.worker.netty.FileTransferType;
/**
* Unit test for TachyonConf class
*/
public class TachyonConfTest {
private static final String DEFAULT_HADOOP_UFS_PREFIX = "hdfs://,s3://,s3n://,glusterfs:///";
private static TachyonConf sDefaultTachyonConf;
private static final Map<String, String> sTestProperties = new LinkedHashMap<String, String>();
private TachyonConf mCustomPropsTachyonConf;
private TachyonConf mSystemPropsTachyonConf;
@AfterClass
public static void afterClass() {
System.clearProperty(Constants.MASTER_HOSTNAME);
System.clearProperty(Constants.MASTER_PORT);
System.clearProperty(Constants.USE_ZOOKEEPER);
}
@BeforeClass
public static void beforeClass() {
// initialize the test properties.
sTestProperties.put("home", "hometest");
sTestProperties.put("homeandpath", "${home}/path1");
sTestProperties.put("homeandstring", "${home} string1");
sTestProperties.put("path2", "path2");
sTestProperties.put("multiplesubs", "${home}/path1/${path2}");
sTestProperties.put("recursive", "${multiplesubs}");
sTestProperties.put("home.port", "8080");
sTestProperties.put("complex.address", "tachyon://${home}:${home.port}");
// initialize the system properties
System.setProperty(Constants.MASTER_HOSTNAME, "master");
System.setProperty(Constants.MASTER_PORT, "20001");
System.setProperty(Constants.USE_ZOOKEEPER, "true");
// initialize
sDefaultTachyonConf = new TachyonConf(false);
}
@Before
public void beforeTests() {
// init TachyonConf
mCustomPropsTachyonConf = new TachyonConf(sTestProperties);
mSystemPropsTachyonConf = new TachyonConf();
}
// test default properties
@Test
public void testCommonDefault() {
String tachyonHome = sDefaultTachyonConf.get(Constants.TACHYON_HOME, null);
Assert.assertTrue(tachyonHome != null);
Assert.assertTrue("/mnt/tachyon_default_home".equals(tachyonHome));
String ufsAddress = sDefaultTachyonConf.get(Constants.UNDERFS_ADDRESS, null);
Assert.assertTrue(ufsAddress != null);
Assert.assertTrue((tachyonHome + "/underFSStorage").equals(ufsAddress));
String value = sDefaultTachyonConf.get(Constants.WEB_RESOURCES, null);
Assert.assertTrue(value != null);
Assert.assertTrue((tachyonHome + "/core/src/main/webapp").equals(value));
value = sDefaultTachyonConf.get(Constants.UNDERFS_HDFS_IMPL, null);
Assert.assertTrue(value != null);
Assert.assertTrue("org.apache.hadoop.hdfs.DistributedFileSystem".equals(value));
value = sDefaultTachyonConf.get(Constants.UNDERFS_HADOOP_PREFIXS, null);
Assert.assertTrue(value != null);
Assert.assertTrue(DEFAULT_HADOOP_UFS_PREFIX.equals(value));
value = sDefaultTachyonConf.get(Constants.UNDERFS_GLUSTERFS_IMPL, null);
Assert.assertTrue(value != null);
Assert.assertTrue("org.apache.hadoop.fs.glusterfs.GlusterFileSystem".equals(value));
value = sDefaultTachyonConf.get(Constants.UNDERFS_DATA_FOLDER, null);
Assert.assertTrue(value != null);
Assert.assertTrue((ufsAddress + "/tachyon/data").equals(value));
value = sDefaultTachyonConf.get(Constants.UNDERFS_WORKERS_FOLDER, null);
Assert.assertTrue(value != null);
Assert.assertTrue((ufsAddress + "/tachyon/workers").equals(value));
boolean booleanValue = sDefaultTachyonConf.getBoolean(Constants.USE_ZOOKEEPER, true);
Assert.assertTrue(!booleanValue);
booleanValue = sDefaultTachyonConf.getBoolean(Constants.IN_TEST_MODE, true);
Assert.assertTrue(!booleanValue);
booleanValue = sDefaultTachyonConf.getBoolean(Constants.ASYNC_ENABLED, true);
Assert.assertTrue(!booleanValue);
int intValue = sDefaultTachyonConf.getInt(Constants.MAX_COLUMNS, 0);
Assert.assertTrue(intValue == 1000);
intValue = sDefaultTachyonConf.getInt(Constants.HOST_RESOLUTION_TIMEOUT_MS, 0);
Assert.assertEquals(Constants.DEFAULT_HOST_RESOLUTION_TIMEOUT_MS, intValue);
long longBytesValue = sDefaultTachyonConf.getBytes(Constants.MAX_TABLE_METADATA_BYTE, 0L);
Assert.assertTrue(longBytesValue == Constants.MB * 5);
}
@Test
public void testMasterDefault() {
String tachyonHome = sDefaultTachyonConf.get(Constants.TACHYON_HOME, null);
Assert.assertTrue(tachyonHome != null);
Assert.assertTrue("/mnt/tachyon_default_home".equals(tachyonHome));
String value = sDefaultTachyonConf.get(Constants.MASTER_JOURNAL_FOLDER, null);
Assert.assertTrue(value != null);
Assert.assertTrue((tachyonHome + "/journal/").equals(value));
value = sDefaultTachyonConf.get(Constants.MASTER_HOSTNAME, null);
Assert.assertTrue(value != null);
Assert.assertTrue(NetworkUtils.getLocalHostName(100).equals(value));
value = sDefaultTachyonConf.get(Constants.MASTER_TEMPORARY_FOLDER, null);
Assert.assertTrue(value != null);
Assert.assertTrue("/tmp".equals(value));
value = sDefaultTachyonConf.get(Constants.MASTER_FORMAT_FILE_PREFIX, null);
Assert.assertTrue(value != null);
Assert.assertTrue(Constants.FORMAT_FILE_PREFIX.equals(value));
value = sDefaultTachyonConf.get(Constants.MASTER_ADDRESS, null);
Assert.assertTrue(value != null);
int intValue = sDefaultTachyonConf.getInt(Constants.MASTER_PORT, 0);
Assert.assertTrue(intValue == 19998);
intValue = sDefaultTachyonConf.getInt(Constants.MASTER_WEB_PORT, 0);
Assert.assertTrue(intValue == 19999);
intValue = sDefaultTachyonConf.getInt(Constants.WEB_THREAD_COUNT, 0);
Assert.assertTrue(intValue == 1);
intValue = sDefaultTachyonConf.getInt(Constants.MASTER_HEARTBEAT_INTERVAL_MS, 0);
Assert.assertTrue(intValue == Constants.SECOND_MS);
intValue = sDefaultTachyonConf.getInt(Constants.MASTER_MIN_WORKER_THREADS, 0);
Assert.assertTrue(intValue == Runtime.getRuntime().availableProcessors());
intValue = sDefaultTachyonConf.getInt(Constants.MASTER_WORKER_TIMEOUT_MS, 0);
Assert.assertTrue(intValue == 10 * Constants.SECOND_MS);
}
@Test
public void testWorkerDefault() {
String value = sDefaultTachyonConf.get(Constants.WORKER_DATA_FOLDER, null);
Assert.assertTrue(value != null);
Assert.assertTrue(("/mnt/ramdisk").equals(value));
Class<? extends DataServer> dataServer =
sDefaultTachyonConf.getClass(Constants.WORKER_DATA_SERVER, null);
Assert.assertTrue(dataServer != null);
Assert.assertTrue(dataServer.equals(Constants.WORKER_DATA_SERVER_CLASS));
ChannelType channelType =
sDefaultTachyonConf.getEnum(Constants.WORKER_NETWORK_NETTY_CHANNEL, ChannelType.NIO);
Assert.assertTrue(channelType != null);
Assert.assertTrue(channelType == ChannelType.defaultType());
FileTransferType fileTransferType =
sDefaultTachyonConf.getEnum(Constants.WORKER_NETTY_FILE_TRANSFER_TYPE,
FileTransferType.MAPPED);
Assert.assertTrue(fileTransferType != null);
Assert.assertTrue(fileTransferType == FileTransferType.MAPPED);
int intValue = sDefaultTachyonConf.getInt(Constants.WORKER_PORT, 0);
Assert.assertTrue(intValue == 29998);
intValue = sDefaultTachyonConf.getInt(Constants.WORKER_DATA_PORT, 0);
Assert.assertTrue(intValue == 29999);
intValue = sDefaultTachyonConf.getInt(Constants.WORKER_HEARTBEAT_TIMEOUT_MS, 0);
Assert.assertTrue(intValue == 10 * Constants.SECOND_MS);
intValue = sDefaultTachyonConf.getInt(Constants.WORKER_TO_MASTER_HEARTBEAT_INTERVAL_MS, 0);
Assert.assertTrue(intValue == Constants.SECOND_MS);
intValue = sDefaultTachyonConf.getInt(Constants.WORKER_MIN_WORKER_THREADS, 0);
Assert.assertTrue(intValue == Runtime.getRuntime().availableProcessors());
intValue = sDefaultTachyonConf.getInt(Constants.WORKER_USER_TIMEOUT_MS, 0);
Assert.assertTrue(intValue == 10 * Constants.SECOND_MS);
intValue = sDefaultTachyonConf.getInt(Constants.WORKER_CHECKPOINT_THREADS, 0);
Assert.assertTrue(intValue == 1);
intValue = sDefaultTachyonConf.getInt(Constants.WORKER_PER_THREAD_CHECKPOINT_CAP_MB_SEC, 0);
Assert.assertTrue(intValue == 1000);
intValue = sDefaultTachyonConf.getInt(Constants.WORKER_NETTY_BOSS_THREADS, 1);
Assert.assertTrue(intValue == 1);
intValue = sDefaultTachyonConf.getInt(Constants.WORKER_NETTY_WORKER_THREADS, 0);
Assert.assertTrue(intValue == 0);
long longValue = sDefaultTachyonConf.getBytes(Constants.WORKER_MEMORY_SIZE, 0L);
Assert.assertTrue(longValue == (128 * Constants.MB));
}
@Test
public void testUserDefault() {
WriteType writeType =
sDefaultTachyonConf.getEnum(Constants.USER_DEFAULT_WRITE_TYPE, WriteType.CACHE_THROUGH);
Assert.assertTrue(writeType != null);
Assert.assertTrue(writeType == WriteType.CACHE_THROUGH);
int intValue = sDefaultTachyonConf.getInt(Constants.USER_FAILED_SPACE_REQUEST_LIMITS, 0);
Assert.assertTrue(intValue == 3);
intValue = sDefaultTachyonConf.getInt(Constants.USER_HEARTBEAT_INTERVAL_MS, 0);
Assert.assertTrue(intValue == Constants.SECOND_MS);
long longValue = sDefaultTachyonConf.getBytes(Constants.USER_QUOTA_UNIT_BYTES, 0L);
Assert.assertTrue(longValue == (8 * Constants.MB));
longValue = sDefaultTachyonConf.getBytes(Constants.USER_FILE_BUFFER_BYTES, 0L);
Assert.assertTrue(longValue == Constants.MB);
longValue = sDefaultTachyonConf.getBytes(Constants.USER_REMOTE_READ_BUFFER_SIZE_BYTE, 0);
Assert.assertTrue(longValue == 8 * Constants.MB);
Class<? extends RemoteBlockReader> reader =
sDefaultTachyonConf.getClass(Constants.USER_REMOTE_BLOCK_READER, null);
Assert.assertTrue(reader != null);
Assert.assertTrue(reader.equals(Constants.USER_REMOTE_BLOCK_READER_CLASS));
}
@Test
public void testVariableSubstitutionSimple() {
String home = mCustomPropsTachyonConf.get("home", null);
Assert.assertTrue("hometest".equals(home));
String homeAndPath = mCustomPropsTachyonConf.get("homeandpath", null);
Assert.assertTrue((home + "/path1").equals(homeAndPath));
String homeAndString = mCustomPropsTachyonConf.get("homeandstring", null);
Assert.assertTrue((home + " string1").equals(homeAndString));
String path2 = mCustomPropsTachyonConf.get("path2", null);
Assert.assertTrue("path2".equals(path2));
String multiplesubs = mCustomPropsTachyonConf.get("multiplesubs", null);
Assert.assertTrue((home + "/path1/" + path2).equals(multiplesubs));
String homePort = mCustomPropsTachyonConf.get("home.port", null);
Assert.assertTrue(("8080").equals(homePort));
sTestProperties.put("complex.address", "tachyon://${home}:${home.port}");
String complexAddress = mCustomPropsTachyonConf.get("complex.address", null);
Assert.assertTrue(("tachyon://" + home + ":" + homePort).equals(complexAddress));
}
@Test
public void testVariableSubstitutionRecursive() {
String multiplesubs = mCustomPropsTachyonConf.get("multiplesubs", null);
String recursive = mCustomPropsTachyonConf.get("recursive", null);
Assert.assertTrue(multiplesubs.equals(recursive));
}
@Test
public void testSystemVariableSubstitutionSample() {
String masterAddress = mSystemPropsTachyonConf.get(Constants.MASTER_ADDRESS, null);
Assert.assertTrue(masterAddress != null);
Assert.assertTrue("tachyon-ft://master:20001".equals(masterAddress));
}
} |
package com.foc.focDataSourceDB.db;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.StringTokenizer;
import com.foc.ConfigInfo;
import com.foc.Globals;
import com.foc.IFocEnvironment;
import com.foc.access.FocDataMap;
import com.foc.business.notifier.FocNotificationConst;
import com.foc.business.notifier.FocNotificationEvent;
import com.foc.business.notifier.FocNotificationManager;
import com.foc.db.DBManager;
import com.foc.desc.FocDesc;
import com.foc.desc.FocObject;
import com.foc.focDataSourceDB.db.connectionPooling.ConnectionCredentials;
import com.foc.focDataSourceDB.db.connectionPooling.ConnectionPool;
import com.foc.focDataSourceDB.db.connectionPooling.CredentialsFileScanner;
import com.foc.focDataSourceDB.db.connectionPooling.StatementWrapper;
public class DBManagerServer {
private ConnectionPool connectionPool = null;
private String dateRequestSQL = null;
private String timeStampRequestSQL = null;
// private boolean transaction_ShouldSurroundWithTransactionIfRequest = false;
// private boolean transaction_Began = false;
// private Thread transactionThread = null ;
// private int nbrOfBeginTransactionsInTransactionThread = 0 ;
//Auxiliary Pools
private HashMap<String, ConnectionPool> auxiliaryPools = null;
public DBManagerServer(){
connectionPool = new ConnectionPool();
Globals.logString("Before Callling the auxPools_LoadFiles");
auxPools_LoadFiles();
}
public void dispose(){
if(connectionPool != null){
connectionPool.dispose();
connectionPool = null;
}
}
private ConnectionPool getConnectionPool(){
return getConnectionPool(null);
}
public ConnectionPool getConnectionPool(String key){
ConnectionPool pool = connectionPool;
if(key != null){
pool = auxPools_Get(key);
}
return pool;
}
public StatementWrapper lockStatement() {
return lockStatement(null);
}
public StatementWrapper lockStatement(String dbSourceKey) {
StatementWrapper stm = null;
ConnectionPool cp = getConnectionPool(dbSourceKey);
if(cp == null){
Globals.logString("Could not getConnectionPool for key:"+dbSourceKey);
}else{
stm = cp.lockStatement();
}
return stm;
}
public void unlockStatement(StatementWrapper stm) {
if(stm != null) stm.unlockStatement();
}
public Connection getConnection() {
return getConnectionPool() != null ? getConnectionPool().getConnection() : null;
}
private String initializeDateRequest(){
if(dateRequestSQL == null || timeStampRequestSQL == null){
try{
DatabaseMetaData dmt = getConnection().getMetaData();
String fcts = dmt.getTimeDateFunctions();
StringTokenizer tokenizer = new StringTokenizer(fcts, ",");
Globals.logString(fcts);
while(tokenizer.hasMoreTokens()){
String tok = tokenizer.nextToken();
if(tok.compareTo("CURDATE") == 0){
if (Globals.getDBManager().getProvider() == DBManager.PROVIDER_ORACLE){
dateRequestSQL = "select sysdate from dual";
break;
}else{
dateRequestSQL = "select CURDATE()";
break;
}
}else if(tok.compareTo("CURRENT_DATE") == 0){
dateRequestSQL = "select CURRENT_DATE()";
break;
}else if(tok.compareTo("CURRENT_TIMESTAMP") == 0){
timeStampRequestSQL = "select CURRENT_TIMESTAMP()";
}
}
if(dateRequestSQL == null){
dateRequestSQL = "";
}
if(timeStampRequestSQL == null){
timeStampRequestSQL = "";
}
}catch (Exception e){
Globals.logException(e);
}
}
return dateRequestSQL;
}
public java.sql.Date getCurrentTimeStamp_AsTime(){
java.sql.Date timeStamp = null;
try{
initializeDateRequest();
if(timeStampRequestSQL.compareTo("") == 0){
timeStamp = new java.sql.Date(System.currentTimeMillis());
}else{
StatementWrapper stm = lockStatement(null);
stm = executeQuery_WithMultipleAttempts(stm, timeStampRequestSQL);
ResultSet resSet = stm != null ? stm.getResultSet() : null;
//ResultSet resSet = stm.executeQuery(timeStampRequestSQL);
if(resSet != null && resSet.next()){
//Globals.logString(resSet.getString(1));
timeStamp = resSet.getDate(1);
}
if(resSet != null) resSet.close();
unlockStatement(stm);
}
}catch (Exception e){
Globals.logException(e);
}
return timeStamp;
}
public void transaction_BeginTransactionIfRequestIsToBeExecuted(){
getConnectionPool().transaction_BeginTransactionIfRequestIsToBeExecuted();
// if(transaction_ShouldSurroundWithTransactionIfRequest && !transaction_Began){
// transaction_Began = true;
// beginTransaction();
}
public void transaction_setShouldSurroundWithTransactionIfRequest(){
getConnectionPool().transaction_setShouldSurroundWithTransactionIfRequest();
/*
if(nbrOfBeginTransactionsInTransactionThread == 0){
transaction_Began = false;
}
nbrOfBeginTransactionsInTransactionThread++;
this.transaction_ShouldSurroundWithTransactionIfRequest = true;
*/
}
public void transaction_SeeIfShouldCommit(){
getConnectionPool().transaction_SeeIfShouldCommit();
// if(nbrOfBeginTransactionsInTransactionThread > 0){
// nbrOfBeginTransactionsInTransactionThread--;
// if(nbrOfBeginTransactionsInTransactionThread == 0){
// if(transaction_Began){
// commitTransaction();
// this.transaction_ShouldSurroundWithTransactionIfRequest = false;
}
public Hashtable newAllRealTables(){
Hashtable<String, String> tables = new Hashtable<String, String>();
try {
if (Globals.getDBManager() != null && Globals.getDBManager().getProvider() == DBManager.PROVIDER_ORACLE){
//The JDBC way can be very slow on Oracle especially 12c with JDBC 8
if(Globals.getApp() != null && Globals.getApp().getDataSource() != null) {
ArrayList<String> tablesArrayList = Globals.getApp().getDataSource().command_SelectRequest(new StringBuffer("SELECT table_name FROM all_tables"));
if(tablesArrayList != null) {
for(int i=0; i<tablesArrayList.size(); i++) {
String tableName = tablesArrayList.get(i);
tables.put(tableName, tableName);
}
}
}
} else {
DatabaseMetaData dmt = getConnection().getMetaData();
Globals.logString(dmt.getTimeDateFunctions());
if (dmt != null) {
ResultSet resultSet = dmt.getTables(null, null, null, new String[] { "TABLE" });
if (resultSet != null) {
while (resultSet.next()) {
String tableName = resultSet.getString(3);
tables.put(tableName, tableName);
}
resultSet.close();
}
}
}
} catch (Exception e) {
Globals.logException(e);
}
return tables;
}
public static final int MAX_NUMBER_OF_ATTEMPTS = 3;
public StatementWrapper executeQuery_WithMultipleAttempts(StatementWrapper stmt, String req){
return executeQuery_WithMultipleAttempts(stmt, req, SQLRequest.TYPE_SELECT, null);
}
public StatementWrapper executeQuery_WithMultipleAttempts(StatementWrapper stmt, String req, int queryType, FocObject focObject){
if(req != null){
if(ConfigInfo.isLogDBRequestActive() && (queryType != SQLRequest.TYPE_SELECT || ConfigInfo.isLogDBSelectActive())){
Globals.logString(req);
}
boolean successful = false;
int attemptsCount = 0;
while(attemptsCount < MAX_NUMBER_OF_ATTEMPTS && !successful){
attemptsCount++;
try{
if(queryType != SQLRequest.TYPE_SELECT){
FocDesc focDesc = focObject != null ? focObject.getThisFocDesc() : null;
if(queryType == SQLRequest.TYPE_INSERT
&& focObject != null
&& focDesc != null
&& (
focDesc.getProvider() == DBManager.PROVIDER_MYSQL
|| focDesc.getProvider() == DBManager.PROVIDER_MSSQL
|| focDesc.getProvider() == DBManager.PROVIDER_H2
)
){
//We are here if we are MySQL and Insert
Statement s = stmt != null ? stmt.getStatement() : null;
if(s != null){
s.executeUpdate(req, Statement.RETURN_GENERATED_KEYS);
ResultSet rs = s.getGeneratedKeys();
while(rs.next()){
int ref = rs.getInt(1);
focObject.setReference_WithFocListRefHashMapAdjustment(ref);
}
if(rs != null) rs.close();
}
}else if(queryType == SQLRequest.TYPE_DELETE){
// Globals.getApp().getDataSource().transaction_BeginTransactionIfRequestIsToBeExecuted();
DBManagerServer.getInstance().transaction_BeginTransactionIfRequestIsToBeExecuted();
Statement s = stmt != null ? stmt.getStatement() : null;
if(s != null){
s.executeUpdate(req);
}
Globals.getApp().getDataSource().transaction_SeeIfShouldCommit();
}else{
Statement s = stmt != null ? stmt.getStatement() : null;
if(s != null){
s.executeUpdate(req);
}
}
}else{
Statement s = stmt != null ? stmt.getStatement() : null;
if(s != null){
s.executeQuery(req);
}
}
successful = true;
if(focObject != null){
FocDataMap focDataMap = new FocDataMap(focObject);
focDataMap.putString("TABLE_NAME", focObject.getThisFocDesc().getStorageName());
switch(queryType){
case SQLRequest.TYPE_INSERT :
FocNotificationManager.getInstance().fireEvent(new FocNotificationEvent(FocNotificationConst.EVT_TABLE_ADD, focDataMap));
break;
case SQLRequest.TYPE_DELETE:
FocNotificationManager.getInstance().fireEvent(new FocNotificationEvent(FocNotificationConst.EVT_TABLE_DELETE, focDataMap));
break;
case SQLRequest.TYPE_UPDATE:
FocNotificationManager.getInstance().fireEvent(new FocNotificationEvent(FocNotificationConst.EVT_TABLE_UPDATE, focDataMap));
break;
default:
break;
}
}
}catch(Exception e){
if(attemptsCount < MAX_NUMBER_OF_ATTEMPTS){
Globals.logExceptionWithoutPopup(e);
Globals.logString("FOC will Attempt Again");
getConnectionPool().closeReopenConnection();
stmt = lockStatement(stmt.getDBSourceKey());
}else{
Globals.logException(e);
Globals.showNotification("DB ERROR", ""+e.getMessage(), IFocEnvironment.TYPE_ERROR_MESSAGE);
}
}
}
}
return stmt;
}
//Auxiliary Pools
private HashMap<String, ConnectionPool> auxPools_GetMap(boolean create){
if(auxiliaryPools == null && create){
auxiliaryPools = new HashMap<String, ConnectionPool>();
}
return auxiliaryPools;
}
public void auxPools_Put(String key, ConnectionCredentials cred){
ConnectionPool pool = new ConnectionPool(cred);
HashMap<String, ConnectionPool> map = auxPools_GetMap(true);
if(map != null){
map.put(key, pool);
}
}
private ConnectionPool auxPools_Get(String key){
ConnectionPool pool = null;
HashMap<String, ConnectionPool> map = auxPools_GetMap(false);
if(map != null){
pool = map.get(key);
}
return pool;
}
public Iterator<ConnectionPool> auxPools_Iterator(){
Iterator<ConnectionPool> iter = null;
HashMap<String, ConnectionPool> map = auxPools_GetMap(false);
if(map != null && map.values() != null){
iter = map.values().iterator();
}
return iter;
}
private void auxPools_LoadFiles(){
CredentialsFileScanner scanner = new CredentialsFileScanner("properties/db/");
scanner.scanDirectory(this);
scanner.dispose();
}
public StringBuffer getMonitoringText() {
StringBuffer buffer = new StringBuffer();
if(getConnectionPool() != null) {
StringBuffer poolBuffer = getConnectionPool().getMonitoringText();
buffer.append(poolBuffer);
Iterator<ConnectionPool> iter = auxPools_Iterator();
while(iter != null && iter.hasNext()) {
ConnectionPool pool = iter.next();
if(pool != null) {
poolBuffer = pool.getMonitoringText();
buffer.append(poolBuffer);
}
}
}
return buffer;
}
// DBManagerServer
public static DBManagerServer getInstance(){
return (DBManagerServer) Globals.getApp().getDataSource().getDBManagerServer();
}
} |
package im.status.ethereum;
import android.content.Context;
import android.app.AlertDialog;
import android.app.ActivityManager;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.os.Looper;
import android.util.Log;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import com.facebook.react.ReactActivity;
import com.cboy.rn.splashscreen.SplashScreen;
import com.testfairy.TestFairy;
import java.util.Properties;
public class MainActivity extends ReactActivity {
private static void registerUncaughtExceptionHandler(final Context context) {
final Thread.UncaughtExceptionHandler defaultUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(final Thread thread, final Throwable t) {
new Thread() {
@Override
public void run() {
Looper.prepare();
new AlertDialog.Builder(context)
.setTitle("Error")
.setMessage(t.toString())
.setNegativeButton("Exit", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, final int id) {
dialog.dismiss();
defaultUncaughtExceptionHandler.uncaughtException(thread, t);
}
}).show();
Looper.loop();
}
}.start();
}
});
}
private ActivityManager getActivityManager() {
return (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
}
private ActivityManager.MemoryInfo getAvailableMemory(final ActivityManager activityManager) {
final ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
activityManager.getMemoryInfo(memoryInfo);
return memoryInfo;
}
protected void configureStatus() {
// Required because of crazy APN settings redirecting localhost (found in GB)
Properties properties = System.getProperties();
properties.setProperty("http.nonProxyHosts", "localhost|127.0.0.1");
properties.setProperty("https.nonProxyHosts", "localhost|127.0.0.1");
}
@Override
protected void onCreate(Bundle savedInstanceState) {
// Make sure we get an Alert for every uncaught exceptions
registerUncaughtExceptionHandler(MainActivity.this);
// Report memory details for this application
final ActivityManager activityManager = getActivityManager();
Log.v("RNBootstrap", "Available system memory "+getAvailableMemory(activityManager).availMem + ", maximum usable application memory " + activityManager.getLargeMemoryClass()+"M");
SplashScreen.show(this);
super.onCreate(savedInstanceState);
if(BuildConfig.TESTFAIRY_ENABLED == "1") {
TestFairy.begin(this, "969f6c921cb435cea1d41d1ea3f5b247d6026d55");
}
if (!shouldShowRootedNotification()) {
configureStatus();
} else {
AlertDialog dialog = new AlertDialog.Builder(MainActivity.this)
.setMessage(getResources().getString(R.string.root_warning))
.setPositiveButton(getResources().getString(R.string.root_okay), new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
rejectRootedNotification();
dialog.dismiss();
configureStatus();
}
})
.setNegativeButton(getResources().getString(R.string.root_cancel), new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
MainActivity.this.finishAffinity();
}
})
.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
dialog.dismiss();
MainActivity.this.finishAffinity();
}
})
.create();
dialog.show();
}
Thread thread = new Thread() {
@Override
public void run() {
System.loadLibrary("status-logs");
}
};
thread.start();
}
@Override
protected void onDestroy() {
super.onDestroy();
}
/**
* Returns the name of the main component registered from JavaScript.
* This is used to schedule rendering of the component.
*/
@Override
protected String getMainComponentName() {
return "StatusIm";
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
Intent intent = new Intent("onConfigurationChanged");
intent.putExtra("newConfig", newConfig);
this.sendBroadcast(intent);
}
private static final String REJECTED_ROOTED_NOTIFICATION = "rejectedRootedNotification";
private static final Integer FREQUENCY_OF_REMINDER_IN_PERCENT = 5;
private boolean shouldShowRootedNotification() {
if (RootUtil.isDeviceRooted()) {
if (userRejectedRootedNotification()) {
return ((Math.random() * 100) < FREQUENCY_OF_REMINDER_IN_PERCENT);
} else return true;
} else {
return false;
}
}
private boolean userRejectedRootedNotification() {
SharedPreferences preferences = getPreferences(0);
return preferences.getBoolean(REJECTED_ROOTED_NOTIFICATION, false);
}
private void rejectRootedNotification() {
SharedPreferences preferences = getPreferences(0);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(REJECTED_ROOTED_NOTIFICATION, true);
editor.commit();
}
} |
package com.reactlibrary;
import com.facebook.react.bridge.*;
import org.tensorflow.Graph;
import org.tensorflow.contrib.android.TensorFlowInferenceInterface;
public class RNTensorflowModule extends ReactContextBaseJavaModule {
private final ReactApplicationContext reactContext;
private TensorFlowInferenceInterface inference;
public RNTensorflowModule(ReactApplicationContext reactContext) {
super(reactContext);
this.reactContext = reactContext;
}
@Override
public String getName() {
return "RNTensorflow";
}
@ReactMethod
public void instantiateTensorflow(String modelFilePath) {
this.inference = new TensorFlowInferenceInterface(reactContext.getAssets(), modelFilePath);
}
@ReactMethod
public void feed(String inputName, double[] src, long[] dims) {
this.inference.feed(inputName, src, dims);
}
@ReactMethod
public void feed(String inputName, double[] src) {
this.inference.feed(inputName, src);
}
@ReactMethod
public void run(String[] outputNames) {
this.inference.run(outputNames);
}
@ReactMethod
public void run(String[] outputNames, boolean enableStats) {
this.inference.run(outputNames, enableStats);
}
@ReactMethod
public void fetch(String outputName, int outputSize, Promise promise) {
try {
double[] dst = new double[outputSize];
this.inference.fetch(outputName, dst);
promise.resolve(dst);
} catch (Exception e) {
promise.reject(e);
}
}
@ReactMethod
public void graph(Promise promise) {
try {
RNTensorflowGraphModule graphModule = reactContext.getNativeModule(RNTensorflowGraphModule.class);
graphModule.init(this.inference.graph());
promise.resolve(true);
} catch (Exception e) {
promise.reject(e);
}
}
@ReactMethod
public void graphOperation(String operationName, Promise promise) {
try {
promise.resolve(this.inference.graphOperation(operationName));
} catch (Exception e) {
promise.reject(e);
}
}
@ReactMethod
public void stats(Promise promise) {
try {
promise.resolve(this.inference.getStatString());
} catch (Exception e) {
promise.reject(e);
}
}
@ReactMethod
public void close() {
this.inference.close();
}
} |
package net.iaeste.iws.api.dtos;
import net.iaeste.iws.api.constants.IWSConstants;
import net.iaeste.iws.api.enums.Privacy;
import net.iaeste.iws.api.enums.UserStatus;
import net.iaeste.iws.api.exceptions.VerificationException;
import net.iaeste.iws.api.util.AbstractFallible;
import net.iaeste.iws.api.util.Verifiable;
import java.util.HashMap;
import java.util.Map;
public final class User extends AbstractFallible implements Verifiable {
/** {@link IWSConstants#SERIAL_VERSION_UID}. */
private static final long serialVersionUID = IWSConstants.SERIAL_VERSION_UID;
private String userId = null;
// The Username is the users private e-mail address
private String username = null;
// The Alias is an e-mail address provided by the system
private String alias = null;
private String firstname = null;
private String lastname = null;
private UserStatus status = null;
private Privacy privacy = Privacy.PRIVATE;
private String notifications = null;
private String memberCountryId = null;
private Person person = null;
/**
* Empty Constructor, to use if the setters are invoked. This is required
* for WebServices to work properly.
*/
public User() {
}
/**
* Constructor for an existing user, where the personal details should be
* updated.
*
* @param userId The internal Id of the user
* @param person The personal details
*/
public User(final String userId, final Person person) {
this.userId = userId;
this.person = person;
}
/**
* Constructor for an existing user, where the personal details should be
* updated. Please note, that there is a state machine checking the current
* status against the new.<br />
* Below is the State machine presented. A User always starts with Status
* "New", and can from there either get the status "Active" or "Blocked".
* If the user is removed, the status is then set to "Deleted" - meaning
* that all private data is removed from the system, and the user account
* is deactivated. However, it is important to note that the User Object in
* the system will remain there - the reason for this, is that the User may
* also have worked with Group data, and thus the information about the
* person must be preserved in the history.
* <pre>
* NEW
* / \
* / \
* ACTIVE <-> BLOCKED
* \ /
* \ /
* DELETED
* </pre>
*
* @param userId The internal Id of the user
* @param status The new Status
*/
public User(final String userId, final UserStatus status) {
this.userId = userId;
this.status = status;
}
/**
* Copy Constructor.
*
* @param user User Object to copy
*/
public User(final User user) {
if (user != null) {
userId = user.userId;
username = user.username;
alias = user.alias;
firstname = user.firstname;
lastname = user.lastname;
status = user.status;
privacy = user.privacy;
memberCountryId = user.memberCountryId;
person = new Person(user.person);
}
}
// Standard Setters & Getters
public void setUserId(final String userId) {
this.userId = userId;
}
public String getUserId() {
return userId;
}
public void setUsername(final String username) {
this.username = username;
}
public String getUsername() {
return username;
}
public void setAlias(final String alias) {
this.alias = alias;
}
public String getAlias() {
return alias;
}
public void setFirstname(final String firstname) {
this.firstname = firstname;
}
public String getFirstname() {
return firstname;
}
public void setLastname(final String lastname) {
this.lastname = lastname;
}
public String getLastname() {
return lastname;
}
public void setStatus(final UserStatus status) {
this.status = status;
}
public UserStatus getStatus() {
return status;
}
public void setPrivacy(final Privacy privacy) {
this.privacy = privacy;
}
public Privacy getPrivacy() {
return privacy;
}
public void setNotifications(final String notifications) {
this.notifications = notifications;
}
public String getNotifications() {
return notifications;
}
public void setMemberCountryId(final String memberCountryId) {
this.memberCountryId = memberCountryId;
}
public String getMemberCountryId() {
return memberCountryId;
}
public void setPerson(final Person person) {
this.person = person;
}
public Person getPerson() {
return person;
}
// DTO required methods
/**
* {@inheritDoc}
*/
@Override
public void verify() {
final Map<String, String> validationResult = validate();
if (!validationResult.isEmpty()) {
throw new VerificationException("Validation failed: " + validationResult.toString());
}
}
/**
* {@inheritDoc}
*/
@Override
public Map<String, String> validate() {
final Map<String, String> validation = new HashMap<>(0);
if ((userId == null) || (userId.length() != 36)) {
validation.put("userId", "Invalid UserId.");
}
return validation;
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof User)) {
return false;
}
if (!super.equals(obj)) {
return false;
}
final User user = (User) obj;
// Note, the Notifications & Person Objects are omitted, since they are
// not set for all views of this Object, and we need to verify that two
// instances are identical, regardless of who is viewing them
if (userId != null ? !userId.equals(user.userId) : user.userId != null) {
return false;
}
if (username != null ? !username.equals(user.username) : user.username != null) {
return false;
}
if (alias != null ? !alias.equals(user.alias) : user.alias != null) {
return false;
}
if (firstname != null ? !firstname.equals(user.firstname) : user.firstname != null) {
return false;
}
if (lastname != null ? !lastname.equals(user.lastname) : user.lastname != null) {
return false;
}
if (status != user.status) {
return false;
}
if (privacy != user.privacy) {
return false;
}
return !(memberCountryId != null ? !memberCountryId.equals(user.memberCountryId) : user.memberCountryId != null);
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
int result = super.hashCode();
// Note, the Notifications & Person Objects are omitted, since they are
// not set for all views of this Object, and we need to verify that two
// instances are identical, regardless of who is viewing them
result = IWSConstants.HASHCODE_MULTIPLIER * result + (userId != null ? userId.hashCode() : 0);
result = IWSConstants.HASHCODE_MULTIPLIER * result + (username != null ? username.hashCode() : 0);
result = IWSConstants.HASHCODE_MULTIPLIER * result + (alias != null ? alias.hashCode() : 0);
result = IWSConstants.HASHCODE_MULTIPLIER * result + (firstname != null ? firstname.hashCode() : 0);
result = IWSConstants.HASHCODE_MULTIPLIER * result + (lastname != null ? lastname.hashCode() : 0);
result = IWSConstants.HASHCODE_MULTIPLIER * result + (status != null ? status.hashCode() : 0);
result = IWSConstants.HASHCODE_MULTIPLIER * result + (privacy != null ? privacy.hashCode() : 0);
result = IWSConstants.HASHCODE_MULTIPLIER * result + (memberCountryId != null ? memberCountryId.hashCode() : 0);
return result;
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
// Note, the Notifications & Person Objects are omitted, since they are
// not set for all views of this Object, and we need to verify that two
// instances are identical, regardless of who is viewing them
return "User{" +
"userId='" + userId + '\'' +
", username='" + username + '\'' +
", alias='" + alias + '\'' +
", firstname='" + firstname + '\'' +
", lastname='" + lastname + '\'' +
", status=" + status +
", privacy=" + privacy +
", memberCountryId='" + memberCountryId + '\'' +
'}';
}
} |
package squeek.veganoption.content.modules;
import net.minecraft.block.Block;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemFishFood;
import net.minecraft.item.ItemFood;
import net.minecraft.item.ItemStack;
import net.minecraft.potion.Potion;
import net.minecraftforge.client.MinecraftForgeClient;
import net.minecraftforge.oredict.OreDictionary;
import net.minecraftforge.oredict.ShapedOreRecipe;
import net.minecraftforge.oredict.ShapelessOreRecipe;
import squeek.veganoption.ModInfo;
import squeek.veganoption.VeganOption;
import squeek.veganoption.blocks.BlockCompost;
import squeek.veganoption.blocks.BlockComposter;
import squeek.veganoption.blocks.renderers.RenderComposter;
import squeek.veganoption.blocks.tiles.TileEntityComposter;
import squeek.veganoption.content.ContentHelper;
import squeek.veganoption.content.IContentModule;
import squeek.veganoption.content.Modifiers;
import squeek.veganoption.content.registry.CompostRegistry;
import squeek.veganoption.content.registry.RelationshipRegistry;
import squeek.veganoption.content.registry.CompostRegistry.FoodSpecifier;
import squeek.veganoption.items.ItemFertilizer;
import cpw.mods.fml.client.registry.ClientRegistry;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class Composting implements IContentModule
{
public static Block composter;
public static Item rottenPlants;
public static Block compost;
public static Item fertilizer;
@Override
public void create()
{
composter = new BlockComposter()
.setHardness(2.5F)
.setStepSound(Block.soundTypeWood)
.setBlockName(ModInfo.MODID + ".composter")
.setCreativeTab(VeganOption.creativeTab)
.setBlockTextureName(ModInfo.MODID_LOWER + ":composter");
GameRegistry.registerBlock(composter, "composter");
GameRegistry.registerTileEntity(TileEntityComposter.class, ModInfo.MODID + ".composter");
if (FMLCommonHandler.instance().getEffectiveSide() == Side.CLIENT)
{
createComposterRenderer();
}
rottenPlants = new ItemFood(4, 0.1F, true)
.setPotionEffect(Potion.hunger.id, 30, 0, 0.8F)
.setUnlocalizedName(ModInfo.MODID + ".rottenPlants")
.setCreativeTab(VeganOption.creativeTab)
.setTextureName(ModInfo.MODID_LOWER + ":rotten_plants");
GameRegistry.registerItem(rottenPlants, "rottenPlants");
fertilizer = new ItemFertilizer()
.setUnlocalizedName(ModInfo.MODID + ".fertilizer")
.setCreativeTab(VeganOption.creativeTab)
.setTextureName(ModInfo.MODID_LOWER + ":fertilizer");
GameRegistry.registerItem(fertilizer, "fertilizer");
compost = new BlockCompost()
.setHardness(0.5F)
.setStepSound(Block.soundTypeGravel)
.setBlockName(ModInfo.MODID + ".compost")
.setCreativeTab(VeganOption.creativeTab)
.setBlockTextureName(ModInfo.MODID_LOWER + ":compost");
GameRegistry.registerBlock(compost, "compost");
}
@Override
public void oredict()
{
OreDictionary.registerOre(ContentHelper.rottenOreDict, new ItemStack(Items.rotten_flesh));
OreDictionary.registerOre(ContentHelper.rottenOreDict, rottenPlants);
OreDictionary.registerOre(ContentHelper.fertilizerOreDict, fertilizer);
OreDictionary.registerOre(ContentHelper.brownDyeOreDict, fertilizer);
}
@Override
public void recipes()
{
Modifiers.recipes.convertInput(new ItemStack(Items.rotten_flesh), ContentHelper.rottenOreDict);
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(composter), "/c/", "/ /", '/', ContentHelper.stickOreDict, 'c', new ItemStack(Blocks.chest)));
GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(fertilizer, 8), new ItemStack(compost), ContentHelper.saltpeterOreDict));
}
@Override
public void finish()
{
RelationshipRegistry.addRelationship(new ItemStack(compost), new ItemStack(composter));
RelationshipRegistry.addRelationship(new ItemStack(rottenPlants), new ItemStack(composter));
CompostRegistry.addBrown(ContentHelper.stickOreDict);
CompostRegistry.addBrown(Items.paper);
CompostRegistry.addBrown(ContentHelper.bastFibreOreDict);
CompostRegistry.addBrown(ContentHelper.woodAshOreDict);
CompostRegistry.addBrown(Blocks.deadbush);
CompostRegistry.addBrown(ContentHelper.sawDustOreDict);
CompostRegistry.addBrown(ContentHelper.sawDustAltOreDict);
CompostRegistry.addGreen(ContentHelper.saplingOreDict);
CompostRegistry.addGreen(rottenPlants);
CompostRegistry.addGreen(Blocks.tallgrass);
CompostRegistry.addGreen(Blocks.double_plant);
CompostRegistry.addGreen(ContentHelper.leavesOreDict);
CompostRegistry.addGreen(Blocks.pumpkin);
CompostRegistry.addGreen(Blocks.melon_block);
CompostRegistry.addGreen(Blocks.vine);
CompostRegistry.addGreen(Blocks.yellow_flower);
CompostRegistry.addGreen(Blocks.red_flower);
CompostRegistry.addGreen(Blocks.brown_mushroom);
CompostRegistry.addGreen(Blocks.red_mushroom);
CompostRegistry.blacklist(new FoodSpecifier()
{
@Override
public boolean matches(ItemStack itemStack)
{
// meat is bad for composting
if (itemStack.getItem() instanceof ItemFood && ((ItemFood) itemStack.getItem()).isWolfsFavoriteMeat())
return true;
else if (itemStack.getItem() instanceof ItemFishFood)
return true;
int[] oreIDs = OreDictionary.getOreIDs(itemStack);
for (int oreID : oreIDs)
{
String oreName = OreDictionary.getOreName(oreID);
if (oreName.startsWith("listAllmeat") || oreName.contains("Meat"))
return true;
}
return false;
}
});
CompostRegistry.registerAllFoods();
}
@SideOnly(Side.CLIENT)
public void createComposterRenderer()
{
RenderComposter composterRenderer = new RenderComposter();
ClientRegistry.bindTileEntitySpecialRenderer(TileEntityComposter.class, composterRenderer);
MinecraftForgeClient.registerItemRenderer(ItemBlock.getItemFromBlock(composter), composterRenderer);
}
} |
package io.crate.jdbc.sample;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import spark.Response;
import spark.utils.IOUtils;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import static spark.Spark.*;
public class Controller {
private final Gson gson = new GsonBuilder().serializeNulls().create();
private static final int INTERNAL_ERROR = 500;
private static final int BAD_REQUEST = 400;
private static final int NOT_FOUND = 404;
private static final int NO_CONTENT = 204;
private static final int CREATED = 201;
private static final int OK = 200;
public Controller(final DataProvider model) {
before(((request, response) -> {
response.header("Access-Control-Allow-Origin", "*");
response.header("Access-Control-Request-Method", "*");
response.header("Access-Control-Allow-Headers", "*");
}));
get("/posts", (request, response) ->
model.getPosts(), gson::toJson);
post("/posts", (request, response) -> {
String body = request.body();
if (body.isEmpty()) {
return argumentRequired(response, "Request body is required");
}
Map post = gson.fromJson(body, Map.class);
if (!post.containsKey("text")) {
return argumentRequired(response, "Argument \"text\" is required");
}
Map user = (Map) post.get("user");
if (!user.containsKey("location")) {
return argumentRequired(response, "Argument \"location\" is required");
}
response.status(CREATED);
return model.insertPost(post);
}, gson::toJson);
get("/post/:id", (request, response) -> {
String id = request.params(":id");
Map post = model.getPost(id);
if (post.isEmpty()) {
return notFound(response, (String.format("Post with id=\"%s\" not found", id)));
}
response.status(OK);
return post;
}, gson::toJson);
put("/post/:id", (request, response) -> {
String body = request.body();
if (body.isEmpty()) {
return argumentRequired(response, "Request body is required");
}
Map post = gson.fromJson(body, Map.class);
if (!post.containsKey("text")) {
return argumentRequired(response, "Argument \"text\" is required");
}
String id = request.params(":id");
Map updatePost = model.updatePost(id, (String) post.get("text"));
if (updatePost.isEmpty()) {
return notFound(response, (String.format("Post with id=\"%s\" not found", id)));
}
response.status(OK);
return updatePost;
}, gson::toJson);
delete("/post/:id", (request, response) -> {
String id = request.params(":id");
if (model.deletePost(id)) {
response.status(NO_CONTENT);
JsonObject responseJson = new JsonObject();
responseJson.addProperty("success", true);
return responseJson;
} else {
return notFound(response, String.format("Post with id=\"%s\" not found", id));
}
}, gson::toJson);
put("/post/:id/like", (request, response) -> {
String id = request.params(":id");
Map post = model.incrementLike(id);
if (post.isEmpty()) {
return notFound(response, (String.format("Post with id=\"%s\" not found", id)));
}
response.status(OK);
return post;
}, gson::toJson);
get("/images", (request, response) -> model.getBlobs(), gson::toJson);
post("/images", (request, response) -> {
String body = request.body();
if (body.isEmpty()) {
return argumentRequired(response, "Request body is required");
}
Map blobMap = gson.fromJson(body, Map.class);
if (!blobMap.containsKey("blob")) {
return argumentRequired(response, "Argument \"blob\" is required");
}
byte[] decoded = Base64.getDecoder().decode((String) blobMap.get("blob"));
String digest = DigestUtils.shaHex(decoded);
Map<String, String> responseMap = model.insertBlob(digest, decoded);
response.status(Integer.parseInt(responseMap.get("status")));
return responseMap;
}, gson::toJson);
get("/image/:digest", (request, response) -> {
String digest = request.params(":digest");
if (model.blobExists(digest)) {
CloseableHttpResponse closeableHttpResponse = model.getBlob(digest);
Arrays.stream(closeableHttpResponse.getAllHeaders()).forEach(header ->
response.header(header.getName(), header.getValue())
);
response.status(closeableHttpResponse.getStatusLine().getStatusCode());
response.header("Content-Type", "image/gif");
response.body(IOUtils.toString(closeableHttpResponse.getEntity().getContent()));
return response;
} else {
return gson.toJson(
notFound(response, String.format("Image with digest=\"%s\" not found", digest))
);
}
});
delete("/image/:digest", (request, response) -> {
String digest = request.params(":digest");
if (model.blobExists(digest)) {
CloseableHttpResponse closeableHttpResponse = model.deleteBlob(digest);
int status = closeableHttpResponse.getStatusLine().getStatusCode();
response.status(status);
JsonObject responseJson = new JsonObject();
responseJson.addProperty("success", status == OK);
return responseJson;
} else {
return notFound(response, String.format("Image with digest=\"%s\" not found", digest));
}
}, gson::toJson);
post("/search", (request, response) -> {
String body = request.body();
if (body.isEmpty()) {
return argumentRequired(response, "Request body is required");
}
Map bodyMap = gson.fromJson(body, Map.class);
if (!bodyMap.containsKey("query_string")) {
return argumentRequired(response, "Argument \"query_string\" is required");
}
return model.searchPosts((String) bodyMap.get("query_string"));
}, gson::toJson);
exception(SQLException.class, (e, request, response) -> {
response.status(INTERNAL_ERROR);
response.body(e.getLocalizedMessage());
});
}
private Map<String, Object> notFound(Response response, String msg) {
return errorResponse(response, msg, NOT_FOUND);
}
private Map<String, Object> argumentRequired(Response response, String msg) {
return errorResponse(response, msg, BAD_REQUEST);
}
private Map<String, Object> errorResponse(Response response, String msg, int code) {
response.status(code);
Map<String, Object> responseMap = new HashMap<>();
responseMap.put("status", code);
responseMap.put("error", msg);
return responseMap;
}
} |
package pack.osakidetza.vistas;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JScrollPane;
import javax.swing.JList;
import javax.swing.AbstractListModel;
import javax.swing.JCheckBox;
import javax.swing.ButtonGroup;
import pack.osakidetza.controladoras.C_Doctor;
import pack.osakidetza.controladoras.Paciente;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import com.toedter.calendar.JDateChooser;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.ListSelectionEvent;
@SuppressWarnings("serial")
public class IU_Pacientes extends JFrame {
private JPanel contentPane;
private JTextField textCI;
private JTextField txtNHistorial;
private final ButtonGroup buttonGroup = new ButtonGroup();
private String historial;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
IU_Pacientes frame = new IU_Pacientes();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public IU_Pacientes() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 550, 433);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
historial=new String();
JLabel lblPacientes = new JLabel("Pacientes");
lblPacientes.setFont(new Font("Dialog", Font.BOLD | Font.ITALIC, 18));
lblPacientes.setBounds(157, 12, 117, 31);
contentPane.add(lblPacientes);
JLabel lblCasondice = new JLabel("Caso índice");
lblCasondice.setBounds(24, 93, 117, 15);
contentPane.add(lblCasondice);
textCI = new JTextField();
textCI.setBounds(157, 91, 234, 19);
contentPane.add(textCI);
textCI.setColumns(10);
txtNHistorial = new JTextField();
txtNHistorial.setBounds(157, 150, 234, 19);
contentPane.add(txtNHistorial);
txtNHistorial.setColumns(10);
JCheckBox chckbxDiagnosticos = new JCheckBox("Diagnósticos");
buttonGroup.add(chckbxDiagnosticos);
chckbxDiagnosticos.setBounds(24, 243, 117, 23);
contentPane.add(chckbxDiagnosticos);
final JCheckBox chckbxNuevo = new JCheckBox("Añadir nuevo");
buttonGroup.add(chckbxNuevo);
chckbxNuevo.setBounds(407, 243, 129, 23);
contentPane.add(chckbxNuevo);
final JCheckBox chckbxEliminar = new JCheckBox("Eliminar");
buttonGroup.add(chckbxEliminar);
chckbxEliminar.setBounds(407, 270, 129, 23);
contentPane.add(chckbxEliminar);
final JCheckBox chckbxActualizar = new JCheckBox("Actualizar");
buttonGroup.add(chckbxActualizar);
chckbxActualizar.setBounds(407, 297, 129, 23);
contentPane.add(chckbxActualizar);
JCheckBox chckbxVisitas = new JCheckBox("Visitas");
buttonGroup.add(chckbxVisitas);
chckbxVisitas.setBounds(24, 274, 73, 23);
contentPane.add(chckbxVisitas);
JCheckBox chckbxCancer = new JCheckBox("Cancer\n");
buttonGroup.add(chckbxCancer);
chckbxCancer.setBounds(24, 301, 74, 23);
contentPane.add(chckbxCancer);
final JCheckBox chckbxBuscar = new JCheckBox("Buscar");
buttonGroup.add(chckbxBuscar);
chckbxBuscar.setBounds(407, 223, 129, 23);
contentPane.add(chckbxBuscar);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(157, 225, 242, 99);
contentPane.add(scrollPane);
final JList listPacientes = new JList();
listPacientes.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
if(e.getValueIsAdjusting()){
historial = (String) listPacientes.getSelectedValue();
}
}
});
scrollPane.setViewportView(listPacientes);
listPacientes.setModel(new AbstractListModel() {
String[] values = new String[] {};
public int getSize() {
return values.length;
}
public Object getElementAt(int index) {
return values[index];
}
});
final JButton btnAceptar = new JButton("Aceptar");
btnAceptar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(e.getSource()==btnAceptar){
if(chckbxNuevo.isSelected()){
IU_FormPaciente IU_FP= new IU_FormPaciente(null);
IU_FP.setVisible(true);
}
//borrar paciente
if(chckbxEliminar.isSelected()){
if(!listPacientes.isSelectionEmpty()){
IU_FastIdent IU_FI= new IU_FastIdent("",historial,false,true);
IU_FI.setVisible(true);
}
else{
JOptionPane.showMessageDialog(null, "No ha escogido un paciente para eliminar");
}
}
//obtener pacientes
if(chckbxBuscar.isSelected())
//Buscar paciente dado historial
{
if(txtNHistorial.getText().length()>0){
String paciente = C_Doctor.getMiDoctor().buscarPaciente(txtNHistorial.getText());
if(paciente!=null){
DefaultListModel encontrado = new DefaultListModel();
encontrado.addElement(paciente);
listPacientes.setModel(encontrado);
}
}
//listar pacientes dado ci
else if(textCI.getText().length()>0){
String CI = textCI.getText();
ArrayList<String> listaPacientesDCI = C_Doctor.getMiDoctor().listarPacientesDado(CI);
java.util.Iterator<String> itr = listaPacientesDCI.iterator();
DefaultListModel modelo = new DefaultListModel();
while(itr.hasNext()){
modelo.addElement(itr.next());
}
listPacientes.setModel(modelo);
}
//listar pacientes
else{
ArrayList<String> listaPacientes = C_Doctor.getMiDoctor().listarPacientes();
java.util.Iterator<String> itr = listaPacientes.iterator();
DefaultListModel modelo =new DefaultListModel();
while(itr.hasNext()){
modelo.addElement(itr.next());
}
listPacientes.setModel(modelo);
}
}
if(chckbxActualizar.isSelected()){
Paciente pacienteCurrent = C_Doctor.getMiDoctor().obtenerPaciente(historial);
IU_FormPaciente IU_FP= new IU_FormPaciente(pacienteCurrent);
IU_FP.setVisible(true);
}
}
}
});
btnAceptar.setBounds(290, 370, 117, 25);
contentPane.add(btnAceptar);
final JButton btnVolver = new JButton("Volver");
btnVolver.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(e.getSource()==btnVolver)dispose();
}
});
btnVolver.setBounds(419, 370, 117, 25);
contentPane.add(btnVolver);
JLabel lblPacientes_1 = new JLabel("Pacientes");
lblPacientes_1.setBounds(157, 198, 70, 15);
contentPane.add(lblPacientes_1);
JLabel lblPaciente = new JLabel("Paciente");
lblPaciente.setBounds(24, 152, 70, 15);
contentPane.add(lblPaciente);
}
} |
package jade.core;
import jade.util.leap.Properties;
import jade.util.leap.List;
import jade.util.leap.ArrayList;
import jade.util.leap.Iterator;
import jade.util.BasicProperties;
import java.io.IOException;
import java.net.*;
import java.util.Hashtable;
/**
* This class allows the JADE core to retrieve configuration-dependent classes
* and boot parameters.
* <p>
* Take care of using different instances of this class when launching
* different containers/main-containers on the same JVM otherwise
* they would conflict!
*
* @author Federico Bergenti
* @author Giovanni Caire - TILAB
* @author Giovanni Rimassa - Universita` di Parma
* @version 1.0, 22/11/00
*
*/
public class ProfileImpl extends Profile {
private BasicProperties props = null;
// private Properties props = null;
/**
* Default communication port number.
*/
public static final int DEFAULT_PORT = 1099;
/**
This constant is the key of the property whose value is the class name of
the mobility manager.
**/
public static final String MOBILITYMGRCLASSNAME = "mobility";
private Platform myPlatform = null;
private IMTPManager myIMTPManager = null;
private acc myACC = null;
private MobilityManager myMobilityManager = null;
private NotificationManager myNotificationManager = null;
private ResourceManager myResourceManager = null;
public ProfileImpl(BasicProperties aProp) {
props = aProp;
try {
// Set default values
String host = InetAddress.getLocalHost().getHostName();
props.setProperty(MAIN, "true");
props.setProperty(MAIN_PROTO, "rmi");
props.setProperty(MAIN_HOST, host);
props.setProperty(MAIN_PORT, Integer.toString(DEFAULT_PORT));
updatePlatformID();
Specifier s = new Specifier();
s.setClassName("jade.mtp.iiop.MessageTransportProtocol");
List l = new ArrayList(1);
l.add(s);
props.put(MTPS, l);
}
catch (UnknownHostException uhe) {
uhe.printStackTrace();
}
catch (IOException ioe) {
ioe.printStackTrace();
}
}
/**
* Creates a Profile implementation with the default configuration
* for launching a main-container on the localhost,
* RMI internal Message Transport Protocol, port number 1099,
* iiop MTP.
*/
public ProfileImpl() {
this(new BasicProperties());
}
/**
* This constructor creates a default Profile for launching a platform.
* @param host is the name of the host where the main-container should
* be listen to. A null value means use the default (i.e. localhost)
* @param port is the port number where the main-container should be
* listen
* for other containers. A negative value should be used for using
* the default port number.
* @param platformID is the synbolic name of the platform, if
* different from default. A null value means use the default
* (i.e. localhost)
**/
public ProfileImpl(String host, int port, String platformID) {
this(); // Call default constructor
if(host != null)
props.setProperty(MAIN_HOST, host);
if(port > 0)
props.setIntProperty(MAIN_PORT, port);
if(platformID != null)
props.setProperty(PLATFORM_ID, platformID);
else
updatePlatformID();
}
public void updatePlatformID() {
String h = props.getProperty(MAIN_HOST);
String p = props.getProperty(MAIN_PORT);
props.setProperty(PLATFORM_ID, h + ":" + p + "/JADE");
}
/**
* Copy a collection of properties into this profile.
* @param source The collection to be copied.
*/
void copyProperties(BasicProperties source) {
props.copyProperties(source);
}
/**
* Return the underlying properties collection.
* @return BasicProperties The properties collection.
*/
public BasicProperties getProperties() {
return props;
}
/** HP.
private MainContainerImpl theMainContainer = null;
public void addPlatformListener(AgentManager.Listener aListener) throws NotFoundException {
if (theMainContainer == null) {
throw new NotFoundException("Unable to add listener, main container not set");
}
theMainContainer.addListener(aListener);
}
public void removePlatformListener(AgentManager.Listener aListener) throws NotFoundException {
if (theMainContainer == null) {
throw new NotFoundException("Unable to remove listener, main container not set");
}
theMainContainer.removeListener(aListener);
}
**/
/**
* Assign the given value to the given property name.
*
* @param key is the property name
* @param value is the property value
*/
public void setParameter(String key, String value) {
props.put(key, value);
}
/**
* Assign the given property value to the given property name
*
* @param key is the property name
* @param value is the property value
*/
public void setSpecifiers(String key, List value) {
props.put(key, value);
}
protected Platform getPlatform() throws ProfileException {
if (myPlatform == null) {
createPlatform();
}
return myPlatform;
}
protected IMTPManager getIMTPManager() throws ProfileException {
if (myIMTPManager == null) {
createIMTPManager();
}
return myIMTPManager;
}
protected acc getAcc() throws ProfileException {
if (myACC == null) {
createACC();
}
return myACC;
}
protected MobilityManager getMobilityManager() throws ProfileException {
if (myMobilityManager == null) {
createMobilityManager();
}
return myMobilityManager;
}
protected ResourceManager getResourceManager() throws ProfileException {
if (myResourceManager == null) {
createResourceManager();
}
return myResourceManager;
}
protected NotificationManager getNotificationManager() throws ProfileException {
if (myNotificationManager == null) {
createNotificationManager();
}
return myNotificationManager;
}
/**
* Method declaration
*
* @throws ProfileException
*
* @see
*/
private void createPlatform() throws ProfileException {
try {
String isMain = props.getProperty(MAIN);
if (isMain == null || CaseInsensitiveString.equalsIgnoreCase(isMain, "true")) {
// The real Main
myPlatform = new MainContainerImpl(this);
// HP myPlatform = theMainContainer = new MainContainerImpl(this);
}
else {
// A proxy to the Main
myPlatform = new MainContainerProxy(this);
}
}
catch (IMTPException imtpe) {
throw new ProfileException("Can't get a stub of the MainContainer: "+imtpe.getMessage());
}
}
/**
* Method declaration
*
* @throws ProfileException
*
* @see
*/
private void createIMTPManager() throws ProfileException {
// Use the RMI IMTP by default
String className = new String("jade.imtp.rmi.RMIIMTPManager");
try {
myIMTPManager = (IMTPManager) Class.forName(className).newInstance();
}
catch (Exception e) {
e.printStackTrace();
throw new ProfileException("Error loading IMTPManager class "+className);
}
}
/**
* Method declaration
*
* @throws ProfileException
*
* @see
*/
private void createACC() throws ProfileException {
// Use the Full ACC by default
String className = new String("jade.core.FullAcc");
try {
myACC = (acc) Class.forName(className).newInstance();
}
catch (Exception e) {
throw new ProfileException("Error loading acc class "+className);
}
}
/**
* Method declaration
*
* @throws ProfileException
*
* @see
*/
private void createMobilityManager() throws ProfileException {
String className = getParameter(MOBILITYMGRCLASSNAME);
if (className == null) // default is real mobility manager
className = new String("jade.core.RealMobilityManager");
try {
myMobilityManager = (MobilityManager) Class.forName(className).newInstance();
}
catch (Exception e) {
throw new ProfileException("Error loading MobilityManager class "+className);
}
}
private void createResourceManager() throws ProfileException {
myResourceManager = new FullResourceManager();
}
private void createNotificationManager() throws ProfileException {
myNotificationManager = new RealNotificationManager();
}
/**
* Retrieve a String value from the configuration properties.
* If no parameter corresponding to the specified key is found,
* null is returned.
* @param key The key identifying the parameter to be retrieved
* among the configuration properties.
*/
public String getParameter(String key) throws ProfileException {
return props.getProperty(key);
}
/**
* Retrieve a list of Specifiers from the configuration properties.
* Agents, MTPs and other items are specified among the configuration
* properties in this way.
* If no list of Specifiers corresponding to the specified key is found,
* an empty list is returned.
* @param key The key identifying the list of Specifiers to be retrieved
* among the configuration properties.
*/
public List getSpecifiers(String key) throws ProfileException {
List l = (List)props.get(key);
if(l == null)
l = new ArrayList(0);
return l;
}
public String toString() {
return "(Profile "+props.toString()+")";
}
} |
package nxt;
import nxt.crypto.HashFunction;
import java.util.EnumSet;
import java.util.Set;
/**
* Define and validate currency capabilities
*/
public enum CurrencyType {
/**
* Can be exchanged from/to NXT<br>
*/
EXCHANGEABLE(0x01) {
@Override
void validate(Currency currency, Transaction transaction, Set<CurrencyType> validators) throws NxtException.NotValidException {
}
@Override
void validateMissing(Currency currency, Transaction transaction, Set<CurrencyType> validators) throws NxtException.NotValidException {
if (transaction.getType() == MonetarySystem.CURRENCY_ISSUANCE) {
if (!validators.contains(CLAIMABLE)) {
throw new NxtException.NotValidException("Currency is not exchangeable and not claimable");
}
}
if (transaction.getType() instanceof MonetarySystem.MonetarySystemExchange || transaction.getType() == MonetarySystem.PUBLISH_EXCHANGE_OFFER) {
throw new NxtException.NotValidException("Currency is not exchangeable");
}
}
},
/**
* Transfers are only allowed from/to issuer account<br>
* Only issuer account can publish exchange offer<br>
*/
CONTROLLABLE(0x02) {
@Override
void validate(Currency currency, Transaction transaction, Set<CurrencyType> validators) throws NxtException.NotValidException {
if (transaction.getType() == MonetarySystem.CURRENCY_TRANSFER) {
if (currency == null || (currency.getAccountId() != transaction.getSenderId() && currency.getAccountId() != transaction.getRecipientId())) {
throw new NxtException.NotValidException("Controllable currency can only be transferred to/from issuer account");
}
}
if (transaction.getType() == MonetarySystem.PUBLISH_EXCHANGE_OFFER) {
if (currency == null || currency.getAccountId() != transaction.getSenderId()) {
throw new NxtException.NotValidException("Only currency issuer can publish an exchange offer for controllable currency");
}
}
}
@Override
void validateMissing(Currency currency, Transaction transaction, Set<CurrencyType> validators) {}
},
/**
* Can be reserved before the currency is active, reserve is distributed to founders once the currency becomes active<br>
*/
RESERVABLE(0x04) {
@Override
void validate(Currency currency, Transaction transaction, Set<CurrencyType> validators) throws NxtException.ValidationException {
if (transaction.getType() == MonetarySystem.CURRENCY_ISSUANCE) {
int issuanceHeight = ((Attachment.MonetarySystemCurrencyIssuance) transaction.getAttachment()).getIssuanceHeight();
if (issuanceHeight <= Nxt.getBlockchain().getHeight()) {
throw new NxtException.NotCurrentlyValidException(
String.format("Reservable currency activation height %d not higher than current height %d",
issuanceHeight, Nxt.getBlockchain().getHeight()));
}
}
if (transaction.getType() == MonetarySystem.RESERVE_INCREASE) {
if (currency != null && currency.isActive()) {
throw new NxtException.NotCurrentlyValidException("Cannot increase reserve for active currency");
}
}
}
@Override
void validateMissing(Currency currency, Transaction transaction, Set<CurrencyType> validators) throws NxtException.NotValidException {
if (transaction.getType() == MonetarySystem.RESERVE_INCREASE) {
throw new NxtException.NotValidException("Cannot increase reserve since currency is not reservable");
}
if (transaction.getType() == MonetarySystem.CURRENCY_ISSUANCE) {
int issuanceHeight = ((Attachment.MonetarySystemCurrencyIssuance) transaction.getAttachment()).getIssuanceHeight();
if (issuanceHeight != 0) {
throw new NxtException.NotValidException("Issuance height for non-reservable currency must be 0");
}
}
}
},
/**
* Is {@link #RESERVABLE} and can be claimed after currency is active<br>
* Cannot be {@link #EXCHANGEABLE}
*/
CLAIMABLE(0x08) {
@Override
void validate(Currency currency, Transaction transaction, Set<CurrencyType> validators) throws NxtException.ValidationException {
if (transaction.getType() == MonetarySystem.CURRENCY_ISSUANCE) {
if (!validators.contains(RESERVABLE)) {
throw new NxtException.NotValidException("Claimable currency must be reservable");
}
}
if (transaction.getType() == MonetarySystem.RESERVE_CLAIM) {
if (currency == null || !currency.isActive()) {
throw new NxtException.NotCurrentlyValidException("Cannot claim reserve since currency is not yet active");
}
}
}
@Override
void validateMissing(Currency currency, Transaction transaction, Set<CurrencyType> validators) throws NxtException.NotValidException {
if (transaction.getType() == MonetarySystem.RESERVE_CLAIM) {
throw new NxtException.NotValidException("Cannot claim reserve since currency is not claimable");
}
}
},
/**
* Can be minted using proof of work algorithm<br>
*/
MINTABLE(0x10) {
@Override
void validate(Currency currency, Transaction transaction, Set<CurrencyType> validators) throws NxtException.NotValidException {
if (transaction.getType() == MonetarySystem.CURRENCY_ISSUANCE) {
Attachment.MonetarySystemCurrencyIssuance issuanceAttachment = (Attachment.MonetarySystemCurrencyIssuance) transaction.getAttachment();
try {
HashFunction.getHashFunction(issuanceAttachment.getAlgorithm());
} catch(IllegalArgumentException e) {
throw new NxtException.NotValidException("Illegal algorithm code specified" , e);
}
if (issuanceAttachment.getMinDifficulty() <= 0 ||
issuanceAttachment.getMaxDifficulty() < issuanceAttachment.getMinDifficulty()) {
throw new NxtException.NotValidException(
String.format("Invalid minting difficulties min %d max %d",
issuanceAttachment.getMinDifficulty(), issuanceAttachment.getMaxDifficulty()));
}
}
}
@Override
void validateMissing(Currency currency, Transaction transaction, Set<CurrencyType> validators) throws NxtException.NotValidException {
if (transaction.getType() == MonetarySystem.CURRENCY_ISSUANCE) {
Attachment.MonetarySystemCurrencyIssuance issuanceAttachment = (Attachment.MonetarySystemCurrencyIssuance) transaction.getAttachment();
if (issuanceAttachment.getMinDifficulty() != 0 ||
issuanceAttachment.getMaxDifficulty() != 0 ||
issuanceAttachment.getAlgorithm() != 0) {
throw new NxtException.NotValidException("Non mintable currency should not specify algorithm or difficulty");
}
}
if (transaction.getType() == MonetarySystem.CURRENCY_MINTING) {
throw new NxtException.NotValidException("Currency is not mintable");
}
}
},
/**
* Support shuffling - not implemented yet<br>
*/
SHUFFLEABLE(0x20) {
@Override
void validate(Currency currency, Transaction transaction, Set<CurrencyType> validators) throws NxtException.ValidationException {
throw new NxtException.NotYetEnabledException("Shuffling not yet implemented");
}
@Override
void validateMissing(Currency currency, Transaction transaction, Set<CurrencyType> validators) {
}
};
private final int code;
private CurrencyType(int code) {
this.code = code;
}
public int getCode() {
return code;
}
abstract void validate(Currency currency, Transaction transaction, Set<CurrencyType> validators) throws NxtException.ValidationException;
abstract void validateMissing(Currency currency, Transaction transaction, Set<CurrencyType> validators) throws NxtException.ValidationException;
static void validate(Currency currency, Transaction transaction) throws NxtException.ValidationException {
if (currency == null) {
throw new NxtException.NotValidException("Unknown currency: " + transaction.getAttachment().getJSONObject());
}
validate(currency, currency.getType(), transaction);
}
static void validate(int type, Transaction transaction) throws NxtException.ValidationException {
validate(null, type, transaction);
}
private static void validate(Currency currency, int type, Transaction transaction) throws NxtException.ValidationException {
// sanity checks for all currency types
if (Nxt.getBlockchain().getLastBlock().getHeight() < Constants.MONETARY_SYSTEM_BLOCK) {
throw new NxtException.NotYetEnabledException("Monetary System not yet enabled at height " + Nxt.getBlockchain().getLastBlock().getHeight());
}
if (transaction.getAmountNQT() != 0) {
throw new NxtException.NotValidException("Currency transaction NXT amount must be 0");
}
final EnumSet<CurrencyType> validators = EnumSet.noneOf(CurrencyType.class);
for (CurrencyType validator : CurrencyType.values()) {
if ((validator.getCode() & type) != 0) {
validators.add(validator);
}
}
if (validators.isEmpty()) {
throw new NxtException.NotValidException("Currency type not specified");
}
for (CurrencyType validator : CurrencyType.values()) {
if ((validator.getCode() & type) != 0) {
validator.validate(currency, transaction, validators);
} else {
validator.validateMissing(currency, transaction, validators);
}
}
}
static void validateCurrencyNaming(long issuerAccountId, Attachment.MonetarySystemCurrencyIssuance attachment) throws NxtException.ValidationException {
String name = attachment.getName();
String code = attachment.getCode();
String description = attachment.getDescription();
if (name.length() < Constants.MIN_CURRENCY_NAME_LENGTH || name.length() > Constants.MAX_CURRENCY_NAME_LENGTH
|| code.length() != Constants.CURRENCY_CODE_LENGTH
|| description.length() > Constants.MAX_CURRENCY_DESCRIPTION_LENGTH) {
throw new NxtException.NotValidException(String.format("Invalid currency name %s code %s or description %s", name, code, description));
}
String normalizedName = name.toLowerCase();
for (int i = 0; i < normalizedName.length(); i++) {
if (Constants.ALPHABET.indexOf(normalizedName.charAt(i)) < 0) {
throw new NxtException.NotValidException("Invalid currency name: " + normalizedName);
}
}
for (int i = 0; i < code.length(); i++) {
if (Constants.ALLOWED_CURRENCY_CODE_LETTERS.indexOf(code.charAt(i)) < 0) {
throw new NxtException.NotValidException("Invalid currency code: " + code + " code must be all upper case");
}
}
if ("NXT".equals(code) || "nxt".equals(normalizedName)) {
throw new NxtException.NotValidException("Currency name already used");
}
Currency currency;
if ((currency = Currency.getCurrencyByName(normalizedName)) != null && ! currency.isSoleOwner(issuerAccountId)) {
throw new NxtException.NotCurrentlyValidException("Currency name already used: " + normalizedName);
}
if ((currency = Currency.getCurrencyByCode(name.toUpperCase())) != null && ! currency.isSoleOwner(issuerAccountId)) {
throw new NxtException.NotCurrentlyValidException("Currency name already used as code: " + normalizedName);
}
if ((currency = Currency.getCurrencyByCode(code)) != null && ! currency.isSoleOwner(issuerAccountId)) {
throw new NxtException.NotCurrentlyValidException("Currency code already used: " + code);
}
if ((currency = Currency.getCurrencyByName(code.toLowerCase())) != null && ! currency.isSoleOwner(issuerAccountId)) {
throw new NxtException.NotCurrentlyValidException("Currency code already used as name: " + code);
}
}
} |
package com.orm.util;
import android.content.ContentValues;
import android.content.Context;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.util.Log;
import com.orm.SugarRecord;
import com.orm.dsl.Ignore;
import com.orm.dsl.Table;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.math.BigDecimal;
import java.net.URL;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import dalvik.system.DexFile;
public class ReflectionUtil {
public static List<Field> getTableFields(Class table) {
List<Field> fieldList = SugarConfig.getFields(table);
if (fieldList != null) return fieldList;
Log.d("Sugar", "Fetching properties");
List<Field> typeFields = new ArrayList<Field>();
getAllFields(typeFields, table);
List<Field> toStore = new ArrayList<Field>();
for (Field field : typeFields) {
if (!field.isAnnotationPresent(Ignore.class) && !Modifier.isStatic(field.getModifiers()) && !Modifier.isTransient(field.getModifiers())) {
toStore.add(field);
}
}
SugarConfig.setFields(table, toStore);
return toStore;
}
private static List<Field> getAllFields(List<Field> fields, Class<?> type) {
Collections.addAll(fields, type.getDeclaredFields());
if (type.getSuperclass() != null) {
fields = getAllFields(fields, type.getSuperclass());
}
return fields;
}
public static void addFieldValueToColumn(ContentValues values, Field column, Object object,
Map<Object, Long> entitiesMap) {
column.setAccessible(true);
Class<?> columnType = column.getType();
try {
String columnName = NamingHelper.toSQLName(column);
Object columnValue = column.get(object);
if (columnType.isAnnotationPresent(Table.class)) {
Field field = null;
try {
field = columnType.getDeclaredField("id");
field.setAccessible(true);
values.put(columnName,
(field != null)
? String.valueOf(field.get(columnValue)) : "0");
} catch (NoSuchFieldException e) {
if (entitiesMap.containsKey(columnValue)) {
values.put(columnName, entitiesMap.get(columnValue));
}
}
} else if (SugarRecord.class.isAssignableFrom(columnType)) {
values.put(columnName,
(columnValue != null)
? String.valueOf(((SugarRecord) columnValue).getId())
: "0");
} else {
if (columnType.equals(Short.class) || columnType.equals(short.class)) {
values.put(columnName, (Short) columnValue);
} else if (columnType.equals(Integer.class) || columnType.equals(int.class)) {
values.put(columnName, (Integer) columnValue);
} else if (columnType.equals(Long.class) || columnType.equals(long.class)) {
values.put(columnName, (Long) columnValue);
} else if (columnType.equals(Float.class) || columnType.equals(float.class)) {
values.put(columnName, (Float) columnValue);
} else if (columnType.equals(Double.class) || columnType.equals(double.class)) {
values.put(columnName, (Double) columnValue);
} else if (columnType.equals(Boolean.class) || columnType.equals(boolean.class)) {
values.put(columnName, (Boolean) columnValue);
} else if (columnType.equals(BigDecimal.class)) {
try {
values.put(columnName, column.get(object).toString());
} catch (NullPointerException e) {
values.putNull(columnName);
}
} else if (Timestamp.class.equals(columnType)) {
try {
values.put(columnName, ((Timestamp) column.get(object)).getTime());
} catch (NullPointerException e) {
values.put(columnName, (Long) null);
}
} else if (Date.class.equals(columnType)) {
try {
values.put(columnName, ((Date) column.get(object)).getTime());
} catch (NullPointerException e) {
values.put(columnName, (Long) null);
}
} else if (Calendar.class.equals(columnType)) {
try {
values.put(columnName, ((Calendar) column.get(object)).getTimeInMillis());
} catch (NullPointerException e) {
values.put(columnName, (Long) null);
}
} else if (columnType.equals(byte[].class)) {
if (columnValue == null) {
values.put(columnName, "".getBytes());
} else {
values.put(columnName, (byte[]) columnValue);
}
} else {
if (columnValue == null) {
values.putNull(columnName);
} else if (columnType.isEnum()) {
values.put(columnName, ((Enum) columnValue).name());
} else {
values.put(columnName, String.valueOf(columnValue));
}
}
}
} catch (IllegalAccessException e) {
Log.e("Sugar", e.getMessage());
}
}
public static void setFieldValueFromCursor(Cursor cursor, Field field, Object object) {
field.setAccessible(true);
try {
Class fieldType = field.getType();
String colName = NamingHelper.toSQLName(field);
int columnIndex = cursor.getColumnIndex(colName);
if (cursor.isNull(columnIndex)) {
return;
}
if (colName.equalsIgnoreCase("id")) {
long cid = cursor.getLong(columnIndex);
field.set(object, Long.valueOf(cid));
} else if (fieldType.equals(long.class) || fieldType.equals(Long.class)) {
field.set(object,
cursor.getLong(columnIndex));
} else if (fieldType.equals(String.class)) {
String val = cursor.getString(columnIndex);
field.set(object, val != null && val.equals("null") ? null : val);
} else if (fieldType.equals(double.class) || fieldType.equals(Double.class)) {
field.set(object,
cursor.getDouble(columnIndex));
} else if (fieldType.equals(boolean.class) || fieldType.equals(Boolean.class)) {
field.set(object,
cursor.getString(columnIndex).equals("1"));
} else if (fieldType.equals(int.class) || fieldType.equals(Integer.class)) {
field.set(object,
cursor.getInt(columnIndex));
} else if (fieldType.equals(float.class) || fieldType.equals(Float.class)) {
field.set(object,
cursor.getFloat(columnIndex));
} else if (fieldType.equals(short.class) || fieldType.equals(Short.class)) {
field.set(object,
cursor.getShort(columnIndex));
} else if (fieldType.equals(BigDecimal.class)) {
String val = cursor.getString(columnIndex);
field.set(object, val != null && val.equals("null") ? null : new BigDecimal(val));
} else if (fieldType.equals(Timestamp.class)) {
long l = cursor.getLong(columnIndex);
field.set(object, new Timestamp(l));
} else if (fieldType.equals(Date.class)) {
long l = cursor.getLong(columnIndex);
field.set(object, new Date(l));
} else if (fieldType.equals(Calendar.class)) {
long l = cursor.getLong(columnIndex);
Calendar c = Calendar.getInstance();
c.setTimeInMillis(l);
field.set(object, c);
} else if (fieldType.equals(byte[].class)) {
byte[] bytes = cursor.getBlob(columnIndex);
if (bytes == null) {
field.set(object, "".getBytes());
} else {
field.set(object, cursor.getBlob(columnIndex));
}
} else if (Enum.class.isAssignableFrom(fieldType)) {
try {
Method valueOf = field.getType().getMethod("valueOf", String.class);
String strVal = cursor.getString(columnIndex);
Object enumVal = valueOf.invoke(field.getType(), strVal);
field.set(object, enumVal);
} catch (Exception e) {
Log.e("Sugar", "Enum cannot be read from Sqlite3 database. Please check the type of field " + field.getName());
}
} else
Log.e("Sugar", "Class cannot be read from Sqlite3 database. Please check the type of field " + field.getName() + "(" + field.getType().getName() + ")");
} catch (IllegalArgumentException e) {
Log.e("field set error", e.getMessage());
} catch (IllegalAccessException e) {
Log.e("field set error", e.getMessage());
}
}
private static Field getDeepField(String fieldName, Class<?> type) throws NoSuchFieldException {
try {
Field field = type.getDeclaredField(fieldName);
return field;
} catch (NoSuchFieldException e) {
Class superclass = type.getSuperclass();
if (superclass != null) {
Field field = getDeepField(fieldName, superclass);
return field;
} else {
throw e;
}
}
}
public static void setFieldValueForId(Object object, Long value) {
try {
Field field = getDeepField("id", object.getClass());
field.setAccessible(true);
field.set(object, value);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
}
public static List<Class> getDomainClasses(Context context) {
List<Class> domainClasses = new ArrayList<Class>();
try {
for (String className : getAllClasses(context)) {
Class domainClass = getDomainClass(className, context);
if (domainClass != null) domainClasses.add(domainClass);
}
} catch (IOException e) {
Log.e("Sugar", e.getMessage());
} catch (PackageManager.NameNotFoundException e) {
Log.e("Sugar", e.getMessage());
}
return domainClasses;
}
private static Class getDomainClass(String className, Context context) {
Class<?> discoveredClass = null;
try {
discoveredClass = Class.forName(className, true, context.getClass().getClassLoader());
} catch (ClassNotFoundException e) {
Log.e("Sugar", e.getMessage());
}
if ((discoveredClass != null) &&
((SugarRecord.class.isAssignableFrom(discoveredClass) &&
!SugarRecord.class.equals(discoveredClass)) ||
discoveredClass.isAnnotationPresent(Table.class)) &&
!Modifier.isAbstract(discoveredClass.getModifiers())) {
Log.i("Sugar", "domain class : " + discoveredClass.getSimpleName());
return discoveredClass;
} else {
return null;
}
}
private static List<String> getAllClasses(Context context) throws PackageManager.NameNotFoundException, IOException {
String packageName = ManifestHelper.getDomainPackageName(context);
String path = getSourcePath(context);
List<String> classNames = new ArrayList<String>();
DexFile dexfile = null;
try {
dexfile = new DexFile(path);
Enumeration<String> dexEntries = dexfile.entries();
while (dexEntries.hasMoreElements()) {
String className = dexEntries.nextElement();
if (className.startsWith(packageName)) classNames.add(className);
}
} catch (NullPointerException e) {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
Enumeration<URL> urls = classLoader.getResources("");
while (urls.hasMoreElements()) {
List<String> fileNames = new ArrayList<String>();
String classDirectoryName = urls.nextElement().getFile();
if (classDirectoryName.contains("bin") || classDirectoryName.contains("classes")) {
File classDirectory = new File(classDirectoryName);
for (File filePath : classDirectory.listFiles()) {
populateFiles(filePath, fileNames, "");
}
for (String fileName : fileNames) {
if (fileName.startsWith(packageName)) classNames.add(fileName);
}
}
}
} finally {
if (null != dexfile) dexfile.close();
}
return classNames;
}
private static void populateFiles(File path, List<String> fileNames, String parent) {
if (path.isDirectory()) {
for (File newPath : path.listFiles()) {
if ("".equals(parent)) {
populateFiles(newPath, fileNames, path.getName());
} else {
populateFiles(newPath, fileNames, parent + "." + path.getName());
}
}
} else {
String pathName = path.getName();
String classSuffix = ".class";
pathName = pathName.endsWith(classSuffix) ?
pathName.substring(0, pathName.length() - classSuffix.length()) : pathName;
if ("".equals(parent)) {
fileNames.add(pathName);
} else {
fileNames.add(parent + "." + pathName);
}
}
}
private static String getSourcePath(Context context) throws PackageManager.NameNotFoundException {
return context.getPackageManager().getApplicationInfo(context.getPackageName(), 0).sourceDir;
}
} |
package net.ossrs.yasea;
import android.media.MediaCodec;
import android.media.MediaFormat;
import android.util.Log;
import com.github.faucamp.simplertmp.DefaultRtmpPublisher;
import com.github.faucamp.simplertmp.RtmpHandler;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;
public class SrsFlvMuxer {
private static final int VIDEO_ALLOC_SIZE = 128 * 1024;
private static final int AUDIO_ALLOC_SIZE = 4 * 1024;
private volatile boolean connected = false;
private DefaultRtmpPublisher publisher;
private RtmpHandler mHandler;
private Thread worker;
private final Object txFrameLock = new Object();
public SrsFlv flv = new SrsFlv();
public boolean needToFindKeyFrame = true;
private SrsFlvFrame mVideoSequenceHeader;
private SrsFlvFrame mAudioSequenceHeader;
private SrsAllocator mVideoAllocator = new SrsAllocator(VIDEO_ALLOC_SIZE);
private SrsAllocator mAudioAllocator = new SrsAllocator(AUDIO_ALLOC_SIZE);
private ConcurrentLinkedQueue<SrsFlvFrame> mFlvTagCache = new ConcurrentLinkedQueue<>();
public static final int VIDEO_TRACK = 100;
public static final int AUDIO_TRACK = 101;
private static final String TAG = "SrsFlvMuxer";
/**
* Start presentation timestamp
*/
private long startPTS;
private long lastVideoPTS;
private long lastAudioPTS;
private long offset;
/**
* constructor.
*
* @param handler the rtmp event handler.
*/
public SrsFlvMuxer(RtmpHandler handler) {
mHandler = handler;
publisher = new DefaultRtmpPublisher(handler);
}
/**
* get cached video frame number in publisher
*/
public AtomicInteger getVideoFrameCacheNumber() {
return publisher == null ? null : publisher.getVideoFrameCacheNumber();
}
/**
* set video resolution for publisher
*
* @param width width
* @param height height
*/
public void setVideoResolution(int width, int height) {
if (publisher != null) {
publisher.setVideoResolution(width, height);
}
}
/**
* Adds a track with the specified format.
*
* @param format The media format for the track.
* @return The track index for this newly added track.
*/
public int addTrack(MediaFormat format) {
if (format.getString(MediaFormat.KEY_MIME).contentEquals(SrsEncoder.VCODEC)) {
flv.setVideoTrack(format);
return VIDEO_TRACK;
} else {
flv.setAudioTrack(format);
return AUDIO_TRACK;
}
}
public void disconnect() {
try {
publisher.close();
} catch (IllegalStateException e) {
}
mFlvTagCache.clear();
flv.reset();
connected = false;
mVideoSequenceHeader = null;
mAudioSequenceHeader = null;
Log.i(TAG, "worker: disconnect ok.");
}
public boolean connect(String url) {
startPTS = 0;
offset = 10;
if (url.contains("goeasy")) offset = 0; // Workaround for EasyLive
lastVideoPTS = 0;
lastAudioPTS = 0;
needToFindKeyFrame = true;
if (!connected) {
Log.i(TAG, String.format("worker: connecting to RTMP server by url=%s\n", url));
if (publisher.connect(url)) {
connected = publisher.publish("live");
}
mVideoSequenceHeader = null;
mAudioSequenceHeader = null;
}
return connected;
}
private void sendFlvTag(SrsFlvFrame frame) {
if (!connected || frame == null) {
return;
}
if (frame.isVideo()) {
if (frame.isKeyFrame()) {
Log.d(TAG, String.format("worker: send frame type=%d, dts=%d, size=%dB",
frame.type, frame.dts, frame.flvTag.array().length));
}
publisher.publishVideoData(frame.flvTag.array(), frame.flvTag.size(), frame.dts);
mVideoAllocator.release(frame.flvTag);
} else if (frame.isAudio()) {
publisher.publishAudioData(frame.flvTag.array(), frame.flvTag.size(), frame.dts);
mAudioAllocator.release(frame.flvTag);
}
}
/**
* start to the remote server for remux.
*/
public void start(final String rtmpUrl) {
worker = new Thread(new Runnable() {
@Override
public void run() {
Log.i(TAG, "SrsFlvMuxer started");
if (!connect(rtmpUrl)) {
Log.e(TAG, "SrsFlvMuxer disconnected");
return;
}
Log.i(TAG, "SrsFlvMuxer connected");
while (worker != null) {
sendFlvTags();
// Waiting for next frame
synchronized (txFrameLock) {
try {
// isEmpty() may take some time, so we set timeout to detect next frame
txFrameLock.wait(500);
} catch (InterruptedException ie) {
worker = null;
}
}
}
disconnect();
Log.i(TAG, "SrsFlvMuxer stopped");
}
});
worker.setPriority(Thread.MAX_PRIORITY);
worker.setDaemon(true);
worker.start();
}
/**
* Send all FLV tags from cache
*/
public void sendFlvTags() {
// if (!mFlvTagCache.isEmpty()) {
SrsFlvFrame frame = mFlvTagCache.poll();
if (frame==null) return;
if (frame.isSequenceHeader()) {
if (frame.isVideo()) {
mVideoSequenceHeader = frame;
sendFlvTag(mVideoSequenceHeader);
} else if (frame.isAudio()) {
mAudioSequenceHeader = frame;
sendFlvTag(mAudioSequenceHeader);
}
} else {
if (frame.isVideo() && mVideoSequenceHeader != null) {
sendFlvTag(frame);
} else if (frame.isAudio() && mAudioSequenceHeader != null) {
sendFlvTag(frame);
}
}
}
/**
* stop the muxer, disconnect RTMP connection.
*/
public void stop() {
worker = null;
}
/**
* Mux video sample
*
* @param byteBuf The encoded sample.
* @param bufferInfo The buffer information related to this sample.
*/
public void writeVideoSample(ByteBuffer byteBuf, MediaCodec.BufferInfo bufferInfo) {
if (startPTS == 0) startPTS = bufferInfo.presentationTimeUs - offset;
bufferInfo.presentationTimeUs -= startPTS;
if (bufferInfo.presentationTimeUs < lastVideoPTS) return;
lastVideoPTS = bufferInfo.presentationTimeUs;
AtomicInteger videoFrameCacheNumber = getVideoFrameCacheNumber();
if (videoFrameCacheNumber != null && videoFrameCacheNumber.get() < SrsAvcEncoder.VGOP) {
flv.writeVideoSample(byteBuf, bufferInfo);
} else {
Log.w(TAG, "Network throughput too low");
}
}
/**
* Mux audio sample
*
* @param byteBuf The encoded sample.
* @param bufferInfo The buffer information related to this sample.
*/
public void writeAudioSample(ByteBuffer byteBuf, MediaCodec.BufferInfo bufferInfo) {
if (startPTS == 0) startPTS = bufferInfo.presentationTimeUs - offset;
bufferInfo.presentationTimeUs -= startPTS;
if (bufferInfo.presentationTimeUs < lastAudioPTS) return;
lastAudioPTS = bufferInfo.presentationTimeUs;
flv.writeAudioSample(byteBuf, bufferInfo);
}
// E.4.3.1 VIDEODATA
// Frame Type UB [4]
// Type of video frame. The following values are defined:
// 1 = key frame (for AVC, a seekable frame)
// 2 = inter frame (for AVC, a non-seekable frame)
// 3 = disposable inter frame (H.263 only)
// 4 = generated key frame (reserved for server use only)
// 5 = video info/command frame
private class SrsCodecVideoAVCFrame {
// set to the zero to reserved, for array map.
public final static int Reserved = 0;
public final static int Reserved1 = 6;
public final static int KeyFrame = 1;
public final static int InterFrame = 2;
public final static int DisposableInterFrame = 3;
public final static int GeneratedKeyFrame = 4;
public final static int VideoInfoFrame = 5;
}
// AVCPacketType IF CodecID == 7 UI8
// The following values are defined:
// 0 = AVC sequence header
// 1 = AVC NALU
// 2 = AVC end of sequence (lower level NALU sequence ender is
// not required or supported)
private class SrsCodecVideoAVCType {
// set to the max value to reserved, for array map.
public final static int Reserved = 3;
public final static int SequenceHeader = 0;
public final static int NALU = 1;
public final static int SequenceHeaderEOF = 2;
}
/**
* E.4.1 FLV Tag, page 75
*/
private class SrsCodecFlvTag {
// set to the zero to reserved, for array map.
public final static int Reserved = 0;
// 8 = audio
public final static int Audio = 8;
// 9 = video
public final static int Video = 9;
// 18 = script data
public final static int Script = 18;
}
// E.4.3.1 VIDEODATA
// CodecID UB [4]
// Codec Identifier. The following values are defined:
// 2 = Sorenson H.263
// 3 = Screen video
// 4 = On2 VP6
// 5 = On2 VP6 with alpha channel
// 6 = Screen video version 2
// 7 = AVC
private class SrsCodecVideo {
// set to the zero to reserved, for array map.
public final static int Reserved = 0;
public final static int Reserved1 = 1;
public final static int Reserved2 = 9;
// for user to disable video, for example, use pure audio hls.
public final static int Disabled = 8;
public final static int SorensonH263 = 2;
public final static int ScreenVideo = 3;
public final static int On2VP6 = 4;
public final static int On2VP6WithAlphaChannel = 5;
public final static int ScreenVideoVersion2 = 6;
public final static int AVC = 7;
}
/**
* the aac object type, for RTMP sequence header
* for AudioSpecificConfig, @see aac-mp4a-format-ISO_IEC_14496-3+2001.pdf, page 33
* for audioObjectType, @see aac-mp4a-format-ISO_IEC_14496-3+2001.pdf, page 23
*/
private class SrsAacObjectType {
public final static int Reserved = 0;
// @see @see aac-mp4a-format-ISO_IEC_14496-3+2001.pdf, page 23
public final static int AacMain = 1;
public final static int AacLC = 2;
public final static int AacSSR = 3;
// AAC HE = LC+SBR
public final static int AacHE = 5;
// AAC HEv2 = LC+SBR+PS
public final static int AacHEV2 = 29;
}
/**
* the aac profile, for ADTS(HLS/TS)
*/
private class SrsAacProfile {
public final static int Reserved = 3;
// @see 7.1 Profiles, aac-iso-13818-7.pdf, page 40
public final static int Main = 0;
public final static int LC = 1;
public final static int SSR = 2;
}
/**
* the FLV/RTMP supported audio sample rate.
* Sampling rate. The following values are defined:
* 0 = 5.5 kHz = 5512 Hz
* 1 = 11 kHz = 11025 Hz
* 2 = 22 kHz = 22050 Hz
* 3 = 44 kHz = 44100 Hz
*/
private class SrsCodecAudioSampleRate {
public final static int R5512 = 5512;
public final static int R11025 = 11025;
public final static int R22050 = 22050;
public final static int R44100 = 44100;
public final static int R32000 = 32000;
public final static int R16000 = 16000;
}
private class SrsAvcNaluType {
// Unspecified
public final static int Reserved = 0;
// Coded slice of a non-IDR picture slice_layer_without_partitioning_rbsp( )
public final static int NonIDR = 1;
// Coded slice data partition A slice_data_partition_a_layer_rbsp( )
public final static int DataPartitionA = 2;
// Coded slice data partition B slice_data_partition_b_layer_rbsp( )
public final static int DataPartitionB = 3;
// Coded slice data partition C slice_data_partition_c_layer_rbsp( )
public final static int DataPartitionC = 4;
// Coded slice of an IDR picture slice_layer_without_partitioning_rbsp( )
public final static int IDR = 5;
// Supplemental enhancement information (SEI) sei_rbsp( )
public final static int SEI = 6;
// Sequence parameter set seq_parameter_set_rbsp( )
public final static int SPS = 7;
// Picture parameter set pic_parameter_set_rbsp( )
public final static int PPS = 8;
// Access unit delimiter access_unit_delimiter_rbsp( )
public final static int AccessUnitDelimiter = 9;
// End of sequence end_of_seq_rbsp( )
public final static int EOSequence = 10;
// End of stream end_of_stream_rbsp( )
public final static int EOStream = 11;
// Filler data filler_data_rbsp( )
public final static int FilterData = 12;
// Sequence parameter set extension seq_parameter_set_extension_rbsp( )
public final static int SPSExt = 13;
// Prefix NAL unit prefix_nal_unit_rbsp( )
public final static int PrefixNALU = 14;
// Subset sequence parameter set subset_seq_parameter_set_rbsp( )
public final static int SubsetSPS = 15;
// Coded slice of an auxiliary coded picture without partitioning slice_layer_without_partitioning_rbsp( )
public final static int LayerWithoutPartition = 19;
// Coded slice extension slice_layer_extension_rbsp( )
public final static int CodedSliceExt = 20;
}
/**
* the search result for annexb.
*/
private class SrsAnnexbSearch {
public int nb_start_code = 0;
public boolean match = false;
}
/**
* the demuxed tag frame.
*/
private class SrsFlvFrameBytes {
public ByteBuffer data;
public int size;
}
/**
* the muxed flv frame.
*/
private class SrsFlvFrame {
// the tag bytes.
public SrsAllocator.Allocation flvTag;
// the codec type for audio/aac and video/avc for instance.
public int avc_aac_type;
// the frame type, keyframe or not.
public int frame_type;
// the tag type, audio, video or data.
public int type;
// the dts in ms, tbn is 1000.
public int dts;
public boolean isKeyFrame() {
return isVideo() && frame_type == SrsCodecVideoAVCFrame.KeyFrame;
}
public boolean isSequenceHeader() {
return avc_aac_type == 0;
}
public boolean isVideo() {
return type == SrsCodecFlvTag.Video;
}
public boolean isAudio() {
return type == SrsCodecFlvTag.Audio;
}
}
/**
* the raw h.264 stream, in annexb.
*/
private class SrsRawH264Stream {
private final static String TAG = "SrsFlvMuxer";
private SrsAnnexbSearch annexb = new SrsAnnexbSearch();
private SrsFlvFrameBytes seq_hdr = new SrsFlvFrameBytes();
private SrsFlvFrameBytes sps_hdr = new SrsFlvFrameBytes();
private SrsFlvFrameBytes sps_bb = new SrsFlvFrameBytes();
private SrsFlvFrameBytes pps_hdr = new SrsFlvFrameBytes();
private SrsFlvFrameBytes pps_bb = new SrsFlvFrameBytes();
public boolean isSps(SrsFlvFrameBytes frame) {
return frame.size >= 1 && (frame.data.get(0) & 0x1f) == SrsAvcNaluType.SPS;
}
public boolean isPps(SrsFlvFrameBytes frame) {
return frame.size >= 1 && (frame.data.get(0) & 0x1f) == SrsAvcNaluType.PPS;
}
public SrsFlvFrameBytes muxNaluHeader(SrsFlvFrameBytes frame) {
SrsFlvFrameBytes nalu_hdr = new SrsFlvFrameBytes();
nalu_hdr.data = ByteBuffer.allocateDirect(4);
nalu_hdr.size = 4;
// 5.3.4.2.1 Syntax, H.264-AVC-ISO_IEC_14496-15.pdf, page 16
// lengthSizeMinusOne, or NAL_unit_length, always use 4bytes size
int NAL_unit_length = frame.size;
// mux the avc NALU in "ISO Base Media File Format"
// from H.264-AVC-ISO_IEC_14496-15.pdf, page 20
// NALUnitLength
nalu_hdr.data.putInt(NAL_unit_length);
// reset the buffer.
nalu_hdr.data.rewind();
return nalu_hdr;
}
public void muxSequenceHeader(ByteBuffer sps, ByteBuffer pps, int dts, int pts,
ArrayList<SrsFlvFrameBytes> frames) {
// 5bytes sps/pps header:
// configurationVersion, AVCProfileIndication, profile_compatibility,
// AVCLevelIndication, lengthSizeMinusOne
// 3bytes size of sps:
// numOfSequenceParameterSets, sequenceParameterSetLength(2B)
// Nbytes of sps.
// sequenceParameterSetNALUnit
// 3bytes size of pps:
// numOfPictureParameterSets, pictureParameterSetLength
// Nbytes of pps:
// pictureParameterSetNALUnit
// decode the SPS:
// @see: 7.3.2.1.1, H.264-AVC-ISO_IEC_14496-10-2012.pdf, page 62
if (seq_hdr.data == null) {
seq_hdr.data = ByteBuffer.allocate(5);
seq_hdr.size = 5;
}
seq_hdr.data.rewind();
// @see: Annex A Profiles and levels, H.264-AVC-ISO_IEC_14496-10.pdf, page 205
// Baseline profile profile_idc is 66(0x42).
// Main profile profile_idc is 77(0x4d).
// Extended profile profile_idc is 88(0x58).
byte profile_idc = sps.get(1);
//u_int8_t constraint_set = frame[2];
byte level_idc = sps.get(3);
// generate the sps/pps header
// 5.3.4.2.1 Syntax, H.264-AVC-ISO_IEC_14496-15.pdf, page 16
// configurationVersion
seq_hdr.data.put((byte) 0x01);
// AVCProfileIndication
seq_hdr.data.put(profile_idc);
// profile_compatibility
seq_hdr.data.put((byte) 0x00);
// AVCLevelIndication
seq_hdr.data.put(level_idc);
// lengthSizeMinusOne, or NAL_unit_length, always use 4bytes size,
// so we always set it to 0x03.
seq_hdr.data.put((byte) 0x03);
// reset the buffer.
seq_hdr.data.rewind();
frames.add(seq_hdr);
// sps
if (sps_hdr.data == null) {
sps_hdr.data = ByteBuffer.allocate(3);
sps_hdr.size = 3;
}
sps_hdr.data.rewind();
// 5.3.4.2.1 Syntax, H.264-AVC-ISO_IEC_14496-15.pdf, page 16
// numOfSequenceParameterSets, always 1
sps_hdr.data.put((byte) 0x01);
// sequenceParameterSetLength
sps_hdr.data.putShort((short) sps.array().length);
sps_hdr.data.rewind();
frames.add(sps_hdr);
// sequenceParameterSetNALUnit
sps_bb.size = sps.array().length;
sps_bb.data = sps.duplicate();
frames.add(sps_bb);
// pps
if (pps_hdr.data == null) {
pps_hdr.data = ByteBuffer.allocate(3);
pps_hdr.size = 3;
}
pps_hdr.data.rewind();
// 5.3.4.2.1 Syntax, H.264-AVC-ISO_IEC_14496-15.pdf, page 16
// numOfPictureParameterSets, always 1
pps_hdr.data.put((byte) 0x01);
// pictureParameterSetLength
pps_hdr.data.putShort((short) pps.array().length);
pps_hdr.data.rewind();
frames.add(pps_hdr);
// pictureParameterSetNALUnit
pps_bb.size = pps.array().length;
pps_bb.data = pps.duplicate();
frames.add(pps_bb);
}
public SrsAllocator.Allocation muxFlvTag(ArrayList<SrsFlvFrameBytes> frames, int frame_type,
int avc_packet_type, int dts, int pts) {
// for h264 in RTMP video payload, there is 5bytes header:
// 1bytes, FrameType | CodecID
// 1bytes, AVCPacketType
// 3bytes, CompositionTime, the cts.
// @see: E.4.3 Video Tags, video_file_format_spec_v10_1.pdf, page 78
int size = 5;
for (int i = 0; i < frames.size(); i++) {
size += frames.get(i).size;
}
SrsAllocator.Allocation allocation = mVideoAllocator.allocate(size);
// @see: E.4.3 Video Tags, video_file_format_spec_v10_1.pdf, page 78
// Frame Type, Type of video frame.
// CodecID, Codec Identifier.
// set the rtmp header
allocation.put((byte) ((frame_type << 4) | SrsCodecVideo.AVC));
// AVCPacketType
allocation.put((byte) avc_packet_type);
// CompositionTime
// pts = dts + cts, or
// cts = pts - dts.
// where cts is the header in rtmp video packet payload header.
int cts = pts - dts;
allocation.put((byte) (cts >> 16));
allocation.put((byte) (cts >> 8));
allocation.put((byte) cts);
// h.264 raw data.
for (int i = 0; i < frames.size(); i++) {
SrsFlvFrameBytes frame = frames.get(i);
frame.data.get(allocation.array(), allocation.size(), frame.size);
allocation.appendOffset(frame.size);
}
return allocation;
}
private SrsAnnexbSearch searchAnnexb(ByteBuffer bb, MediaCodec.BufferInfo bi) {
annexb.match = false;
annexb.nb_start_code = 0;
for (int i = bb.position(); i < bi.size - 3; i++) {
// not match.
if (bb.get(i) != 0x00 || bb.get(i + 1) != 0x00) {
break;
}
// match N[00] 00 00 01, where N>=0
if (bb.get(i + 2) == 0x01) {
annexb.match = true;
annexb.nb_start_code = i + 3 - bb.position();
break;
}
}
return annexb;
}
public SrsFlvFrameBytes demuxAnnexb(ByteBuffer bb, MediaCodec.BufferInfo bi) {
SrsFlvFrameBytes tbb = new SrsFlvFrameBytes();
while (bb.position() < bi.size) {
// each frame must prefixed by annexb format.
// about annexb, @see H.264-AVC-ISO_IEC_14496-10.pdf, page 211.
SrsAnnexbSearch tbbsc = searchAnnexb(bb, bi);
if (!tbbsc.match || tbbsc.nb_start_code < 3) {
Log.e(TAG, "annexb not match.");
mHandler.notifyRtmpIllegalArgumentException(new IllegalArgumentException(
String.format("annexb not match for %dB, pos=%d", bi.size, bb.position())));
}
// the start codes.
for (int i = 0; i < tbbsc.nb_start_code; i++) {
bb.get();
}
// find out the frame size.
tbb.data = bb.slice();
int pos = bb.position();
while (bb.position() < bi.size) {
SrsAnnexbSearch bsc = searchAnnexb(bb, bi);
if (bsc.match) {
break;
}
bb.get();
}
tbb.size = bb.position() - pos;
break;
}
return tbb;
}
}
private class SrsRawAacStreamCodec {
public byte protection_absent;
// SrsAacObjectType
public int aac_object;
public byte sampling_frequency_index;
public byte channel_configuration;
public short frame_length;
public byte sound_format;
public byte sound_rate;
public byte sound_size;
public byte sound_type;
// 0 for sh; 1 for raw data.
public byte aac_packet_type;
public byte[] frame;
}
/**
* remux the annexb to flv tags.
*/
private class SrsFlv {
private MediaFormat videoTrack;
private MediaFormat audioTrack;
private int achannel;
private int asample_rate;
private SrsRawH264Stream avc = new SrsRawH264Stream();
private ArrayList<SrsFlvFrameBytes> ipbs = new ArrayList<>();
private SrsAllocator.Allocation audio_tag;
private SrsAllocator.Allocation video_tag;
private ByteBuffer h264_sps;
private boolean h264_sps_changed;
private ByteBuffer h264_pps;
private boolean h264_pps_changed;
private boolean h264_sps_pps_sent;
private boolean aac_specific_config_got;
public SrsFlv() {
reset();
}
public void reset() {
h264_sps_changed = false;
h264_pps_changed = false;
h264_sps_pps_sent = false;
aac_specific_config_got = false;
}
public void setVideoTrack(MediaFormat format) {
videoTrack = format;
}
public void setAudioTrack(MediaFormat format) {
audioTrack = format;
achannel = format.getInteger(MediaFormat.KEY_CHANNEL_COUNT);
asample_rate = format.getInteger(MediaFormat.KEY_SAMPLE_RATE);
}
public void writeAudioSample(final ByteBuffer bb, MediaCodec.BufferInfo bi) {
int pts = (int) (bi.presentationTimeUs / 1000);
int dts = pts;
audio_tag = mAudioAllocator.allocate(bi.size + 2);
byte aac_packet_type = 1; // 1 = AAC raw
if (!aac_specific_config_got) {
// @see aac-mp4a-format-ISO_IEC_14496-3+2001.pdf
// AudioSpecificConfig (), page 33
// 1.6.2.1 AudioSpecificConfig
// audioObjectType; 5 bslbf
byte ch = (byte) (bb.get(0) & 0xf8);
// 3bits left.
// samplingFrequencyIndex; 4 bslbf
byte samplingFrequencyIndex = 0x04;
if (asample_rate == SrsCodecAudioSampleRate.R22050) {
samplingFrequencyIndex = 0x07;
} else if (asample_rate == SrsCodecAudioSampleRate.R11025) {
samplingFrequencyIndex = 0x0a;
}
ch |= (samplingFrequencyIndex >> 1) & 0x07;
audio_tag.put(ch, 2);
ch = (byte) ((samplingFrequencyIndex << 7) & 0x80);
// 7bits left.
// channelConfiguration; 4 bslbf
byte channelConfiguration = 1;
if (achannel == 2) {
channelConfiguration = 2;
}
ch |= (channelConfiguration << 3) & 0x78;
// 3bits left.
// GASpecificConfig(), page 451
// 4.4.1 Decoder configuration (GASpecificConfig)
// frameLengthFlag; 1 bslbf
// dependsOnCoreCoder; 1 bslbf
// extensionFlag; 1 bslbf
audio_tag.put(ch, 3);
aac_specific_config_got = true;
aac_packet_type = 0; // 0 = AAC sequence header
writeAdtsHeader(audio_tag.array(), 4);
audio_tag.appendOffset(7);
} else {
bb.get(audio_tag.array(), 2, bi.size);
audio_tag.appendOffset(bi.size + 2);
}
byte sound_format = 10; // AAC
byte sound_type = 0; // 0 = Mono sound
if (achannel == 2) {
sound_type = 1; // 1 = Stereo sound
}
byte sound_size = 1; // 1 = 16-bit samples
byte sound_rate = 3; // 44100, 22050, 11025
if (asample_rate == 22050) {
sound_rate = 2;
} else if (asample_rate == 11025) {
sound_rate = 1;
}
// for audio frame, there is 1 or 2 bytes header:
// 1bytes, SoundFormat|SoundRate|SoundSize|SoundType
// 1bytes, AACPacketType for SoundFormat == 10, 0 is sequence header.
byte audio_header = (byte) (sound_type & 0x01);
audio_header |= (sound_size << 1) & 0x02;
audio_header |= (sound_rate << 2) & 0x0c;
audio_header |= (sound_format << 4) & 0xf0;
audio_tag.put(audio_header, 0);
audio_tag.put(aac_packet_type, 1);
writeRtmpPacket(SrsCodecFlvTag.Audio, dts, 0, aac_packet_type, audio_tag);
}
private void writeAdtsHeader(byte[] frame, int offset) {
// adts sync word 0xfff (12-bit)
frame[offset] = (byte) 0xff;
frame[offset + 1] = (byte) 0xf0;
// versioin 0 for MPEG-4, 1 for MPEG-2 (1-bit)
frame[offset + 1] |= 0 << 3;
// layer 0 (2-bit)
frame[offset + 1] |= 0 << 1;
// protection absent: 1 (1-bit)
frame[offset + 1] |= 1;
// profile: audio_object_type - 1 (2-bit)
frame[offset + 2] = (SrsAacObjectType.AacLC - 1) << 6;
// sampling frequency index: 4 (4-bit)
frame[offset + 2] |= (4 & 0xf) << 2;
// channel configuration (3-bit)
frame[offset + 2] |= (2 & (byte) 0x4) >> 2;
frame[offset + 3] = (byte) ((2 & (byte) 0x03) << 6);
// original: 0 (1-bit)
frame[offset + 3] |= 0 << 5;
// home: 0 (1-bit)
frame[offset + 3] |= 0 << 4;
frame[offset + 3] |= 0 << 3;
frame[offset + 3] |= 0 << 2;
// frame size (13-bit)
frame[offset + 3] |= ((frame.length - 2) & 0x1800) >> 11;
frame[offset + 4] = (byte) (((frame.length - 2) & 0x7f8) >> 3);
frame[offset + 5] = (byte) (((frame.length - 2) & 0x7) << 5);
// buffer fullness (0x7ff for variable bitrate)
frame[offset + 5] |= (byte) 0x1f;
frame[offset + 6] = (byte) 0xfc;
// number of data block (nb - 1)
frame[offset + 6] |= 0x0;
}
private void writeVideoSample(final ByteBuffer bb, MediaCodec.BufferInfo bi) {
int pts = (int) (bi.presentationTimeUs / 1000);
int dts = pts;
int type = SrsCodecVideoAVCFrame.InterFrame;
// send each frame.
while (bb.position() < bi.size) {
SrsFlvFrameBytes frame = avc.demuxAnnexb(bb, bi);
// 5bits, 7.3.1 NAL unit syntax,
// H.264-AVC-ISO_IEC_14496-10.pdf, page 44.
// 7: SPS, 8: PPS, 5: I Frame, 1: P Frame
int nal_unit_type = frame.data.get(0) & 0x1f;
if (nal_unit_type == SrsAvcNaluType.SPS || nal_unit_type == SrsAvcNaluType.PPS) {
Log.i(TAG, String.format("annexb demux %dB, pts=%d, frame=%dB, nalu=%d",
bi.size, pts, frame.size, nal_unit_type));
}
// for IDR frame, the frame is keyframe.
if (nal_unit_type == SrsAvcNaluType.IDR) {
type = SrsCodecVideoAVCFrame.KeyFrame;
}
// ignore the nalu type aud(9)
if (nal_unit_type == SrsAvcNaluType.AccessUnitDelimiter) {
continue;
}
// for sps
if (avc.isSps(frame)) {
if (!frame.data.equals(h264_sps)) {
byte[] sps = new byte[frame.size];
frame.data.get(sps);
h264_sps_changed = true;
h264_sps = ByteBuffer.wrap(sps);
}
continue;
}
// for pps
if (avc.isPps(frame)) {
if (!frame.data.equals(h264_pps)) {
byte[] pps = new byte[frame.size];
frame.data.get(pps);
h264_pps_changed = true;
h264_pps = ByteBuffer.wrap(pps);
}
continue;
}
// IPB frame.
ipbs.add(avc.muxNaluHeader(frame));
ipbs.add(frame);
}
writeH264SpsPps(dts, pts);
writeH264IpbFrame(ipbs, type, dts, pts);
ipbs.clear();
}
private void writeH264SpsPps(int dts, int pts) {
// when sps or pps changed, update the sequence header,
// for the pps maybe not changed while sps changed.
// so, we must check when each video ts message frame parsed.
if (h264_sps_pps_sent && !h264_sps_changed && !h264_pps_changed) {
return;
}
// when not got sps/pps, wait.
if (h264_pps == null || h264_sps == null) {
return;
}
// h264 raw to h264 packet.
ArrayList<SrsFlvFrameBytes> frames = new ArrayList<>();
avc.muxSequenceHeader(h264_sps, h264_pps, dts, pts, frames);
// h264 packet to flv packet.
int frame_type = SrsCodecVideoAVCFrame.KeyFrame;
int avc_packet_type = SrsCodecVideoAVCType.SequenceHeader;
video_tag = avc.muxFlvTag(frames, frame_type, avc_packet_type, dts, pts);
// the timestamp in rtmp message header is dts.
writeRtmpPacket(SrsCodecFlvTag.Video, dts, frame_type, avc_packet_type, video_tag);
// reset sps and pps.
h264_sps_changed = false;
h264_pps_changed = false;
h264_sps_pps_sent = true;
Log.i(TAG, String.format("flv: h264 sps/pps sent, sps=%dB, pps=%dB",
h264_sps.array().length, h264_pps.array().length));
}
private void writeH264IpbFrame(ArrayList<SrsFlvFrameBytes> frames, int type, int dts, int pts) {
// when sps or pps not sent, ignore the packet.
if (!h264_sps_pps_sent) {
return;
}
video_tag = avc.muxFlvTag(frames, type, SrsCodecVideoAVCType.NALU, dts, pts);
// the timestamp in rtmp message header is dts.
writeRtmpPacket(SrsCodecFlvTag.Video, dts, type, SrsCodecVideoAVCType.NALU, video_tag);
}
private void writeRtmpPacket(int type, int dts, int frame_type, int avc_aac_type, SrsAllocator.Allocation tag) {
SrsFlvFrame frame = new SrsFlvFrame();
frame.flvTag = tag;
frame.type = type;
frame.dts = dts;
frame.frame_type = frame_type;
frame.avc_aac_type = avc_aac_type;
if (frame.isVideo()) {
if (needToFindKeyFrame) {
if (frame.isKeyFrame()) {
needToFindKeyFrame = false;
flvTagCacheAdd(frame);
}
} else {
flvTagCacheAdd(frame);
}
} else if (frame.isAudio()) {
flvTagCacheAdd(frame);
}
}
private void flvTagCacheAdd(SrsFlvFrame frame) {
mFlvTagCache.add(frame);
if (frame.isVideo()) {
getVideoFrameCacheNumber().incrementAndGet();
}
synchronized (txFrameLock) {
txFrameLock.notifyAll();
}
}
}
} |
package org.dynmap;
import org.dynmap.MapType.ImageFormat;
import org.dynmap.common.DynmapListenerManager.EventType;
import org.dynmap.common.DynmapListenerManager.PlayerEventListener;
import org.dynmap.common.DynmapPlayer;
import org.dynmap.debug.Debug;
import org.dynmap.storage.MapStorage;
import org.dynmap.utils.BufferOutputStream;
import org.dynmap.utils.DynmapBufferedImage;
import org.dynmap.utils.ImageIOManager;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.util.UUID;
/**
* Listen for player logins, and process player faces by fetching skins *
*/
public class PlayerFaces {
private boolean fetchskins;
private boolean refreshskins;
private String skinurl;
public MapStorage storage;
public enum FaceType {
FACE_8X8("8x8", 0),
FACE_16X16("16x16", 1),
FACE_32X32("32x32", 2),
BODY_32X32("body", 3);
public final String id;
public final int typeID;
FaceType(String id, int typeid) {
this.id = id;
this.typeID = typeid;
}
public static FaceType byID(String i_d) {
for (FaceType ft : values()) {
if (ft.id.equals(i_d)) {
return ft;
}
}
return null;
}
public static FaceType byTypeID(int tid) {
for (FaceType ft : values()) {
if (ft.typeID == tid) {
return ft;
}
}
return null;
}
}
private void copyLayersToTarget(BufferedImage srcimg, int layer1x, int layer1y, int layer2x, int layer2y, int w, int h, int[] dest, int destoff, int destscansize)
{
int[] l1 = new int[w * h];
int[] l2 = new int[w * h];
int imgh = srcimg.getHeight();
// Read layer 1
if (imgh >= (layer1y+h))
srcimg.getRGB(layer1x, layer1y, w, h, l1, 0, w);
// Read layer 2
if (imgh >= (layer2y+h))
srcimg.getRGB(layer2x, layer2y, w, h, l2, 0, w);
// Apply layer1 to layer 1
boolean transp = false;
int v = l2[0];
for (int i = 0; i < (w*h); i++) {
if ((l2[i] & 0xFF000000) == 0) {
transp = true;
break;
}
/* If any different values, render face too */
else if (l2[i] != v) {
transp = true;
break;
}
}
if(transp) {
for (int i = 0; i < (w*h); i++) {
if ((l2[i] & 0xFF000000) != 0)
l1[i] = l2[i];
}
}
// Write to dest
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
dest[destoff + (y*destscansize + x)] = l1[(y*w)+x];
}
}
}
private class LoadPlayerImages implements Runnable {
public final String playername;
public final String playerskinurl;
public LoadPlayerImages(String playername, String playerskinurl, UUID playeruuid) {
this.playername = playername;
this.playerskinurl = playerskinurl;
}
public void run() {
boolean has_8x8 = storage.hasPlayerFaceImage(playername, FaceType.FACE_8X8);
boolean has_16x16 = storage.hasPlayerFaceImage(playername, FaceType.FACE_16X16);
boolean has_32x32 = storage.hasPlayerFaceImage(playername, FaceType.FACE_32X32);
boolean has_body = storage.hasPlayerFaceImage(playername, FaceType.BODY_32X32);
boolean missing_any = !(has_8x8 && has_16x16 && has_32x32 && has_body);
BufferedImage img = null;
try {
if(fetchskins && (refreshskins || missing_any)) {
URL url = null;
if (skinurl.equals("") == false) {
url = new URL(skinurl.replace("%player%", URLEncoder.encode(playername, "UTF-8")));
}
else if (playerskinurl != null) {
url = new URL(playerskinurl);
}
if (url != null) {
img = ImageIO.read(url); /* Load skin for player */
}
}
} catch (IOException iox) {
Debug.debug("Error loading skin for '" + playername + "' - " + iox);
}
if(img == null) {
try {
InputStream in = getClass().getResourceAsStream("/char.png");
img = ImageIO.read(in); /* Load generic skin for player */
in.close();
} catch (IOException iox) {
Debug.debug("Error loading default skin for '" + playername + "' - " + iox);
}
}
if(img == null) { /* No image to process? Quit */
return;
}
if((img.getWidth() < 64) || (img.getHeight() < 32)) {
img.flush();
return;
}
int[] faceaccessory = new int[64]; /* 8x8 of face accessory */
/* Get buffered image for face at 8x8 */
DynmapBufferedImage face8x8 = DynmapBufferedImage.allocateBufferedImage(8, 8);
// Copy face and overlay to icon
copyLayersToTarget(img, 8, 8, 40, 8, 8, 8, face8x8.argb_buf, 0, 8);
/* Write 8x8 file */
if(refreshskins || (!has_8x8)) {
BufferOutputStream bos = ImageIOManager.imageIOEncode(face8x8.buf_img, ImageFormat.FORMAT_PNG);
if (bos != null) {
storage.setPlayerFaceImage(playername, FaceType.FACE_8X8, bos);
}
}
/* Write 16x16 file */
if(refreshskins || (!has_16x16)) {
/* Make 16x16 version */
DynmapBufferedImage face16x16 = DynmapBufferedImage.allocateBufferedImage(16, 16);
for(int i = 0; i < 16; i++) {
for(int j = 0; j < 16; j++) {
face16x16.argb_buf[i*16+j] = face8x8.argb_buf[(i/2)*8 + (j/2)];
}
}
BufferOutputStream bos = ImageIOManager.imageIOEncode(face16x16.buf_img, ImageFormat.FORMAT_PNG);
if (bos != null) {
storage.setPlayerFaceImage(playername, FaceType.FACE_16X16, bos);
}
DynmapBufferedImage.freeBufferedImage(face16x16);
}
/* Write 32x32 file */
if(refreshskins || (!has_32x32)) {
/* Make 32x32 version */
DynmapBufferedImage face32x32 = DynmapBufferedImage.allocateBufferedImage(32, 32);
for(int i = 0; i < 32; i++) {
for(int j = 0; j < 32; j++) {
face32x32.argb_buf[i*32+j] = face8x8.argb_buf[(i/4)*8 + (j/4)];
}
}
BufferOutputStream bos = ImageIOManager.imageIOEncode(face32x32.buf_img, ImageFormat.FORMAT_PNG);
if (bos != null) {
storage.setPlayerFaceImage(playername, FaceType.FACE_32X32, bos);
}
DynmapBufferedImage.freeBufferedImage(face32x32);
}
/* Write body file */
if(refreshskins || (!has_body)) {
/* Make 32x32 version */
DynmapBufferedImage body32x32 = DynmapBufferedImage.allocateBufferedImage(32, 32);
/* Copy face at 12,0 to 20,8 (already handled accessory) */
for(int i = 0; i < 8; i++) {
for(int j = 0; j < 8; j++) {
body32x32.argb_buf[i*32+j+12] = face8x8.argb_buf[i*8 + j];
}
}
/* Copy body at 20, 20 and chest at to 20, 36 to 12,8 */
copyLayersToTarget(img, 20, 20, 20, 36, 8, 12, body32x32.argb_buf, 8*32+12, 32);
/* Copy legs at 4,20 and 4,366 to 20,12; 44,20 and 44,36 to 20,16 */
copyLayersToTarget(img, 4, 20, 4,36, 8, 12, body32x32.argb_buf, 20*32+12, 32);
copyLayersToTarget(img, 20, 52, 4, 52, 8, 12, body32x32.argb_buf, 20*32+16, 32);
/* Copy arms at 44, 20 and 8,8 to 12,20 and 20,8 to 24,20 */
copyLayersToTarget(img, 44, 20, 44, 36, 8, 12, body32x32.argb_buf, 8*32+8, 32);
copyLayersToTarget(img, 36, 52, 52, 52, 8, 12, body32x32.argb_buf, 8*32+20, 32);
BufferOutputStream bos = ImageIOManager.imageIOEncode(body32x32.buf_img, ImageFormat.FORMAT_PNG);
if (bos != null) {
storage.setPlayerFaceImage(playername, FaceType.BODY_32X32, bos);
}
DynmapBufferedImage.freeBufferedImage(body32x32);
}
DynmapBufferedImage.freeBufferedImage(face8x8);
img.flush();
}
}
public PlayerFaces(DynmapCore core) {
fetchskins = core.configuration.getBoolean("fetchskins", true); /* Control whether to fetch skins */
refreshskins = core.configuration.getBoolean("refreshskins", true); /* Control whether to update existing fetched skins or faces */
skinurl = core.configuration.getString("skin-url", "");
// These don't work anymore - Mojang retired them
if (skinurl.equals("http://s3.amazonaws.com/MinecraftSkins/%player%.png") ||
skinurl.equals("http://skins.minecraft.net/MinecraftSkins/%player%.png")) {
skinurl = "";
}
core.listenerManager.addListener(EventType.PLAYER_JOIN, new PlayerEventListener() {
@Override
public void playerEvent(DynmapPlayer p) {
Runnable job = new LoadPlayerImages(p.getName(), p.getSkinURL(), p.getUUID());
if(fetchskins)
MapManager.scheduleDelayedJob(job, 0);
else
job.run();
}
});
storage = core.getDefaultMapStorage();
}
} |
package com.hsuforum.eas;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class PageRedirect implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("redirect:/default.jsf");
registry.addViewController("/error").setViewName("forward:/exception/exception.jsf");
registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.