answer
stringlengths 17
10.2M
|
|---|
package com.infinityraider.infinitylib.modules.keyboard;
import com.google.common.collect.ImmutableList;
import com.infinityraider.infinitylib.modules.Module;
import net.minecraft.client.KeyMapping;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import java.util.List;
import java.util.OptionalInt;
public class ModuleKeyboard extends Module {
private static final ModuleKeyboard INSTANCE = new ModuleKeyboard();
public static ModuleKeyboard getInstance() {
return INSTANCE;
}
private ModuleKeyboard() {}
@OnlyIn(Dist.CLIENT)
public void registerKeyListener(IKeyListener listener) {
KeyEventHandler.getInstance().registerListener(listener);
}
@OnlyIn(Dist.CLIENT)
public boolean isKeyPressed(KeyMapping key) {
return this.isKeyPressed(key.getKey().getValue());
}
@OnlyIn(Dist.CLIENT)
public boolean isKeyPressed(int key) {
return KeyEventHandler.getInstance().isKeyPressed(key);
}
@OnlyIn(Dist.CLIENT)
public boolean isKeyRepeated(int key) {
return KeyEventHandler.getInstance().isKeyRepeated(key);
}
@OnlyIn(Dist.CLIENT)
public int getKeyHoldDownTime(int key) {
return KeyEventHandler.getInstance().getKeyHoldDownTime(key);
}
@OnlyIn(Dist.CLIENT)
public int getKeyModifier(int key) {
return KeyEventHandler.getInstance().getKeyModifier(key);
}
@Override
@OnlyIn(Dist.CLIENT)
public List<Object> getClientEventHandlers() {
return ImmutableList.of(KeyEventHandler.getInstance());
}
}
|
package com.jaamsim.input;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;
import com.jaamsim.input.Input.ParseContext;
import com.jaamsim.ui.ExceptionBox;
import com.jaamsim.ui.FrameBox;
import com.jaamsim.ui.LogBox;
import com.sandwell.JavaSimulation.Entity;
import com.sandwell.JavaSimulation.ErrorException;
import com.sandwell.JavaSimulation.FileEntity;
import com.sandwell.JavaSimulation.Group;
import com.sandwell.JavaSimulation.InputErrorException;
import com.sandwell.JavaSimulation.ObjectType;
import com.sandwell.JavaSimulation.Simulation;
import com.sandwell.JavaSimulation3D.GUIFrame;
public class InputAgent {
private static final String recordEditsMarker = "RecordEdits";
private static int numErrors = 0;
private static int numWarnings = 0;
private static FileEntity logFile;
private static double lastTimeForTrace;
private static File configFile; // present configuration file
private static boolean batchRun;
private static boolean sessionEdited; // TRUE if any inputs have been changed after loading a configuration file
private static boolean recordEditsFound; // TRUE if the "RecordEdits" marker is found in the configuration file
private static boolean recordEdits; // TRUE if input changes are to be marked as edited.
private static final String INP_ERR_DEFINEUSED = "The name: %s has already been used and is a %s";
private static File reportDir;
static {
recordEditsFound = false;
sessionEdited = false;
batchRun = false;
configFile = null;
reportDir = null;
lastTimeForTrace = -1.0d;
}
public static void clear() {
logFile = null;
numErrors = 0;
numWarnings = 0;
recordEditsFound = false;
sessionEdited = false;
configFile = null;
reportDir = null;
lastTimeForTrace = -1.0d;
setReportDirectory(null);
}
private static String getReportDirectory() {
if (reportDir != null)
return reportDir.getPath() + File.separator;
if (configFile != null)
return configFile.getParentFile().getPath() + File.separator;
return null;
}
public static String getReportFileName(String name) {
return getReportDirectory() + name;
}
public static void setReportDirectory(File dir) {
reportDir = dir;
}
public static void prepareReportDirectory() {
if (reportDir != null) reportDir.mkdirs();
}
/**
* Sets the present configuration file.
*
* @param file - the present configuration file.
*/
public static void setConfigFile(File file) {
configFile = file;
}
/**
* Returns the present configuration file.
* <p>
* Null is returned if no configuration file has been loaded or saved yet.
* <p>
* @return the present configuration file.
*/
public static File getConfigFile() {
return configFile;
}
/**
* Returns the name of the simulation run.
* <p>
* For example, if the configuration file name is "case1.cfg", then the
* run name is "case1".
* <p>
* @return the name of simulation run.
*/
public static String getRunName() {
if( InputAgent.getConfigFile() == null )
return "";
String name = InputAgent.getConfigFile().getName();
int index = name.lastIndexOf( "." );
if( index == -1 )
return name;
return name.substring( 0, index );
}
/**
* Specifies whether a RecordEdits marker was found in the present configuration file.
*
* @param bool - TRUE if a RecordEdits marker was found.
*/
public static void setRecordEditsFound(boolean bool) {
recordEditsFound = bool;
}
/**
* Indicates whether a RecordEdits marker was found in the present configuration file.
*
* @return - TRUE if a RecordEdits marker was found.
*/
public static boolean getRecordEditsFound() {
return recordEditsFound;
}
/**
* Returns the "RecordEdits" mode for the InputAgent.
* <p>
* When RecordEdits is TRUE, any model inputs that are changed and any objects that
* are defined are marked as "edited". When FALSE, model inputs and object
* definitions are marked as "unedited".
* <p>
* RecordEdits mode is used to determine the way JaamSim saves a configuration file
* through the graphical user interface. Object definitions and model inputs
* that are marked as unedited will be copied exactly as they appear in the original
* configuration file that was first loaded. Object definitions and model inputs
* that are marked as edited will be generated automatically by the program.
*
* @return the RecordEdits mode for the InputAgent.
*/
public static boolean recordEdits() {
return recordEdits;
}
/**
* Sets the "RecordEdits" mode for the InputAgent.
* <p>
* When RecordEdits is TRUE, any model inputs that are changed and any objects that
* are defined are marked as "edited". When FALSE, model inputs and object
* definitions are marked as "unedited".
* <p>
* RecordEdits mode is used to determine the way JaamSim saves a configuration file
* through the graphical user interface. Object definitions and model inputs
* that are marked as unedited will be copied exactly as they appear in the original
* configuration file that was first loaded. Object definitions and model inputs
* that are marked as edited will be generated automatically by the program.
*
* @param b - boolean value for the RecordEdits mode
*/
public static void setRecordEdits(boolean b) {
recordEdits = b;
}
public static boolean isSessionEdited() {
return sessionEdited;
}
public static void setBatch(boolean batch) {
batchRun = batch;
}
public static boolean getBatch() {
return batchRun;
}
private static int getBraceDepth(ArrayList<String> tokens, int startingBraceDepth, int startingIndex) {
int braceDepth = startingBraceDepth;
for (int i = startingIndex; i < tokens.size(); i++) {
String token = tokens.get(i);
if (token.equals("{"))
braceDepth++;
if (token.equals("}"))
braceDepth
if (braceDepth < 0) {
InputAgent.logBadInput(tokens, "Extra closing braces found");
tokens.clear();
}
if (braceDepth > 3) {
InputAgent.logBadInput(tokens, "Maximum brace depth (3) exceeded");
tokens.clear();
}
}
return braceDepth;
}
private static URI resRoot;
private static URI resPath;
private static final String res = "/resources/";
static {
try {
// locate the resource folder, and create
resRoot = InputAgent.class.getResource(res).toURI();
}
catch (URISyntaxException e) {}
resPath = URI.create(resRoot.toString());
}
private static void rethrowWrapped(Exception ex) {
StringBuilder causedStack = new StringBuilder();
for (StackTraceElement elm : ex.getStackTrace())
causedStack.append(elm.toString()).append("\n");
throw new InputErrorException("Caught exception: %s", ex.getMessage() + "\n" + causedStack.toString());
}
public static final void readResource(String res) {
if (res == null)
return;
try {
readStream(resRoot.toString(), resPath, res);
GUIFrame.instance().setProgressText(null);
}
catch (URISyntaxException ex) {
rethrowWrapped(ex);
}
}
public static final boolean readStream(String root, URI path, String file) throws URISyntaxException {
String shortName = file.substring(file.lastIndexOf('/') + 1, file.length());
GUIFrame.instance().setProgressText(shortName);
URI resolved = getFileURI(path, file, root);
URL url = null;
try {
url = resolved.normalize().toURL();
}
catch (MalformedURLException e) {
rethrowWrapped(e);
}
if (url == null) {
InputAgent.logWarning("Unable to resolve path %s%s - %s", root, path.toString(), file);
return false;
}
BufferedReader buf = null;
try {
InputStream in = url.openStream();
buf = new BufferedReader(new InputStreamReader(in));
} catch (IOException e) {
InputAgent.logWarning("Could not read from %s", url.toString());
return false;
}
try {
ArrayList<String> record = new ArrayList<String>();
int braceDepth = 0;
Input.ParseContext pc = new Input.ParseContext();
pc.jail = root;
pc.context = resolved;
while (true) {
String line = buf.readLine();
// end of file, stop reading
if (line == null)
break;
int previousRecordSize = record.size();
Parser.tokenize(record, line, true);
braceDepth = InputAgent.getBraceDepth(record, braceDepth, previousRecordSize);
if( braceDepth != 0 )
continue;
if (record.size() == 0)
continue;
InputAgent.echoInputRecord(record);
if ("DEFINE".equalsIgnoreCase(record.get(0))) {
InputAgent.processDefineRecord(record);
record.clear();
continue;
}
if ("INCLUDE".equalsIgnoreCase(record.get(0))) {
try {
InputAgent.processIncludeRecord(pc, record);
}
catch (URISyntaxException ex) {
rethrowWrapped(ex);
}
record.clear();
continue;
}
if ("RECORDEDITS".equalsIgnoreCase(record.get(0))) {
InputAgent.setRecordEditsFound(true);
InputAgent.setRecordEdits(true);
record.clear();
continue;
}
// Otherwise assume it is a Keyword record
InputAgent.processKeywordRecord(record, pc);
record.clear();
}
// Leftover Input at end of file
if (record.size() > 0)
InputAgent.logBadInput(record, "Leftover input at end of file");
buf.close();
}
catch (IOException e) {
// Make best effort to ensure it closes
try { buf.close(); } catch (IOException e2) {}
}
return true;
}
private static void processIncludeRecord(ParseContext pc, ArrayList<String> record) throws URISyntaxException {
if (record.size() != 2) {
InputAgent.logError("Bad Include record, should be: Include <File>");
return;
}
InputAgent.readStream(pc.jail, pc.context, record.get(1).replaceAll("\\\\", "/"));
}
private static void processDefineRecord(ArrayList<String> record) {
if (record.size() < 5 ||
!record.get(2).equals("{") ||
!record.get(record.size() - 1).equals("}")) {
InputAgent.logError("Bad Define record, should be: Define <Type> { <names>... }");
return;
}
Class<? extends Entity> proto = null;
try {
if( record.get( 1 ).equalsIgnoreCase( "ObjectType" ) ) {
proto = ObjectType.class;
}
else {
proto = Input.parseEntityType(record.get(1));
}
}
catch (InputErrorException e) {
InputAgent.logError("%s", e.getMessage());
return;
}
// Loop over all the new Entity names
for (int i = 3; i < record.size() - 1; i++) {
InputAgent.defineEntity(proto, record.get(i), InputAgent.recordEdits());
}
}
public static <T extends Entity> T defineEntityWithUniqueName(Class<T> proto, String key, boolean addedEntity) {
return InputAgent.defineEntityWithUniqueName(proto, key, "-", addedEntity);
}
/**
* Like defineEntity(), but will generate a unique name if a name collision exists
* @param proto
* @param key
* @param sep
* @param addedEntity
* @return
*/
public static <T extends Entity> T defineEntityWithUniqueName(Class<T> proto, String key, String sep, boolean addedEntity) {
// Has the provided name been used already?
if (Entity.getNamedEntity(key) == null) {
return defineEntity(proto, key, addedEntity);
}
// Try the provided name plus "1", "2", etc. until an unused name is found
int entityNum = 1;
while(true) {
String name = String.format("%s%s%d", key, sep, entityNum);
if (Entity.getNamedEntity(name) == null) {
return defineEntity(proto, name, addedEntity);
}
entityNum++;
}
}
/**
* if addedEntity is true then this is an entity defined
* by user interaction or after added record flag is found;
* otherwise, it is from an input file define statement
* before the model is configured
* @param proto
* @param key
* @param addedEntity
*/
public static <T extends Entity> T defineEntity(Class<T> proto, String key, boolean addedEntity) {
Entity existingEnt = Input.tryParseEntity(key, Entity.class);
if (existingEnt != null) {
InputAgent.logError(INP_ERR_DEFINEUSED, key, existingEnt.getClass().getSimpleName());
return null;
}
if (key.contains(" ") || key.contains("\t") || key.contains("{") || key.contains("}")) {
InputAgent.logError("Entity names cannot contain spaces, tabs, { or }: %s", key);
return null;
}
T ent = null;
try {
ent = proto.newInstance();
if (addedEntity) {
ent.setFlag(Entity.FLAG_ADDED);
sessionEdited = true;
}
}
catch (InstantiationException e) {}
catch (IllegalAccessException e) {}
finally {
if (ent == null) {
InputAgent.logError("Could not create new Entity: %s", key);
return null;
}
}
ent.setInputName(key);
return ent;
}
public static void processKeywordRecord(ArrayList<String> record, Input.ParseContext context) {
Entity ent = Input.tryParseEntity(record.get(0), Entity.class);
if (ent == null) {
InputAgent.logError("Could not find Entity: %s", record.get(0));
return;
}
// Validate the tokens have the Entity Keyword { Args... } Keyword { Args... }
ArrayList<KeywordIndex> words = InputAgent.getKeywords(record, context);
for (KeywordIndex keyword : words) {
try {
InputAgent.processKeyword(ent, keyword);
}
catch (Throwable e) {
InputAgent.logInpError("Entity: %s, Keyword: %s - %s", ent.getInputName(), keyword.keyword, e.getMessage());
}
}
}
private static ArrayList<KeywordIndex> getKeywords(ArrayList<String> input, ParseContext context) {
ArrayList<KeywordIndex> ret = new ArrayList<KeywordIndex>();
int braceDepth = 0;
int keyWordIdx = 1;
for (int i = 1; i < input.size(); i++) {
String tok = input.get(i);
if ("{".equals(tok)) {
braceDepth++;
continue;
}
if ("}".equals(tok)) {
braceDepth
if (braceDepth == 0) {
// validate keyword form
String keyword = input.get(keyWordIdx);
if (keyword.equals("{") || keyword.equals("}") || !input.get(keyWordIdx + 1).equals("{"))
throw new InputErrorException("The input for a keyword must be enclosed by braces. Should be <keyword> { <args> }");
ret.add(new KeywordIndex(input, keyword, keyWordIdx + 2, i, context));
keyWordIdx = i + 1;
continue;
}
}
}
if (keyWordIdx != input.size())
throw new InputErrorException("The input for a keyword must be enclosed by braces. Should be <keyword> { <args> }");
return ret;
}
public static void doError(Throwable e) {
if (!batchRun)
return;
LogBox.logLine("An error occurred in the simulation environment. Please check inputs for an error:");
LogBox.logLine(e.toString());
GUIFrame.shutdown(1);
}
// Load the run file
public static void loadConfigurationFile( File file) throws URISyntaxException {
String inputTraceFileName = InputAgent.getRunName() + ".log";
// Initializing the tracing for the model
try {
System.out.println( "Creating trace file" );
URI confURI = file.toURI();
URI logURI = confURI.resolve(new URI(null, inputTraceFileName, null)); // The new URI here effectively escapes the file name
// Set and open the input trace file name
logFile = new FileEntity( logURI.getPath());
}
catch( Exception e ) {
InputAgent.logWarning("Could not create trace file");
}
URI dirURI = file.getParentFile().toURI();
InputAgent.readStream("", dirURI, file.getName());
GUIFrame.instance().setProgressText(null);
GUIFrame.instance().setProgress(0);
// At this point configuration file is loaded
// The session is not considered to be edited after loading a configuration file
sessionEdited = false;
// Save and close the input trace file
if (logFile != null) {
if (InputAgent.numWarnings == 0 && InputAgent.numErrors == 0) {
logFile.close();
logFile.delete();
logFile = new FileEntity( inputTraceFileName);
}
}
// Check for found errors
if( InputAgent.numErrors > 0 )
throw new InputErrorException("%d input errors and %d warnings found, check %s", InputAgent.numErrors, InputAgent.numWarnings, inputTraceFileName);
if (Simulation.getPrintInputReport())
InputAgent.printInputFileKeywords();
}
public static final void apply(Entity ent, KeywordIndex kw) {
Input<?> in = ent.getInput(kw.keyword);
if (in == null) {
InputAgent.logWarning("Keyword %s could not be found for Entity %s.", kw.keyword, ent.getInputName());
return;
}
InputAgent.apply(ent, in, kw);
FrameBox.valueUpdate();
}
public static final void apply(Entity ent, Input<?> in, KeywordIndex kw) {
in.parse(kw);
// Only mark the keyword edited if we have finished initial configuration
if ( InputAgent.recordEdits() )
in.setEdited(true);
ent.updateForInput(in);
if(ent.testFlag(Entity.FLAG_GENERATED))
return;
if(in.isEdited()) {
ent.setFlag(Entity.FLAG_EDITED);
sessionEdited = true;
}
if (kw.numArgs() < 1000)
in.setValueString(kw.argString());
}
public static void processKeyword(Entity entity, KeywordIndex key) {
if (entity.testFlag(Entity.FLAG_LOCKED))
throw new InputErrorException("Entity: %s is locked and cannot be modified", entity.getName());
Input<?> input = entity.getInput( key.keyword );
if (input != null) {
InputAgent.apply(entity, input, key);
FrameBox.valueUpdate();
return;
}
if (!(entity instanceof Group))
throw new InputErrorException("Not a valid keyword");
Group grp = (Group)entity;
grp.saveGroupKeyword(key);
// Store the keyword data for use in the edit table
for( int i = 0; i < grp.getList().size(); i++ ) {
Entity ent = grp.getList().get( i );
InputAgent.apply(ent, key);
}
}
public static void load(GUIFrame gui) {
LogBox.logLine("Loading...");
// Create a file chooser
final JFileChooser chooser = new JFileChooser(InputAgent.getConfigFile());
// Set the file extension filters
chooser.setAcceptAllFileFilterUsed(true);
FileNameExtensionFilter cfgFilter =
new FileNameExtensionFilter("JaamSim Configuration File (*.cfg)", "CFG");
chooser.addChoosableFileFilter(cfgFilter);
chooser.setFileFilter(cfgFilter);
// Show the file chooser and wait for selection
int returnVal = chooser.showOpenDialog(gui);
// Load the selected file
if (returnVal == JFileChooser.APPROVE_OPTION) {
File temp = chooser.getSelectedFile();
InputAgent.setLoadFile(gui, temp);
}
}
public static void save(GUIFrame gui) {
LogBox.logLine("Saving...");
if( InputAgent.getConfigFile() != null ) {
setSaveFile(gui, InputAgent.getConfigFile().getPath() );
}
else {
saveAs( gui );
}
}
public static void saveAs(GUIFrame gui) {
LogBox.logLine("Save As...");
// Create a file chooser
final JFileChooser chooser = new JFileChooser(InputAgent.getConfigFile());
// Set the file extension filters
chooser.setAcceptAllFileFilterUsed(true);
FileNameExtensionFilter cfgFilter =
new FileNameExtensionFilter("JaamSim Configuration File (*.cfg)", "CFG");
chooser.addChoosableFileFilter(cfgFilter);
chooser.setFileFilter(cfgFilter);
// Show the file chooser and wait for selection
int returnVal = chooser.showSaveDialog(gui);
// Load the selected file
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
String filePath = file.getPath();
// Add the file extension ".cfg" if needed
filePath = filePath.trim();
if (filePath.indexOf(".") == -1)
filePath = filePath.concat(".cfg");
// Confirm overwrite if file already exists
File temp = new File(filePath);
if (temp.exists()) {
int userOption = JOptionPane.showConfirmDialog( null,
file.getName() + " already exists.\n" +
"Do you wish to replace it?", "Confirm Save As",
JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE );
if (userOption == JOptionPane.NO_OPTION) {
return;
}
}
// Save the configuration file
InputAgent.setSaveFile(gui, filePath);
}
}
public static void configure(GUIFrame gui, File file) {
try {
gui.clear();
InputAgent.setConfigFile(file);
gui.updateForSimulationState(GUIFrame.SIM_STATE_UNCONFIGURED);
try {
InputAgent.loadConfigurationFile(file);
}
catch( InputErrorException iee ) {
if (!batchRun)
ExceptionBox.instance().setErrorBox(iee.getMessage());
else
LogBox.logLine( iee.getMessage() );
}
LogBox.logLine("Configuration File Loaded");
// show the present state in the user interface
gui.setTitle( Simulation.getModelName() + " - " + InputAgent.getRunName() );
gui.updateForSimulationState(GUIFrame.SIM_STATE_CONFIGURED);
gui.enableSave(InputAgent.getRecordEditsFound());
}
catch( Throwable t ) {
ExceptionBox.instance().setError(t);
}
}
/**
* Loads the configuration file.
* <p>
* @param gui - the Control Panel.
* @param file - the configuration file to be loaded.
*/
private static void setLoadFile(final GUIFrame gui, File file) {
final File chosenfile = file;
new Thread(new Runnable() {
@Override
public void run() {
InputAgent.setRecordEdits(false);
InputAgent.configure(gui, chosenfile);
InputAgent.setRecordEdits(true);
GUIFrame.displayWindows();
FrameBox.valueUpdate();
}
}).start();
}
/**
* Saves the configuration file.
* @param gui = Control Panel window for JaamSim
* @param fileName = absolute file path and file name for the file to be saved
*/
private static void setSaveFile(GUIFrame gui, String fileName) {
// Set root directory
File temp = new File(fileName);
// Save the configuration file
InputAgent.printNewConfigurationFileWithName( fileName );
sessionEdited = false;
InputAgent.setConfigFile(temp);
// Set the title bar to match the new run name
gui.setTitle( Simulation.getModelName() + " - " + InputAgent.getRunName() );
}
/*
* write input file keywords and values
*
* input file format:
* Define Group { <Group names> }
* Define <Object> { <Object names> }
*
* <Object name> <Keyword> { < values > }
*
*/
public static void printInputFileKeywords() {
// Create report file for the inputs
String inputReportFileName = InputAgent.getReportFileName(InputAgent.getRunName() + ".inp");
FileEntity inputReportFile = new FileEntity( inputReportFileName);
inputReportFile.flush();
// Loop through the entity classes printing Define statements
for (ObjectType type : ObjectType.getAll()) {
Class<? extends Entity> each = type.getJavaClass();
// Loop through the instances for this entity class
int count = 0;
for (Entity ent : Entity.getInstanceIterator(each)) {
boolean hasinput = false;
for (Input<?> in : ent.getEditableInputs()) {
// If the keyword has been used, then add a record to the report
if (in.getValueString().length() != 0) {
hasinput = true;
count++;
break;
}
}
if (hasinput) {
String entityName = ent.getInputName();
if ((count - 1) % 5 == 0) {
inputReportFile.putString("Define");
inputReportFile.putTab();
inputReportFile.putString(type.getInputName());
inputReportFile.putTab();
inputReportFile.putString("{ " + entityName);
inputReportFile.putTab();
}
else if ((count - 1) % 5 == 4) {
inputReportFile.putString(entityName + " }");
inputReportFile.newLine();
}
else {
inputReportFile.putString(entityName);
inputReportFile.putTab();
}
}
}
if (!Entity.getInstanceIterator(each).hasNext()) {
if (count % 5 != 0) {
inputReportFile.putString(" }");
inputReportFile.newLine();
}
inputReportFile.newLine();
}
}
for (ObjectType type : ObjectType.getAll()) {
Class<? extends Entity> each = type.getJavaClass();
// Get the list of instances for this entity class
// sort the list alphabetically
ArrayList<? extends Entity> cloneList = Entity.getInstancesOf(each);
// Print the entity class name to the report (in the form of a comment)
if (cloneList.size() > 0) {
inputReportFile.putString("\" " + each.getSimpleName() + " \"");
inputReportFile.newLine();
inputReportFile.newLine(); // blank line below the class name heading
}
Collections.sort(cloneList, new Comparator<Entity>() {
@Override
public int compare(Entity a, Entity b) {
return a.getInputName().compareTo(b.getInputName());
}
});
// Loop through the instances for this entity class
for (int j = 0; j < cloneList.size(); j++) {
// Make sure the clone is an instance of the class (and not an instance of a subclass)
if (cloneList.get(j).getClass() == each) {
Entity ent = cloneList.get(j);
String entityName = ent.getInputName();
boolean hasinput = false;
// Loop through the editable keywords for this instance
for (Input<?> in : ent.getEditableInputs()) {
// If the keyword has been used, then add a record to the report
if (in.getValueString().length() != 0) {
if (!in.getCategory().contains("Graphics")) {
hasinput = true;
inputReportFile.putTab();
inputReportFile.putString(entityName);
inputReportFile.putTab();
inputReportFile.putString(in.getKeyword());
inputReportFile.putTab();
if (in.getValueString().lastIndexOf("{") > 10) {
String[] item1Array;
item1Array = in.getValueString().trim().split(" }");
inputReportFile.putString("{ " + item1Array[0] + " }");
for (int l = 1; l < (item1Array.length); l++) {
inputReportFile.newLine();
inputReportFile.putTabs(5);
inputReportFile.putString(item1Array[l] + " } ");
}
inputReportFile.putString(" }");
}
else {
inputReportFile.putString("{ " + in.getValueString() + " }");
}
inputReportFile.newLine();
}
}
}
// Put a blank line after each instance
if (hasinput) {
inputReportFile.newLine();
}
}
}
}
// Close out the report
inputReportFile.flush();
inputReportFile.close();
}
public static void closeLogFile() {
if (logFile == null)
return;
logFile.flush();
logFile.close();
if (numErrors ==0 && numWarnings == 0) {
logFile.delete();
}
logFile = null;
}
private static final String errPrefix = "*** ERROR *** %s%n";
private static final String inpErrPrefix = "*** INPUT ERROR *** %s%n";
private static final String wrnPrefix = "***WARNING*** %s%n";
public static int numErrors() {
return numErrors;
}
public static int numWarnings() {
return numWarnings;
}
private static void echoInputRecord(ArrayList<String> tokens) {
if (logFile == null)
return;
for (int i = 0; i < tokens.size(); i++) {
if (i > 0)
logFile.write(" ");
String tok = tokens.get(i);
logFile.write(tok);
if (tok.startsWith("\""))
logFile.newLine();
}
logFile.flush();
}
private static void logBadInput(ArrayList<String> tokens, String msg) {
InputAgent.echoInputRecord(tokens);
InputAgent.logError("%s", msg);
}
public static void logMessage(String fmt, Object... args) {
String msg = String.format(fmt, args);
System.out.println(msg);
LogBox.logLine(msg);
if (logFile == null)
return;
logFile.write(msg);
logFile.newLine();
logFile.flush();
}
public static void trace(int indent, Entity ent, String meth, String... text) {
// Create an indent string to space the lines
StringBuilder ind = new StringBuilder("");
for (int i = 0; i < indent; i++)
ind.append(" ");
String spacer = ind.toString();
// Print a TIME header every time time has advanced
double traceTime = ent.getCurrentTime();
if (lastTimeForTrace != traceTime) {
System.out.format(" \nTIME = %.5f\n", traceTime);
lastTimeForTrace = traceTime;
}
// Output the traces line(s)
System.out.format("%s%s %s\n", spacer, ent.getName(), meth);
for (String line : text) {
System.out.format("%s%s\n", spacer, line);
}
System.out.flush();
}
public static void logWarning(String fmt, Object... args) {
numWarnings++;
String msg = String.format(fmt, args);
InputAgent.logMessage(wrnPrefix, msg);
}
public static void logError(String fmt, Object... args) {
numErrors++;
String msg = String.format(fmt, args);
InputAgent.logMessage(errPrefix, msg);
}
public static void logInpError(String fmt, Object... args) {
numErrors++;
String msg = String.format(fmt, args);
InputAgent.logMessage(inpErrPrefix, msg);
}
/**
* Prepares the keyword and input value for processing.
*
* @param ent - the entity whose keyword and value have been entered.
* @param in - the input object for the keyword.
* @param value - the input value String for the keyword.
*/
public static void processEntity_Keyword_Value(Entity ent, Input<?> in, String value){
processEntity_Keyword_Value(ent, in.getKeyword(), value);
}
/**
* Prepares the keyword and input value for processing.
*
* @param ent - the entity whose keyword and value has been entered.
* @param keyword - the keyword.
* @param value - the input value String for the keyword.
*/
public static void processEntity_Keyword_Value(Entity ent, String keyword, String value){
// Keyword
ArrayList<String> tokens = new ArrayList<String>();
// Value
if (!value.equals(Input.getNoValue()))
Parser.tokenize(tokens, value, true);
// Parse the keyword inputs
KeywordIndex kw = new KeywordIndex(tokens, keyword, 0, tokens.size(), null);
InputAgent.processKeyword(ent, kw);
}
/**
* Prints the present state of the model to a new configuration file.
*
* @param fileName - the full path and file name for the new configuration file.
*/
public static void printNewConfigurationFileWithName( String fileName ) {
// 1) WRITE LINES FROM THE ORIGINAL CONFIGURATION FILE
// Copy the original configuration file up to the "RecordEdits" marker (if present)
// Temporary storage for the copied lines is needed in case the original file is to be overwritten
ArrayList<String> preAddedRecordLines = new ArrayList<String>();
if( InputAgent.getConfigFile() != null ) {
try {
BufferedReader in = new BufferedReader( new FileReader(InputAgent.getConfigFile()) );
String line;
while ( ( line = in.readLine() ) != null ) {
preAddedRecordLines.add( line );
if ( line.startsWith( recordEditsMarker ) ) {
break;
}
}
in.close();
}
catch ( Exception e ) {
throw new ErrorException( e );
}
}
// Create the new configuration file and copy the saved lines
FileEntity file = new FileEntity( fileName);
for( int i=0; i < preAddedRecordLines.size(); i++ ) {
file.format("%s%n", preAddedRecordLines.get( i ));
}
// If not already present, insert the "RecordEdits" marker at the end of the original configuration file
if( ! InputAgent.getRecordEditsFound() ) {
file.format("%n%s%n", recordEditsMarker);
InputAgent.setRecordEditsFound(true);
}
// 2) WRITE THE DEFINITION STATEMENTS FOR NEW OBJECTS
// Determine all the new classes that were created
ArrayList<Class<? extends Entity>> newClasses = new ArrayList<Class<? extends Entity>>();
for (Entity ent : Entity.getAll()) {
if (!ent.testFlag(Entity.FLAG_ADDED) || ent.testFlag(Entity.FLAG_GENERATED))
continue;
if (!newClasses.contains(ent.getClass()))
newClasses.add(ent.getClass());
}
// Add a blank line before the first object definition
if( !newClasses.isEmpty() )
file.format("%n");
// Identify the object types for which new instances were defined
for( Class<? extends Entity> newClass : newClasses ) {
for (ObjectType o : ObjectType.getAll()) {
if (o.getJavaClass() == newClass) {
// Print the first part of the "Define" statement for this object type
file.format("Define %s {", o.getInputName());
break;
}
}
// Print the new instances that were defined
for (Entity ent : Entity.getAll()) {
if (!ent.testFlag(Entity.FLAG_ADDED) || ent.testFlag(Entity.FLAG_GENERATED))
continue;
if (ent.getClass() == newClass)
file.format(" %s ", ent.getInputName());
}
// Close the define statement
file.format("}%n");
}
// 3) WRITE THE ATTRIBUTE DEFINITIONS
boolean blankLinePrinted = false;
for (Entity ent : Entity.getAll()) {
if (ent.testFlag(Entity.FLAG_EDITED) && !ent.testFlag(Entity.FLAG_GENERATED)) {
for (Input<?> in : ent.getEditableInputs()) {
if (in.isEdited() && in.getKeyword().equals("AttributeDefinitionList")) {
if (!blankLinePrinted) {
file.format("%n");
blankLinePrinted = true;
}
writeInputOnFile_ForEntity(in, file, ent);
}
}
}
}
// 4) WRITE THE INPUTS FOR KEYWORDS THAT WERE EDITED
// Identify the entities whose inputs were edited
for (Entity ent : Entity.getAll()) {
if (ent.testFlag(Entity.FLAG_EDITED) && !ent.testFlag(Entity.FLAG_GENERATED)) {
file.format("%n");
writeInputsOnFile_ForEntity( file, ent );
}
}
// Close the new configuration file
file.flush();
file.close();
}
/**
* Prints the configuration file entries for Entity ent to the FileEntity file.
*
* @param file - the target configuration file.
* @param ent - the entity whose configuration file entries are to be written.
*/
static void writeInputsOnFile_ForEntity( FileEntity file, Entity ent ) {
// Print keywords for this entity that are in the "Key Inputs" category
for (Input<?> in : ent.getEditableInputs()) {
if (in.isEdited() && in.getCategory().equals("Key Inputs")
&& !in.getKeyword().equals("AttributeDefinitionList")) {
writeInputOnFile_ForEntity(in, file, ent);
}
}
// Print keywords for this entity that are NOT in the "Key Inputs" category
for (Input<?> in : ent.getEditableInputs()) {
if (in.isEdited() && !in.getCategory().equals("Key Inputs")) {
writeInputOnFile_ForEntity(in, file, ent);
}
}
}
static void writeInputOnFile_ForEntity(Input<?> in, FileEntity file, Entity ent) {
file.format("%s %s { %s }%n",
ent.getInputName(), in.getKeyword(), in.getValueString());
}
/**
* Returns the relative file path for the specified URI.
* <p>
* The path can start from either the folder containing the present
* configuration file or from the resources folder.
* <p>
* @param uri - the URI to be relativized.
* @return the relative file path.
*/
static public String getRelativeFilePath(URI uri) {
// Relativize the file path against the resources folder
String resString = resRoot.toString();
String inputString = uri.toString();
if (inputString.startsWith(resString)) {
return String.format("'<res>/%s'", inputString.substring(resString.length()));
}
// Relativize the file path against the configuration file
try {
URI configDirURI = InputAgent.getConfigFile().getParentFile().toURI();
return String.format("'%s'", configDirURI.relativize(uri).getPath());
}
catch (Exception ex) {
return String.format("'%s'", uri.getPath());
}
}
/**
* Loads the default configuration file.
*/
public static void loadDefault() {
// Read the default configuration file
InputAgent.readResource("inputs/default.cfg");
// A RecordEdits marker in the default configuration must be ignored
InputAgent.setRecordEditsFound(false);
// Set the model state to unedited
sessionEdited = false;
}
/**
* Split an input (list of strings) down to a single level of nested braces, this may then be called again for
* further nesting.
* @param input
* @return
*/
public static ArrayList<ArrayList<String>> splitForNestedBraces(List<String> input) {
ArrayList<ArrayList<String>> inputs = new ArrayList<ArrayList<String>>();
int braceDepth = 0;
ArrayList<String> currentLine = null;
for (int i = 0; i < input.size(); i++) {
if (currentLine == null)
currentLine = new ArrayList<String>();
currentLine.add(input.get(i));
if (input.get(i).equals("{")) {
braceDepth++;
continue;
}
if (input.get(i).equals("}")) {
braceDepth
if (braceDepth == 0) {
inputs.add(currentLine);
currentLine = null;
continue;
}
}
}
return inputs;
}
/**
* Converts a file path String to a URI.
* <p>
* The specified file path can be either relative or absolute. In the case
* of a relative file path, a 'context' folder must be specified. A context
* of null indicates an absolute file path.
* <p>
* To avoid bad input accessing an inappropriate file, a 'jail' folder can
* be specified. The URI to be returned must include the jail folder for it
* to be valid.
* <p>
* @param context - full file path for the folder that is the reference for relative file paths.
* @param filePath - string to be resolved to a URI.
* @param jailPrefix - file path to a base folder from which a relative cannot escape.
* @return the URI corresponding to the context and filePath.
*/
public static URI getFileURI(URI context, String filePath, String jailPrefix) throws URISyntaxException {
// Replace all backslashes with slashes
String path = filePath.replaceAll("\\\\", "/");
int colon = path.indexOf(':');
int openBrace = path.indexOf('<');
int closeBrace = path.indexOf('>');
int firstSlash = path.indexOf('/');
// Add a leading slash if needed to convert from Windows format (e.g. from "C:" to "/C:")
if (colon == 1)
path = String.format("/%s", path);
// 1) File path starts with a tagged folder, using the syntax "<tagName>/"
URI ret = null;
if (openBrace == 0 && closeBrace != -1 && firstSlash == closeBrace + 1) {
String specPath = path.substring(openBrace + 1, closeBrace);
// Resources folder in the Jar file
if (specPath.equals("res")) {
ret = new URI(resRoot.getScheme(), resRoot.getSchemeSpecificPart() + path.substring(closeBrace+2), null).normalize();
}
}
// 2) Normal file path
else {
URI pathURI = new URI(null, path, null).normalize();
if (context != null) {
if (context.isOpaque()) {
// Things are going to get messy in here
URI schemeless = new URI(null, context.getSchemeSpecificPart(), null);
URI resolved = schemeless.resolve(pathURI).normalize();
// Note: we are using the one argument constructor here because the 'resolved' URI is already encoded
// and we do not want to double-encode (and schemes should never need encoding, I hope)
ret = new URI(context.getScheme() + ":" + resolved.toString());
} else {
ret = context.resolve(pathURI).normalize();
}
} else {
// We have no context, so append a 'file' scheme if necessary
if (pathURI.getScheme() == null) {
ret = new URI("file", pathURI.getPath(), null);
} else {
ret = pathURI;
}
}
}
// Check that the file path includes the jail folder
if (jailPrefix != null && ret.toString().indexOf(jailPrefix) != 0) {
LogBox.format("Failed jail test: %s in jail: %s context: %s\n", ret.toString(), jailPrefix, context.toString());
LogBox.getInstance().setVisible(true);
return null; // This resolved URI is not in our jail
}
return ret;
}
/**
* Determines whether or not a file exists.
* <p>
* @param filePath - URI for the file to be tested.
* @return true if the file exists, false if it does not.
*/
public static boolean fileExists(URI filePath) {
try {
InputStream in = filePath.toURL().openStream();
in.close();
return true;
}
catch (MalformedURLException ex) {
return false;
}
catch (IOException ex) {
return false;
}
}
}
|
package de.tum.in.www1.artemis.config.websocket;
import java.security.Principal;
import java.util.*;
import javax.annotation.PostConstruct;
import javax.validation.constraints.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.messaging.converter.MappingJackson2MessageConverter;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.WebSocketMessageBrokerStats;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurationSupport;
import org.springframework.web.socket.config.annotation.WebSocketTransportRegistration;
import org.springframework.web.socket.server.HandshakeInterceptor;
import org.springframework.web.socket.server.support.DefaultHandshakeHandler;
import org.springframework.web.socket.sockjs.transport.handler.WebSocketTransportHandler;
import com.fasterxml.jackson.databind.ObjectMapper;
import de.tum.in.www1.artemis.security.AuthoritiesConstants;
@Configuration
public class WebsocketConfiguration extends WebSocketMessageBrokerConfigurationSupport {
private final Logger log = LoggerFactory.getLogger(WebsocketConfiguration.class);
public static final String IP_ADDRESS = "IP_ADDRESS";
private final ObjectMapper objectMapper;
private TaskScheduler messageBrokerTaskScheduler;
private WebSocketMessageBrokerStats webSocketMessageBrokerStats;
private ThreadPoolTaskExecutor inboundChannelExecutor;
private ThreadPoolTaskExecutor outboundChannelExecutor;
public WebsocketConfiguration(MappingJackson2HttpMessageConverter springMvcJacksonConverter) {
this.objectMapper = springMvcJacksonConverter.getObjectMapper();
}
@PostConstruct
public void init() {
// using Autowired leads to a weird bug, because the order of the method execution is changed. This somehow prevents messages send to single clients
// later one, e.g. in the code editor. Therefore we call this method here directly to get a reference and adapt the logging period!
webSocketMessageBrokerStats = webSocketMessageBrokerStats();
webSocketMessageBrokerStats.setLoggingPeriod(5 * 1000);
}
@Override
protected void configureWebSocketTransport(WebSocketTransportRegistration registration) {
// limit these values to prevent problems with slow clients
registration.setSendTimeLimit(5 * 1000).setSendBufferSizeLimit(128 * 1024);
}
@Autowired
public void setMessageBrokerTaskScheduler(TaskScheduler taskScheduler) {
this.messageBrokerTaskScheduler = taskScheduler;
}
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic").setHeartbeatValue(new long[] { 25000, 25000 }).setTaskScheduler(messageBrokerTaskScheduler);
// increase the limit of concurrent connections (default is 1024 which is much too low)
config.setCacheLimit(10000);
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
DefaultHandshakeHandler handshakeHandler = defaultHandshakeHandler();
// NOTE: by setting a WebSocketTransportHandler we disable http poll, http stream and other exotic workarounds and only support real websocket connections.
// nowadays all modern browsers support websockets and workarounds are not necessary any more and might only lead to problems
WebSocketTransportHandler webSocketTransportHandler = new WebSocketTransportHandler(handshakeHandler);
registry.addEndpoint("/websocket/tracker").setAllowedOrigins("*").withSockJS().setTransportHandlers(webSocketTransportHandler)
.setInterceptors(httpSessionHandshakeInterceptor());
}
// TODO: allow to customize these settings via application.yml file
@Override
public ThreadPoolTaskExecutor clientOutboundChannelExecutor() {
outboundChannelExecutor = super.clientOutboundChannelExecutor();
// outboundChannelExecutor.setQueueCapacity(100 * 1000);
// a higher pool size can help when problems with slow clients occur
outboundChannelExecutor.setCorePoolSize(Runtime.getRuntime().availableProcessors() * 4);
// outboundChannelExecutor.setMaxPoolSize(Runtime.getRuntime().availableProcessors() * 8);
outboundChannelExecutor.setKeepAliveSeconds(10);
outboundChannelExecutor.setAllowCoreThreadTimeOut(true);
return outboundChannelExecutor;
}
@Override
public ThreadPoolTaskExecutor clientInboundChannelExecutor() {
inboundChannelExecutor = super.clientInboundChannelExecutor();
// inboundChannelExecutor.setQueueCapacity(100 * 1000);
// outboundChannelExecutor.setMaxPoolSize(Runtime.getRuntime().availableProcessors() * 8);
inboundChannelExecutor.setKeepAliveSeconds(10);
inboundChannelExecutor.setAllowCoreThreadTimeOut(true);
return inboundChannelExecutor;
}
@NotNull
@Override
protected MappingJackson2MessageConverter createJacksonConverter() {
// NOTE: We need to adapt the default messageConverter for WebSocket messages
// with a messageConverter that uses the same ObjectMapper that our REST endpoints use.
// This gives us consistency in how specific datatypes are serialized (e.g. timestamps)
MappingJackson2MessageConverter converter = super.createJacksonConverter();
converter.setObjectMapper(objectMapper);
return converter;
}
@Bean
public HandshakeInterceptor httpSessionHandshakeInterceptor() {
return new HandshakeInterceptor() {
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) {
if (request instanceof ServletServerHttpRequest) {
ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
attributes.put(IP_ADDRESS, servletRequest.getRemoteAddress());
}
return true;
}
@Override
public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
if (exception != null) {
log.warn("Exception occurred in WS.afterHandshake: " + exception.getMessage());
}
}
};
}
private DefaultHandshakeHandler defaultHandshakeHandler() {
return new DefaultHandshakeHandler() {
@Override
protected Principal determineUser(ServerHttpRequest request, WebSocketHandler wsHandler, Map<String, Object> attributes) {
Principal principal = request.getPrincipal();
if (principal == null) {
Collection<SimpleGrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.ANONYMOUS));
principal = new AnonymousAuthenticationToken("WebsocketConfiguration", "anonymous", authorities);
}
log.debug("determineUser: " + principal);
return principal;
}
};
}
}
|
package io.github.jython234.nectar.server.controller;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.Filters;
import io.github.jython234.nectar.server.NectarServerApplication;
import io.github.jython234.nectar.server.struct.SessionToken;
import io.jsonwebtoken.*;
import lombok.AccessLevel;
import lombok.Getter;
import org.bson.Document;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
/**
* Controller that handles sessions, including
* token requests and revokes.
*
* @author jython234
*/
@RestController
public class SessionController {
@Getter(AccessLevel.PROTECTED) private static SessionController instance;
private Map<String, SessionToken> tokens;
public SessionController() {
this.tokens = new ConcurrentHashMap<>();
instance = this;
}
@Scheduled(fixedDelay = 500) // Check for tokens every half second
public void checkTokens() {
tokens.values().forEach((SessionToken token) -> {
if((System.currentTimeMillis() - token.getTimestamp()) >= token.getExpires()) { // Check if the token has expired
// Token has expired, revoke it
NectarServerApplication.getLogger().info("Token for " + token.getUuid() + " has expired.");
tokens.remove(token.getUuid());
}
});
}
/**
* Checks a SessionToken to see if it is found
* in the issued tokens map.
* @param token The token to check.
* @return If the token has been found and verified issued.
*/
public boolean checkToken(SessionToken token) {
for(SessionToken session : tokens.values()) {
if(session.getUuid().equals(token.getUuid())
&& session.getTimestamp() == token.getTimestamp()
&& session.getExpires() == token.getExpires()) {
return true;
}
}
return false;
}
@RequestMapping(NectarServerApplication.ROOT_PATH + "/session/tokenRequest")
public ResponseEntity<String> tokenRequest(@RequestParam(value="uuid") String uuid, HttpServletRequest request) {
/*try {
Jwt jwt = Jwts.parser().setSigningKey(NectarServerApplication.getConfiguration().getClientPublicKey())
.parse(info);
} catch(MalformedJwtException e) {
NectarServerApplication.getLogger().warn("Malformed JWT from client \"" + uuid
+ "\" while processing token request."
);
return ResponseEntity.badRequest().body("JWT \"clientInfo\" is malformed!");
} catch(SignatureException e) {
NectarServerApplication.getLogger().warn("Invalid JWT signature from client \"" + uuid
+ "\" while processing token request."
);
return ResponseEntity.badRequest().body("JWT \"clientInfo\" signature is invalid!");
} catch(Exception e) {
NectarServerApplication.getLogger().error(" Failed to verify JWT from client \"" + uuid
+ "\" while processing token request."
);
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to verify JWT.");
}*/
// Verify "uuid"
// TODO: Check MongoDB database for UUID
MongoCollection<Document> clients = NectarServerApplication.getDb().getCollection("clients");
Document doc = clients.find(Filters.eq("uuid", uuid)).first();
if(doc == null) {
// We can't find this client in the database
// This means that the client is unregistered, so we drop the request
NectarServerApplication.getLogger().warn("Received token request from unregistered client "
+ request.getRemoteAddr() + " with UUID: " + uuid
);
return ResponseEntity.status(HttpStatus.FORBIDDEN).body("UUID not found in database.");
}
try {
UUID.fromString(uuid);
} catch(IllegalArgumentException e) {
// UUID is invalid
return ResponseEntity.badRequest().body("Invalid UUID!");
}
// Check if we have issued a token already for this UUID
if(this.tokens.containsKey(uuid)) {
// Token has been issued
return ResponseEntity.status(HttpStatus.FORBIDDEN).body("Token already issued for this UUID!");
}
SessionToken token = new SessionToken(uuid, System.currentTimeMillis(), 500);
this.tokens.put(uuid, token); // Insert the token into the Map
String jwt = Jwts.builder()
.setPayload(token.constructJSON().toJSONString())
.signWith(SignatureAlgorithm.ES384, NectarServerApplication.getConfiguration().getServerPrivateKey())
.compact(); // Sign and build the JWT
NectarServerApplication.getLogger().info("Issued token for new client " + request.getRemoteAddr() + " with UUID: " + uuid);
return ResponseEntity.ok(jwt); // Return the token
}
}
|
package io.github.m0pt0pmatt.spongesurvivalgames.tasks;
import io.github.m0pt0pmatt.spongesurvivalgames.BukkitSurvivalGamesPlugin;
import io.github.m0pt0pmatt.spongesurvivalgames.SurvivalGame;
import org.bukkit.GameMode;
import org.bukkit.entity.Player;
/**
* Task for resetting the players' food and health levels
*/
public class ReadyPlayerTask implements SurvivalGameTask {
@Override
public boolean execute(SurvivalGame game) {
BukkitSurvivalGamesPlugin.getPlayers(game.getPlayerUUIDs())
.forEach(player -> {
player.setGameMode(GameMode.ADVENTURE);
player.setMaxHealth(20);
player.setHealth(player.getMaxHealth());
player.setFoodLevel(20);
player.setSaturation(player.getFoodLevel());
player.setExhaustion(0);
player.getInventory().clear();
clearEquipment(player);
});
return true;
}
private void clearEquipment(Player player) {
player.getInventory().setHelmet(null);
player.getInventory().setChestplate(null);
player.getInventory().setLeggings(null);
player.getInventory().setBoots(null);
}
}
|
package com.jcabi.github;
import com.jcabi.aspects.Immutable;
import com.jcabi.aspects.Loggable;
import com.jcabi.http.Request;
import com.jcabi.http.response.RestResponse;
import java.io.IOException;
import java.net.HttpURLConnection;
import javax.json.JsonObject;
import lombok.EqualsAndHashCode;
import org.hamcrest.Matchers;
/**
* Github Assignees.
*
* @author Paul Polishchuk (ppol@ua.fm)
* @version $Id$
* @since 0.7
* @checkstyle MultipleStringLiterals (500 lines)
*/
@Immutable
@Loggable(Loggable.DEBUG)
@EqualsAndHashCode(of = { "entry", "request", "owner" })
final class RtAssignees implements Assignees {
/**
* API entry point.
*/
private final transient Request entry;
/**
* RESTful request.
*/
private final transient Request request;
/**
* Repository we're in.
*/
private final transient Repo owner;
/**
* Public ctor.
* @param repo Repo
* @param req Request
*/
RtAssignees(final Request req, final Repo repo) {
this.entry = req;
final Coordinates coords = repo.coordinates();
this.request = this.entry.uri()
.path("/repos")
.path(coords.user())
.path(coords.repo())
.path("/assignees")
.back();
this.owner = repo;
}
@Override
public Iterable<User> iterate() {
return new RtPagination<User>(
this.request,
new RtPagination.Mapping<User, JsonObject>() {
@Override
public User map(final JsonObject object) {
return new RtUser(
RtAssignees.this.owner.github(),
RtAssignees.this.entry,
object.getString("login")
);
}
}
);
}
@Override
public boolean check(final String login) throws IOException {
return this.request
.method(Request.GET)
.uri().path(login).back()
.fetch()
.as(RestResponse.class)
.assertStatus(
Matchers.isOneOf(
HttpURLConnection.HTTP_NO_CONTENT,
HttpURLConnection.HTTP_NOT_FOUND
)
).status() == HttpURLConnection.HTTP_NO_CONTENT;
}
@Override
public String toString() {
return this.request.uri().get().toString();
}
}
|
package com.mr208.UBCOres;
public class References {
public final static String MODID = "ubcores";
public final static String MODNAME = "UBC Ore Registrar";
public final static String VERSION = "1.7.10-0.2.9.2";
public final static String DEPENDENCIES = "required-after:UndergroundBiomes;" +
"after:factorization;" +
"after:Thaumcraft;" +
"after:steamcraft2;" +
"after:BiomesOPlenty;" +
"after:ThermalFoundation;" +
"after:harvestcraft;" +
"after:Steamcraft;" +
"after:Railcraft;" +
"after:Mekanism;" +
"after:BigReactors;" +
"after:farlanders;" +
"after:IC2;" +
"after:appliedenergistics2;" +
"after:magicalcrops;" +
"after:ProjRed|Exploration;" +
"after:Forestry;" +
"after:TConstruct;" +
"after:bluepower;" +
"after:ImmersiveEngineering;" +
"after:arsmagica2;" +
"after:IC2-Classic-Spmod;" +
"after:GalacticraftCore;" +
"after:Jaffas-Technic;" +
"after:TaintedMagic;" +
"after:clockworkphase;" +
"after:rftools;" +
"after:Eln;" +
"after:fossil;" +
"after:DraconicEvolution;" +
"after:Mariculture;" +
"after:deepresonance";
}
|
package nl.ovapi.rid.gtfsrt.services;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;
import lombok.NonNull;
import nl.ovapi.ZeroMQUtils;
import nl.ovapi.arnu.TrainProcessor;
import nl.ovapi.rid.model.Block;
import nl.tt_solutions.schemas.ns.rti._1.PutServiceInfoIn;
import nl.tt_solutions.schemas.ns.rti._1.ServiceInfoKind;
import nl.tt_solutions.schemas.ns.rti._1.ServiceInfoServiceType;
import nl.tt_solutions.schemas.ns.rti._1.ServiceInfoStopType;
import org.onebusaway.gtfs_realtime.exporter.GtfsRealtimeGuiceBindingTypes.TripUpdates;
import org.onebusaway.gtfs_realtime.exporter.GtfsRealtimeSink;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zeromq.ZMQ;
import org.zeromq.ZMQ.Context;
import org.zeromq.ZMQ.Socket;
import org.zeromq.ZMsg;
import com.google.common.collect.Maps;
@Singleton
public class ARNUritInfoToGtfsRealTimeServices {
private ExecutorService _executor;
private Future<?> _task;
private static final Logger _log = LoggerFactory.getLogger(ARNUritInfoToGtfsRealTimeServices.class);
private final static String pubAddress = "tcp://post.ndovloket.nl:7662";
private GtfsRealtimeSink _tripUpdatesSink;
private RIDservice _ridService;
private Map<String, TrainProcessor> journeyProcessors;
@Inject
public void setRIDService(RIDservice ridService) {
_ridService = ridService;
}
@Inject
public void setTripUpdatesSink(@TripUpdates GtfsRealtimeSink tripUpdates) {
_tripUpdatesSink = tripUpdates;
}
@PostConstruct
public void start() {
_executor = Executors.newCachedThreadPool();
journeyProcessors = Maps.newHashMap();
_task = _executor.submit(new ProcessTask());
_task = _executor.submit(new ReceiveTask());
}
@PreDestroy
public void stop() {
if (_task != null) {
_task.cancel(true);
_task = null;
}
if (_executor != null) {
_executor.shutdownNow();
_executor = null;
}
}
private TrainProcessor getOrCreateProcessorForId(@NonNull String id){
TrainProcessor tp = journeyProcessors.get(id);
if (tp != null){
return tp;
}
List<Block> trains = _ridService.getTrains(id);
if (trains == null || trains.size() == 0){
return null; //Journey not found
}
tp = new TrainProcessor(trains);
journeyProcessors.put(id, tp);
return tp;
}
private final static String INPROC_PORT = "51546";
private class ProcessTask implements Runnable {
int messagecounter = 0;
@Override
public void run() {
Context context = ZMQ.context(1);
Socket pull = context.socket(ZMQ.PULL);
pull.setRcvHWM(500000);
JAXBContext jc = null;
Unmarshaller unmarshaller = null;
try {
jc = JAXBContext.newInstance(PutServiceInfoIn.class);
unmarshaller = jc.createUnmarshaller();
} catch (JAXBException e1) {
_log.error("Error with JAXB",e1);
e1.printStackTrace();
}
final String PULL_ADDRESS = "tcp://127.0.0.1:"+INPROC_PORT;
pull.connect(PULL_ADDRESS);
while (!Thread.interrupted()) {
messagecounter++;
if (messagecounter % 1000 == 0){
_log.debug(messagecounter + " BISON messages received");
}
try {
String[] m = ZeroMQUtils.gunzipMultifameZMsg(ZMsg.recvMsg(pull));
InputStream stream = new ByteArrayInputStream(m[1].getBytes("UTF-8"));
JAXBElement<PutServiceInfoIn> feed = unmarshaller.unmarshal(new StreamSource(stream), PutServiceInfoIn.class);
if (feed == null || feed.getValue() == null || feed.getValue().getServiceInfoList() == null){
continue;
}
System.out.println(m[0]);
for (ServiceInfoServiceType info : feed.getValue().getServiceInfoList().getServiceInfo()){
switch(info.getServiceType()){
case CANCELLED_SERVICE:
case NORMAL_SERVICE:
case NEW_SERVICE:
case DIVERTED_SERVICE:
case SCHEDULE_CHANGED_SERVICE:
break;
case EXTENDED_SERVICE:
case SPLIT_SERVICE:
System.out.println(m[1]);
default:
break;
}
String id = String.format("%s:IFF:%s:%s",getDate(info),info.getTransportModeCode(),info.getServiceCode());
TrainProcessor jp = getOrCreateProcessorForId(id);
if (jp == null && info.getServiceType() != ServiceInfoKind.NORMAL_SERVICE){
jp = createFromARNU(info);
if (jp != null)
journeyProcessors.put(id, jp);
}
if (jp != null){
if (info.getServiceType() != null){
switch (info.getServiceType()){
case NORMAL_SERVICE:
case SPLIT_SERVICE:
case CANCELLED_SERVICE:
break;
case NEW_SERVICE:
case DIVERTED_SERVICE:
case EXTENDED_SERVICE:
case SCHEDULE_CHANGED_SERVICE:
jp.changeService(_ridService,info);
default:
break;
}
}
_tripUpdatesSink.handleIncrementalUpdate(jp.process(info));
}else{
System.out.println(m[1]);
_log.error("Train {} not found",id);
}
}
} catch (Exception e) {
_log.error("Error ARNU {}",e);
e.printStackTrace();
}
}
_log.error("ARNU2GTFSrealtime service interrupted");
pull.disconnect(PULL_ADDRESS);
}
}
private String getDate(ServiceInfoServiceType info){
if (info.getStopList() == null || info.getStopList().getStop() == null || info.getStopList().getStop().size() == 0){
return null;
}
Calendar operatingDate = null;
for (ServiceInfoStopType s : info.getStopList().getStop()){
if (s.getDeparture() != null){
operatingDate = s.getDeparture().toGregorianCalendar();
break;
}
}
if (operatingDate.get(Calendar.HOUR_OF_DAY) < 4){
operatingDate.add(Calendar.DAY_OF_MONTH, -1);
}
operatingDate.set(Calendar.HOUR_OF_DAY, 0);
operatingDate.set(Calendar.MINUTE, 0);
operatingDate.set(Calendar.SECOND, 0);
operatingDate.set(Calendar.MILLISECOND, 0);
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
return df.format(operatingDate.getTime());
}
private TrainProcessor createFromARNU(ServiceInfoServiceType info){
TrainProcessor jp = TrainProcessor.fromArnu(_ridService,info);
// If possible place this new train in an existing GTFS route.
Integer originalTrainNumber = TrainProcessor.orginalTrainNumber(info.getServiceCode());
if (jp != null && originalTrainNumber != null){
TrainProcessor origJp = null;
// Fuzzy matching for ARNU bug where split Intercity's are suddenly Sneltrein etc.
for (String transportModeCode : new String[] {info.getTransportModeCode(),"S","ST","SPR","HSN","IC","INT","THA","TGV"}){
String origId = String.format("%s:IFF:%s:%s",getDate(info),transportModeCode,originalTrainNumber);
origJp = getOrCreateProcessorForId(origId);
//The original journey has to be the journey this new service is a subset of.
if (origJp != null && !jp.isDisjoint(origJp)){
_log.debug("set routeid {} for {} ",origJp.getRouteId(originalTrainNumber),info.getServiceCode());
//Set routeId for easier consumption of split trips
jp.setRouteId(origJp.getRouteId(originalTrainNumber));
break;
}
}
}
return jp;
}
private class ReceiveTask implements Runnable {
@Override
public void run() {
Context context = ZMQ.context(1);
Socket subscriber = context.socket(ZMQ.SUB);
subscriber.connect(pubAddress);
subscriber.subscribe("".getBytes());
Socket push = context.socket(ZMQ.PUSH);
push.setSndHWM(500000);
|
package org.antlr.intellij.plugin.structview;
import com.intellij.icons.AllIcons;
import com.intellij.ide.structureView.StructureViewModel;
import com.intellij.ide.structureView.StructureViewModelBase;
import com.intellij.ide.structureView.StructureViewTreeElement;
import com.intellij.ide.util.treeView.smartTree.ActionPresentation;
import com.intellij.ide.util.treeView.smartTree.ActionPresentationData;
import com.intellij.ide.util.treeView.smartTree.Sorter;
import com.intellij.ide.util.treeView.smartTree.SorterUtil;
import com.intellij.psi.PsiFile;
import org.antlr.intellij.plugin.ANTLRv4FileRoot;
import org.antlr.intellij.plugin.psi.LexerRuleSpecNode;
import org.antlr.intellij.plugin.psi.ParserRuleSpecNode;
import org.jetbrains.annotations.NotNull;
import java.util.Comparator;
public class ANTLRv4StructureViewModel
extends StructureViewModelBase
// extends TextEditorBasedStructureViewModel
implements StructureViewModel.ElementInfoProvider
{
private static final Sorter PARSER_LEXER_RULE_SORTER = new Sorter() {
public Comparator<?> getComparator() {
return (o1, o2) -> {
String s1 = SorterUtil.getStringPresentation(o1);
String s2 = SorterUtil.getStringPresentation(o2);
// flip case of char 0 so it puts parser rules first
if ( Character.isLowerCase(s1.charAt(0)) ) {
s1 = Character.toUpperCase(s1.charAt(0))+s1.substring(1);
}
else {
s1 = Character.toLowerCase(s1.charAt(0))+s1.substring(1);
}
if ( Character.isLowerCase(s2.charAt(0)) ) {
s2 = Character.toUpperCase(s2.charAt(0))+s2.substring(1);
}
else {
s2 = Character.toLowerCase(s2.charAt(0))+s2.substring(1);
}
return s1.compareTo(s2);
};
}
public boolean isVisible() {
return true;
}
@NotNull
public ActionPresentation getPresentation() {
// how it's described in sort by dropdown in nav window.
String name = "Sort by rule type";
return new ActionPresentationData(name, name, AllIcons.ObjectBrowser.SortByType);
}
@NotNull
public String getName() {
return "PARSER_LEXER_RULE_SORTER";
}
};
ANTLRv4FileRoot rootElement;
public ANTLRv4StructureViewModel(ANTLRv4FileRoot rootElement) {
super(rootElement, new ANTLRv4StructureViewElement(rootElement));
this.rootElement = rootElement;
}
@NotNull
public Sorter[] getSorters() {
return new Sorter[] {PARSER_LEXER_RULE_SORTER, Sorter.ALPHA_SORTER};
}
@Override
protected PsiFile getPsiFile() {
return rootElement;
}
@Override
public boolean isAlwaysShowsPlus(StructureViewTreeElement element) {
Object value = element.getValue();
return value instanceof ANTLRv4FileRoot;
}
@Override
public boolean isAlwaysLeaf(StructureViewTreeElement element) {
Object value = element.getValue();
return value instanceof ParserRuleSpecNode || value instanceof LexerRuleSpecNode;
}
/**
Intellij: The implementation of StructureViewTreeElement.getChildren()
needs to be matched by TextEditorBasedStructureViewModel.getSuitableClasses().
The latter method returns an array of PsiElement-derived classes which can
be shown as structure view elements, and is used to select the Structure
View item matching the cursor position when the structure view is first
opened or when the "Autoscroll from source" option is used.
*/
@NotNull
protected Class<?>[] getSuitableClasses() {
return new Class[] {ANTLRv4FileRoot.class,
LexerRuleSpecNode.class,
ParserRuleSpecNode.class};
}
}
|
/**
* @author verphen
* @date 20141030 11:42:14
*/
package com.verphen.utils;
public class ImagesUtils {
public static void main(String[] args){
System.out.println("
}
}
|
package org.jboss.as.jpa.hibernate;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Configuration;
import org.jboss.as.jpa.config.PersistenceUnitMetadata;
import org.jboss.as.jpa.spi.PersistenceProviderAdaptor;
import org.jboss.as.naming.deployment.ContextNames;
import org.jboss.as.naming.deployment.JndiName;
import org.jboss.msc.service.ServiceName;
import java.util.ArrayList;
import java.util.Map;
/**
* Implements the PersistenceProviderAdaptor for Hibernate
*
* @author Scott Marlow
*/
public class HibernatePersistenceProviderAdaptor implements PersistenceProviderAdaptor {
@Override
public void addProviderProperties(Map properties, PersistenceUnitMetadata pu) {
properties.put(Configuration.USE_NEW_ID_GENERATOR_MAPPINGS, "true");
properties.put(org.hibernate.ejb.AvailableSettings.SCANNER,"org.jboss.as.jpa.hibernate.HibernateAnnotationScanner");
properties.put(AvailableSettings.APP_CLASSLOADER, pu.getClassLoader());
properties.put(AvailableSettings.JTA_PLATFORM, new JBossAppServerJtaPlatform());
}
@Override
public Iterable<ServiceName> getProviderDependencies(PersistenceUnitMetadata pu) {
String cacheManager;
// AS7-680 Add BinderService dependency for infinispan hibernate 2LC
if ((cacheManager = pu.getProperties().getProperty("hibernate.cache.infinispan.cachemanager")) != null) {
ArrayList<ServiceName> result = new ArrayList<ServiceName>();
result.add(adjustJndiName(cacheManager));
return result;
}
return null;
}
private ServiceName adjustJndiName(String jndiName) {
jndiName = toJndiName(jndiName).toString();
int index = jndiName.indexOf("/");
String namespace = (index > 5) ? jndiName.substring(5, index) : null;
String binding = (index > 5) ? jndiName.substring(index + 1) : jndiName.substring(5);
ServiceName naming = (namespace != null) ? ContextNames.JAVA_CONTEXT_SERVICE_NAME.append(namespace) : ContextNames.JAVA_CONTEXT_SERVICE_NAME;
return naming.append(binding);
}
private static JndiName toJndiName(String value) {
return value.startsWith("java:") ? JndiName.of(value) : JndiName.of("java:jboss").append(value.startsWith("/") ? value.substring(1) : value);
}
@Override
public void beforeCreateContainerEntityManagerFactory(PersistenceUnitMetadata pu) {
// set backdoor annotation scanner access to pu
HibernateAnnotationScanner.setThreadLocalPersistenceUnitMetadata(pu);
}
@Override
public void afterCreateContainerEntityManagerFactory(PersistenceUnitMetadata pu) {
// clear backdoor annotation scanner access to pu
HibernateAnnotationScanner.clearThreadLocalPersistenceUnitMetadata();
}
}
|
package de.woerteler.fibheap;
import java.util.*;
/**
* A priority queue implemented as a fibonacci heap.
* @author Leo Woerteler
*
* @param <P> priority type
* @param <V> value type
*/
public final class FibHeap<V, P> {
/** Comparator for {@link Comparable} types. */
private static final Comparator<Comparable<Object>> COMP_COMP =
new Comparator<Comparable<Object>>() {
@Override
public int compare(final Comparable<Object> o1, final Comparable<Object> o2) {
return o1.compareTo(o2);
}
};
/** Key comparator. */
private final Comparator<P> comp;
/** Minimum node, {@code null} if the heap is empty. */
private FibNode<V, P> min;
/**
* Constructor taking a comparator for the keys.
* @param comp comparator
*/
private FibHeap(final Comparator<P> comp) {
this.comp = comp;
}
/**
* Creates a new fibonacci heap where the priorities are ordered according to
* the given {@link Comparator}.
* @param <V> value type
* @param <P> priority type
* @param comp comparator for priorities, must be non-{@code null}
* @return a new fibonacci heap
* @throws NullPointerException if {@code comp} is {@code null}
*/
public static <V, P> FibHeap<V, P> newHeap(final Comparator<P> comp) {
return new FibHeap<>(Objects.requireNonNull(comp));
}
/**
* Creates a new fibonacci heap for priorities that are {@link Comparable}.
* @param <V> value type
* @param <P> priority type
* @return a new fibonacci heap
*/
public static <V, P extends Comparable<P>> FibHeap<V, P> newComparableHeap() {
@SuppressWarnings("unchecked")
final Comparator<P> comp = (Comparator<P>) COMP_COMP;
return new FibHeap<>(comp);
}
/**
* Tests if this heap is empty.
* @return {@code true} if the heap is empty, {@code false} otherwise
*/
public boolean isEmpty() {
return this.min == null;
}
/**
* Inserts a new entry into this heap. <em>O(1)</em>
* @param v value to insert
* @param k key to insert
* @return the inserted entry
*/
public FibNode<V, P> insert(final V v, final P k) {
final FibNode<V, P> node = new FibNode<>(this, k, v);
this.insertIntoRootList(node);
if(node != this.min && this.comp.compare(node.key, this.min.key) < 0) {
this.min = node;
}
return node;
}
/**
* Gets the entry currently at the top of this heap. <em>O(1)</em>
* @return a minimal entry if the queue is non-empty, {@code null} otherwise
*/
public FibNode<V, P> getMin() {
return this.min;
}
public V extractMin() {
final FibNode<V, P> mn = this.min;
if(mn == null) {
throw new IllegalStateException("empty heap");
}
// remove node from root list
if(mn.right == mn) {
this.min = null;
} else {
mn.left.right = mn.right;
mn.right.left = mn.left;
this.min = mn.right;
}
mn.left = mn.right = mn;
// remove children
final FibNode<V, P> fst = mn.firstChild;
mn.firstChild = null;
if(fst != null) {
// add children to root list
FibNode<V, P> curr = fst;
do {
final FibNode<V, P> next = curr.right;
curr.parent = null;
this.insertIntoRootList(curr);
curr = next;
} while(curr != fst);
}
// consolidate the root list
if(!this.isEmpty()) {
this.consolidate();
}
// invalidate and return the root entry
mn.heap = null;
return mn.value;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("FibHeap[");
if(this.min != null) {
sb.append('\n');
FibNode<V, P> curr = this.min;
do {
curr.toString(sb, 1);
curr = curr.right;
} while(curr != this.min);
}
return sb.append(']').toString();
}
/**
* Inserts the given node into the root list. <em>O(1)</em>
* @param nd node to insert
*/
private void insertIntoRootList(final FibNode<V, P> nd) {
final FibNode<V, P> mn = this.min;
if(mn == null) {
nd.left = nd.right = nd;
this.min = nd;
} else {
nd.left = mn;
nd.right = mn.right;
mn.right.left = nd;
mn.right = nd;
}
}
/**
* Consolidates the root list after a call to {@link #extractMin()}.<br/>
* <em>O(r)</em> where <em>r</em> is the length of the root list
*/
private void consolidate() {
final ArrayList<FibNode<V, P>> degrees = new ArrayList<>();
final FibNode<V, P> fst = this.min;
this.min = null;
// go through the root list and merge nodes with the same degree
FibNode<V, P> curr = fst;
do {
final FibNode<V, P> next = curr.right;
FibNode<V, P> other;
int d = curr.degree;
while(d < degrees.size() && (other = degrees.set(d, null)) != null) {
// the smaller key goes on top
if(comp.compare(other.key, curr.key) < 0) {
final FibNode<V, P> temp = curr;
curr = other;
other = temp;
}
// add `other` as a child to `curr`
other.parent = curr;
final FibNode<V, P> fstChild = curr.firstChild;
if(fstChild == null) {
curr.firstChild = other;
other.left = other.right = other;
} else {
other.left = fstChild;
other.right = fstChild.right;
fstChild.right.left = other;
fstChild.right = other;
}
curr.degree = ++d;
}
// insert the new node
while(degrees.size() <= d) {
degrees.add(null);
}
degrees.set(d, curr);
curr = next;
} while(curr != fst);
// re-add all nodes to the root list and update the minimum
FibNode<V, P> mn = null;
for(final FibNode<V, P> nd : degrees) {
if(nd != null) {
this.insertIntoRootList(nd);
if(mn == null || this.comp.compare(nd.key, mn.key) < 0) {
mn = nd;
}
}
}
this.min = mn;
}
/**
* A node in a {@link FibHeap}.
* @author Leo Woerteler
* @param <V> value type
* @param <P> priority type
*/
public static final class FibNode<V, P> {
/** This node's heap. */
private FibHeap<V, P> heap;
/** Current key. */
P key;
/** Value. */
final V value;
/** Parent pointer, {@code null} if the node is in the root list. */
FibNode<V, P> parent;
/** Pointer to some child, {@code null} iff {@link #degree} is {@code 0}. */
FibNode<V, P> firstChild;
/** Pointer to this node's left sibling (non-{@code null}, can be {@code this}). */
FibNode<V, P> left = this;
/** Pointer to this node's left sibling (non-{@code null}, can be {@code this}). */
FibNode<V, P> right = this;
/** Flag for nodes that already lost a child. */
private boolean lost;
/** Number of children. */
int degree;
/**
* Constructor.
* @param heap heap of this node
* @param key priority
* @param value value
*/
FibNode(final FibHeap<V, P> heap, final P key, final V value) {
this.heap = heap;
this.key = key;
this.value = value;
}
/**
* Getter for this node's current key.
* @return the key currently associated with this node
*/
public P getKey() {
return this.key;
}
/**
* Getter for this node's value.
* @return the value associated with this node
*/
public V getValue() {
return this.value;
}
/**
* Checks if this entry is still contained in its heap.
* @return result of check
*/
public boolean isValid() {
return this.heap != null;
}
public void decreaseKey(final P newKey) {
if(this.heap == null) {
throw new IllegalStateException("node is not valid");
}
final Comparator<P> comp = this.heap.comp;
if(comp.compare(newKey, this.key) > 0) {
throw new IllegalArgumentException("new key is greater than old one");
}
this.key = newKey;
if(this.parent != null && comp.compare(newKey, this.parent.key) < 0) {
FibNode<V, P> curr = this, par = this.parent;
do {
// delete node from parent
if(--par.degree == 0) {
par.firstChild = null;
} else {
if(par.firstChild == curr) {
par.firstChild = curr.right;
}
curr.right.left = curr.left;
curr.left.right = curr.right;
}
// insert into root list and unmark
curr.parent = null;
curr.lost = false;
this.heap.insertIntoRootList(curr);
if(!par.lost) {
par.lost = true;
break;
}
// cascade
curr = par;
par = curr.parent;
} while(par != null);
}
// update min pointer
if(comp.compare(newKey, this.heap.min.key) < 0) {
this.heap.min = this;
}
}
@Override
public String toString() {
return "Node[key=" + this.key + ", value=" + this.value + "]";
}
/**
* Recursive helper for {@link FibHeap#toString()}.
* @param sb string builder
* @param indent indentation level
*/
private void toString(final StringBuilder sb, final int indent) {
for(int i = 0; i < indent; i++) {
sb.append(" ");
}
sb.append("Node").append(this.lost ? "'" : "").append('#').append(this.degree).append("[\n");
for(int i = 0; i <= indent; i++) {
sb.append(" ");
}
sb.append('(').append(this.key).append(", ").append(this.value).append(")");
if(this.firstChild == null) {
sb.append("\n");
} else {
sb.append(",\n");
FibNode<V, P> curr = this.firstChild;
do {
curr.toString(sb, indent + 1);
curr = curr.right;
} while(curr != this.firstChild);
}
for(int i = 0; i < indent; i++) {
sb.append(" ");
}
sb.append("]\n");
}
}
}
|
/* *\
** SICU Stress Measurement System **
** Project P04 | C380 Team A **
** EBME 380: Biomedical Engineering Design Experience **
** Case Western Reserve University **
** 2016 Fall Semester **
\* */
package edu.cwru.sicu_sms;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.fxml.FXML;
import javafx.scene.chart.CategoryAxis;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.control.*;
import java.io.FileWriter;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Executors;
import jssc.SerialPort;
import jssc.SerialPortException;
import jssc.SerialPortList;
/**
* The controller for the front-end program.
*
* @since October 13, 2016
* @author Ted Frohlich <ttf10@case.edu>
* @author Abby Walker <amw138@case.edu>
*/
public class Controller {
@FXML private Menu connectMenu;
@FXML private ToggleGroup connectGroup;
@FXML private LineChart eegChart;
@FXML private LineChart ekgChart;
@FXML private ToggleButton recordButton;
private ObservableList<String> serialPortList;
private SerialPort eegPort, ekgPort;
private enum SignalType {EEG_PORT, EKGPORT}
private List<LineChart.Series> eegChannels;
private LineChart.Series ekgChannel;
private FileWriter fileWriter;
/**
* Construct a controller for the front-end program by performing the setup routine:
* <ul>
* 1. Detect serial ports. <br>
* 2. Connect to the first port by default, if it exists. <br>
* </ul>
*/
public Controller() {
if (detectSerialPorts() && serialPortList.size() == 1) {
connect(serialPortList.get(0));
}
}
/**
* Initialize the list of detected ports.
*
* @return <code>true</code> if at least one serial port was detected; <code>false</code> otherwise
*/
private boolean detectSerialPorts() {
serialPortList = FXCollections.observableArrayList();
serialPortList.addAll(SerialPortList.getPortNames());
return !serialPortList.isEmpty();
}
/**
* Connect to the specified serial port.
*
* @param portName the name of the serial port
* @return <code>true</code> if the serial port was successfully connected; <code>false</code> if there is already another port currently open, or just if something went wrong connecting this one
*/
private boolean connect(String portName) {
boolean success = false;
try {
System.out.print("Connecting to serial port " + portName + "...");
if (eegPort != null && eegPort.isOpened()) {
System.out.println("\t->\tAlready connected!");
} else {
eegPort = new SerialPort(portName);
success = eegPort.openPort();
System.out.println("\t->\tSuccessfully connected!");
}
} catch (SerialPortException e) {
System.out.println("\t->\tCouldn't connect!");
}
return success;
}
/**
* Disconnect from the serial port.
*
* @return <code>true</code> if the serial port was successfully disconnected; <code>false</code> if none of the ports were connected to begin with, or just if something went wrong disconnecting this one
*/
private boolean disconnect() {
boolean success = false;
try {
System.out.print("Disconnecting from serial port " + eegPort.getPortName() + "...");
success = eegPort.closePort();
eegPort = null;
if (success) System.out.println("\t->\tSuccessfully disconnected!");
} catch (Exception e) {
System.out.println("\t->\tAlready disconnected!");
}
return success;
}
/**
* Get whether data recording is currently toggled 'on' in the front-end.
*
* @return <code>true</code> if the 'record' toggle button has been pushed; <code>false</code> if no data recording is currently happening
*/
private boolean isRecording() {
return recordButton.isSelected();
}
@FXML
public void connect(ActionEvent actionEvent) {
connect("COM5"); // TODO: Figure out how to get item text from action event.
}
@FXML
private void onMouseEnteredRecordButton() {
recordButton.setText((isRecording() ? "Stop" : "Start") + " Recording");
}
@FXML
private void onMouseExitedRecordButton() {
recordButton.setText("Record" + (isRecording() ? "ing..." : ""));
}
@FXML
private void onMousePressedRecordButton() {
recordButton.setStyle("-fx-background-color: darkred");
}
@FXML
private void onMouseReleasedRecordButton() {
recordButton.setStyle("-fx-background-color: red");
}
@FXML
public void onConnectMenuValidation(Event event) {
connectMenu.getItems().clear();
String[] portNames = SerialPortList.getPortNames();
if (portNames.length == 0) {
MenuItem dummy = new MenuItem("<no ports available>");
dummy.setDisable(true);
connectMenu.getItems().add(dummy);
return;
}
for (String portName : portNames) {
connectMenu.getItems().add(new RadioMenuItem(portName));
}
}
@FXML
private void record() {
if (isRecording()) { // start recording...
//TODO: Run thread for saving data to file.
}
else { // stop recording...
//TODO: End thread for saving data to file.
}
onMouseEnteredRecordButton(); // indicate what next click would do
}
@FXML
private void confirmExit() throws Exception {
Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
alert.setTitle("Confirm Exit");
alert.setHeaderText("Are you sure you want to exit?");
ButtonType result = alert.showAndWait().orElse(ButtonType.CANCEL);
if (result == ButtonType.OK) {
disconnect();
Platform.exit();
}
}
/**
* A controller for the EEG tab.
*/
private class EEGController {
@FXML private LineChart<String, Number>
leftRostralChart, rightRostralChart,
leftCaudalChart, rightCaudalChart;
private CategoryAxis xAxis;
private NumberAxis yAxis;
private ObservableList<String> xAxisCategories;
private LineChart.Series<String, Number>[] electrodes;
private ObservableList<LineChart.Data<String, Number>>
leftRostralList, rightRostralList,
leftCaudalList, rightCaudalList;
private int lastObservedChangelistSize, changesBeforeUpdate = 10;
private Task<Date> chartUpdateTask;
private EEGController() {
initObservableLists();
getObservableLists().forEach(list ->
list.addListener(dataListChangeListener()));
initAxes();
xAxis.setCategories(xAxisCategories);
// xAxis.setAutoRanging(false);
//TODO: instantiate and add data series
initChartUpdateTask();
Executors.newSingleThreadExecutor().submit(chartUpdateTask);
}
private void initAxes() {
xAxis = new CategoryAxis(); yAxis = new NumberAxis();
xAxis.setLabel("Time (sec)"); yAxis.setLabel("Relative Amplitude");
}
private void initChartUpdateTask() {
chartUpdateTask = new Task<Date>() {
@Override
protected Date call() throws Exception {
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
if (isCancelled()) break;
updateValue(new Date());
}
return new Date();
}
};
chartUpdateTask.valueProperty().addListener(new ChangeListener<Date>() {
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); //TODO: eventually just want seconds
Random random = new Random();
@Override
public void changed(ObservableValue<? extends Date> observableDate, Date oldDate, Date newDate) {
String strDate = dateFormat.format(newDate);
xAxisCategories.add(strDate);
getObservableLists().forEach(list ->
list.add(new LineChart.Data(strDate, newDate.getMinutes() + random.nextInt(100500))));
}
});
}
private void initObservableLists() {
leftRostralList = rightRostralList = leftCaudalList = rightCaudalList
= FXCollections.observableArrayList();
xAxisCategories
= FXCollections.observableArrayList();
}
private List<LineChart<String, Number>> getCharts() {
List<LineChart<String, Number>> charts = Collections.emptyList();
charts.add(leftRostralChart); charts.add(rightRostralChart);
charts.add(leftCaudalChart); charts.add(rightCaudalChart);
return charts;
}
private List<ObservableList<LineChart.Data<String, Number>>> getObservableLists() {
List<ObservableList<LineChart.Data<String, Number>>> lists = Collections.emptyList();
lists.add(leftRostralList); lists.add(rightRostralList);
lists.add(leftCaudalList); lists.add(rightCaudalList);
return lists;
}
private ListChangeListener<LineChart.Data<String, Number>> dataListChangeListener() {
return change -> {
if (change.getList().size() - lastObservedChangelistSize > changesBeforeUpdate) {
lastObservedChangelistSize += changesBeforeUpdate;
xAxis.getCategories().remove(0, changesBeforeUpdate);
}
};
}
}
/**
* A controller for the EKG tab.
*/
private class EKGController {
//TODO:
}
}
|
package p.rn.util;
import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashSet;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
public class FileOut {
public interface OutHandler extends Closeable {
public void write(boolean isDir, String name, InputStream is, Object nameObject) throws IOException;
public void write(boolean isDir, String name, byte[] data, Object nameObject) throws IOException;
public OutputStream openOutput(String name, Object nameObject) throws IOException;
}
public static OutHandler create(File dirORzip) throws IOException {
return create(dirORzip, dirORzip.exists() ? (dirORzip.isFile()) : true);
}
public static OutHandler create(File dirORzip, boolean isZip) throws IOException {
if (isZip) {
return new ZipOutHandler(FileUtils.openOutputStream(dirORzip));
} else {
return new FileOutHandler(dirORzip);
}
}
private static class FileOutHandler implements OutHandler {
public void close() throws IOException {
}
public FileOutHandler(File dir) {
super();
this.dir = dir;
}
File dir;
public void write(boolean isDir, String name, InputStream is, Object nameObject) throws IOException {
if (!isDir) {
FileOutputStream fos = null;
try {
fos = FileUtils.openOutputStream(new File(dir, name));
IOUtils.copy(is, fos);
} finally {
IOUtils.closeQuietly(fos);
}
}
}
public void write(boolean isDir, String name, byte[] data, Object nameObject) throws IOException {
if (!isDir) {
FileUtils.writeByteArrayToFile(new File(dir, name), data);
}
}
@Override
public OutputStream openOutput(String name, Object nameObject) throws IOException {
return FileUtils.openOutputStream(new File(dir, name));
}
}
private static class ZipOutHandler implements OutHandler {
private Set<String> dirs = new HashSet<String>();
private ZipOutputStream zos;
public ZipOutHandler(OutputStream os) {
zos = new ZipOutputStream(os);
}
private void check(String dir) throws IOException {
if (dirs.contains(dir)) {
return;
}
dirs.add(dir);
int i = dir.lastIndexOf('/');
if (i > 0) {
check(dir.substring(0, i));
}
zos.putNextEntry(new ZipEntry(dir + "/"));
zos.closeEntry();
}
public void close() {
IOUtils.closeQuietly(zos);
}
public void write(boolean isDir, String name, byte[] data, Object nameObject) throws IOException {
zos.putNextEntry(buildEntry(name, nameObject));
if (!isDir) {
zos.write(data);
}
zos.closeEntry();
}
public void write(boolean isDir, String name, InputStream is, Object nameObject) throws IOException {
zos.putNextEntry(buildEntry(name, nameObject));
if (!isDir) {
IOUtils.copy(is, zos);
}
zos.closeEntry();
}
private ZipEntry buildEntry(String name, Object nameObject) throws IOException {
int i = name.lastIndexOf('/');
if (i > 0) {
check(name.substring(0, i));
}
if (nameObject instanceof ZipEntry) {
ZipEntry ze = (ZipEntry) nameObject;
if (name.equals(ze.getName())) {
ZipEntry nZe = new ZipEntry(name);
nZe.setComment(ze.getComment());
nZe.setTime(ze.getTime());
return nZe;
}
}
return new ZipEntry(name);
}
@Override
public OutputStream openOutput(String name, Object nameObject) throws IOException {
zos.putNextEntry(buildEntry(name, nameObject));
return new FilterOutputStream(zos) {
@Override
public void close() throws IOException {
this.flush();
zos.closeEntry();
}
};
}
}
}
|
package eu.amidst.scai2015;
import eu.amidst.core.datastream.DataInstance;
import eu.amidst.core.datastream.DataOnMemory;
import eu.amidst.core.datastream.DataOnMemoryListContainer;
import eu.amidst.core.datastream.DataStream;
import eu.amidst.core.distribution.Multinomial;
import eu.amidst.core.inference.InferenceEngineForBN;
import eu.amidst.core.io.DataStreamLoader;
import eu.amidst.core.models.BayesianNetwork;
import eu.amidst.core.models.DAG;
import eu.amidst.core.utils.Utils;
import eu.amidst.core.variables.StaticVariables;
import eu.amidst.core.variables.Variable;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class wrapperBN {
int seed = 0;
Variable classVariable;
static int DEFAULTER_VALUE_INDEX = 1;
public int getSeed() {
return seed;
}
public void setSeed(int seed) {
this.seed = seed;
}
public Variable getClassVariable() {
return classVariable;
}
public void setClassVariable(Variable classVariable) {
this.classVariable = classVariable;
}
public BayesianNetwork wrapperBNOneMonth(DataOnMemory<DataInstance> data) throws IOException {
StaticVariables Vars = new StaticVariables(data.getAttributes());
int nbrVars = Vars.getNumberOfVars();
Variable classVar = Vars.getVariableById(-1);
//Split the whole data into training and testing
List<DataOnMemory<DataInstance>> splitData = this.splitTrainAndTest(data,66.0);
DataOnMemory<DataInstance> trainingData = splitData.get(0);
DataOnMemory<DataInstance> testData = splitData.get(1);
StaticVariables NonSelectedVars = Vars; // All the features variables minus the C and C'
int nbrNonSelected = nbrVars-2; //nbr of all features except the 2 classes C and C'?
StaticVariables SelectedVars = new StaticVariables();
Boolean stop = false;
DAG dag = new DAG(Vars);
BayesianNetwork bn = BayesianNetwork.newBayesianNetwork(dag);
//Learn the initial BN with training data including only the class variable
// bn = trainModel(trainingData,SelectedVars)
//Evaluate the initial BN with testing data including only the class variable, i.e., initial score or initial auc
double score = computeAccuracy (bn, testData, classVar); //add HashMap
//iterate until there is no improvement in score
while (nbrNonSelected > 0 && stop == false ) {
double[] scores = new double[nbrVars]; //save the score for each potential considered variable
for(Variable V:NonSelectedVars){
//learn a naive bayes including the class and the new selected set of variables including the variable V
//bn = trainModel(trainingData,NewSelectedVars)
//evaluate using the testing data
//auc = testModel(testData, bn, HashMap)
scores[V.getVarID()] = computeAccuracy (bn, testData, classVar);
//determine the max score and the index of the Variable
int maxScore = max(scores);
int index = maxIndex(scores);
if (score < maxScore){
score = maxScore;
//add the variable with index to the list of SelectedVars
//SelectedVars = SelectedVars + V
nbrNonSelected = nbrNonSelected -1;
}
else{
stop = true;
}
}
}
//Update HashMap considering the winning subset of the selected features and all the data (i.e., training +testing data)
//HashMap = updateHM (data, SelectedVars)
return bn;
}
public static double computeAccuracy(BayesianNetwork bn, DataOnMemory<DataInstance> data, Variable classVar){
double predictions = 0;
InferenceEngineForBN.setModel(bn);
for (DataInstance instance : data) {
double realValue = instance.getValue(classVar);
instance.setValue(classVar, Utils.missingValue());
InferenceEngineForBN.setEvidence(instance);
InferenceEngineForBN.runInference();
Multinomial posterior = InferenceEngineForBN.getPosterior(classVar);
if (Utils.maxIndex(posterior.getProbabilities())==realValue)
predictions++;
instance.setValue(classVar, realValue);
}
return predictions/data.getNumberOfDataInstances();
}
List<DataOnMemory<DataInstance>> splitTrainAndTest(DataOnMemory<DataInstance> data, double trainPercentage) {
Random random = new Random(this.seed);
DataOnMemoryListContainer<DataInstance> train = new DataOnMemoryListContainer(data.getAttributes());
DataOnMemoryListContainer<DataInstance> test = new DataOnMemoryListContainer(data.getAttributes());
for (DataInstance dataInstance : data) {
if (dataInstance.getValue(classVariable) == DEFAULTER_VALUE_INDEX)
continue;
if (random.nextDouble()<trainPercentage/100.0)
train.add(dataInstance);
else
test.add(dataInstance);
}
for (DataInstance dataInstance : data) {
if (dataInstance.getValue(classVariable) != DEFAULTER_VALUE_INDEX)
continue;
if (random.nextDouble()<trainPercentage/100.0)
train.add(dataInstance);
}
Collections.shuffle(train.getList(), random);
Collections.shuffle(test.getList(), random);
return Arrays.asList(train, test);
}
public static void main(String[] args) throws IOException {
DataStream<DataInstance> data = DataStreamLoader.loadFromFile("datasets/randomdata.arff");
//BayesianNetwork bn = wrapperBN.wrapperBNOneMonth(data);
}
}
|
package factchecking.news;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
public class HttpHelper {
public static Document getDocumentByUrl(final String url) throws IOException {
return Jsoup.connect(url).validateTLSCertificates(false).userAgent("Chrome").get();
}
public static String encodeValue(String value) throws UnsupportedEncodingException {
return URLEncoder.encode(value, StandardCharsets.UTF_8.toString());
}
}
|
package com.nicefish;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.web.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
/*@SpringBootApplication(scanBasePackages={
"com.nicefish.config","com.nicefish.common","com.nicefish.service",
"com.nicefish.message","com.nicefish.swagger","com.nicefish.web"})*/
@SpringBootApplication
@RestController
@MapperScan(basePackages = {"com.nicefish.mapper"})
public class NicefishApplication {
@RequestMapping("/")
public String greeting() {
return "Hello World,kimmking!";
}
public static void main(String[] args) {
SpringApplication.run(NicefishApplication.class, args);
}
@Bean
public HttpMessageConverters fastjsonHttpMessageConverter(){
FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
FastJsonConfig jsonConfig = new FastJsonConfig();
jsonConfig.setSerializerFeatures(
SerializerFeature.PrettyFormat,
SerializerFeature.QuoteFieldNames
);
jsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
converter.setFastJsonConfig(jsonConfig);
List<MediaType> mediaTypes = new ArrayList<>();
mediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
converter.setSupportedMediaTypes(mediaTypes);
return new HttpMessageConverters(converter);
}
}
|
package hudson.ivy;
import hudson.AbortException;
import hudson.EnvVars;
import hudson.Launcher;
import hudson.Util;
import hudson.ivy.IvyBuild.ProxyImpl2;
import hudson.ivy.builder.IvyBuilderType;
import hudson.model.AbstractProject;
import hudson.model.Action;
import hudson.model.Build;
import hudson.model.BuildListener;
import hudson.model.DependencyGraph;
import hudson.model.Environment;
import hudson.model.Fingerprint;
import hudson.model.Hudson;
import hudson.model.ParametersAction;
import hudson.model.Result;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.model.Cause.UpstreamCause;
import hudson.remoting.Callable;
import hudson.remoting.Channel;
import hudson.scm.ChangeLogSet;
import hudson.tasks.BuildWrapper;
import hudson.tasks.Publisher;
import hudson.util.StreamTaskListener;
import java.io.File;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.io.PrintStream;
import java.io.Serializable;
import java.net.MalformedURLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.Map.Entry;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.lang.StringUtils;
import org.apache.ivy.Ivy;
import org.apache.ivy.Ivy.IvyCallback;
import org.apache.ivy.core.IvyContext;
import org.apache.ivy.core.module.descriptor.ModuleDescriptor;
import org.apache.ivy.core.settings.IvySettings;
import org.apache.ivy.core.sort.SortOptions;
import org.apache.ivy.plugins.parser.ModuleDescriptorParserRegistry;
import org.apache.ivy.util.Message;
import org.apache.tools.ant.BuildEvent;
import org.apache.tools.ant.types.FileSet;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
/**
* {@link Build} for {@link IvyModuleSet}.
*
* <p>
* A "build" of {@link IvyModuleSet} consists of:
*
* <ol>
* <li>Update the workspace.
* <li>Parse ivy.xml files
* <li>Trigger module builds.
* </ol>
*
* This object remembers the changelog and what {@link IvyBuild}s are done on
* this.
*
* @author Timothy Bingaman
*/
public class IvyModuleSetBuild extends AbstractIvyBuild<IvyModuleSet, IvyModuleSetBuild> {
/**
* {@link IvyReporter}s that will contribute project actions. Can be null if
* there's none.
*/
/* package */List<IvyReporter> projectActionReporters;
public IvyModuleSetBuild(IvyModuleSet job) throws IOException {
super(job);
}
public IvyModuleSetBuild(IvyModuleSet project, File buildDir) throws IOException {
super(project, buildDir);
}
/**
* Exposes {@code ANT_OPTS} to forked processes.
*
* When we fork Ant, we do so directly by executing Java, thus this
* environment variable is pointless (we have to tweak JVM launch option
* correctly instead, which can be seen in {@link IvyProcessFactory}), but
* setting the environment variable explicitly is still useful in case this
* Ant forks other Ant processes via normal way. See HUDSON-3644.
*/
@Override
public EnvVars getEnvironment(TaskListener log) throws IOException, InterruptedException {
EnvVars envs = super.getEnvironment(log);
envs.putAll(project.getIvyBuilderType().getEnvironment());
return envs;
}
/**
* Displays the combined status of all modules.
* <p>
* More precisely, this picks up the status of this build itself, plus all
* the latest builds of the modules that belongs to this build.
*/
@Override
public Result getResult() {
Result r = super.getResult();
for (IvyBuild b : getModuleLastBuilds().values()) {
Result br = b.getResult();
if (r == null)
r = br;
else if (br == Result.NOT_BUILT)
continue; // UGLY: when computing combined status, ignore the
// modules that were not built
else if (br != null)
r = r.combine(br);
}
return r;
}
/**
* Returns the filtered changeset entries that match the given module.
*/
/* package */List<ChangeLogSet.Entry> getChangeSetFor(final IvyModule mod) {
return new ArrayList<ChangeLogSet.Entry>() {
{
for (ChangeLogSet.Entry e : getChangeSet()) {
if (isDescendantOf(e, mod)) {
add(e);
}
}
}
/**
* Does this change happen somewhere in the given module or its
* descendants?
*/
private boolean isDescendantOf(ChangeLogSet.Entry e, IvyModule mod) {
for (String path : e.getAffectedPaths())
if (path.startsWith(mod.getRelativePathToModuleRoot()))
return true;
return false;
}
};
}
/**
* Computes the module builds that correspond to this build.
* <p>
* A module may be built multiple times (by the user action), so the value
* is a list.
*/
public Map<IvyModule, List<IvyBuild>> getModuleBuilds() {
Collection<IvyModule> mods = getParent().getModules();
// identify the build number range. [start,end)
IvyModuleSetBuild nb = getNextBuild();
int end = nb != null ? nb.getNumber() : Integer.MAX_VALUE;
// preserve the order by using LinkedHashMap
Map<IvyModule, List<IvyBuild>> r = new LinkedHashMap<IvyModule, List<IvyBuild>>(mods.size());
for (IvyModule m : mods) {
List<IvyBuild> builds = new ArrayList<IvyBuild>();
IvyBuild b = m.getNearestBuild(number);
while (b != null && b.getNumber() < end) {
builds.add(b);
b = b.getNextBuild();
}
r.put(m, builds);
}
return r;
}
@Override
public Object getDynamic(String token, StaplerRequest req, StaplerResponse rsp) {
// map corresponding module build under this object
if (token.indexOf('$') > 0) {
IvyModule m = getProject().getModule(token);
if (m != null)
return m.getBuildByNumber(getNumber());
}
return super.getDynamic(token, req, rsp);
}
/**
* Computes the latest module builds that correspond to this build.
*/
public Map<IvyModule, IvyBuild> getModuleLastBuilds() {
Collection<IvyModule> mods = getParent().getModules();
// identify the build number range. [start,end)
IvyModuleSetBuild nb = getNextBuild();
int end = nb != null ? nb.getNumber() : Integer.MAX_VALUE;
// preserve the order by using LinkedHashMap
Map<IvyModule, IvyBuild> r = new LinkedHashMap<IvyModule, IvyBuild>(mods.size());
for (IvyModule m : mods) {
IvyBuild b = m.getNearestOldBuild(end - 1);
if (b != null && b.getNumber() >= getNumber())
r.put(m, b);
}
return r;
}
public void registerAsProjectAction(IvyReporter reporter) {
if (projectActionReporters == null)
projectActionReporters = new ArrayList<IvyReporter>();
projectActionReporters.add(reporter);
}
/**
* Finds {@link Action}s from all the module builds that belong to this
* {@link IvyModuleSetBuild}. One action per one {@link IvyModule}, and
* newer ones take precedence over older ones.
*/
public <T extends Action> List<T> findModuleBuildActions(Class<T> action) {
Collection<IvyModule> mods = getParent().getModules();
List<T> r = new ArrayList<T>(mods.size());
// identify the build number range. [start,end)
IvyModuleSetBuild nb = getNextBuild();
int end = nb != null ? nb.getNumber() - 1 : Integer.MAX_VALUE;
for (IvyModule m : mods) {
IvyBuild b = m.getNearestOldBuild(end);
while (b != null && b.getNumber() >= number) {
T a = b.getAction(action);
if (a != null) {
r.add(a);
break;
}
b = b.getPreviousBuild();
}
}
return r;
}
@Override
public void run() {
run(new RunnerImpl());
getProject().updateTransientActions();
}
@Override
public Fingerprint.RangeSet getDownstreamRelationship(AbstractProject that) {
Fingerprint.RangeSet rs = super.getDownstreamRelationship(that);
for (List<IvyBuild> builds : getModuleBuilds().values())
for (IvyBuild b : builds)
rs.add(b.getDownstreamRelationship(that));
return rs;
}
/**
* Called when a module build that corresponds to this module set build has
* completed.
*/
/* package */void notifyModuleBuild(IvyBuild newBuild) {
try {
// update module set build number
getParent().updateNextBuildNumber();
// update actions
Map<IvyModule, List<IvyBuild>> moduleBuilds = getModuleBuilds();
// actions need to be replaced atomically especially
// given that two builds might complete simultaneously.
synchronized (this) {
boolean modified = false;
List<Action> actions = getActions();
Set<Class<? extends AggregatableAction>> individuals = new HashSet<Class<? extends AggregatableAction>>();
for (Action a : actions) {
if (a instanceof IvyAggregatedReport) {
IvyAggregatedReport mar = (IvyAggregatedReport) a;
mar.update(moduleBuilds, newBuild);
individuals.add(mar.getIndividualActionType());
modified = true;
}
}
// see if the new build has any new aggregatable action that we
// haven't seen.
for (AggregatableAction aa : newBuild.getActions(AggregatableAction.class)) {
if (individuals.add(aa.getClass())) {
// new AggregatableAction
IvyAggregatedReport mar = aa.createAggregatedAction(this, moduleBuilds);
mar.update(moduleBuilds, newBuild);
actions.add(mar);
modified = true;
}
}
if (modified) {
save();
getProject().updateTransientActions();
}
}
// symlink to this module build
String moduleFsName = newBuild.getProject().getModuleName().toFileSystemName();
Util.createSymlink(getRootDir(),
"../../modules/" + moduleFsName + "/builds/" + newBuild.getId() /*ugly!*/,
moduleFsName, StreamTaskListener.NULL);
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to update " + this, e);
} catch (InterruptedException e) {
LOGGER.log(Level.WARNING, "Failed to update " + this, e);
}
}
/**
* The sole job of the {@link IvyModuleSet} build is to update SCM and
* triggers module builds.
*/
private class RunnerImpl extends AbstractRunner {
private Map<ModuleName,IvyBuild.ProxyImpl2> proxies;
@Override
protected Result doRun(final BuildListener listener) throws Exception {
PrintStream logger = listener.getLogger();
try {
EnvVars envVars = getEnvironment(listener);
parseIvyDescriptorFiles(listener, logger, envVars);
if (!project.isAggregatorStyleBuild()) {
// start module builds
DependencyGraph graph = Hudson.getInstance().getDependencyGraph();
Set<IvyModule> triggeredModules = new HashSet<IvyModule>();
if (!project.isIncrementalBuild() || IvyModuleSetBuild.this.getChangeSet().isEmptySet()) {
for (IvyModule module : project.sortedActiveModules) {
// Don't trigger builds if we've already triggered
// one
// of their dependencies.
// It's safe to just get the direct dependencies
// since
// the modules are sorted in dependency order.
List<AbstractProject> ups = module.getUpstreamProjects();
boolean triggerBuild = true;
for (AbstractProject upstreamDep : ups) {
if (triggeredModules.contains(upstreamDep)) {
triggerBuild = false;
break;
}
}
if (triggerBuild) {
logger.println("Triggering " + module.getModuleName());
module.scheduleBuild(new UpstreamCause((Run<?, ?>) IvyModuleSetBuild.this));
}
triggeredModules.add(module);
}
} else {
for (IvyModule module : project.sortedActiveModules) {
// If there are changes for this module, add it.
// Also add it if we've never seen this module
// before,
// or if the previous build of this module
// failed or was unstable.
boolean triggerBuild = false;
if ((module.getLastBuild() == null) || (!getChangeSetFor(module).isEmpty())
|| (module.getLastBuild().getResult().isWorseThan(Result.SUCCESS))) {
triggerBuild = true;
List<AbstractProject> ups = module.getUpstreamProjects();
for (AbstractProject upstreamDep : ups) {
if (triggeredModules.contains(upstreamDep)) {
triggerBuild = false;
triggeredModules.add(module);
break;
}
}
}
if (triggerBuild) {
logger.println("Triggering " + module.getModuleName());
module.scheduleBuild(new UpstreamCause((Run<?, ?>) IvyModuleSetBuild.this));
triggeredModules.add(module);
}
}
}
} else {
// do builds here
try {
List<BuildWrapper> wrappers = new ArrayList<BuildWrapper>();
for (BuildWrapper w : project.getBuildWrappersList())
wrappers.add(w);
ParametersAction parameters = getAction(ParametersAction.class);
if (parameters != null)
parameters.createBuildWrappers(IvyModuleSetBuild.this, wrappers);
for (BuildWrapper w : wrappers) {
Environment e = w.setUp(IvyModuleSetBuild.this, launcher, listener);
if (e == null)
return Result.FAILURE;
buildEnvironments.add(e);
e.buildEnvVars(envVars); // #3502: too late for
// getEnvironment to do
// this
}
if (!preBuild(listener, project.getPublishers()))
return Result.FAILURE;
List<String> changedModules = new ArrayList<String>();
for (IvyModule m : project.sortedActiveModules) {
// Check if incrementalBuild is selected and that
// there are changes -
// we act as if incrementalBuild is not set if there
// are no changes.
if (!IvyModuleSetBuild.this.getChangeSet().isEmptySet() && project.isIncrementalBuild()) {
// If there are changes for this module, add it.
if (!getChangeSetFor(m).isEmpty()) {
changedModules.add(m.getModuleName().name);
}
}
}
Properties additionalProperties = null;
if (project.isAggregatorStyleBuild() && project.isIncrementalBuild()) {
additionalProperties = new Properties();
additionalProperties.put(project.getChangedModulesProperty() == null ? "hudson.ivy.changedModules" : project
.getChangedModulesProperty(), StringUtils.join(changedModules, ','));
}
IvyBuilderType ivyBuilderType = project.getIvyBuilderType();
hudson.tasks.Builder builder = ivyBuilderType.getBuilder(additionalProperties, null, buildEnvironments);
logger.println("Building project with " + ivyBuilderType.getDescriptor().getDisplayName());
if (builder.perform(IvyModuleSetBuild.this, launcher, listener))
return Result.SUCCESS;
return Result.FAILURE;
} finally {
// tear down in reverse order
boolean failed = false;
for (int i = buildEnvironments.size() - 1; i >= 0; i
if (!buildEnvironments.get(i).tearDown(IvyModuleSetBuild.this, listener)) {
failed = true;
}
}
buildEnvironments = null;
// WARNING The return in the finally clause will trump
// any return before
if (failed)
return Result.FAILURE;
}
}
return null;
} catch (AbortException e) {
if (e.getMessage() != null)
listener.error(e.getMessage());
return Result.FAILURE;
} catch (InterruptedIOException e) {
e.printStackTrace(listener.error("Aborted Ivy execution for InterruptedIOException"));
return Result.ABORTED;
} catch (InterruptedException e) {
e.printStackTrace(listener.error("Aborted Ivy execution for InterruptedException"));
return Result.ABORTED;
} catch (IOException e) {
e.printStackTrace(listener.error(Messages.IvyModuleSetBuild_FailedToParseIvyXml()));
return Result.FAILURE;
} catch (RunnerAbortedException e) {
return Result.FAILURE;
} catch (RuntimeException e) {
// bug in the code.
e.printStackTrace(listener.error("Processing failed due to a bug in the code. Please report this to users@hudson.dev.java.net"));
logger.println("project=" + project);
logger.println("project.getModules()=" + project.getModules());
throw e;
}
}
private void parseIvyDescriptorFiles(BuildListener listener, PrintStream logger, EnvVars envVars) throws IOException, InterruptedException {
logger.println("Parsing Ivy Descriptor Files");
List<IvyModuleInfo> ivyDescriptors;
try {
IvyXmlParser parser = new IvyXmlParser(listener, project, getModuleRoot().getRemote());
if (getModuleRoot().getChannel() instanceof Channel)
((Channel) getModuleRoot().getChannel()).preloadJar(parser, Ivy.class);
ivyDescriptors = getModuleRoot().act(parser);
} catch (IOException e) {
if (e.getCause() instanceof AbortException)
throw (AbortException) e.getCause();
throw e;
} catch (Throwable e) {
throw new IOException("Unable to parse ivy descriptors", e);
}
// update the module list
Map<ModuleName, IvyModule> modules = project.modules;
synchronized (modules) {
Map<ModuleName, IvyModule> old = new HashMap<ModuleName, IvyModule>(modules);
List<IvyModule> sortedModules = new ArrayList<IvyModule>();
modules.clear();
for (IvyModuleInfo ivyDescriptor : ivyDescriptors) {
IvyModule mm = old.get(ivyDescriptor.name);
if (mm != null) {// found an existing matching module
if (debug)
logger.println("Reconfiguring " + mm);
mm.reconfigure(ivyDescriptor);
modules.put(ivyDescriptor.name, mm);
} else {// this looks like a new module
logger.println(Messages.IvyModuleSetBuild_DiscoveredModule(ivyDescriptor.name, ivyDescriptor.displayName));
mm = new IvyModule(project, ivyDescriptor, getNumber());
modules.put(mm.getModuleName(), mm);
}
sortedModules.add(mm);
mm.save();
}
// at this point the list contains all the live modules
project.sortedActiveModules = sortedModules;
// remaining modules are no longer active.
old.keySet().removeAll(modules.keySet());
for (IvyModule om : old.values()) {
if (debug)
logger.println("Disabling " + om);
om.makeDisabled(true);
}
modules.putAll(old);
}
// we might have added new modules
Hudson.getInstance().rebuildDependencyGraph();
// module builds must start with this build's number
for (IvyModule m : modules.values())
m.updateNextBuildNumber(getNumber());
}
@Override
protected void post2(BuildListener listener) throws Exception {
// asynchronous executions from the build might have left some
// unsaved state,
// so just to be safe, save them all.
// TODO: uncomment when proxying stuff is done
// for (IvyBuild b : getModuleLastBuilds().values())
// b.save();
if (project.isAggregatorStyleBuild()) {
performAllBuildSteps(listener, project.getPublishers(), true);
}
performAllBuildSteps(listener, project.getProperties(), true);
// aggregate all module fingerprints to us,
// so that dependencies between module builds can be understood as
// dependencies between module set builds.
// TODO: we really want to implement this as a publisher,
// but we don't want to ask for a user configuration, nor should it
// show up in the persisted record.
// IvyFingerprinter.aggregate(IvyModuleSetBuild.this);
}
@Override
public void cleanUp(BuildListener listener) throws Exception {
if (project.isAggregatorStyleBuild()) {
// schedule downstream builds. for non aggregator style builds,
// this is done by each module
scheduleDownstreamBuilds(listener);
performAllBuildSteps(listener, project.getPublishers(), false);
}
performAllBuildSteps(listener, project.getProperties(), false);
}
}
/**
* Runs Ant and builds the project.
*
* This is only used for {@link IvyModuleSet#isAggregatorStyleBuild() the
* aggregator style build}.
*/
private static final class Builder extends IvyBuilder {
private final Map<ModuleName,IvyBuildProxy2> proxies;
private final Map<ModuleName,List<Publisher>> modulePublishers = new HashMap<ModuleName,List<Publisher>>();
private IvyBuildProxy2 lastProxy;
/**
* Kept so that we can finalize them in the end method.
*/
private final transient Map<ModuleName,ProxyImpl2> sourceProxies;
public Builder(BuildListener listener,Map<ModuleName,ProxyImpl2> proxies, Collection<IvyModule> modules, List<String> goals, Map<String,String> systemProps) {
super(listener,goals,systemProps);
this.sourceProxies = proxies;
this.proxies = new HashMap<ModuleName, IvyBuildProxy2>(proxies);
for (Entry<ModuleName,IvyBuildProxy2> e : this.proxies.entrySet())
e.setValue(new FilterImpl(e.getValue()));
for (IvyModule m : modules)
modulePublishers.put(m.getModuleName(),m.createModulePublishers());
}
private class FilterImpl extends IvyBuildProxy2.Filter<IvyBuildProxy2> implements Serializable {
public FilterImpl(IvyBuildProxy2 core) {
super(core);
}
@Override
public void executeAsync(final BuildCallable<?,?> program) throws IOException {
futures.add(Channel.current().callAsync(new AsyncInvoker(core,program)));
}
private static final long serialVersionUID = 1L;
}
/**
* Invoked after the Ant has finished running, and in the master, not in the Ant process.
*/
void end(Launcher launcher) throws IOException, InterruptedException {
for (Map.Entry<ModuleName,ProxyImpl2> e : sourceProxies.entrySet()) {
ProxyImpl2 p = e.getValue();
for (Publisher publisher : modulePublishers.get(e.getKey())) {
// we'd love to do this when the module build ends, but doing so requires
// we know how many task segments are in the current build.
publisher.perform(p.owner(),launcher,listener);
p.appendLastLog();
}
p.close();
}
}
@Override
public Result call() throws IOException {
try {
return super.call();
} finally {
if(lastProxy!=null)
lastProxy.appendLastLog();
}
}
@Override
void preBuild(BuildEvent event) throws IOException, InterruptedException {
// TODO
}
@Override
void postBuild(BuildEvent event) throws IOException, InterruptedException {
// TODO
}
@Override
void preModule(BuildEvent event) throws InterruptedException, IOException, AbortException {
File baseDir = event.getProject().getBaseDir();
// TODO: find the module that contains this path?
// ModuleName name = new ModuleName(event.getProject().getBaseDir());
// IvyBuildProxy2 proxy = proxies.get(name);
// listener.getLogger().flush(); // make sure the data until here are all written
// proxy.start();
// for (IvyReporter r : reporters.get(name))
// if(!r.preBuild(proxy,event,listener))
// throw new AbortException(r+" failed");
}
@Override
void postModule(BuildEvent event) throws InterruptedException, IOException, AbortException {
// ModuleName name = new ModuleName(project);
// IvyBuildProxy2 proxy = proxies.get(name);
// List<IvyReporter> rs = reporters.get(name);
// if(rs==null) { // probe for issue #906
// throw new AssertionError("reporters.get("+name+")==null. reporters="+reporters+" proxies="+proxies);
// for (IvyReporter r : rs)
// if(!r.postBuild(proxy,event,listener))
// throw new hudson.maven.agent.AbortException(r+" failed");
// listener.getLogger().flush(); // make sure the data until here are all written
// proxy.end();
// lastProxy = proxy;
}
private static final long serialVersionUID = 1L;
}
/**
* Used to tunnel exception from Ant through remoting.
*/
private static final class AntExecutionException extends RuntimeException {
private AntExecutionException(Exception cause) {
super(cause);
}
@Override
public Exception getCause() {
return (Exception) super.getCause();
}
private static final long serialVersionUID = 1L;
}
/**
* Executed on the slave to parse ivy.xml files and extract information into
* {@link IvyModuleInfo}, which will be then brought back to the master.
*/
private static final class IvyXmlParser implements Callable<List<IvyModuleInfo>, Throwable> {
private static final String IVY_XML_PATTERN = "**/ivy.xml";
private final BuildListener listener;
/**
* Capture the value of the static field so that the debug flag takes an
* effect even when {@link IvyXmlParser} runs in a slave.
*/
private final boolean verbose = debug;
private final String ivyFilePattern;
private final String ivyFileExcludePattern;
private final String ivySettingsFile;
private final String ivySettingsPropertyFiles;
private final String ivyBranch;
private final String workspace;
private final String workspaceProper;
public IvyXmlParser(BuildListener listener, IvyModuleSet project, String workspace) {
// project cannot be shipped to the remote JVM, so all the relevant
// properties need to be captured now.
this.listener = listener;
this.ivyFilePattern = project.getIvyFilePattern() == null ? IVY_XML_PATTERN : project.getIvyFilePattern();
this.ivyFileExcludePattern = project.getIvyFileExcludesPattern();
this.ivyBranch = project.getIvyBranch();
this.workspace = workspace;
this.ivySettingsFile = project.getIvySettingsFile();
this.ivySettingsPropertyFiles = project.getIvySettingsPropertyFiles();
this.workspaceProper = project.getLastBuild().getWorkspace().getRemote();
}
@SuppressWarnings("unchecked")
public List<IvyModuleInfo> call() throws Throwable {
File ws = new File(workspace);
FileSet ivyFiles = Util.createFileSet(ws, ivyFilePattern, ivyFileExcludePattern);
final PrintStream logger = listener.getLogger();
Ivy ivy = getIvy(logger);
HashMap<ModuleDescriptor, String> moduleDescriptors = new HashMap<ModuleDescriptor, String>();
for (String ivyFilePath : ivyFiles.getDirectoryScanner().getIncludedFiles()) {
final File ivyFile = new File(ws, ivyFilePath);
ModuleDescriptor module = (ModuleDescriptor) ivy.execute(new IvyCallback() {
public Object doInIvyContext(Ivy ivy, IvyContext context) {
try {
return ModuleDescriptorParserRegistry.getInstance().parseDescriptor(ivy.getSettings(), ivyFile.toURI().toURL(),
ivy.getSettings().doValidate());
} catch (MalformedURLException e) {
logger.println("The URL is malformed : " + ivyFile);
return null;
} catch (ParseException e) {
logger.println("Parsing error while reading the ivy file " + ivyFile);
return null;
} catch (IOException e) {
logger.println("I/O error while reading the ivy file " + ivyFile);
return null;
}
}
});
moduleDescriptors.put(module, ivyFilePath.replace('\\', '/'));
}
List<IvyModuleInfo> infos = new ArrayList<IvyModuleInfo>();
List<ModuleDescriptor> sortedModuleDescriptors = ivy.sortModuleDescriptors(moduleDescriptors.keySet(), SortOptions.DEFAULT);
for (ModuleDescriptor moduleDescriptor : sortedModuleDescriptors) {
infos.add(new IvyModuleInfo(moduleDescriptor, moduleDescriptors.get(moduleDescriptor)));
}
if (verbose) {
for (IvyModuleInfo moduleInfo : infos) {
logger.printf("Discovered module %s at %s.\n", moduleInfo.displayName, moduleInfo.relativePathToDescriptor);
}
}
return infos;
}
/**
*
* @return the Ivy instance based on the {@link #ivyConfName}
* @throws AbortException
*
* @throws ParseException
* @throws IOException
*/
public Ivy getIvy(PrintStream logger) throws AbortException {
Message.setDefaultLogger(new IvyMessageImpl());
File settingsLoc = (ivySettingsFile == null) ? null : new File(workspaceProper, ivySettingsFile);
if ((settingsLoc != null) && (!settingsLoc.exists())) {
throw new AbortException(Messages.IvyModuleSetBuild_NoSuchIvySettingsFile(settingsLoc.getAbsolutePath()));
}
ArrayList<File> propertyFiles = new ArrayList<File>();
if (StringUtils.isNotBlank(ivySettingsPropertyFiles)) {
for (String file : ivySettingsPropertyFiles.split(",")) {
File propertyFile = new File(workspaceProper, file.trim());
if (!propertyFile.exists()) {
throw new AbortException(Messages.IvyModuleSetBuild_NoSuchPropertyFile(propertyFile.getAbsolutePath()));
}
propertyFiles.add(propertyFile);
}
}
try {
IvySettings ivySettings = new IvySettings();
for (File file : propertyFiles) {
ivySettings.loadProperties(file);
}
if (settingsLoc != null) {
ivySettings.load(settingsLoc);
if (verbose)
logger.println("Configured Ivy using custom settings " + settingsLoc.getAbsolutePath());
} else {
ivySettings.loadDefault();
if (verbose)
logger.println("Configured Ivy using default 2.1 settings");
}
if (ivyBranch != null) {
ivySettings.setDefaultBranch(ivyBranch);
}
return Ivy.newInstance(ivySettings);
} catch (Exception e) {
logger.println("Error while reading the default Ivy 2.1 settings: " + e.getMessage());
logger.println(e.getStackTrace());
}
return null;
}
private static final long serialVersionUID = 1L;
}
private static final Logger LOGGER = Logger.getLogger(IvyModuleSetBuild.class.getName());
/**
* Extra verbose debug switch.
*/
public static boolean debug = false;
@Override
public IvyModuleSet getParent() {// don't know why, but javac wants this
return super.getParent();
}
private static final class IvyPreloadTask implements Callable<Boolean, IOException> {
private static final long serialVersionUID = 1L;
public Boolean call() throws IOException {
try {
return Channel.current().preloadJar(this, Ivy.class);
} catch (InterruptedException e) {
}
return false;
}
}
}
|
package uk.org.whitecottage.ea.gnosis.repository.applications;
import java.awt.Color;
import java.awt.geom.Rectangle2D;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import org.apache.poi.xslf.usermodel.LineDecoration;
import org.apache.poi.xslf.usermodel.TextAlign;
import org.apache.poi.xslf.usermodel.VerticalAlignment;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFAutoShape;
import org.apache.poi.xslf.usermodel.XSLFConnectorShape;
import org.apache.poi.xslf.usermodel.XSLFShapeType;
import org.apache.poi.xslf.usermodel.XSLFSlide;
import org.apache.poi.xslf.usermodel.XSLFTextParagraph;
import org.apache.poi.xslf.usermodel.XSLFTextRun;
import org.exist.xmldb.EXistResource;
import org.xml.sax.SAXException;
import org.xmldb.api.base.Collection;
import org.xmldb.api.base.XMLDBException;
import org.xmldb.api.modules.XMLResource;
import uk.org.whitecottage.ea.gnosis.jaxb.applications.Application;
import uk.org.whitecottage.ea.gnosis.jaxb.applications.Applications;
import uk.org.whitecottage.ea.gnosis.jaxb.applications.Classification;
import uk.org.whitecottage.ea.gnosis.jaxb.applications.Investment;
import uk.org.whitecottage.ea.gnosis.jaxb.applications.Migration;
import uk.org.whitecottage.ea.gnosis.jaxb.applications.Stage;
import uk.org.whitecottage.ea.gnosis.jaxb.framework.Activity;
import uk.org.whitecottage.ea.gnosis.jaxb.framework.Capability;
import uk.org.whitecottage.ea.gnosis.jaxb.framework.CapabilityInstance;
import uk.org.whitecottage.ea.gnosis.jaxb.framework.Ecosystem;
import uk.org.whitecottage.ea.gnosis.jaxb.framework.Framework;
import uk.org.whitecottage.ea.gnosis.jaxb.framework.Milestone;
import uk.org.whitecottage.ea.gnosis.jaxb.framework.TechnologyDomain;
import uk.org.whitecottage.ea.gnosis.repository.roadmap.Timeline;
import uk.org.whitecottage.ea.xmldb.XmldbProcessor;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
public class LifecyclePresentation extends XmldbProcessor {
// Default page size is 720x540
protected double X0 = 69;
protected double Y0 = 40;
protected double DOMAIN_WIDTH = 60;
protected double DOMAIN_HEIGHT = 50;
protected double APP_WIDTH = 65;
protected double APP_HEIGHT = 16;
protected double STAGE_WIDTH = 97;
protected double INV_WIDTH = 40;
protected double INV_HEIGHT = 16;
protected double MILESTONE_WIDTH = 80;
protected double MILESTONE_HEIGHT = 16;
protected double MILESTONE = 10;
protected double CORNER = 10;
protected double H_SPACING = 5;
protected double V_SPACING = 5;
protected double MARKER = 5;
protected double COST_HEIGHT = 10;
protected double CONNECTOR = 3;
protected double LINE = 2;
protected double TUBE_LINE = 6;
protected double TEXT_OFFSET = 0;
protected double TEXT_WIDTH = 80;
protected double TITLE_WIDTH = 700;
protected double TITLE_HEIGHT = 40;
protected double TITLE_POSITION = 10;
protected double ARROW = 5;
protected int SUMMARY_PAGINATION = 7;
protected int PAGINATION = 16;
protected static final int CLR_CANDIDATE = 0xc020c0;
protected static final int CLR_EMERGING = 0x20c0c0;
protected static final int CLR_MAINSTREAM = 0x20c020;
protected static final int CLR_HERITAGE = 0x808080;
protected static final int CLR_SUNSET = 0xc0c020;
protected static final int CLR_RETIRE = 0xc02020;
protected static final int CLR_REMOVE = 0xc12020;
protected static final int CLR_UNKNOWN = 0x000000;
protected static final int CLR_DOMAIN = 0xe0e0e0;
protected static final int[] STAGE_CLRS = {
CLR_CANDIDATE, CLR_EMERGING, CLR_MAINSTREAM, CLR_HERITAGE, CLR_SUNSET, CLR_RETIRE, CLR_REMOVE, CLR_UNKNOWN
};
protected static final String[] STAGE_NAMES = {
"Candidate", "Emerging", "Mainstream", "Heritage", "Sunset", "Retire"
};
protected static final String[] STAGE_VALUES = {
"candidate", "emerging", "mainstream", "heritage", "sunset", "retire", "remove", "unknown"
};
protected Applications applications;
protected Framework framework;
protected List<String> capabilityFilter = null;
protected Unmarshaller applicationsUnmarshaller = null;
protected Marshaller applicationsMarshaller = null;
protected Unmarshaller frameworkUnmarshaller = null;
protected Marshaller frameworkMarshaller = null;
@SuppressWarnings("unused")
private static final Log log = LogFactoryUtil.getLog(LifecyclePresentation.class);
protected class EcosystemComparator implements Comparator<Application> {
@Override
public int compare(Application app1, Application app2) {
if (app1.getEcosystem().isEmpty()) {
if (app2.getEcosystem().isEmpty()) {
return 0;
} else {
return -1;
}
} else if (app2.getEcosystem().isEmpty()) {
return 1;
}
uk.org.whitecottage.ea.gnosis.jaxb.applications.Capability eco1 = app1.getEcosystem().get(0).getCapability().get(0);
uk.org.whitecottage.ea.gnosis.jaxb.applications.Capability eco2 = app2.getEcosystem().get(0).getCapability().get(0);
return compareEcosystem(eco1.getCapability(), eco2.getCapability());
}
protected int compareEcosystem(String eco1, String eco2) {
int i1 = ecosystemIndex(eco1);
int i2 = ecosystemIndex(eco2);
//log.info("Eco1: " + eco1 + " index: " + i1);
if (i1 < i2) {
return -1;
} else if (i1 == i2) {
return 0;
} else {
return 1;
}
}
protected int ecosystemIndex(String capability) {
int index = 0;
for (Activity a: framework.getValueChain().getPrimaryActivities().getActivity()) {
for (Ecosystem e: a.getEcosystem()) {
for (CapabilityInstance c: e.getCapabilityInstance()) {
if (c.getCapabilityId().equals(capability)) {
return index;
}
index++;
}
}
}
for (Activity a: framework.getValueChain().getSupportActivities().getActivity()) {
for (Ecosystem e: a.getEcosystem()) {
for (CapabilityInstance c: e.getCapabilityInstance()) {
if (c.getCapabilityId().equals(capability)) {
return index;
}
index++;
}
}
}
return -1;
}
}
public LifecyclePresentation(String URI, String repositoryRoot, String context) {
super(URI, repositoryRoot);
Collection repository = null;
XMLResource applicationsResource = null;
XMLResource frameworkResource = null;
try {
JAXBContext applicationsContext = JAXBContext.newInstance("uk.org.whitecottage.ea.gnosis.jaxb.applications");
applicationsUnmarshaller = createUnmarshaller(applicationsContext, context + "/WEB-INF/xsd/applications.xsd");
applicationsMarshaller = applicationsContext.createMarshaller();
JAXBContext frameworkContext = JAXBContext.newInstance("uk.org.whitecottage.ea.gnosis.jaxb.framework");
frameworkUnmarshaller = createUnmarshaller(frameworkContext, context + "/WEB-INF/xsd/framework.xsd");
frameworkMarshaller = frameworkContext.createMarshaller();
repository = getCollection("");
applicationsResource = getResource(repository, "applications.xml");
applications = (Applications) applicationsUnmarshaller.unmarshal(applicationsResource.getContentAsDOM());
frameworkResource = getResource(repository, "framework.xml");
framework = (uk.org.whitecottage.ea.gnosis.jaxb.framework.Framework) frameworkUnmarshaller.unmarshal(frameworkResource.getContentAsDOM());
} catch (JAXBException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (XMLDBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if(applicationsResource != null) {
try { ((EXistResource) applicationsResource).freeResources(); } catch(XMLDBException xe) {xe.printStackTrace();}
}
if(repository != null) {
try { repository.close(); } catch(XMLDBException xe) {xe.printStackTrace();}
}
}
}
public void setCapabilityFilter(String filter) {
if (filter == null || filter.isEmpty()) {
capabilityFilter = null;
return;
}
capabilityFilter = Arrays.asList(filter.split(","));
}
public void render(XMLSlideShow presentation) {
renderSummary(presentation);
renderRoadmap(presentation);
for (Activity activity: framework.getValueChain().getPrimaryActivities().getActivity()) {
renderTubemap(presentation, activity, 7);
}
for (Activity activity: framework.getValueChain().getPrimaryActivities().getActivity()) {
renderTubemap(presentation, activity, 6);
}
renderTubemap(presentation, null, 2);
}
protected boolean inCapabilityFilter(String capabilityId) {
if (capabilityFilter == null) {
return true;
}
return capabilityFilter.contains(capabilityId);
}
protected boolean inCapabilityFilter(Application app) {
if (capabilityFilter == null) {
return true;
}
for (Classification classification: app.getClassification()) {
if (inCapabilityFilter(classification.getCapability())) {
return true;
}
}
return false;
}
protected void renderSummary(XMLSlideShow presentation) {
XSLFSlide slide;
XSLFAutoShape shape;
List<TechnologyDomain> domains = new ArrayList<TechnologyDomain>();
domains.addAll(framework.getBusinessApplications().getTechnologyDomain());
domains.addAll(framework.getCommonServices().getTechnologyDomain());
domains.addAll(framework.getInfrastructure().getTechnologyDomain());
slide = presentation.createSlide();
summaryHeader(slide);
double y = Y0 + APP_HEIGHT;
int count = 0;
for (TechnologyDomain domain: domains) {
List<Capability> capabilities = new ArrayList<Capability>();
for (Capability c: domain.getCapability()) {
if (inCapabilityFilter(c.getCapabilityId())) {
capabilities.add(c);
}
}
if (capabilities.size() > 0) {
if (capabilities.size() + count > SUMMARY_PAGINATION) {
slide = presentation.createSlide();
summaryHeader(slide);
y = Y0 + APP_HEIGHT;
count = 0;
}
double domainHeight = capabilities.size() * DOMAIN_HEIGHT;
shape = textShape(slide, X0 - DOMAIN_WIDTH, y , DOMAIN_WIDTH, domainHeight, domain.getName(), 6.0);
shape.setFillColor(new Color(CLR_DOMAIN));
int offset = 0;
for (Capability capability: capabilities) {
if (inCapabilityFilter(capability.getCapabilityId())) {
shape = textShape(slide, X0, y + offset, DOMAIN_WIDTH, DOMAIN_HEIGHT, capability.getName(), 6.0);
shape.setFillColor(new Color(CLR_DOMAIN));
for (int k=0;k < STAGE_NAMES.length; k++) {
shape = textShape(slide, X0 + DOMAIN_WIDTH + k * STAGE_WIDTH, y + offset, STAGE_WIDTH, DOMAIN_HEIGHT,
getAppListByStage(STAGE_VALUES[k], capability, applications), 7.0);
shape.setFillColor(new Color(STAGE_CLRS[k] + 0x2f2f2f));
}
offset += DOMAIN_HEIGHT;
}
}
y += domainHeight;
count += capabilities.size();
}
}
}
protected void summaryHeader(XSLFSlide slide) {
XSLFAutoShape shape;
for (int i=0;i < STAGE_NAMES.length; i++) {
shape = textShape(slide, X0 + DOMAIN_WIDTH + i * STAGE_WIDTH, Y0, STAGE_WIDTH, APP_HEIGHT, STAGE_NAMES[i], 8.0);
shape.setFillColor(new Color(STAGE_CLRS[i]));
shape.getTextParagraphs().get(0).getTextRuns().get(0).setFontSize(8.0);
}
}
protected String getAppListByStage(String stage, Capability capability, Applications applications) {
List<Application> apps = applications.getApplication();
String list = "";
Iterator<Application> a = apps.iterator();
while (a.hasNext()) {
Application app = a.next();
if (providesCapability(app, capability)) {
Stage appStage = getCurrentStage(app);
if (appStage != null) {
if (appStage.getLifecycle().equals(stage)) {
if (list.length() > 0) {
list += ", ";
}
list += app.getName();
}
}
}
}
return list;
}
protected Stage getCurrentStage(Application app) {
Stage currentStage = new Stage();
currentStage.setLifecycle("unknown");
GregorianCalendar date = new GregorianCalendar();
List<Stage> stages = app.getStage();
Collections.sort(stages, new StageComparator());
Iterator<Stage> s = stages.iterator();
while (s.hasNext()) {
Stage stage = s.next();
if (stage.getDate() == null) {
currentStage = stage;
} else {
GregorianCalendar stageDate = stage.getDate().toGregorianCalendar();
if (stageDate.after(date)) {
return currentStage;
} else {
currentStage = stage;
}
}
}
return currentStage;
}
protected void renderRoadmap(XMLSlideShow presentation) {
List<TechnologyDomain> domains = new ArrayList<TechnologyDomain>();
domains.addAll(framework.getBusinessApplications().getTechnologyDomain());
domains.addAll(framework.getCommonServices().getTechnologyDomain());
domains.addAll(framework.getInfrastructure().getTechnologyDomain());
for (TechnologyDomain domain: domains) {
List<ApplicationGroup> groups = groupAppsByDomain(applications, domain, 2);
Iterator<ApplicationGroup> j = groups.iterator();
List<ApplicationGroup> groupPage = new ArrayList<ApplicationGroup>();
int count = 0;
while (j.hasNext()) {
ApplicationGroup group = j.next();
if (count != 0 && count + group.size() > PAGINATION) {
createSlide2(presentation.createSlide(), groupPage, domain);
groupPage = new ArrayList<ApplicationGroup>();
count = 0;
}
if (group.size() > PAGINATION) {
List<ApplicationGroup> splitGroups = group.split(PAGINATION);
Iterator<ApplicationGroup> k = splitGroups.iterator();
while (k.hasNext()) {
ApplicationGroup sgroup = k.next();
if (sgroup.size() + count > PAGINATION) {
createSlide2(presentation.createSlide(), groupPage, domain);
groupPage = new ArrayList<ApplicationGroup>();
count = 0;
}
groupPage.add(sgroup);
count += sgroup.size();
}
} else {
groupPage.add(group);
count += group.size();
}
}
if (count > 0) {
createSlide2(presentation.createSlide(), groupPage, domain);
}
}
}
protected void createSlide2(XSLFSlide slide, List<ApplicationGroup> groups, TechnologyDomain domain) {
XSLFAutoShape shape;
XSLFConnectorShape connector;
Timeline tl = new Timeline(X0 + APP_WIDTH + H_SPACING, Y0);
tl.setRange(3);
tl.setCalendar(true);
tl.addAll(getMilestones(domain));
header(slide, tl, domain.getName() + " roadmap");
double y = Y0 + 3 * tl.getHeight();
double ag = 0;
Iterator<ApplicationGroup> i = groups.iterator();
while (i.hasNext()) {
ApplicationGroup group = i.next();
if (group.size() > 0) {
double gs = group.size() * (APP_HEIGHT + V_SPACING) - V_SPACING;
shape = textShape(slide, X0 - DOMAIN_WIDTH, y, DOMAIN_WIDTH, gs, " " + group.getName(), 6.0);
shape.setLineColor(null);
shape.setFillColor(new Color(CLR_DOMAIN));
}
Iterator<Application> a = group.iterator();
while (a.hasNext()) {
Application app = a.next();
if (!app.getAppId().isEmpty()) {
Stage current = getCurrentStage(app);
shape = textShape(slide, X0 + H_SPACING, y , APP_WIDTH, APP_HEIGHT, " " + app.getName(), 6.0);
shape.setShapeType(XSLFShapeType.ROUND_RECT);
if (current == null) {
shape.setLineColor(new Color(0xaaaaaa));
} else {
shape.setLineColor(new Color(setColour(current.getLifecycle())));
}
}
List<Migration> migrations = app.getMigration();
Iterator<Migration> k = migrations.iterator();
while (k.hasNext()) {
Migration migration = k.next();
if (tl.contains(migration.getDate())) {
String to = migration.getTo();
int target = findApp2(group, to);
if (target >= 0) {
double yt = Y0 + 3 * tl.getHeight() + ((target + ag) % PAGINATION) * (APP_HEIGHT + V_SPACING);
//double xm = X0 + APP_WIDTH + H_SPACING + tl.position(migration.getDate()) + tl.getOffset();
double xm = X0 + APP_WIDTH + H_SPACING + tl.truePosition(migration.getDate());
if (yt != y) {
connector = slide.createConnector();
if (yt < y) {
connector.setAnchor(new Rectangle2D.Double(xm, yt + (APP_HEIGHT + MARKER) / 2, 0, y - yt - MARKER / 2));
connector.setFlipVertical(true);
} else {
connector.setAnchor(new Rectangle2D.Double(xm, y + APP_HEIGHT / 2, 0, yt - y - MARKER / 2));
}
connector.setLineColor(Color.black);
connector.setLineWidth(LINE);
connector.setLineHeadDecoration(LineDecoration.OVAL);
connector.setLineTailDecoration(LineDecoration.TRIANGLE);
}
}
}
}
List<Stage> stages = app.getStage();
Collections.sort(stages, new StageComparator());
int lineColour = 0xffffff;
double x = X0 + APP_WIDTH + H_SPACING;
double w0 = 0;
double mOffset = 0;
for (Stage stage: stages) {
int leadLineColour = lineColour;
if (tl.contains(stage.getDate())) {
lineColour = setColour(stage.getLifecycle());
if (stage.getDate() != null) {
//double w = tl.position(stage.getDate()) - w0;
double w = tl.truePosition(stage.getDate()) - w0;
double pOffset = 0;
//if (w0 == 0) {
// pOffset = tl.getOffset();
if (w > mOffset) {
connector = slide.createConnector();
connector.setAnchor(new Rectangle2D.Double(x + mOffset, y + APP_HEIGHT / 2, w + pOffset - mOffset, 0));
connector.setLineColor(new Color(leadLineColour));
connector.setLineWidth(LINE);
}
mOffset = MARKER / 2;
w0 += w;
x += w + pOffset;
marker(slide, x, y + APP_HEIGHT / 2, lineColour);
}
}
}
if (lineColour != CLR_REMOVE && stages.size() > 0) {
connector = slide.createConnector();
connector.setAnchor(new Rectangle2D.Double(x + mOffset, y + APP_HEIGHT / 2, tl.getWidth() + X0 + APP_WIDTH + H_SPACING - x - mOffset, 0));
connector.setLineColor(new Color(lineColour));
connector.setLineWidth(2.0);
}
List<Investment> investments = app.getInvestment();
Collections.sort(investments, new InvestmentComparator());
for (Investment inv: investments) {
BigInteger capital = inv.getCapital();
BigInteger runrate = inv.getRunrate();
if (tl.contains(inv.getDate())) {
if (inv.getDate() != null) {
//x = X0 + APP_WIDTH + H_SPACING + tl.position(inv.getDate());
x = X0 + APP_WIDTH + H_SPACING + tl.truePosition(inv.getDate());
investment(slide, x, y + APP_HEIGHT / 2, inv.getValue());
costs(slide, x + INV_WIDTH, y + APP_HEIGHT / 2, capital, runrate);
} else {
costs(slide, x, y + APP_HEIGHT / 2, capital, runrate);
}
}
}
y += APP_HEIGHT + V_SPACING;
}
ag += group.size();
}
}
protected void renderTubemap(XMLSlideShow presentation, Activity activity, int mask) {
XSLFSlide slide = null;
XSLFAutoShape shape;
Timeline tl = new Timeline(X0 + APP_WIDTH + H_SPACING, Y0);
tl.setRange(3);
tl.setCalendar(true);
//tl.addAll(getMilestones(domain));
double y = 0;
boolean createSlide = true;
boolean useFutureFilter = (mask & 1) != 0;
boolean useCapabilityFilter = (mask & 2) != 0;
boolean useActivityFilter = (mask & 4) != 0;
List<Application> appsList = applications.getApplication();
Collections.sort(appsList, new EcosystemComparator());
for (Application app: appsList) {
boolean include = (!useFutureFilter || isFuture(app));
include = include && (!useCapabilityFilter || inCapabilityFilter(app));
include = include && (!useActivityFilter || inValueChain(app, activity));
if (include) {
if (createSlide) {
String slideTitle = "Application Tube Map";
if (activity != null) {
slideTitle += ": " + activity.getName();
}
y = Y0 + 3 * tl.getHeight();
slide = presentation.createSlide();
header(slide, tl, slideTitle);
createSlide = false;
}
List<Stage> stages = app.getStage();
Collections.sort(stages, new StageComparator());
int lineColour = 0xffffff;
double x = X0 + APP_WIDTH + H_SPACING;
double w0 = 0;
for (Stage stage: stages) {
int leadLineColour = lineColour;
lineColour = setColour(stage.getLifecycle());
if (tl.contains(stage.getDate())) {
if (stage.getDate() != null) {
//double w = tl.position(stage.getDate()) - w0;
double w = tl.truePosition(stage.getDate()) - w0;
double pOffset = 0;
//if (w0 == 0) {
// pOffset = tl.getOffset();
shape = textShape(slide, x, y , w + pOffset, APP_HEIGHT, "", 6.0);
shape.setShapeType(XSLFShapeType.RECT);
shape.setFillColor(new Color(leadLineColour));
shape.setLineColor(null);
w0 += w;
x += w + pOffset;
}
}
}
if (lineColour != CLR_REMOVE) {
shape = textShape(slide, x, y , tl.getWidth() + X0 + APP_WIDTH + H_SPACING - x, APP_HEIGHT, "", 6.0);
shape.setShapeType(XSLFShapeType.RECT);
shape.setFillColor(new Color(lineColour));
shape.setLineColor(null);
}
List<Investment> investments = app.getInvestment();
Collections.sort(investments, new InvestmentComparator());
for (Investment inv: investments) {
if (tl.contains(inv.getDate())) {
if (inv.getDate() != null) {
//x = X0 + APP_WIDTH + H_SPACING + tl.position(inv.getDate());
x = X0 + APP_WIDTH + H_SPACING + tl.truePosition(inv.getDate());
milestone(slide, x , y + APP_HEIGHT / 2, inv.getValue());
}
}
}
Stage current = getCurrentStage(app);
shape = textShape(slide, X0 - DOMAIN_WIDTH + H_SPACING, y , APP_WIDTH + DOMAIN_WIDTH, APP_HEIGHT, " " + app.getName(), 6.0);
shape.setShapeType(XSLFShapeType.ROUND_RECT);
if (current == null) {
shape.setLineColor(new Color(0xaaaaaa));
} else {
shape.setLineColor(new Color(setColour(current.getLifecycle())));
}
y += APP_HEIGHT + V_SPACING;
if (y > 450.0) {
createSlide = true;
}
}
}
}
protected void header(XSLFSlide slide, Timeline tl, String domainName) {
XSLFAutoShape shape;
double tx = (720 - TITLE_WIDTH) / 2;
shape = textShape(slide, tx, TITLE_POSITION, TITLE_WIDTH, TITLE_HEIGHT, domainName, 28.0);
shape.setLineColor(null);
tl.render(slide);
}
protected static List<Milestone> getMilestones(TechnologyDomain domain) {
List<Milestone> milestones = new ArrayList<Milestone>();
for (uk.org.whitecottage.ea.gnosis.jaxb.framework.Milestone m: domain.getMilestone()) {
Milestone milestone = new Milestone();
milestone.setValue(m.getValue());
milestone.setDate(m.getDate());
milestones.add(milestone);
}
for (Capability c: domain.getCapability()) {
milestones.addAll(getMilestones(c));
}
return milestones;
}
protected static List<Milestone> getMilestones(Capability capability) {
List<Milestone> milestones = new ArrayList<Milestone>();
for (Milestone m: capability.getMilestone()) {
Milestone milestone = new Milestone();
milestone.setValue(m.getValue());
milestone.setDate(m.getDate());
milestones.add(milestone);
}
return milestones;
}
protected static int findApp(List<Application> applications, String id) {
for (int i=0;i<applications.size();i++) {
if (applications.get(i).getAppId().equals(id)) {
return i;
}
}
return -1;
}
protected static int findApp2(ApplicationGroup group, String id) {
for (int i=0;i<group.getApplications().size();i++) {
if (group.getApplications().get(i) == null) {
} else if (group.getApplications().get(i).getAppId().equals(id)) {
return i;
}
}
return -1;
}
protected XSLFAutoShape textShape(XSLFSlide slide, double x, double y, double width, double height, String label, double size) {
XSLFAutoShape shape;
XSLFTextParagraph labelPara;
XSLFTextRun labelText;
shape = slide.createAutoShape();
shape.setShapeType(XSLFShapeType.RECT);
shape.setAnchor(new Rectangle2D.Double(x, y , width, height));
shape.setLineColor(Color.black);
labelPara = shape.addNewTextParagraph();
labelPara.setTextAlign(TextAlign.CENTER);
labelText = labelPara.addNewTextRun();
labelText.setText(label);
labelText.setFontSize(size);
shape.setVerticalAlignment(VerticalAlignment.MIDDLE);
return shape;
}
protected void arrow(XSLFSlide slide, double x, double y, boolean up) {
XSLFAutoShape shape;
double xo = ARROW / 2;
double height = ARROW * 14 / 10;
double yo = height / 2;
shape = slide.createAutoShape();
shape.setShapeType(XSLFShapeType.TRIANGLE);
shape.setLineColor(Color.black);
shape.setAnchor(new Rectangle2D.Double(x - xo, y - yo, ARROW, height));
if (!up) {
shape.setFlipVertical(true);
}
shape.setLineWidth(LINE);
}
protected void marker(XSLFSlide slide, double x, double y, int colour) {
XSLFAutoShape shape;
double marker = MARKER;
shape = slide.createAutoShape();
shape.setShapeType(XSLFShapeType.ELLIPSE);
shape.setLineColor(new Color(colour));
shape.setLineWidth(LINE);
if (colour == CLR_REMOVE) {
marker = MARKER * 2;
shape.setFillColor(Color.white);
} else {
shape.setFillColor(new Color(colour));
}
shape.setAnchor(new Rectangle2D.Double(x - marker / 2, y - marker / 2, marker, marker));
if (colour == CLR_REMOVE) {
XSLFConnectorShape connector;
double o = marker / 2.82842;
connector = slide.createConnector();
connector.setAnchor(new Rectangle2D.Double(x - o, y - o, 2 * o, 2 * o));
connector.setLineColor(new Color(colour));
connector.setLineWidth(LINE);
}
}
protected void investment(XSLFSlide slide, double x, double y, String text) {
XSLFAutoShape shape;
shape = textShape(slide, x, y - INV_HEIGHT / 2 , INV_WIDTH, INV_HEIGHT, text, 3.0);
shape.setShapeType(XSLFShapeType.ROUND_RECT);
shape.setFillColor(new Color(0xffffff));
}
protected void milestone(XSLFSlide slide, double x, double y, String text) {
XSLFAutoShape shape;
shape = textShape(slide, x, y - MILESTONE / 2 , MILESTONE, MILESTONE, "", 3.0);
shape.setShapeType(XSLFShapeType.RECT);
shape.setRotation(45.0);
shape.setFillColor(new Color(0x000000));
shape = textShape(slide, x + 20, y - (10 + MILESTONE_HEIGHT), MILESTONE_WIDTH, MILESTONE_HEIGHT, text, 4.0);
shape.setShapeType(XSLFShapeType.RECT);
shape.setFillColor(new Color(0xffff66));
XSLFConnectorShape connector;
connector = slide.createConnector();
connector.setAnchor(new Rectangle2D.Double(x + MILESTONE/2, y - (10 + MILESTONE_HEIGHT/2), 0, 10 + MILESTONE_HEIGHT/2));
connector.setLineColor(new Color(0x000000));
connector.setLineWidth(LINE);
connector = slide.createConnector();
connector.setAnchor(new Rectangle2D.Double(x + MILESTONE/2, y - (10 + MILESTONE_HEIGHT/2), 20 - MILESTONE/2, 0));
connector.setLineColor(new Color(0x000000));
connector.setLineWidth(LINE);
}
protected void costs(XSLFSlide slide, double x, double y, BigInteger capital, BigInteger runrate) {
XSLFAutoShape shape;
XSLFTextParagraph labelPara;
XSLFTextRun labelText;
String label;
if (capital != null) {
label = "£" + capital + "k";
} else {
label = "£???k";
}
shape = slide.createAutoShape();
shape.setAnchor(new Rectangle2D.Double(x, y, TEXT_WIDTH, COST_HEIGHT));
labelPara = shape.addNewTextParagraph();
labelPara.setTextAlign(TextAlign.LEFT);
labelText = labelPara.addNewTextRun();
labelText.setText(label);
labelText.setFontSize(6.0);
labelText.setFontColor(new Color(CLR_HERITAGE));
shape.setVerticalAlignment(VerticalAlignment.MIDDLE);
if (runrate != null) {
label = "£" + runrate + "k p.a.";
} else {
label = "£???k p.a.";
}
shape = slide.createAutoShape();
shape.setAnchor(new Rectangle2D.Double(x + TEXT_OFFSET, y - COST_HEIGHT, TEXT_WIDTH, COST_HEIGHT));
labelPara = shape.addNewTextParagraph();
labelPara.setTextAlign(TextAlign.LEFT);
labelText = labelPara.addNewTextRun();
labelText.setText(label);
labelText.setFontSize(6.0);
labelText.setFontColor(new Color(CLR_HERITAGE));
shape.setVerticalAlignment(VerticalAlignment.MIDDLE);
}
protected int setColour(String s) {
if (s.equals("candidate")) {
return CLR_CANDIDATE;
}
if (s.equals("emerging")) {
return CLR_EMERGING;
}
if (s.equals("mainstream")) {
return CLR_MAINSTREAM;
}
if (s.equals("heritage")) {
return CLR_HERITAGE;
}
if (s.equals("sunset")) {
return CLR_SUNSET;
}
if (s.equals("retire")) {
return CLR_RETIRE;
}
if (s.equals("remove")) {
return CLR_REMOVE;
}
return CLR_UNKNOWN;
}
protected List<ApplicationGroup> groupAppsByDomain(Applications applications, TechnologyDomain domain, int level) {
List<ApplicationGroup> groups = new ArrayList<ApplicationGroup>();
List<Capability> capabilities = domain.getCapability();
for (Capability capability: capabilities) {
ApplicationGroup g = new ApplicationGroup();
g.setId(capability.getCapabilityId());
g.setName(capability.getName());
for (Application app: applications.getApplication()) {
if (providesCapability(app, capability) && inCapabilityFilter(capability.getCapabilityId())) {
g.add(app);
}
}
groups.add(g);
}
return groups;
}
protected boolean isFuture(Application app) {
Stage stage = getCurrentStage(app);
if (stage.getLifecycle().equals(STAGE_VALUES[0]) || stage.getLifecycle().equals(STAGE_VALUES[1]) || stage.getLifecycle().equals(STAGE_VALUES[2]) || stage.getLifecycle().equals("unknown")) {
return true;
} else {
return false;
}
}
protected boolean providesCapability(Application app, Capability capability) {
Iterator<Classification> c = app.getClassification().iterator();
while (c.hasNext()) {
if (c.next().getCapability().equals(capability.getCapabilityId())) {
return true;
}
}
return false;
}
protected boolean inEcosystem(Application app, Ecosystem ecosystem) {
for (uk.org.whitecottage.ea.gnosis.jaxb.applications.Ecosystem e: app.getEcosystem()) {
if (e.getEcosystem().equals(ecosystem.getEcosystemId())) {
return true;
}
}
return false;
}
protected boolean inValueChain(Application app, Activity activity) {
for (Ecosystem ecosystem: activity.getEcosystem()) {
if (inEcosystem(app, ecosystem)) {
return true;
}
}
return false;
}
}
|
package io.egen.service;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import io.egen.entity.Admin;
import io.egen.entity.BrowseList;
import io.egen.entity.Comments;
import io.egen.entity.User;
import io.egen.util.DBUtils;
import org.springframework.stereotype.Service;
@Service
public class AdminService {
public Boolean validate(Admin admin){
boolean st =false;
try{
DBUtils db = new DBUtils();
Connection con=db.connect();
PreparedStatement ps =con.prepareStatement("select userid from admin where userid='"+admin.getUserid()+"' and password='"+admin.getPassword()+"'");
ResultSet rs =ps.executeQuery();
st = rs.next();
}catch(Exception e)
{
e.printStackTrace();
}
return st;
}
public Admin getdetails(Admin admin){
try{
//loading drivers for mysql
DBUtils db = new DBUtils();
//creating connection with the database
Connection con=db.connect();
PreparedStatement ps =con.prepareStatement("select * from admin where userid='"+admin.getUserid()+"' and password='"+admin.getPassword()+"'");
ResultSet rs =ps.executeQuery();
while (rs.next()) {
admin.setFirstName(rs.getString("firstname"));
admin.setLastName(rs.getString("lastname"));
}
}catch(Exception e)
{
e.printStackTrace();
}
return admin;
}
public void addTitle(BrowseList bl) {
String query = "insert into movie values ('"+bl.getImdbId()+"','"+bl.getActors()+"','"+bl.getAwards()+"','"+bl.getCountry()+"','"+bl.getDirector()+"','"+bl.getGenre()+"','"+bl.getLanguage()+"','"+bl.getMetascore()+"','"+bl.getPlot()+"','"+bl.getPoster()+"','"+bl.getRated()+"','"+bl.getReleased()+"','"+bl.getRuntime()+"','"+bl.getTitle()+"','"+bl.getType()+"','"+bl.getWriter()+"','"+bl.getYear()+"','"+bl.getImdbRating()+"','"+bl.getImdbVotes()+"')";
//System.out.println(query);
Connection con = DBUtils.connect();
Statement st = null;
try {
st = con.createStatement();
st.executeUpdate(query);
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public void editTitle(String attName,String attVal,String imdbId) {
String query = "UPDATE Movie SET "+attName+" ='"+attVal+"'where imdbid = '"+imdbId+"'";
//System.out.println(query);
Connection con = DBUtils.connect();
Statement st = null;
try {
st = con.createStatement();
st.executeUpdate(query);
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public void deleteTitle(String imdbId) {
String query = "DELETE FROM Movie WHERE imdbid = '"+imdbId+"'";
//System.out.println(query);
Connection con = DBUtils.connect();
Statement st = null;
try {
st = con.createStatement();
st.executeUpdate(query);
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
|
package org.techern.infinitewater.blocks;
import net.minecraft.block.Block;
import net.minecraft.block.BlockLiquid;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import org.techern.infinitewater.InfinitelySpreadingWaterMod;
import java.util.Random;
/**
* A {@link Block} for infinitely spreading water
*
* @since 1.0.0
*/
public class BlockInfinitelySpreadingWater extends Block {
/**
* Creates a new {@link BlockInfinitelySpreadingWater}
*
* @since 1.0.0
*/
public BlockInfinitelySpreadingWater() {
super(Material.BARRIER);
this.setCreativeTab(CreativeTabs.MISC);
this.setUnlocalizedName("infinitely_spreading_water");
this.setRegistryName("infinitely_spreading_water");
this.setBlockUnbreakable();
}
/**
* Called on a tick
*
* @param worldIn The {@link World} we're in
* @param pos The {@link BlockPos} of this {@link BlockInfinitelySpreadingWater}
* @param state The current {@link IBlockState}
* @param rand The {@link Random} attach to the tick
*
* @since 1.0.0
*/
@Override
public void updateTick(World worldIn, BlockPos pos, IBlockState state, Random rand) {
super.updateTick(worldIn, pos, state, rand);
//Let's expand
expand(worldIn, pos.north());
expand(worldIn, pos.south());
expand(worldIn, pos.east());
expand(worldIn, pos.west());
worldIn.setBlockState(pos, Blocks.WATER.getStateFromMeta(0));
}
/**
* Attempt to expand by just replacing air
*
* @param world The {@link World}
* @param position The {@link BlockPos} to replace
*
* @since 1.0.0
*/
private void expand(World world, BlockPos position) {
IBlockState state = world.getBlockState(position);
if (state.equals(Blocks.AIR.getDefaultState())) {
world.setBlockState(position, getDefaultState());
world.scheduleBlockUpdate(position, this, 20, 1);
}
}
/**
* Called when this {@link BlockInfinitelySpreadingWater} is placed
*
* @param worldIn The {@link World}
* @param pos The {@link BlockPos}
* @param state The {@link IBlockState}
* @param placer The {@link EntityLivingBase} that placed this {@link BlockInfinitelySpreadingWater}
* @param stack The {@link ItemStack} used to place
*/
@Override
public void onBlockPlacedBy(World worldIn, BlockPos pos, IBlockState state, EntityLivingBase placer, ItemStack stack) {
super.onBlockPlacedBy(worldIn, pos, state, placer, stack);
worldIn.scheduleBlockUpdate(pos, this, 100, 2);
}
}
|
package io.jboot.aop;
import com.jfinal.aop.AopFactory;
import com.jfinal.aop.Inject;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Singleton;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Model;
import io.jboot.aop.annotation.Bean;
import io.jboot.aop.annotation.BeanExclude;
import io.jboot.aop.annotation.ConfigValue;
import io.jboot.app.config.JbootConfigManager;
import io.jboot.app.config.annotation.ConfigModel;
import io.jboot.components.event.JbootEventListener;
import io.jboot.components.mq.JbootmqMessageListener;
import io.jboot.components.rpc.Jbootrpc;
import io.jboot.components.rpc.JbootrpcManager;
import io.jboot.components.rpc.JbootrpcServiceConfig;
import io.jboot.components.rpc.annotation.RPCInject;
import io.jboot.db.model.JbootModel;
import io.jboot.service.JbootServiceBase;
import io.jboot.utils.AnnotationUtil;
import io.jboot.utils.ArrayUtil;
import io.jboot.utils.ClassScanner;
import io.jboot.utils.StrUtil;
import io.jboot.web.controller.JbootController;
import io.jboot.web.fixedinterceptor.FixedInterceptor;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class JbootAopFactory extends AopFactory {
private JbootAopInterceptor aopInterceptor = new JbootAopInterceptor();
protected ThreadLocal<HashMap<Class<?>, Object>> singletonTl = ThreadLocal.withInitial(() -> new HashMap<>());
protected ThreadLocal<HashMap<Class<?>, Object>> prototypeTl = ThreadLocal.withInitial(() -> new HashMap<>());
public JbootAopFactory() {
initBeanMapping();
}
@Override
protected <T> T doGet(Class<T> targetClass, int injectDepth) throws ReflectiveOperationException {
return doGet(targetClass);
}
@SuppressWarnings("unchecked")
protected <T> T doGet(Class<T> targetClass) throws ReflectiveOperationException {
targetClass = (Class<T>) getMappingClass(targetClass);
Singleton si = targetClass.getAnnotation(Singleton.class);
boolean singleton = (si != null ? si.value() : this.singleton);
if (singleton) {
return doGetSingleton(targetClass);
} else {
return doGetPrototype(targetClass);
}
}
@SuppressWarnings("unchecked")
protected <T> T doGetSingleton(Class<T> targetClass) throws ReflectiveOperationException {
Object ret = singletonCache.get(targetClass);
if (ret != null) {
return (T) ret;
}
ret = singletonTl.get().get(targetClass);
if (ret != null) {
return (T) ret;
}
synchronized (this) {
ret = singletonCache.get(targetClass);
if (ret == null) {
try {
ret = createObject(targetClass);
singletonTl.get().put(targetClass, ret);
doInject(targetClass, ret);
singletonCache.put(targetClass, ret);
} finally {
singletonTl.remove();
}
}
}
return (T) ret;
}
@SuppressWarnings("unchecked")
protected <T> T doGetPrototype(Class<T> targetClass) throws ReflectiveOperationException {
Object ret;
HashMap<Class<?>, Object> map = prototypeTl.get();
if (map.size() > 0) {
ret = map.get(targetClass);
if (ret != null) {
return (T) ret;
}
}
try {
ret = createObject(targetClass);
map.put(targetClass, ret);
doInject(targetClass, ret);
} finally {
map.clear();
}
return (T) ret;
}
@Override
protected Object createObject(Class<?> targetClass) {
ConfigModel configModel = targetClass.getAnnotation(ConfigModel.class);
return configModel != null
? JbootConfigManager.me().get(targetClass)
: com.jfinal.aop.Enhancer.enhance(targetClass, aopInterceptor);
}
@Override
protected void doInject(Class<?> targetClass, Object targetObject, int injectDepth) throws ReflectiveOperationException {
doInject(targetClass, targetObject);
}
protected void doInject(Class<?> targetClass, Object targetObject) throws ReflectiveOperationException {
targetClass = getUsefulClass(targetClass);
// Field[] fields = targetClass.getDeclaredFields();
List<Field> fields = new ArrayList<>();
doGetFields(targetClass, fields);
if (fields.size() == 0) {
return;
}
for (Field field : fields) {
// Inject inject = field.getAnnotation(Inject.class);
// if (inject == null) {
// continue ;
// Class<?> fieldInjectedClass = inject.value();
// if (fieldInjectedClass == Void.class) {
// fieldInjectedClass = field.getType();
// Object fieldInjectedObject = doGet(fieldInjectedClass, injectDepth);
// field.setAccessible(true);
// field.set(targetObject, fieldInjectedObject);
Inject inject = field.getAnnotation(Inject.class);
if (inject != null) {
doInjectJFinalOrginal(targetObject, field, inject);
continue;
}
ConfigValue configValue = field.getAnnotation(ConfigValue.class);
if (configValue != null) {
doInjectConfigValue(targetObject, field, configValue);
continue;
}
RPCInject rpcInject = field.getAnnotation(RPCInject.class);
if (rpcInject != null) {
doInjectRPC(targetObject, field, rpcInject);
continue;
}
}
}
private void doGetFields(Class clazz, List<Field> fields) {
Field[] fs = clazz.getDeclaredFields();
if (fs.length > 0) {
for (Field field : fs) fields.add(field);
}
Class supperClass = clazz.getSuperclass();
if (supperClass == JbootController.class
|| supperClass == Controller.class
|| supperClass == JbootServiceBase.class
|| supperClass == Interceptor.class
|| supperClass == FixedInterceptor.class
|| supperClass == JbootModel.class
|| supperClass == Model.class
|| supperClass == Object.class
|| supperClass == null) {
return;
}
doGetFields(supperClass, fields);
}
/**
* JFinal service
*
* @param targetObject
* @param field
* @param inject
* @throws ReflectiveOperationException
*/
private void doInjectJFinalOrginal(Object targetObject, Field field, Inject inject) throws ReflectiveOperationException {
Class<?> fieldInjectedClass = inject.value();
if (fieldInjectedClass == Void.class) {
fieldInjectedClass = field.getType();
}
Object fieldInjectedObject = doGet(fieldInjectedClass);
field.setAccessible(true);
field.set(targetObject, fieldInjectedObject);
}
private void doInjectRPC(Object targetObject, Field field, RPCInject rpcInject) throws IllegalAccessException {
JbootrpcServiceConfig serviceConfig = new JbootrpcServiceConfig(rpcInject);
Class<?> fieldInjectedClass = field.getType();
Jbootrpc jbootrpc = JbootrpcManager.me().getJbootrpc();
Object fieldInjectedObject = jbootrpc.serviceObtain(fieldInjectedClass, serviceConfig);
field.setAccessible(true);
field.set(targetObject, fieldInjectedObject);
}
private void doInjectConfigValue(Object targetObject, Field field, ConfigValue configValue) throws IllegalAccessException {
String key = AnnotationUtil.get(configValue.value());
Class<?> fieldInjectedClass = field.getType();
String value = getConfigValue(key, targetObject, field);
if (StrUtil.isNotBlank(value)) {
Object fieldInjectedObject = JbootConfigManager.me().convert(fieldInjectedClass, value);
field.setAccessible(true);
field.set(targetObject, fieldInjectedObject);
return;
}
if (configValue.requireNullOrBlank()) {
field.setAccessible(true);
if (fieldInjectedClass == int.class) {
field.set(targetObject, 0);
} else if (fieldInjectedClass == boolean.class) {
field.set(targetObject, false);
} else {
field.set(targetObject, null);
}
}
}
private String getConfigValue(String key, Object targetObject, Field field) {
int indexOf = key.indexOf(":");
String defaultValue = null;
if (indexOf != -1) {
defaultValue = key.substring(indexOf + 1);
key = key.substring(0, indexOf);
}
if (StrUtil.isBlank(key)) {
throw new RuntimeException("can not inject config by empty key in " + targetObject.getClass() + ":" + field.getName());
}
String configValue = JbootConfigManager.me().getConfigValue(key.trim());
return StrUtil.isBlank(configValue) ? defaultValue : configValue;
}
private static Class[] default_excludes = new Class[]{JbootEventListener.class, JbootmqMessageListener.class, Serializable.class};
/**
* @Bean
*/
private void initBeanMapping() {
List<Class> classes = ClassScanner.scanClassByAnnotation(Bean.class, true);
for (Class implClass : classes) {
Class<?>[] interfaceClasses = implClass.getInterfaces();
if (interfaceClasses == null || interfaceClasses.length == 0) {
continue;
}
Class[] excludes = buildExcludeClasses(implClass);
for (Class interfaceClass : interfaceClasses) {
if (inExcludes(interfaceClass, excludes) == false) {
this.addMapping(interfaceClass, implClass);
}
}
}
}
private Class[] buildExcludeClasses(Class implClass) {
BeanExclude beanExclude = (BeanExclude) implClass.getAnnotation(BeanExclude.class);
// Serializable
return beanExclude == null
? default_excludes
: ArrayUtil.concat(default_excludes, beanExclude.value());
}
private boolean inExcludes(Class interfaceClass, Class[] excludes) {
for (Class ex : excludes) {
if (ex.isAssignableFrom(interfaceClass)) {
return true;
}
}
return false;
}
}
|
package permafrost.tundra.server.content;
import com.wm.app.b2b.server.ContentHandler;
import com.wm.app.b2b.server.HTTPState;
import com.wm.app.b2b.server.InvokeState;
import com.wm.app.b2b.server.ProtocolInfoIf;
import com.wm.app.b2b.server.ProtocolState;
import com.wm.net.HttpHeader;
import com.wm.util.Values;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.zip.GZIPInputStream;
public class HTTPCompressionContentHandler extends ProxyContentHandler {
public HTTPCompressionContentHandler(ContentHandler handler) {
super(handler);
}
/**
* Reads input for service invocation. Turns properly formatted input into an instance of Values
* suitable for service invocation. Called before service invocation to provide input. If the
* transport is HTTP, and a Content-Encoding header was specified with the value "gzip", the
* stream is first gzip decompressed before the proxy handler is invoked.
*
* @param inputStream The input stream from which to read.
* @param invokeState The current invocation state (such as the current user).
* @return The prepared service invocation input pipeline.
* @throws IOException If an error occurs reading from the input stream.
*/
public Values getInputValues(InputStream inputStream, InvokeState invokeState) throws IOException {
if (inputStream != null && invokeState != null) {
ProtocolInfoIf protocolInfoIf = invokeState.getProtocolInfoIf();
if (protocolInfoIf instanceof HTTPState) {
HTTPState httpState = (HTTPState)protocolInfoIf;
HttpHeader headers = httpState.getRequestHeader();
if (headers != null) {
String contentEncoding = headers.getFieldValue(HttpHeader.CONTENT_ENCODING);
if (contentEncoding != null && contentEncoding.trim().equalsIgnoreCase("gzip")) {
inputStream = new GZIPInputStream(inputStream);
headers.clearField(HttpHeader.CONTENT_ENCODING);
// regenerate the transport info stored in the protocol state
try {
// use reflection to invoke protected method initProtocolProps
Method initProtocolProps = ProtocolState.class.getDeclaredMethod("initProtocolProps");
initProtocolProps.setAccessible(true);
initProtocolProps.invoke(httpState);
} catch (NoSuchMethodException ex) {
throw new RuntimeException(ex);
} catch (IllegalAccessException ex) {
throw new RuntimeException(ex);
} catch (InvocationTargetException ex) {
throw new RuntimeException(ex);
}
}
}
}
}
return super.getInputValues(inputStream, invokeState);
}
}
|
package techreborn.blockentity.storage.item;
import net.minecraft.block.BlockState;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.text.LiteralText;
import net.minecraft.text.Text;
import net.minecraft.text.TranslatableText;
import net.minecraft.util.Formatting;
import net.minecraft.util.Identifier;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Direction;
import net.minecraft.util.registry.Registry;
import net.minecraft.world.World;
import reborncore.api.IListInfoProvider;
import reborncore.api.IToolDrop;
import reborncore.api.blockentity.InventoryProvider;
import reborncore.client.screen.BuiltScreenHandlerProvider;
import reborncore.client.screen.builder.BuiltScreenHandler;
import reborncore.client.screen.builder.ScreenHandlerBuilder;
import reborncore.common.blockentity.MachineBaseBlockEntity;
import reborncore.common.util.ItemUtils;
import reborncore.common.util.RebornInventory;
import reborncore.common.util.WorldUtils;
import techreborn.init.TRBlockEntities;
import techreborn.init.TRContent;
import javax.annotation.Nullable;
import java.util.List;
public class StorageUnitBaseBlockEntity extends MachineBaseBlockEntity implements InventoryProvider, IToolDrop, IListInfoProvider, BuiltScreenHandlerProvider {
// Inventory constants
public static final int INPUT_SLOT = 0;
public static final int OUTPUT_SLOT = 1;
// Client sync variables for GUI, what and how much stored
public int storedAmount = 0;
protected RebornInventory<StorageUnitBaseBlockEntity> inventory;
private int maxCapacity;
private ItemStack storeItemStack;
private TRContent.StorageUnit type;
// A locked storage unit will continue behaving as if it contains
// the locked-in item, even if the stored amount drops to zero.
private ItemStack lockedItemStack = ItemStack.EMPTY;
public StorageUnitBaseBlockEntity() {
super(TRBlockEntities.STORAGE_UNIT);
}
public StorageUnitBaseBlockEntity(TRContent.StorageUnit type) {
super(TRBlockEntities.STORAGE_UNIT);
configureEntity(type);
}
private void configureEntity(TRContent.StorageUnit type) {
this.maxCapacity = type.capacity;
storeItemStack = ItemStack.EMPTY;
inventory = new RebornInventory<>(2, "ItemInventory", 64, this);
this.type = type;
}
// TileMachineBase
@Override
public void tick() {
super.tick();
if (world == null || world.isClient) {
return;
}
// If there is an item in the input AND stored is less than max capacity
if (!inventory.getStack(INPUT_SLOT).isEmpty() && !isFull()) {
inventory.setStack(INPUT_SLOT, processInput(inventory.getStack(INPUT_SLOT)));
}
// Fill output slot with goodies when stored has items and output count is less than max stack size
if (storeItemStack.getCount() > 0 && inventory.getStack(OUTPUT_SLOT).getCount() < getStoredStack().getMaxCount()) {
populateOutput();
}
if (type == TRContent.StorageUnit.CREATIVE) {
if (!isFull() && !isEmpty()) {
fillToCapacity();
}
}
if (inventory.hasChanged()) {
syncWithAll();
inventory.resetChanged();
}
}
private void populateOutput() {
// Set to storeItemStack to get the stack type
ItemStack output = storeItemStack.copy();
int outputSlotCount = inventory.getStack(OUTPUT_SLOT).getCount();
// Set to current outputSlot count
output.setCount(outputSlotCount);
// Calculate amount needed to fill stack in output slot
int amountToFill = getStoredStack().getMaxCount() - outputSlotCount;
if (storeItemStack.getCount() >= amountToFill) {
storeItemStack.decrement(amountToFill);
if (storeItemStack.isEmpty()) {
storeItemStack = ItemStack.EMPTY;
}
output.increment(amountToFill);
} else {
output.increment(storeItemStack.getCount());
storeItemStack = ItemStack.EMPTY;
}
inventory.setStack(OUTPUT_SLOT, output);
}
private void addStoredItemCount(int amount) {
storeItemStack.increment(amount);
}
public ItemStack getStoredStack() {
return storeItemStack.isEmpty() ? inventory.getStack(OUTPUT_SLOT) : storeItemStack;
}
public void setStoredStack(ItemStack itemStack) {
storeItemStack = itemStack;
}
// Returns the ItemStack to be displayed to the player via UI / model
public ItemStack getDisplayedStack() {
if (!isLocked()) {
return getStoredStack();
} else {
// Render the locked stack even if the unit is empty
return lockedItemStack;
}
}
public ItemStack getAll() {
ItemStack returnStack = ItemStack.EMPTY;
if (!isEmpty()) {
returnStack = getStoredStack().copy();
returnStack.setCount(getCurrentCapacity());
}
return returnStack;
}
public ItemStack processInput(ItemStack inputStack) {
boolean isSameStack = isSameType(inputStack);
if (storeItemStack == ItemStack.EMPTY && (isSameStack || (getCurrentCapacity() == 0 && !isLocked()))) {
// Check if storage is empty, NOT including the output slot
storeItemStack = inputStack.copy();
if (inputStack.getCount() <= maxCapacity) {
inputStack = ItemStack.EMPTY;
} else {
// Stack is higher than capacity
storeItemStack.setCount(maxCapacity);
inputStack.decrement(maxCapacity);
}
} else if (isSameStack) {
// Not empty but same type
// Amount of items that can be added before reaching capacity
int reminder = maxCapacity - getCurrentCapacity();
if (inputStack.getCount() <= reminder) {
// Add full stack
addStoredItemCount(inputStack.getCount());
inputStack = ItemStack.EMPTY;
} else {
// Add only what is needed to reach max capacity
addStoredItemCount(reminder);
inputStack.decrement(reminder);
}
}
inventory.setChanged();
return inputStack;
}
public boolean isSameType(ItemStack inputStack) {
if (isLocked()) {
return ItemUtils.isItemEqual(lockedItemStack, inputStack, true, true);
}
if (inputStack != ItemStack.EMPTY) {
return ItemUtils.isItemEqual(getStoredStack(), inputStack, true, true);
}
return false;
}
// Creative function
private void fillToCapacity() {
storeItemStack = getStoredStack();
storeItemStack.setCount(maxCapacity);
inventory.setStack(OUTPUT_SLOT, ItemStack.EMPTY);
}
public boolean isFull() {
return getCurrentCapacity() == maxCapacity;
}
public boolean isEmpty() {
return getCurrentCapacity() == 0;
}
@Override
public boolean canInsert(int index, ItemStack stack, @Nullable Direction direction) {
return super.canInsert(index, stack, direction) && (this.isEmpty() && !isLocked() || isSameType(stack));
}
public int getCurrentCapacity() {
return storeItemStack.getCount() + inventory.getStack(OUTPUT_SLOT).getCount();
}
public int getMaxCapacity() {
return maxCapacity;
}
// Other stuff
@Override
public boolean canBeUpgraded() {
return false;
}
@Override
public void fromTag(BlockState blockState, CompoundTag tagCompound) {
super.fromTag(blockState, tagCompound);
if (tagCompound.contains("unitType")) {
this.type = TRContent.StorageUnit.valueOf(tagCompound.getString("unitType"));
configureEntity(type);
} else {
this.type = TRContent.StorageUnit.QUANTUM;
}
storeItemStack = ItemStack.EMPTY;
if (tagCompound.contains("storedStack")) {
storeItemStack = ItemStack.fromTag(tagCompound.getCompound("storedStack"));
}
if (!storeItemStack.isEmpty()) {
storeItemStack.setCount(Math.min(tagCompound.getInt("storedQuantity"), this.maxCapacity));
}
// Renderer only
if (tagCompound.contains("totalStoredAmount")) {
storedAmount = tagCompound.getInt("totalStoredAmount");
}
if (tagCompound.contains("lockedItem")) {
lockedItemStack = ItemStack.fromTag(tagCompound.getCompound("lockedItem"));
}
inventory.read(tagCompound);
}
@Override
public CompoundTag toTag(CompoundTag tagCompound) {
super.toTag(tagCompound);
tagCompound.putString("unitType", this.type.name());
if (!storeItemStack.isEmpty()) {
ItemStack temp = storeItemStack.copy();
if (storeItemStack.getCount() > storeItemStack.getMaxCount()) {
temp.setCount(storeItemStack.getMaxCount());
}
tagCompound.put("storedStack", temp.toTag(new CompoundTag()));
tagCompound.putInt("storedQuantity", Math.min(storeItemStack.getCount(), maxCapacity));
} else {
tagCompound.putInt("storedQuantity", 0);
}
// Renderer only
tagCompound.putInt("totalStoredAmount", getCurrentCapacity());
if (isLocked()) {
tagCompound.put("lockedItem", lockedItemStack.toTag(new CompoundTag()));
}
inventory.write(tagCompound);
return tagCompound;
}
// ItemHandlerProvider
@Override
public RebornInventory<StorageUnitBaseBlockEntity> getInventory() {
return inventory;
}
// IToolDrop
@Override
public ItemStack getToolDrop(PlayerEntity entityPlayer) {
return getDropWithNBT();
}
public ItemStack getDropWithNBT() {
ItemStack dropStack = new ItemStack(getBlockType(), 1);
final CompoundTag blockEntity = new CompoundTag();
this.toTag(blockEntity);
dropStack.setTag(new CompoundTag());
dropStack.getTag().put("blockEntity", blockEntity);
return dropStack;
}
// IListInfoProvider
@Override
public void addInfo(final List<Text> info, final boolean isReal, boolean hasData) {
if (isReal || hasData) {
if (!this.isEmpty()) {
info.add(
new LiteralText(String.valueOf(this.getCurrentCapacity()))
.append(new TranslatableText("techreborn.tooltip.unit.divider"))
.append(this.getStoredStack().getName())
);
} else {
info.add(new TranslatableText("techreborn.tooltip.unit.empty"));
}
}
info.add(
new TranslatableText("techreborn.tooltip.unit.capacity")
.formatted(Formatting.GRAY)
.append(
new LiteralText(String.valueOf(this.getMaxCapacity()))
.formatted(Formatting.GOLD)
.append(" items (")
.append(String.valueOf(this.getMaxCapacity() / 64))
.append(")")
)
);
}
@Override
public void onBreak(World world, PlayerEntity playerEntity, BlockPos blockPos, BlockState blockState) {
super.onBreak(world, playerEntity, blockPos, blockState);
// No need to drop anything for creative peeps
if (type == TRContent.StorageUnit.CREATIVE) {
this.inventory.clear();
return;
}
if (storeItemStack != ItemStack.EMPTY) {
if (storeItemStack.getMaxCount() == 64) {
// Drop stacks (In one clump, reduce lag)
WorldUtils.dropItem(storeItemStack, world, pos);
} else {
int size = storeItemStack.getMaxCount();
for (int i = 0; i < storeItemStack.getCount() / size; i++) {
ItemStack toDrop = storeItemStack.copy();
toDrop.setCount(size);
WorldUtils.dropItem(toDrop, world, pos);
}
if (storeItemStack.getCount() % size != 0) {
ItemStack toDrop = storeItemStack.copy();
toDrop.setCount(storeItemStack.getCount() % size);
WorldUtils.dropItem(toDrop, world, pos);
}
}
}
// Inventory gets dropped automatically
}
// The int methods are only for ContainerBuilder.sync()
private int isLockedInt() {
return isLocked() ? 1 : 0;
}
private void setLockedInt(int lockedInt) {
setLocked(lockedInt == 1);
}
public boolean isLocked() {
return lockedItemStack != ItemStack.EMPTY;
}
public void setLocked(boolean value) {
if (isLocked() == value) {
return;
}
// Only set lockedItem in response to user input
lockedItemStack = value ? getStoredStack().copy() : ItemStack.EMPTY;
syncWithAll();
}
public boolean canModifyLocking() {
// Can always be unlocked
if (isLocked()) {
return true;
}
// Can only lock if there is an item to lock
return !isEmpty();
}
public int getStoredAmount() {
return this.getCurrentCapacity();
}
public void setStoredAmount(int storedAmount) {
this.storedAmount = storedAmount;
}
public void setStoredStackFromNBT(CompoundTag tag) {
storeItemStack = ItemStack.fromTag(tag);
}
public CompoundTag getStoredStackNBT() {
CompoundTag tag = new CompoundTag();
getStoredStack().toTag(tag);
return tag;
}
@Override
public BuiltScreenHandler createScreenHandler(int syncID, final PlayerEntity playerEntity) {
return new ScreenHandlerBuilder("chest").player(playerEntity.inventory).inventory().hotbar().addInventory()
.blockEntity(this)
.slot(INPUT_SLOT, 100, 53)
.outputSlot(OUTPUT_SLOT, 140, 53)
.sync(this::isLockedInt, this::setLockedInt)
.sync(this::getStoredStackNBT, this::setStoredStackFromNBT)
.sync(this::getStoredAmount, this::setStoredAmount)
.addInventory().create(this, syncID);
// Note that inventory is synced, and it gets the stack from that
}
@Override
public boolean isValid(int slot, ItemStack stack) {
if (slot == INPUT_SLOT && isLocked()) {
return ItemUtils.isItemEqual(lockedItemStack, stack, true, true);
}
if (slot == INPUT_SLOT && !(isEmpty() || isSameType(stack))) {
return false;
}
return super.isValid(slot, stack);
}
}
|
package io.sigpipe.sing.graph;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.NavigableMap;
import java.util.logging.Logger;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.TreeSet;
import io.sigpipe.sing.dataset.Pair;
import io.sigpipe.sing.dataset.feature.Feature;
import io.sigpipe.sing.dataset.feature.FeatureType;
public class Sketch {
private static final Logger logger = Logger.getLogger("io.sigpipe.sing");
/** The root vertex. */
private Vertex root = new Vertex();
/** Describes each level in the Feature hierarchy. */
private Map<String, HierarchyLevel> levels = new HashMap<>();
/**
* We maintain a separate Queue with Feature names inserted in
* hierarchical order. While levels.keySet() contains the same information,
* there is no contractual obligation for HashMap to return the keyset in
* the original insertion order (although in practice, it probably does).
*/
private Queue<String> features = new LinkedList<>();
/**
* Tracks information about each level in the graph hierarchy.
*/
private class HierarchyLevel {
public HierarchyLevel(int order, FeatureType type) {
this.order = order;
this.type = type;
}
public int order;
public FeatureType type;
}
private TreeSet<Float> ts = new TreeSet<>();
public Sketch() {
ts.add(0.0f);
ts.add(0.1f);
ts.add(0.2f);
ts.add(0.3f);
ts.add(0.4f);
ts.add(0.5f);
ts.add(0.6f);
ts.add(0.7f);
ts.add(0.8f);
ts.add(0.9f);
ts.add(1.0f);
}
/**
* Creates a HierarchicalGraph with a set Feature hierarchy. Features are
* entered into the hierarchy in the order they are received.
*
* @param hierarchy Graph hierarchy represented as a
* {@link FeatureHierarchy}.
*/
public Sketch(FeatureHierarchy hierarchy) {
for (Pair<String, FeatureType> feature : hierarchy) {
getOrder(feature.a, feature.b);
}
}
/**
* When a path does not contain a particular Feature, we use a null feature
* (FeatureType.NULL) to act as a "wildcard" in the graph so that the path
* stays linked together. The side effect of this is that 'less than'
* comparisons may return wildcards, which are removed with this method.
*
* @param map The map to remove the first NULL element from. If the map has
* no elements or the first element is not a NULL FeatureType, then no
* modifications are made to the map.
*/
private void removeWildcard(NavigableMap<Feature, Vertex> map) {
if (map.size() <= 0) {
return;
}
Feature first = map.firstKey();
if (first.getType() == FeatureType.NULL) {
map.remove(first);
}
}
/**
* Adds a new {@link Path} to the Hierarchical Graph.
*/
public void addPath(Path path, DataContainer payload)
throws FeatureTypeMismatchException, GraphException {
if (path.size() == 0) {
throw new GraphException("Attempted to add empty path!");
}
//for (Vertex v : path) {
// Float newFloat = ts.ceiling(v.getLabel().getFloat());
// if (newFloat == null) {
// newFloat = 1.0f;
// v.setLabel(new Feature(v.getLabel().getName(), newFloat));
checkFeatureTypes(path);
addNullFeatures(path);
reorientPath(path);
optimizePath(path);
/* Place the path payload (traversal result) at the end of this path. */
path.get(path.size() - 1).setData(payload);
root.addPath(path.iterator());
}
/**
* This method ensures that the Features in the path being added have the
* same FeatureTypes as the current hierarchy. This ensures that different
* FeatureTypes (such as an int and a double) get placed on the same level
* in the hierarchy.
*
* @param path the Path to check for invalid FeatureTypes.
*
* @throws FeatureTypeMismatchException if an invalid type is found
*/
private void checkFeatureTypes(Path path)
throws FeatureTypeMismatchException {
for (Feature feature : path.getLabels()) {
/* If this feature is NULL, then it's effectively a wildcard. */
if (feature.getType() == FeatureType.NULL) {
continue;
}
HierarchyLevel level = levels.get(feature.getName());
if (level != null) {
if (level.type != feature.getType()) {
throw new FeatureTypeMismatchException(
"Feature insertion at graph level " + level.order
+ " is not possible due to a FeatureType mismatch. "
+ "Expected: " + level.type + ", "
+ "found: " + feature.getType() + "; "
+ "Feature: <" + feature + ">");
}
}
}
}
/**
* For missing feature values, add a null feature to a path. This maintains
* the graph structure for sparse schemas or cases where a feature reading
* is not available.
*/
private void addNullFeatures(Path path) {
Set<String> unknownFeatures = new HashSet<>(levels.keySet());
for (Feature feature : path.getLabels()) {
unknownFeatures.remove(feature.getName());
}
/* Create null features for missing values */
for (String featureName : unknownFeatures) {
Vertex v = new Vertex();
v.setLabel(new Feature(featureName));
path.add(v);
}
}
/**
* Reorients a nonhierarchical path in place to match the current graph
* hierarchy.
*/
private void reorientPath(Path path) {
if (path.size() == 1) {
/* This doesn't need to be sorted... */
getOrder(path.get(0).getLabel());
return;
}
path.sort(new Comparator<Vertex>() {
public int compare(Vertex a, Vertex b) {
int o2 = getOrder(b.getLabel());
int o1 = getOrder(a.getLabel());
return o1 - o2;
}
});
}
/**
* Perform optimizations on a path to reduce the number of vertices inserted
* into the graph.
*/
private void optimizePath(Path path) {
/* Remove all trailing null features. During a traversal, trailing null
* features are unnecessary to traverse. */
for (int i = path.size() - 1; i >= 0; --i) {
if (path.get(i).getLabel().getType() == FeatureType.NULL) {
path.remove(i);
} else {
break;
}
}
}
/**
* Removes all null Features from a path. This includes any Features that
* are the standard Java null, or Features with a NULL FeatureType.
*
* @param path Path to remove null Features from.
*/
private void removeNullFeatures(Path path) {
Iterator<Vertex> it = path.iterator();
while (it.hasNext()) {
Feature f = it.next().getLabel();
if (f == null || f.getType() == FeatureType.NULL) {
it.remove();
}
}
}
// private boolean applyPayloadFilter(Path path, PayloadFilter filter) {
// Set<T> payload = path.getPayload();
// if (filter.excludesItems() == false) {
// /* We only include the items in the filter */
// payload.retainAll(filter.getItems());
// } else {
// /* Excludes anything in the filter */
// payload.removeAll(filter.getItems());
// return payload.isEmpty();
/**
* Determines the numeric order of a Feature based on the current
* orientation of the graph. For example, humidity features may come first,
* followed by temperature, etc. If the feature in question has not yet
* been added to the graph, then it is connected to the current leaf nodes,
* effectively placing it at the bottom of the hierarchy, and its order
* number is set to the current number of feature types in the graph.
*
* @return int representing the list ordering of the Feature
*/
private int getOrder(String name, FeatureType type) {
int order;
HierarchyLevel level = levels.get(name);
if (level != null) {
order = level.order;
} else {
order = addNewFeature(name, type);
}
return order;
}
private int getOrder(Feature feature) {
return getOrder(feature.getName(), feature.getType());
}
/**
* Update the hierarchy levels and known Feature list with a new Feature.
*/
private int addNewFeature(String name, FeatureType type) {
logger.info("New feature: " + name + ", type: " + type);
Integer order = levels.keySet().size();
levels.put(name, new HierarchyLevel(order, type));
features.offer(name);
return order;
}
/**
* Retrieves the ordering of Feature names in this graph hierarchy.
*/
public FeatureHierarchy getFeatureHierarchy() {
FeatureHierarchy hierarchy = new FeatureHierarchy();
for (String feature : features) {
try {
hierarchy.addFeature(feature, levels.get(feature).type);
} catch (GraphException e) {
/* If a GraphException is thrown here, something is seriously
* wrong. */
logger.severe("NULL FeatureType found in graph hierarchy!");
}
}
return hierarchy;
}
// public List<Path> getAllPaths() {
// List<Path> paths = root.descendantPaths();
// for (Path<Feature, T> path : paths) {
// removeNullFeatures(path);
// return paths;
public Vertex getRoot() {
return root;
}
@Override
public String toString() {
return root.toString();
}
}
|
/**
* Redis client binding for YCSB.
*
*/
package com.yahoo.ycsb.db;
import com.yahoo.ycsb.DB;
import com.yahoo.ycsb.DBException;
import java.util.HashMap;
import java.util.Properties;
import java.util.Set;
import java.util.Vector;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Protocol;
public class RedisClient extends DB {
private Jedis jedis;
public static final String HOST_PROPERTY = "redis.host";
public static final String PORT_PROPERTY = "redis.port";
public static final String PASSWORD_PROPERTY = "redis.password";
public void init() throws DBException {
Properties props = getProperties();
int port;
String portString = props.getProperty(PORT_PROPERTY);
if (portString != null) {
port = Integer.parseInt(portString);
}
else {
port = Protocol.DEFAULT_PORT;
}
String host = props.getProperty(HOST_PROPERTY);
jedis = new Jedis(host, port);
jedis.connect();
String password = props.getProperty(PASSWORD_PROPERTY);
if (password != null) {
jedis.auth(password);
jedis.flushAll();
}
}
@Override
public int read(String table, String key, Set<String> fields,
HashMap<String, String> result) {
return 0;
}
@Override
public int insert(String table, String key, HashMap<String, String> values) {
return 0;
}
@Override
public int delete(String table, String key) {
return 0;
}
@Override
public int update(String table, String key, HashMap<String, String> values) {
return 0;
}
@Override
public int scan(String table, String startkey, int recordcount,
Set<String> fields, Vector<HashMap<String, String>> result) {
return 0;
}
}
|
package zmaster587.advancedRocketry.client.render;
import org.lwjgl.opengl.GL11;
import zmaster587.advancedRocketry.tile.multiblock.TileMultiBlock;
import zmaster587.advancedRocketry.tile.multiblock.TilePlaceholder;
import zmaster587.libVulpes.block.RotatableBlock;
import zmaster587.libVulpes.render.RenderHelper;
import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.RenderBlocks;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.texture.TextureMap;
import net.minecraft.client.renderer.tileentity.TileEntityRendererDispatcher;
import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.MovingObjectPosition;
import net.minecraftforge.common.util.ForgeDirection;
public class RendererPhantomBlock extends TileEntitySpecialRenderer {
private static RenderBlocks renderBlocks = RenderBlocks.getInstance();
@Override
public void renderTileEntityAt(TileEntity tile, double x,
double y, double z, float t) {
TilePlaceholder tileGhost = (TilePlaceholder)tile;
Block block = tileGhost.getReplacedBlock();
if(tileGhost.getReplacedTileEntity() != null && !(tileGhost.getReplacedTileEntity() instanceof TileMultiBlock) && TileEntityRendererDispatcher.instance.hasSpecialRenderer(tileGhost.getReplacedTileEntity())) {
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_ONE_MINUS_SRC_COLOR, GL11.GL_SRC_ALPHA);
GL11.glColor4f(1f, 1f, 1f,0.7f);
TileEntityRendererDispatcher.instance.renderTileEntityAt(tileGhost.getReplacedTileEntity(), x, y, z, t);
GL11.glDisable(GL11.GL_BLEND);
}
else if(block != null) {
GL11.glPushMatrix();
GL11.glTranslated(x,y,z);
if(block instanceof RotatableBlock) {
ForgeDirection direction = ForgeDirection.getOrientation(tileGhost.getReplacedBlockMeta());
GL11.glTranslated(.5f,.5f,.5f);
if(direction.offsetX != 0 ) {
GL11.glRotatef( -90, 0,direction.offsetX,0);
}
else if(direction.offsetZ == 1) {
GL11.glRotatef( 180, direction.offsetZ,0,0);
GL11.glRotatef( 180, 0,0,1);
}
//GL11.glScalef(-1, -1, -1);
GL11.glTranslated(-.5f,-.5f,-.5f);
}
net.minecraft.client.renderer.RenderHelper.disableStandardItemLighting();
//Render Each block
Minecraft.getMinecraft().getTextureManager().bindTexture(TextureMap.locationBlocksTexture);
renderBlocks.blockAccess = tileGhost.getWorldObj();
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_ONE_MINUS_SRC_COLOR, GL11.GL_SRC_ALPHA);
Tessellator.instance.startDrawingQuads();
if(block.getRenderType() == 0) {
block.setBlockBoundsBasedOnState(tile.getWorldObj(), tile.xCoord, tile.yCoord, tile.zCoord);
renderBlocks.setRenderBoundsFromBlock(block);
int l = block.colorMultiplier(tile.getWorldObj(), tile.xCoord, tile.yCoord, tile.zCoord);
float r = (float)(l >> 16 & 255) / 255.0F;
float g = (float)(l >> 8 & 255) / 255.0F;
float b = (float)(l & 255) / 255.0F;
RenderHelper.renderStandardBlockWithColorMultiplier(block, 0,0,0, r, g, b, .3f);
}
else
renderBlocks.renderBlockByRenderType(block, 0, 0, 0);
Tessellator.instance.draw();
net.minecraft.client.renderer.RenderHelper.enableStandardItemLighting();
GL11.glDisable(GL11.GL_BLEND);
GL11.glPopMatrix();
}
if(block != null) {
//If the player is mousing over this block
MovingObjectPosition movingObjPos = Minecraft.getMinecraft().objectMouseOver;
if(Minecraft.getMinecraft().objectMouseOver != null && movingObjPos.blockX == tile.xCoord && movingObjPos.blockY == tile.yCoord && movingObjPos.blockZ == tile.zCoord) {
ItemStack stack = tile.getWorldObj().getBlock(tile.xCoord, tile.yCoord, tile.zCoord).getPickBlock(movingObjPos, Minecraft.getMinecraft().theWorld, movingObjPos.blockX, movingObjPos.blockY, movingObjPos.blockZ, Minecraft.getMinecraft().thePlayer);
if(stack == null)
return;
RenderHelper.renderTag(Minecraft.getMinecraft().thePlayer.getDistanceSq(movingObjPos.blockX, movingObjPos.blockY, movingObjPos.blockZ), stack.getDisplayName(), x,y,z, 10);
}
}
}
}
|
package io.usethesource.vallang;
import java.util.Iterator;
import org.checkerframework.checker.nullness.qual.Nullable;
import io.usethesource.vallang.visitors.IValueVisitor;
public interface ISet extends ICollection<ISet> {
/**
* Add an element to the set.
* @param element
* @return a relation if the element type is a tuple type, a set otherwise
*/
public default ISet insert(IValue element) {
IWriter<ISet> sw = writer();
sw.insertAll(this);
sw.insert(element);
return sw.done();
}
/**
* Delete one element from the set.
* @param elem
* @return a set with one element removed, if present.
*/
public default ISet delete(IValue elem) {
IWriter<ISet> w = writer();
boolean deleted = false;
for (Iterator<IValue> iterator = iterator(); iterator.hasNext();) {
IValue e = iterator.next();
if (!deleted && e.equals(elem)) {
deleted = true; // skip first occurrence
} else {
w.insert(e);
}
}
return w.done();
}
/**
* Computes the Cartesian product of two sets
* @param set
* @return a relation representing the Cartesian product
*/
@Override
public default ISet product(ISet that) {
IWriter<ISet> w = writer();
for (IValue t1 : this) {
for (IValue t2 : that) {
w.insertTuple(t1, t2);
}
}
return w.done();
}
@Override
public default boolean match(IValue other) {
if (other == this) {
return true;
}
if (other == null) {
return false;
}
if (other instanceof ISet) {
ISet set2 = (ISet) other;
if (size() == set2.size()) {
for (IValue v1 : this) {
// function containsMatch() calls match() but uses O(n) time
if (!set2.containsMatch(v1)) {
return false;
}
}
return true;
}
}
return false;
}
/**
* Compute the union of two sets. To be overridden
* by implementations who know how to do this more efficiently.
* @return the mathematical union of the two sets
*/
@Override
public default ISet union(ISet that) {
if (this == that) {
return this;
}
if (this.isEmpty()) {
return that;
}
if (that.isEmpty()) {
return this;
}
IWriter<ISet> w = writer();
w.insertAll(this);
w.insertAll(that);
return w.done();
}
/**
* Compute the intersection of two sets. To be overridden
* by implementations who know how to do this more efficiently.
* @return the mathematical intersection of the two sets
*/
public default ISet intersect(ISet that) {
if (this == that) {
return this;
}
if (this.isEmpty()) {
return this;
}
if (that.isEmpty()) {
return that;
}
IWriter<ISet> w = writer();
for (IValue v : this) {
if (that.contains(v)) {
w.insert(v);
}
}
return w.done();
}
/**
* Compute the difference of two sets by removing the elements of `that`
* from the receiver. To be implemented more efficiently if possible
* by implementations of ISet.
* @return the mathematical difference of two sets
*/
public default ISet subtract(ISet that) {
if (this == that) {
return writer().done();
}
if (this.isEmpty()) {
return this;
}
if (that.isEmpty()) {
return this;
}
IWriter<ISet> sw = writer();
for (IValue a : this) {
if (!that.contains(a)) {
sw.insert(a);
}
}
return sw.done();
}
/**
* @param element
* @return true if this is an element of the set
*/
public boolean contains(IValue e);
/**
* @param element
* @return true if this set contains an element that matches (IValue.match) an element in this set
*/
public default boolean containsMatch(IValue e) {
for (IValue v : this) {
if (v.match(e)) {
return true;
}
}
return false;
}
/**
* @param that other set to check for subset relation
* @return true if all elements of this set are elements of the other.
*/
public default boolean isSubsetOf(ISet that) {
for (IValue elem : this) {
if (!that.contains(elem)) {
return false;
}
}
return true;
}
/**
* A default implementation of Object.hashCode() for use in implementations of ISet.
*/
public default int defaultHashCode() {
int hash = 0;
Iterator<IValue> iterator = this.iterator();
while (iterator.hasNext()) {
IValue element = iterator.next();
hash ^= element.hashCode();
}
return hash;
}
public default boolean defaultEquals(@Nullable Object that) {
if (that == this) {
return true;
}
if (that == null) {
return false;
}
if (that instanceof ISet) {
ISet set2 = (ISet) that;
if (this.getType() != set2.getType()) {
return false;
}
if (hashCode() != set2.hashCode()) {
return false;
}
if (size() == set2.size()) {
for (IValue v1 : this) {
if (!set2.contains(v1)) {
return false;
}
}
return true;
}
}
return false;
}
@Override
default <T, E extends Throwable> T accept(IValueVisitor<T, E> v) throws E {
return v.visitSet(this);
}
@Override
default IRelation<ISet> asRelation() {
if (!getType().isRelation()) {
throw new UnsupportedOperationException(getType() + " is not a relation");
}
return new IRelation<ISet>() {
@Override
public String toString() {
return ISet.this.toString();
}
@Override
public ISet asContainer() {
return ISet.this;
}
};
}
}
|
package javaslang.collection;
import javaslang.Tuple2;
import javaslang.control.None;
import javaslang.control.Option;
public interface HashMap<K, V> extends Map<K, V> {
EmptyNode<?, ?> EMPTY = new EmptyNode<>();
@SuppressWarnings("unchecked")
static <K, V> HashMap<K, V> empty() {
return (EmptyNode<K, V>) EMPTY;
}
default boolean isEmpty() {
return this == empty();
}
int size();
default V get(K key) {
return getOrDefault(key, null);
}
default V getOrDefault(K key, V defaultValue) {
return ((AbstractNode<K, V>) this).lookup(0, key).orElse(defaultValue);
}
default boolean containsKey(K key) {
// TODO: what if the stored value is null? the result is ambiguous
return get(key) != null;
}
default HashMap<K, V> put(K key, V value) {
return ((AbstractNode<K, V>) this).modify(0, key, value);
}
default HashMap<K, V> remove(K key) {
return ((AbstractNode<K, V>) this).modify(0, key, null);
}
abstract class AbstractNode<K, V> implements HashMap<K, V> {
final static int SIZE = 5;
final static int BUCKET_SIZE = 1 << SIZE;
final static int MAX_INDEX_NODE = BUCKET_SIZE / 2;
final static int MIN_ARRAY_NODE = BUCKET_SIZE / 4;
final static int M1 = 0x55555555;
final static int M2 = 0x33333333;
final static int M4 = 0x0f0f0f0f;
@SuppressWarnings("unchecked")
static <K, V> AbstractNode<K, V> empty() {
return (AbstractNode<K, V>) EMPTY;
}
static int bitCount(int x) {
x = x - ((x >> 1) & M1);
x = (x & M2) + ((x >> 2) & M2);
x = (x + (x >> 4)) & M4;
x = x + (x >> 8);
x = x + (x >> 16);
return x & 0x7f;
}
static int hashFragment(int shift, int hash) {
return (hash >>> shift) & (BUCKET_SIZE - 1);
}
static int toBitmap(int hash) {
return 1 << hash;
}
static int fromBitmap(int bitmap, int bit) {
return bitCount(bitmap & (bit - 1));
}
abstract boolean isLeaf();
abstract Option<V> lookup(int shift, K key);
abstract AbstractNode<K, V> modify(int shift, K key, V value);
}
class EmptyNode<K, V> extends AbstractNode<K, V> {
private EmptyNode() {
}
@Override
public Option<V> lookup(int shift, K key) {
return None.instance();
}
@Override
AbstractNode<K, V> modify(int shift, K key, V value) {
return value == null ? this : new LeafNode<>(key.hashCode(), key, value);
}
@Override
public boolean isLeaf() {
return true;
}
@Override
public int size() {
return 0;
}
}
class LeafNode<K, V> extends AbstractNode<K, V> {
final int hash;
final List<Entry<K, V>> entries;
private LeafNode(int hash, K key, V value) {
this(hash, List.of(new Entry<>(key, value)));
}
private LeafNode(int hash, List<Entry<K, V>> entries) {
this.hash = hash;
this.entries = entries;
}
// TODO
AbstractNode<K, V> update(K key, V value) {
List<Entry<K, V>> filtered = entries.filter(t -> !t.key.equals(key));
if (value == null) {
return filtered.isEmpty() ? empty() : new LeafNode<>(hash, filtered);
} else {
return new LeafNode<>(hash, filtered.append(new Entry<>(key, value)));
}
}
@Override
Option<V> lookup(int shift, K key) {
if (hash != key.hashCode()) {
return None.instance();
}
return entries.filter(t -> t.key.equals(key)).headOption().map(t -> t.value);
}
@Override
AbstractNode<K, V> modify(int shift, K key, V value) {
if (key.hashCode() == hash) {
return update(key, value);
} else {
return value == null ? this : mergeLeaves(shift, new LeafNode<>(key.hashCode(), key, value));
}
}
AbstractNode<K, V> mergeLeaves(int shift, LeafNode<K, V> other) {
int h1 = this.hash;
int h2 = other.hash;
if (h1 == h2) {
List<Entry<K, V>> newList = List.empty();
newList.appendAll(this.entries);
newList.appendAll(other.entries);
return new LeafNode<>(h1, newList);
}
int subH1 = hashFragment(shift, h1);
int subH2 = hashFragment(shift, h2);
return new IndexedNode<>(toBitmap(subH1) | toBitmap(subH2),
subH1 == subH2 ?
List.of(mergeLeaves(shift + SIZE, other))
: subH1 < subH2 ? List.of(this, other) : List.of(other, this));
}
@Override
public boolean isLeaf() {
return true;
}
@Override
public int size() {
return entries.length();
}
}
class IndexedNode<K, V> extends AbstractNode<K, V> {
final int bitmap;
final List<AbstractNode<K, V>> subNodes;
final int size;
IndexedNode(int bitmap, List<AbstractNode<K, V>> subNodes) {
this.bitmap = bitmap;
this.subNodes = subNodes;
this.size = subNodes.map(HashMap::size).sum().intValue();
}
@Override
Option<V> lookup(int shift, K key) {
int h = key.hashCode();
int frag = hashFragment(shift, h);
int bit = toBitmap(frag);
return ((bitmap & bit) != 0) ? subNodes.get(fromBitmap(bitmap, bit)).lookup(shift + SIZE, key) : None.instance();
}
@Override
AbstractNode<K, V> modify(int shift, K key, V value) {
int frag = hashFragment(shift, key.hashCode());
int bit = toBitmap(frag);
int indx = fromBitmap(bitmap, bit);
int mask = bitmap;
boolean exists = (mask & bit) != 0;
AbstractNode<K, V> child = exists ? subNodes.get(indx).modify(shift + SIZE, key, value)
: AbstractNode.<K, V> empty().modify(shift + SIZE, key, value);
boolean removed = exists && child.isEmpty();
boolean added = !exists && !child.isEmpty();
int newBitmap = removed ? mask & ~bit : added ? mask | bit : mask;
if (newBitmap == 0) {
return empty();
} else if (removed) {
if (subNodes.length() <= 2 && subNodes.get(indx ^ 1).isLeaf()) {
return subNodes.get(indx ^ 1); // collapse
} else {
Tuple2<List<AbstractNode<K, V>>, List<AbstractNode<K, V>>> spl = subNodes.splitAt(indx);
List<AbstractNode<K, V>> rem = spl._1;
if (!spl._2.isEmpty()) {
rem = rem.appendAll(spl._2.tail());
}
return new IndexedNode<>(newBitmap, rem);
}
} else if (added) {
if (subNodes.length() >= MAX_INDEX_NODE) {
return expand(frag, child, mask, subNodes);
} else {
return new IndexedNode<>(newBitmap, subNodes.insert(indx, child));
}
} else {
return new IndexedNode<>(newBitmap, subNodes.set(indx, child));
}
}
ArrayNode<K, V> expand(int frag, AbstractNode<K, V> child, int mask, List<AbstractNode<K, V>> subNodes) {
int bit = mask;
int count = 0;
List<AbstractNode<K, V>> sub = subNodes;
List<AbstractNode<K, V>> arr = List.empty();
for (int i = 0; i < 32; i++) {
if ((bit & 1) != 0) {
arr = arr.append(sub.head());
sub = sub.tail();
count++;
} else if (i == frag) {
arr = arr.append(child);
count++;
} else {
arr = arr.append(empty());
}
bit = bit >>> 1;
}
return new ArrayNode<>(count, arr);
}
@Override
public boolean isLeaf() {
return false;
}
@Override
public int size() {
return size;
}
}
class ArrayNode<K, V> extends AbstractNode<K, V> {
final List<AbstractNode<K, V>> subNodes;
final int count;
final int size;
ArrayNode(int count, List<AbstractNode<K, V>> subNodes) {
this.subNodes = subNodes;
this.count = count;
this.size = subNodes.map(HashMap::size).sum().intValue();
}
@Override
Option<V> lookup(int shift, K key) {
int frag = hashFragment(shift, key.hashCode());
AbstractNode<K, V> child = subNodes.get(frag);
return child.lookup(shift + SIZE, key);
}
@Override
AbstractNode<K, V> modify(int shift, K key, V value) {
int frag = hashFragment(shift, key.hashCode());
AbstractNode<K, V> child = subNodes.get(frag);
AbstractNode<K, V> newChild = child.modify(shift + SIZE, key, value);
if (child.isEmpty() && !newChild.isEmpty()) {
return new ArrayNode<>(count + 1, subNodes.set(frag, newChild));
} else if (!child.isEmpty() && newChild.isEmpty()) {
if (count - 1 <= MIN_ARRAY_NODE) {
return pack(frag, this.subNodes);
} else {
return new ArrayNode<>(count - 1, subNodes.set(frag, empty()));
}
} else {
return new ArrayNode<>(count, subNodes.set(frag, newChild));
}
}
IndexedNode<K, V> pack(int idx, List<AbstractNode<K, V>> elements) {
List<AbstractNode<K, V>> sub = elements;
List<AbstractNode<K, V>> arr = List.empty();
int bitmap = 0;
for (int i = 0; !sub.isEmpty(); i++) {
AbstractNode<K, V> elem = sub.head();
sub = sub.tail();
if (i != idx && elem != empty()) {
arr = arr.append(elem);
bitmap = bitmap | (1 << i);
}
}
return new IndexedNode<>(bitmap, arr);
}
@Override
public boolean isLeaf() {
return false;
}
@Override
public int size() {
return size;
}
}
}
|
package jp.gecko655.bot;
import java.io.IOException;
import java.io.InputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import twitter4j.Status;
import twitter4j.StatusUpdate;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.conf.ConfigurationBuilder;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.customsearch.Customsearch;
import com.google.api.services.customsearch.model.Result;
import com.google.api.services.customsearch.model.Search;
public abstract class AbstractCron implements Job{
static final protected Logger logger = Logger.getLogger("Fujimiya");
static final String consumerKey = System.getenv("consumerKey");
static final String consumerSecret = System.getenv("consumerSecret");
static final String accessToken = System.getenv("accessToken");
static final String accessTokenSecret = System.getenv("accessTokenSecret");
static final String customSearchCx = System.getenv("customSearchCx");
static final String customSearchKey = System.getenv("customSearchKey");
static protected Twitter twitter;
static Customsearch search;
public AbstractCron() {
logger.setLevel(Level.FINE);
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthAccessToken(accessToken)
.setOAuthAccessTokenSecret(accessTokenSecret)
.setOAuthConsumerKey(consumerKey)
.setOAuthConsumerSecret(consumerSecret);
twitter = new TwitterFactory(cb.build()).getInstance();
Customsearch.Builder builder = new Customsearch.Builder(new NetHttpTransport(), new JacksonFactory(), null).setApplicationName("Google"); //$NON-NLS-1$
search = builder.build();
}
@Override
public void execute(JobExecutionContext context)
throws JobExecutionException {
twitterCron();
}
/**
* Search fujimiya-san's image and return the url.
* The return is randomly picked up from the 100 result of google image search.
* @param query
* @return
*/
FetchedImage getFujimiyaUrl(String query){
return getFujimiyaUrl(query,100);
}
/**
* Search fujimiya-san's image and return the url.
* The return is randomly picked up from the maxRankOfResult result of google image search.
* @param query
* @param maxRankOfResult
* @return
*/
FetchedImage getFujimiyaUrl(String query,int maxRankOfResult){
try{
//Get SearchResult
Search search = getSearchResult(query, maxRankOfResult);
List<Result> items = search.getItems();
for(Result result: items){
int i = items.indexOf(result);
logger.log(Level.INFO,"query: " + query + " URL: "+result.getLink());
logger.log(Level.INFO,"page URL: "+result.getImage().getContextLink());
if(result.getImage().getWidth()+result.getImage().getHeight()<600){
logger.log(Level.INFO,"Result No."+i+" is too small image. next.");
continue;
}
if(DBConnection.isInBlackList(result.getLink())){
logger.log(Level.INFO,"Result No."+i+" is included in the blacklist. next.");
continue;
}
HttpURLConnection connection = (HttpURLConnection)(new URL(result.getLink())).openConnection();
connection.setRequestMethod("GET");
connection.setInstanceFollowRedirects(false);
connection.connect();
if(connection.getResponseCode()==200){
return new FetchedImage(connection.getInputStream(),result.getLink());
}else{
logger.log(Level.INFO,"Result No."+i+" occurs error while fetching the image. next.");
continue;
}
}
//If execution comes here, connection has failed 10 times.
throw new ConnectException("Connection failed 10 times");
} catch (IOException e) {
// TODO Auto-generated catch block
logger.log(Level.SEVERE,e.toString());
e.printStackTrace();
}
return null;
}
static private int apiLimit = 100;
static private int pageSize = 10;
private Search getSearchResult(String query, int maxRankOfResult) throws IOException {
if(maxRankOfResult>apiLimit-pageSize+1)
maxRankOfResult=apiLimit-pageSize+1;
Customsearch.Cse.List list = search.cse().list(query);
long rand = (long)(Math.random()*maxRankOfResult+1);
list.setCx(customSearchCx)
.setKey(customSearchKey)
.setSearchType("image")
.setNum((long)pageSize)
.setStart(rand);
logger.log(Level.INFO,"rand: "+rand);
return list.execute();
}
protected void updateStatusWithMedia(StatusUpdate update, String query, int maxRankOfResult){
FetchedImage fetchedImage = getFujimiyaUrl(query,maxRankOfResult);
update.media("fujimiya.jpg",fetchedImage.getInputStream());
for(int i=0;i<10;i++){
try{
Status succeededStatus = twitter.updateStatus(update);
logger.log(Level.INFO,"Successfully tweeted: "+succeededStatus.getText());
DBConnection.storeImageUrl(succeededStatus,fetchedImage);
return;
}catch(TwitterException e){
logger.log(Level.INFO,"updateStatusWithMedia failed. try again. "+ e.getErrorMessage());
}
}
logger.log(Level.SEVERE,"updateStatusWithMedia failed 10 times. Stop.");
}
abstract protected void twitterCron();
}
class FetchedImage{
private InputStream in;
private String url;
public FetchedImage(InputStream in, String url) {
this.in = in;
this.url = url;
}
public InputStream getInputStream() {
return in;
}
public String getUrl() {
return url;
}
}
|
package logbook.internal;
import java.awt.Desktop;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonObject;
import javax.json.JsonReader;
import javafx.application.Platform;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.ButtonType;
import javafx.stage.Stage;
import logbook.internal.gui.InternalFXMLLoader;
import logbook.internal.gui.Tools;
public class CheckUpdate {
/** Github tags API */
private static final String TAGS = "https://api.github.com/repos/sanaehirotaka/logbook-kai/tags";
/** Github releases API */
private static final String RELEASES = "https://api.github.com/repos/sanaehirotaka/logbook-kai/releases/tags/";
/** tag */
/* v20.1.1 20.1.1 */
static final Pattern TAG_REGIX = Pattern.compile("\\d+\\.\\d+(?:\\.\\d+)?$");
public static void run(Stage stage) {
run(false, stage);
}
public static void run(boolean isStartUp) {
run(isStartUp, null);
}
private static void run(boolean isStartUp, Stage stage) {
Version remoteVersion = remoteVersion();
if (!Version.UNKNOWN.equals(remoteVersion) && Version.getCurrent().compareTo(remoteVersion) < 0) {
Platform.runLater(() -> CheckUpdate.openInfo(Version.getCurrent(), remoteVersion, isStartUp, stage));
} else if (!isStartUp) {
Tools.Conrtols.alert(AlertType.INFORMATION, "", "", stage);
}
}
/**
*
* @return
*/
private static Version remoteVersion() {
try {
// Githubtagsreleases
JsonArray tags;
try (JsonReader r = Json.createReader(new ByteArrayInputStream(readURI(URI.create(TAGS))))) {
tags = r.readArray();
}
// tags
return tags.stream()
//tag
.map(val -> val.asJsonObject().getString("name"))
// tag??
.filter(tagname -> {
Matcher m = TAG_REGIX.matcher(tagname);
if (m.find()) {
Version remote = new Version(m.group());
return (!Version.UNKNOWN.equals(remote) && Version.getCurrent().compareTo(remote) < 0);
}
return false;
})
// tagreleases?
.filter(name -> {
try {
JsonObject releases;
try (JsonReader r = Json
.createReader(new ByteArrayInputStream(readURI(URI.create(RELEASES + name))))) {
releases = r.readObject();
}
// releases "message": "Not Found"
if (releases.getString("message", null) != null)
return false;
// draft
if (releases.getBoolean("draft", false))
return false;
// prerelease
if (releases.getBoolean("prerelease", false))
return false;
// assets1
if (releases.getJsonArray("assets") == null || releases.getJsonArray("assets").size() == 0)
return false;
return true;
} catch (Exception e) {
return false;
}
})
.findFirst()
.map(tagname -> {
Matcher m = TAG_REGIX.matcher(tagname);
m.find();
return new Version(m.group());
})
.orElse(Version.UNKNOWN);
} catch (Exception e) {
LoggerHolder.get().warn("", e);
}
return Version.UNKNOWN;
}
private static byte[] readURI(URI uri) throws IOException {
HttpURLConnection connection = (HttpURLConnection) uri.toURL().openConnection();
try {
connection.setConnectTimeout((int) TimeUnit.SECONDS.toMillis(10));
connection.setReadTimeout((int) TimeUnit.SECONDS.toMillis(5));
// 200 OKURI
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try (InputStream in = connection.getInputStream()) {
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer, 0, buffer.length)) > 0) {
out.write(buffer, 0, len);
}
}
return out.toByteArray();
}
} finally {
connection.disconnect();
}
return new byte[0];
}
private static void openInfo(Version o, Version n, boolean isStartUp, Stage stage) {
String message = "\n"
+ ":" + o + "\n"
+ ":" + n;
if (isStartUp) {
message += "\n※[]-[]";
}
ButtonType update = new ButtonType("");
ButtonType visible = new ButtonType("");
ButtonType no = new ButtonType("");
Alert alert = new Alert(AlertType.INFORMATION);
alert.getDialogPane().getStylesheets().add("logbook/gui/application.css");
InternalFXMLLoader.setGlobal(alert.getDialogPane());
alert.setTitle("");
alert.setHeaderText("");
alert.setContentText(message);
alert.initOwner(stage);
alert.getButtonTypes().clear();
alert.getButtonTypes().addAll(update, visible, no);
Optional<ButtonType> result = alert.showAndWait();
if (result.isPresent()) {
if (result.get() == update)
launchUpdate(n);
if (result.get() == visible)
openBrowser();
}
}
private static void openBrowser() {
try {
ThreadManager.getExecutorService()
.submit(() -> {
Desktop.getDesktop()
.browse(URI.create("https://github.com/sanaehirotaka/logbook-kai/releases"));
return null;
});
} catch (Exception e) {
LoggerHolder.get().warn("", e);
}
}
private static void launchUpdate(Version newversion) {
try {
Path dir = new File(Launcher.class.getProtectionDomain().getCodeSource().getLocation().toURI())
.toPath()
.getParent();
InputStream is = Launcher.class.getClassLoader().getResourceAsStream("logbook/update/update.js");
Path script = Files.createTempFile("logbook-kai-update-", ".js");
try {
Files.copy(is, script, StandardCopyOption.REPLACE_EXISTING);
// (JAVA_HOME/bin/jjs)
Path command = Paths.get(System.getProperty("java.home"), "bin", "jjs");
new ProcessBuilder(command.toString(), script.toString(),
"-fx",
"-Dupdate_script=" + script,
"-Dinstall_target=" + dir,
"-Dinstall_version=" + newversion)
.inheritIO()
.start();
} catch (Exception e) {
Files.deleteIfExists(script);
throw e;
}
} catch (Exception e) {
LoggerHolder.get().warn("", e);
openBrowser();
}
}
}
|
package mezz.jei.config;
import com.feed_the_beast.mods.ftbguilibrary.config.ConfigGroup;
import com.feed_the_beast.mods.ftbguilibrary.config.NameMap;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import mezz.jei.Internal;
import mezz.jei.color.ColorGetter;
import mezz.jei.color.ColorNamer;
import mezz.jei.ingredients.IngredientSortStage;
import mezz.jei.util.GiveMode;
import net.minecraftforge.common.ForgeConfigSpec;
import org.apache.commons.lang3.EnumUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.annotation.Nullable;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public final class ClientConfig implements IJEIConfig, IClientConfig {
private static final Logger LOGGER = LogManager.getLogger();
@Nullable
private static IClientConfig instance;
public static final int smallestNumColumns = 4;
public static final int largestNumColumns = 100;
public static final int minRecipeGuiHeight = 175;
private final ConfigValues values;
private List<? extends String> searchColors = Arrays.asList(ColorGetter.getColorDefaults());
public static final List<IngredientSortStage> ingredientSorterStagesDefault = Arrays.asList(
IngredientSortStage.MOD_NAME,
IngredientSortStage.INGREDIENT_TYPE,
IngredientSortStage.CREATIVE_MENU
);
private List<IngredientSortStage> ingredientSorterStages = ingredientSorterStagesDefault;
// Forge config
private final ForgeConfigSpec.BooleanValue debugModeEnabled;
private final ForgeConfigSpec.BooleanValue centerSearchBarEnabled;
private final ForgeConfigSpec.BooleanValue lowMemorySlowSearchEnabled;
private final ForgeConfigSpec.EnumValue<GiveMode> giveMode;
private final ForgeConfigSpec.IntValue maxColumns;
private final ForgeConfigSpec.IntValue maxRecipeGuiHeight;
private final ForgeConfigSpec.ConfigValue<List<? extends String>> searchColorsCfg;
private final ForgeConfigSpec.ConfigValue<List<? extends String>> ingredientSorterStagesCfg;
public ClientConfig(ForgeConfigSpec.Builder builder) {
instance = this;
this.values = new ConfigValues();
ConfigValues defaultValues = new ConfigValues();
builder.push("advanced");
{
builder.comment("Debug mode enabled");
debugModeEnabled = builder.define("DebugMode", defaultValues.debugModeEnabled);
builder.comment("Display search bar in the center");
centerSearchBarEnabled = builder.define("CenterSearch", defaultValues.centerSearchBarEnabled);
builder.comment("Set low-memory mode (makes search very slow, but uses less RAM)");
lowMemorySlowSearchEnabled = builder.define("LowMemorySlowSearchEnabled", defaultValues.lowMemorySlowSearchEnabled);
builder.comment("How items should be handed to you");
giveMode = builder.defineEnum("GiveMode", defaultValues.giveMode);
builder.comment("Max number of columns shown");
maxColumns = builder.defineInRange("MaxColumns", defaultValues.maxColumns, smallestNumColumns, largestNumColumns);
builder.comment("Max. recipe gui height");
maxRecipeGuiHeight = builder.defineInRange("RecipeGuiHeight", defaultValues.maxRecipeGuiHeight, minRecipeGuiHeight, Integer.MAX_VALUE);
}
builder.pop();
builder.push("colors");
{
builder.comment("Color values to search for");
searchColorsCfg = builder.defineList("SearchColors", Lists.newArrayList(ColorGetter.getColorDefaults()), obj -> {
if (obj instanceof String) {
String entry = (String) obj;
String[] values = entry.split(":");
if (values.length == 2) {
try {
Integer.decode("0x" + values[1]);
return true;
} catch (NumberFormatException ignored) {
}
}
}
return false;
});
}
builder.pop();
builder.push("sorting");
{
builder.comment(String.format("Sorting order for the ingredient list. Valid stages: %s", Arrays.asList(IngredientSortStage.values())));
List<String> defaults = ingredientSorterStagesDefault.stream()
.map(Enum::name)
.collect(Collectors.toList());
Predicate<Object> elementValidator = validEnumElement(IngredientSortStage.class);
ingredientSorterStagesCfg = builder.defineList("IngredientSortStages", defaults, elementValidator);
}
builder.pop();
}
@Deprecated
public static IClientConfig getInstance() {
Preconditions.checkNotNull(instance);
return instance;
}
@Override
public void buildSettingsGUI(ConfigGroup group) {
ConfigValues defaultVals = new ConfigValues();
group.addBool(cfgTranslation("centerSearchBarEnabled"), values.centerSearchBarEnabled, v -> {
centerSearchBarEnabled.set(v);
values.centerSearchBarEnabled = v;
}, defaultVals.centerSearchBarEnabled);
group.addEnum(cfgTranslation("giveMode"), values.giveMode, v -> {
giveMode.set(v);
values.giveMode = v;
}, NameMap.of(defaultVals.giveMode, GiveMode.values()).create());
group.addInt(cfgTranslation("maxColumns"), values.maxColumns, v -> {
maxColumns.set(v);
values.maxColumns = v;
}, defaultVals.maxColumns, 1, Integer.MAX_VALUE);
group.addInt(cfgTranslation("maxRecipeGuiHeight"), values.maxRecipeGuiHeight, v -> {
maxRecipeGuiHeight.set(v);
values.maxRecipeGuiHeight = v;
}, defaultVals.maxRecipeGuiHeight, 1, Integer.MAX_VALUE);
}
private String cfgTranslation(String name) {
return "advanced."+name;
}
@Override
public void reload() {
this.values.debugModeEnabled = debugModeEnabled.get();
this.values.centerSearchBarEnabled = centerSearchBarEnabled.get();
this.values.lowMemorySlowSearchEnabled = lowMemorySlowSearchEnabled.get();
this.values.giveMode = giveMode.get();
this.values.maxColumns = maxColumns.get();
this.values.maxRecipeGuiHeight = maxRecipeGuiHeight.get();
this.searchColors = searchColorsCfg.get();
this.ingredientSorterStages = ingredientSorterStagesCfg.get()
.stream()
.map(s -> EnumUtils.getEnum(IngredientSortStage.class, s))
.filter(Objects::nonNull)
.collect(Collectors.toList());
if (ingredientSorterStages.isEmpty()) {
this.ingredientSorterStages = ingredientSorterStagesDefault;
}
syncSearchColorsConfig();
}
@Override
public boolean isDebugModeEnabled() {
return values.debugModeEnabled;
}
@Override
public boolean isCenterSearchBarEnabled() {
return values.centerSearchBarEnabled;
}
@Override
public boolean isLowMemorySlowSearchEnabled() {
return values.lowMemorySlowSearchEnabled;
}
@Override
public GiveMode getGiveMode() {
return values.giveMode;
}
@Override
public int getMaxColumns() {
return values.maxColumns;
}
@Override
public int getMaxRecipeGuiHeight() {
return values.maxRecipeGuiHeight;
}
@Override
public List<IngredientSortStage> getIngredientSorterStages() {
return ingredientSorterStages;
}
private void syncSearchColorsConfig() {
final ImmutableMap.Builder<Integer, String> searchColorsMapBuilder = ImmutableMap.builder();
for (String entry : searchColors) {
final String[] values = entry.split(":");
if (values.length != 2) {
LOGGER.error("Invalid format for searchColor entry: {}", entry);
} else {
try {
final String name = values[0];
final Integer colorValue = Integer.decode("0x" + values[1]);
searchColorsMapBuilder.put(colorValue, name);
} catch (NumberFormatException e) {
LOGGER.error("Invalid number format for searchColor entry: {}", entry, e);
}
}
}
final ColorNamer colorNamer = new ColorNamer(searchColorsMapBuilder.build());
Internal.setColorNamer(colorNamer);
}
private static Predicate<Object> validEnumElement(Class<? extends Enum<?>> enumClass) {
Set<String> validEntries = new HashSet<>();
Enum<?>[] enumConstants = enumClass.getEnumConstants();
for (Enum<?> enumConstant : enumConstants) {
String name = enumConstant.name();
validEntries.add(name);
}
return obj -> {
if (obj instanceof String) {
String name = (String) obj;
return validEntries.contains(name);
}
return false;
};
}
}
|
package mezz.jei.config;
import dev.ftb.mods.ftblibrary.config.ConfigGroup;
import dev.ftb.mods.ftblibrary.config.NameMap;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import mezz.jei.Internal;
import mezz.jei.color.ColorGetter;
import mezz.jei.color.ColorNamer;
import mezz.jei.ingredients.IngredientSortStage;
import mezz.jei.util.GiveMode;
import net.minecraftforge.common.ForgeConfigSpec;
import org.apache.commons.lang3.EnumUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.annotation.Nullable;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.function.Predicate;
public final class ClientConfig implements IJEIConfig, IClientConfig {
private static final Logger LOGGER = LogManager.getLogger();
@Nullable
private static IClientConfig instance;
public static final int smallestNumColumns = 4;
public static final int largestNumColumns = 100;
public static final int minRecipeGuiHeight = 175;
private final ConfigValues values;
private List<? extends String> searchColors = Arrays.asList(ColorGetter.getColorDefaults());
public static final List<IngredientSortStage> ingredientSorterStagesDefault = Arrays.asList(
IngredientSortStage.MOD_NAME,
IngredientSortStage.INGREDIENT_TYPE,
IngredientSortStage.CREATIVE_MENU,
IngredientSortStage.ALPHABETICAL,
IngredientSortStage.WEAPON_DAMAGE,
IngredientSortStage.TOOL_TYPE,
IngredientSortStage.ARMOR,
IngredientSortStage.TAG
);
private List<IngredientSortStage> ingredientSorterStages = ingredientSorterStagesDefault;
// Forge config
private final ForgeConfigSpec.BooleanValue debugModeEnabled;
private final ForgeConfigSpec.BooleanValue centerSearchBarEnabled;
private final ForgeConfigSpec.BooleanValue lowMemorySlowSearchEnabled;
private final ForgeConfigSpec.EnumValue<GiveMode> giveMode;
private final ForgeConfigSpec.IntValue maxColumns;
private final ForgeConfigSpec.IntValue maxRecipeGuiHeight;
private final ForgeConfigSpec.ConfigValue<List<? extends String>> searchColorsCfg;
private final ForgeConfigSpec.ConfigValue<List<? extends String>> ingredientSorterStagesCfg;
public ClientConfig(ForgeConfigSpec.Builder builder) {
instance = this;
this.values = new ConfigValues();
ConfigValues defaultValues = new ConfigValues();
builder.push("advanced");
{
builder.comment("Debug mode enabled");
debugModeEnabled = builder.define("DebugMode", defaultValues.debugModeEnabled);
builder.comment("Display search bar in the center");
centerSearchBarEnabled = builder.define("CenterSearch", defaultValues.centerSearchBarEnabled);
builder.comment("Set low-memory mode (makes search very slow, but uses less RAM)");
lowMemorySlowSearchEnabled = builder.define("LowMemorySlowSearchEnabled", defaultValues.lowMemorySlowSearchEnabled);
builder.comment("How items should be handed to you");
giveMode = builder.defineEnum("GiveMode", defaultValues.giveMode);
builder.comment("Max number of columns shown");
maxColumns = builder.defineInRange("MaxColumns", defaultValues.maxColumns, smallestNumColumns, largestNumColumns);
builder.comment("Max. recipe gui height");
maxRecipeGuiHeight = builder.defineInRange("RecipeGuiHeight", defaultValues.maxRecipeGuiHeight, minRecipeGuiHeight, Integer.MAX_VALUE);
}
builder.pop();
builder.push("colors");
{
builder.comment("Color values to search for");
searchColorsCfg = builder.defineList("SearchColors", Lists.newArrayList(ColorGetter.getColorDefaults()), ClientConfig::validSearchColor);
}
builder.pop();
builder.push("sorting");
{
builder.comment(String.format("Sorting order for the ingredient list. Valid stages: %s", Arrays.asList(IngredientSortStage.values())));
List<String> defaults = ingredientSorterStagesDefault.stream()
.map(Enum::name)
.toList();
Predicate<Object> elementValidator = validEnumElement(IngredientSortStage.class);
ingredientSorterStagesCfg = builder.defineList("IngredientSortStages", defaults, elementValidator);
}
builder.pop();
}
@Deprecated
public static IClientConfig getInstance() {
Preconditions.checkNotNull(instance);
return instance;
}
@Override
public void buildSettingsGUI(ConfigGroup group) {
ConfigValues defaultVals = new ConfigValues();
group.addBool(cfgTranslation("centerSearchBarEnabled"), values.centerSearchBarEnabled, v -> {
centerSearchBarEnabled.set(v);
values.centerSearchBarEnabled = v;
}, defaultVals.centerSearchBarEnabled);
group.addEnum(cfgTranslation("giveMode"), values.giveMode, v -> {
giveMode.set(v);
values.giveMode = v;
}, NameMap.of(defaultVals.giveMode, GiveMode.values()).create());
group.addInt(cfgTranslation("maxColumns"), values.maxColumns, v -> {
maxColumns.set(v);
values.maxColumns = v;
}, defaultVals.maxColumns, 1, Integer.MAX_VALUE);
group.addInt(cfgTranslation("maxRecipeGuiHeight"), values.maxRecipeGuiHeight, v -> {
maxRecipeGuiHeight.set(v);
values.maxRecipeGuiHeight = v;
}, defaultVals.maxRecipeGuiHeight, 1, Integer.MAX_VALUE);
}
private String cfgTranslation(String name) {
return "advanced." + name;
}
@Override
public void reload() {
this.values.debugModeEnabled = debugModeEnabled.get();
this.values.centerSearchBarEnabled = centerSearchBarEnabled.get();
this.values.lowMemorySlowSearchEnabled = lowMemorySlowSearchEnabled.get();
this.values.giveMode = giveMode.get();
this.values.maxColumns = maxColumns.get();
this.values.maxRecipeGuiHeight = maxRecipeGuiHeight.get();
this.searchColors = searchColorsCfg.get();
this.ingredientSorterStages = ingredientSorterStagesCfg.get()
.stream()
.map(s -> EnumUtils.getEnum(IngredientSortStage.class, s))
.filter(Objects::nonNull)
.toList();
if (ingredientSorterStages.isEmpty()) {
this.ingredientSorterStages = ingredientSorterStagesDefault;
}
syncSearchColorsConfig();
}
@Override
public boolean isDebugModeEnabled() {
return values.debugModeEnabled;
}
@Override
public boolean isCenterSearchBarEnabled() {
return values.centerSearchBarEnabled;
}
@Override
public boolean isLowMemorySlowSearchEnabled() {
return values.lowMemorySlowSearchEnabled;
}
@Override
public GiveMode getGiveMode() {
return values.giveMode;
}
@Override
public int getMaxColumns() {
return values.maxColumns;
}
@Override
public int getMaxRecipeGuiHeight() {
return values.maxRecipeGuiHeight;
}
@Override
public List<IngredientSortStage> getIngredientSorterStages() {
return ingredientSorterStages;
}
private void syncSearchColorsConfig() {
final ImmutableMap.Builder<Integer, String> searchColorsMapBuilder = ImmutableMap.builder();
for (String entry : searchColors) {
final String[] values = entry.split(":");
if (values.length != 2) {
LOGGER.error("Invalid format for searchColor entry: {}", entry);
} else {
try {
final String name = values[0];
final Integer colorValue = Integer.decode("0x" + values[1]);
searchColorsMapBuilder.put(colorValue, name);
} catch (NumberFormatException e) {
LOGGER.error("Invalid number format for searchColor entry: {}", entry, e);
}
}
}
final ColorNamer colorNamer = new ColorNamer(searchColorsMapBuilder.build());
Internal.setColorNamer(colorNamer);
}
@SuppressWarnings("SameParameterValue")
private static Predicate<Object> validEnumElement(Class<? extends Enum<?>> enumClass) {
Set<String> validEntries = new HashSet<>();
Enum<?>[] enumConstants = enumClass.getEnumConstants();
for (Enum<?> enumConstant : enumConstants) {
String name = enumConstant.name();
validEntries.add(name);
}
return obj -> {
if (obj instanceof String name) {
return validEntries.contains(name);
}
return false;
};
}
private static boolean validSearchColor(Object obj) {
if (obj instanceof String entry) {
String[] values = entry.split(":");
if (values.length == 2) {
try {
@SuppressWarnings("unused")
Integer color = Integer.decode("0x" + values[1]);
return true;
} catch (NumberFormatException ignored) {
}
}
}
return false;
}
}
|
package mimickal.mc.dynamo;
import ic2.api.item.IC2Items;
import mimickal.mc.dynamo.common.CommonProxy;
import mimickal.mc.dynamo.common.ModBlocks;
import mimickal.mc.dynamo.common.ModTileEntities;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.Mod.EventHandler;
import net.minecraftforge.fml.common.Mod.Instance;
import net.minecraftforge.fml.common.SidedProxy;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.registry.GameRegistry;
@Mod(
modid = DynamoMod.MOD_ID,
name = DynamoMod.NAME,
version = DynamoMod.VERSION,
acceptedMinecraftVersions = "[1.10.2]"
)
public class DynamoMod {
public static final String MOD_ID = "dynamo";
public static final String NAME = "Dynamo Generator";
public static final String VERSION = "1.0.0";
@SidedProxy(
serverSide = "mimickal.mc.dynamo.common.CommonProxy",
clientSide = "mimickal.mc.dynamo.client.ClientProxy"
)
public static CommonProxy proxy;
@Instance(MOD_ID)
public static DynamoMod instance;
@EventHandler
public void preInit(FMLPreInitializationEvent event) {
System.out.println("Loading " + NAME);
ModBlocks.init();
ModTileEntities.init();
}
@EventHandler
public void init(FMLInitializationEvent event) {
// IC2 recipes are defined via data, and thus need to be fetched on the fly like this
ItemStack electricMotor = IC2Items.getItem("crafting", "electric_motor");
GameRegistry.addRecipe(new ItemStack(ModBlocks.dynamo),
"P P",
"PSP",
"PMP",
'P', Blocks.PLANKS,
'S', Items.STICK,
'M', electricMotor
);
}
@EventHandler
public void postInit(FMLPostInitializationEvent event) {
}
}
|
package gwap.model.action;
import gwap.model.resource.Location;
import gwap.model.resource.Resource;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Scope;
@NamedQueries({
@NamedQuery(name="locationAssignment.scoreSumByPerson",
query="select sum(la.score) from LocationAssignment la where (la.class = Bet and la.revisedBet is null or la.class=LocationAssignment) and la.person = :person"),
@NamedQuery(name="locationAssignment.countByResourceAndLocation",
query="select count(*) from LocationAssignment la where la.resource = :resource and la.location = :location and la.notEvaluated = false"),
@NamedQuery(name="locationAssignment.countByResource",
query="select count(*) from LocationAssignment la where la.resource = :resource and la.notEvaluated = false"),
@NamedQuery(name="locationAssignment.countAndLocationByResource",
query="select count(*), l.id from LocationAssignment la join la.location l " +
"where la.resource = :resource and la.notEvaluated = false " +
"group by l.id order by count(*) desc"),
@NamedQuery(name="locationAssignment.byResource",
query="from LocationAssignment la where la.resource = :resource and la.notEvaluated = false"),
@NamedQuery(name="locationAssignment.byResourceAndPerson",
query="from LocationAssignment la where la.resource = :resource and la.notEvaluated = false and la.person = :person"),
@NamedQuery(name="locationAssignment.scoringSumByResourceAndLocation",
query="select sum(lh.correlation) from LocationAssignment la join la.location.hierarchies lh " +
"where la.resource = :resource and la.notEvaluated = false and lh.name = 'mit.scoring' and lh.sublocation = :location")
})
@Entity
//@Name("locationAssignment")
@Scope(ScopeType.EVENT)
public class LocationAssignment extends Action {
private static final long serialVersionUID = 1L;
@ManyToOne protected Resource resource;
@ManyToOne protected Location location;
/**
* LocationAssignments can have the property notEvaluated set to true in
* order to exclude them from evaluation. This exclusion is for example
* useful in subclasses where the same LocationAssignment is specified.
*/
private Boolean notEvaluated = false;
public Resource getResource() {
return resource;
}
public void setResource(Resource resource) {
this.resource = resource;
}
public Location getLocation() {
return location;
}
public void setLocation(Location location) {
this.location = location;
}
public Boolean isNotEvaluated() {
return notEvaluated;
}
public void setNotEvaluated(Boolean notEvaluated) {
this.notEvaluated = notEvaluated;
}
}
|
package minestra.collection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.BinaryOperator;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.IntFunction;
import java.util.function.Predicate;
import java.util.function.ToDoubleFunction;
import java.util.function.ToIntFunction;
import java.util.function.ToLongFunction;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* An immutable array of <code>T</code>.
* @param <T> the type of the array elements
*/
public interface ImmArray<T> extends Iterable<T> {
/**
* Returns a new ImmArray of the specified values.
* @param <T> the type of the array elements
* @param a values as an array
* @return the new ImmArray
*/
@SafeVarargs
static <T> ImmArray<T> of(T... a) {
return new ImmArrayImpl<>(a);
}
/**
* Returns a new ImmArray of the specified collection.
* @param <T> the type of the array elements
* @param list a values as a collection
* @return the new ImmArray
*/
static <T> ImmArray<T> of(Collection<T> list) {
return new ImmArrayImpl<T>(list);
}
/**
* Returns a new ImmArray of the specified stream.
* @param <T> the type of the array elements
* @param stream a values as a stream
* @return the new ImmArray
*/
static <T> ImmArray<T> of(Stream<T> stream) {
return new ImmArrayImpl<T>(stream.collect(Collectors.toList()));
}
/**
* Returns the concatenated array of all specified arrays.
* @param first the first array
* @param rest the rest of arrays
* @return the concatenated array
*/
@SuppressWarnings("unchecked")
default ImmArray<T> concat(ImmArray<? extends T> first, ImmArray<? extends T>... rest) {
// XXX varargs
final int selfLength = size();
final int firstLength = first.size();
int newLength = selfLength;
newLength += firstLength;
for (ImmArray<? extends T> o : rest) {
newLength += o.size();
}
// XXX copy twice
T[] a = Arrays.copyOf(toArray(), newLength);
int p = selfLength;
System.arraycopy(first.toArray(), 0, a, p, firstLength);
p += firstLength;
for (ImmArray<? extends T> o : rest) {
final int length = o.size();
System.arraycopy(o.toArray(), 0, a, p, length);
p += length;
}
return of(a);
}
/**
* Returns the number of elements in this array.
* @return the number of elements
*/
default int size() {
return toArray().length;
}
/**
* Returns the element at the specified index in this array.
* @param index index of an desired element
* @return the element
*/
default T at(int index) {
return toArray()[index];
}
/**
* Returns an empty array.
* @param <T> the type of the array elements
* @return the empty array
*/
static <T> ImmArray<T> empty() {
@SuppressWarnings("unchecked")
ImmArray<T> o = (ImmArray<T>) ImmArrayImpl.EMPTY;
return o;
}
/**
* Performs apply function as an action to each element of this array.
* @param action action to apply to each element
*/
@Override
default void forEach(Consumer<? super T> action) {
final int n = size();
for (int i = 0; i < n; i++) {
action.accept(at(i));
}
}
/**
* Returns whether this array is empty.
* @return <code>true</code> if this is empty.
*/
default boolean isEmpty() {
return size() == 0;
}
/**
* Returns whether the element which satisfies predicate exists in this array.
* @param pred predicate
* @return <code>true</code> if the element exists
*/
default boolean exists(Predicate<T> pred) {
final int n = size();
for (int i = 0; i < n; i++) {
if (pred.test(at(i))) {
return true;
}
}
return false;
}
/**
* Returns whether this array contains the element which is same as specified element.
* @param o object to find
* @return <code>true</code> if this array contains specified element
*/
default boolean contains(T o) {
final int n = size();
for (int i = 0; i < n; i++) {
if (Objects.equals(at(i), o)) {
return true;
}
}
return false;
}
/**
* Returns an optional value which satisfies specified predicate from the beginning in this array.
* @param pred predicate
* @return the optional value
*/
default Optional<T> find(Predicate<T> pred) {
return find(pred, 0);
}
/**
* Returns an optional value which satisfies specified predicate after the specified index in this array.
* @param pred predicate
* @param start number of beginning index to find
* @return the element as an optional value
*/
default Optional<T> find(Predicate<T> pred, int start) {
for (int i = start, n = size(); i < n; i++) {
T o = at(i);
if (pred.test(o)) {
return Optional.of(o);
}
}
return Optional.empty();
}
/**
* Returns the index of first element which is same as specified object in this array.
* @param o object to find
* @return number of the index, returns <code>-1</code> if not found
*/
default int indexOf(T o) {
final int n = size();
for (int i = 0; i < n; i++) {
if (Objects.equals(at(i), o)) {
return i;
}
}
return -1;
}
/**
* Returns the index of element which is the first match of the specified predicate in this array.
* @param pred predicate
* @return number of the index, returns <code>-1</code> if not found
*/
default int indexWhere(Predicate<T> pred) {
final int n = size();
for (int i = 0; i < n; i++) {
if (pred.test(at(i))) {
return i;
}
}
return -1;
}
/**
* Returns the first element of this array if it is not empty.
* @return the first element as an optional value
*/
default Optional<T> head() {
return (size() == 0) ? Optional.empty() : Optional.of(at(0));
}
/**
* Returns the tail elements of this array if exists.
* @return the tail elements as an array
*/
default ImmArray<T> tail() {
return (size() > 1) ? subSequence(1, Integer.MAX_VALUE) : empty();
}
/**
* Returns a new array of elements that taken out as many as specified number from the beginning of this array.
* @param count count to take
* @return the array
*/
default ImmArray<T> take(int count) {
return (count == 0) ? empty() : subSequence(0, count - 1);
}
/**
* Returns a new array of elements that taken out only while the specified predicate matches from the beginning of this array.
* @param pred predicate
* @return the array
*/
default ImmArray<T> takeWhile(Predicate<T> pred) {
final int index = indexWhere(pred.negate());
return (index > 0) ? subSequence(0, index - 1) : empty();
}
/**
* Returns the rest of the array that drops the specified number of elements in this array.
* @param count count to drop
* @return the array
*/
default ImmArray<T> drop(int count) {
final int n = size();
return (count >= n) ? empty() : subSequence(count, n);
}
/**
* Returns the rest of the array that drops elements which the specified predicate matches in this array.
* @param pred predicate
* @return the array
*/
default ImmArray<T> dropWhile(Predicate<T> pred) {
final int index = indexWhere(pred.negate());
// TODO refactor
return (index >= 0) ? drop(index) : empty();
}
/**
* Returns the slice of this array.
* @param from inclusive index of first
* @param to exclusive index of end
* @return the array
*/
default ImmArray<T> subSequence(int from, int to) {
final int n = size() - 1;
final int to0 = (to < n) ? to : n;
return of(toList().subList(from, to0 + 1));
}
default <R> ImmArray<R> map(Function<? super T, ? extends R> mapper) {
final int n = size();
List<R> a = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
a.add(mapper.apply(at(i)));
}
return ImmArray.of(a);
}
default IntImmArray mapToInt(ToIntFunction<? super T> mapper) {
final int n = size();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = mapper.applyAsInt(at(i));
}
return IntImmArray.of(a);
}
default LongImmArray mapToLong(ToLongFunction<? super T> mapper) {
final int n = size();
long[] a = new long[n];
for (int i = 0; i < n; i++) {
a[i] = mapper.applyAsLong(at(i));
}
return LongImmArray.of(a);
}
default DoubleImmArray mapToDouble(ToDoubleFunction<? super T> mapper) {
final int n = size();
double[] a = new double[n];
for (int i = 0; i < n; i++) {
a[i] = mapper.applyAsDouble(at(i));
}
return DoubleImmArray.of(a);
}
/**
* Returns the array of elements to which flattened sub-level containers of this array.
* This array includes not only containers of sub-level, but flat level elements.
* @param <R> type of result elements
* @return the flatten array
*/
default <R> ImmArray<R> flatten() {
return of(ImmArrayImpl.flatten0(this, new ArrayList<>()));
}
default <R> ImmArray<R> filterMap(Function<? super T, Optional<? extends R>> mapper) {
T[] values = toArray();
final int n = values.length;
List<R> a = new ArrayList<>();
for (int i = 0; i < n; i++) {
mapper.apply(values[i]).ifPresent(a::add);
}
return of(a);
}
default <S, R> ImmArray<R> flatMap(Function<? super S, ? extends R> mapper) {
List<S> a = new ArrayList<>();
return of(ImmArrayImpl.flatten0(this, a)).map(mapper);
}
/**
* Returns the result that reduce elements of this array with the specified binary operator.
* @param op binary operator
* @return the result as optional, or optional empty if this array is empty
*/
default Optional<T> reduce(BinaryOperator<T> op) {
final int n = size();
if (n == 0) {
return Optional.empty();
}
T result = at(0);
for (int i = 1; i < n; i++) {
result = op.apply(result, at(i));
}
return Optional.of(result);
}
/**
* Returns the result that reduce elements of this array with the specified binary operator.
* @param identity identity element
* @param op binary operator
* @return the result
*/
default T reduce(T identity, BinaryOperator<T> op) {
final int n = size();
if (n == 0) {
return identity;
}
T result = identity;
for (int i = 0; i < n; i++) {
result = op.apply(result, at(i));
}
return result;
}
/**
* Returns the result of folding the elements of this array by the specified operator.
* @param value initial value
* @param op binary operator
* @return the result
*/
default T fold(T value, BinaryOperator<T> op) {
switch (size()) {
case 0:
return value;
case 1:
return op.apply(value, at(0));
default:
return op.apply(value, tail().fold(at(0), op));
}
}
/**
* Returns a new array which consists with unique elements.
* @return the array
*/
default ImmArray<T> distinct() {
return of(new LinkedHashSet<>(toList()));
}
/**
* Returns the result of filtering the elements of this array by specified predicate.
* @param pred predicate
* @return the array
*/
default ImmArray<T> filter(Predicate<? super T> pred) {
final int n = size();
List<T> a = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
T o = at(i);
if (pred.test(o)) {
a.add(o);
}
}
return of(a);
}
/**
* Returns new array which is sorted this array in natural order.
* @return the sorted array
*/
default ImmArray<T> sort() {
T[] values = toArray();
Arrays.sort(values);
return of(values);
}
/**
* Returns new array which is sorted this array with specified order.
* @param cmp order
* @return the sorted array
*/
default ImmArray<T> sortWith(Comparator<T> cmp) {
T[] values = toArray();
Arrays.sort(values, cmp);
return of(values);
}
/**
* Returns new array which is reversed the order of elements in this array.
* @return the array
*/
default ImmArray<T> reverse() {
T[] a = toArray();
final int size = a.length;
final int n = a.length / 2;
for (int i = 0, j = size - 1; i < n; i++, j
T x = a[j];
a[j] = a[i];
a[i] = x;
}
return of(a);
}
/**
* Returns this array as a native array.
* @return the array
*/
T[] toArray();
/**
* Returns this array as a native array.
* @param generator function to generate native array
* @return the array
*/
default T[] toArray(IntFunction<T[]> generator) {
final int n = size();
T[] a = generator.apply(n);
for (int i = 0; i < n; i++) {
a[i] = at(i);
}
return a;
}
/**
* Returns the list which consists same elements in this array.
* @return the list
*/
default List<T> toList() {
return Arrays.asList(toArray());
}
/**
* Returns the set which consists same elements in this array.
* @return the set
*/
default Set<T> toSet() {
Set<T> set = new HashSet<>();
Collections.addAll(set, toArray());
return set;
}
/**
* Returns the map that is created with each element as value and the key generated by specified generator.
* @param <R> type of value in the result map
* @param gen key generator
* @return the map
*/
default <R> Map<T, R> toMapWithKey(Function<? super T, ? extends R> gen) {
Map<T, R> m = new HashMap<>();
for (T k : this) {
m.put(k, gen.apply(k));
}
return m;
}
/**
* Returns the map that is created with each element as key and the value generated by specified generator.
* @param <R> type of key in the result map
* @param gen value generator
* @return the map
*/
default <R> Map<R, T> toMapWithValue(Function<? super T, ? extends R> gen) {
Map<R, T> m = new HashMap<>();
for (T k : this) {
m.put(gen.apply(k), k);
}
return m;
}
/**
* Returns the stream which consist same elements in this array.
* @return the stream
*/
default Stream<T> stream() {
return toList().stream();
}
/**
* Returns this array as a native string array.
* If an element is <code>null</code>, it converts an empty string.
* @return the string array
*/
default String[] toStringArray() {
final int n = size();
String[] a = new String[n];
for (int i = 0; i < n; i++) {
a[i] = Objects.toString(at(i), null);
}
return a;
}
}
|
package SW9.model_canvas;
import SW9.MouseTracker;
import SW9.model_canvas.locations.Location;
import SW9.utility.DragHelper;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.value.ObservableDoubleValue;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.Label;
import javafx.scene.paint.Color;
import javafx.scene.shape.*;
public class ModelComponent extends ModelContainer {
public final DoubleProperty xProperty;
public final DoubleProperty yProperty;
public final DoubleProperty widthProperty;
public final DoubleProperty heightProperty;
// The initial and final locations
private final Location initialLocation;
private final Location finalLocation;
// The frame of the component
private final Path frame = new Path();
// The name of the component
private final Label label;
private final Rectangle labelContainer;
private final Polygon labelTriangle;
private static final double CORNER_SIZE = 50;
public ModelComponent(final double x, final double y, final double width, final double height, final String name, final MouseTracker canvasMouseTracker) {
// Initialize the spacial properties
xProperty = new SimpleDoubleProperty(x);
yProperty = new SimpleDoubleProperty(y);
widthProperty = new SimpleDoubleProperty(width);
heightProperty = new SimpleDoubleProperty(height);
DragHelper.makeDraggable(this, mouseEvent -> {
return (mouseEvent.getX() < xProperty().get() + widthProperty.get()) &&
(mouseEvent.getY() < yProperty().get() + heightProperty.get());
});
// Initialize the frame of the component
initializeFrame(frame);
// Initialize locations
initialLocation = new Location(
xProperty.add(CORNER_SIZE / 2d),
yProperty.add(CORNER_SIZE / 2d),
canvasMouseTracker,
Location.Type.INITIAL
);
finalLocation = new Location(
xProperty.add(widthProperty.subtract(CORNER_SIZE / 2d)),
yProperty.add(heightProperty.subtract(CORNER_SIZE / 2d)),
canvasMouseTracker,
Location.Type.FINAL
);
// Initialize properties for the name of the component
labelContainer = new Rectangle();
label = new Label(name);
labelTriangle = new Polygon(
xProperty.get() + CORNER_SIZE / 2, yProperty.get() + CORNER_SIZE / 2,
xProperty.get() + CORNER_SIZE, yProperty.get(),
xProperty.get() + CORNER_SIZE, yProperty.get() + CORNER_SIZE / 2
);
// Bind the properties for the name of the component
labelContainer.xProperty().bind(xProperty.add(CORNER_SIZE));
labelContainer.yProperty().bind(yProperty);
labelContainer.widthProperty().bind(widthProperty.subtract(CORNER_SIZE));
labelContainer.heightProperty().set(CORNER_SIZE / 2);
label.layoutXProperty().bind(labelContainer.xProperty());
label.layoutYProperty().bind(labelContainer.yProperty());
// Style the name of the component
Color redColor = Color.web("#D50000");
labelContainer.fillProperty().set(redColor);
labelContainer.setStrokeWidth(1d);
labelContainer.setStroke(redColor);
labelContainer.setStrokeType(StrokeType.OUTSIDE);
labelContainer.setStrokeLineJoin(StrokeLineJoin.ROUND);
label.textFillProperty().set(Color.WHITE);
label.alignmentProperty().set(Pos.CENTER);
label.setPrefHeight(CORNER_SIZE / 2);
label.paddingProperty().set(new Insets(0, 0, 0, 10));
label.getStyleClass().add("subhead");
labelTriangle.setFill(redColor);
labelTriangle.setStrokeWidth(1d);
labelTriangle.setStroke(redColor);
labelTriangle.setStrokeType(StrokeType.OUTSIDE);
labelTriangle.setStrokeLineJoin(StrokeLineJoin.ROUND);
labelTriangle.layoutXProperty().bind(xProperty.subtract(x));
labelTriangle.layoutYProperty().bind(yProperty.subtract(y));
addChildren(
frame,
labelTriangle,
labelContainer,
label,
initialLocation,
finalLocation
);
}
private void initializeFrame(final Path frame) {
MoveTo p1 = new MoveTo();
LineTo p2 = new LineTo();
LineTo p3 = new LineTo();
LineTo p4 = new LineTo();
LineTo p5 = new LineTo();
LineTo p6 = new LineTo();
LineTo p7 = new LineTo();
p1.xProperty().bind(xProperty);
p1.yProperty().bind(yProperty.add(CORNER_SIZE));
p2.xProperty().bind(xProperty.add(CORNER_SIZE));
p2.yProperty().bind(yProperty);
p3.xProperty().bind(xProperty.add(widthProperty));
p3.yProperty().bind(yProperty);
p4.xProperty().bind(xProperty.add(widthProperty));
p4.yProperty().bind(yProperty.add(heightProperty).subtract(CORNER_SIZE));
p5.xProperty().bind(xProperty.add(widthProperty).subtract(CORNER_SIZE));
p5.yProperty().bind(yProperty.add(heightProperty));
p6.xProperty().bind(xProperty);
p6.yProperty().bind(yProperty.add(heightProperty));
p7.xProperty().bind(p1.xProperty());
p7.yProperty().bind(p1.yProperty());
frame.getElements().addAll(p1, p2, p3, p4, p5, p6, p7);
frame.setStroke(Color.BLACK);
frame.setStrokeWidth(2d);
frame.setFill(Color.TRANSPARENT);
}
@Override
public MouseTracker getMouseTracker() {
return mouseTracker;
}
@Override
public DoubleProperty xProperty() {
return xProperty;
}
@Override
public DoubleProperty yProperty() {
return yProperty;
}
@Override
public ObservableDoubleValue getXLimit() {
return widthProperty;
}
@Override
public ObservableDoubleValue getYLimit() {
return heightProperty;
}
}
|
package at.jku.pervasive.ecg;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import javax.swing.JFrame;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.data.time.Millisecond;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.xy.XYDataset;
public class ECGMonitor extends JFrame {
private class ListenForUpdates extends Thread implements IHeartManListener {
private final BlockingQueue<Double> buffer;
private final TimeSeries series;
public ListenForUpdates(TimeSeries series) {
super();
this.series = series;
this.buffer = new LinkedBlockingQueue<Double>();
}
@Override
public void dataReceived(String address, double value) {
this.buffer.add(value);
}
@Override
public void run() {
while (!isInterrupted()) {
try {
Double value = this.buffer.take();
this.series.addOrUpdate(new Millisecond(), value);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
private final ListenForUpdates listenForUpdates;
public ECGMonitor() {
super();
setDefaultCloseOperation(EXIT_ON_CLOSE);
TimeSeries timeSeries = new TimeSeries("ecg");
timeSeries.setMaximumItemAge(TimeUnit.SECONDS.toMillis(10));
XYDataset dataset = new TimeSeriesCollection(timeSeries);
JFreeChart chart = ChartFactory.createTimeSeriesChart("ecg", "time", "V",
dataset, false, false, false);
ChartPanel chartPanel = new ChartPanel(chart);
add(chartPanel);
listenForUpdates = new ListenForUpdates(timeSeries);
listenForUpdates.start();
pack();
// center on screen
setLocationRelativeTo(null);
}
public IHeartManListener getHeartManListener() {
return listenForUpdates;
}
}
|
package moba.server.messages;
import moba.server.com.Endpoint;
public class Message implements Comparable {
protected long trigger;
protected Endpoint endpoint = null;
protected Object data = null;
protected int groupId;
protected int messageId;
protected MessageType messageType = null;
public Message(MessageType msgType, Object data, Endpoint ep) {
this(msgType, data);
endpoint = ep;
messageType = msgType;
}
public Message(MessageType msgType, Object data) {
this(msgType.getGroupId(), msgType.getMessageId(), data);
}
public Message(int groupId, int msgId, Object data, Endpoint ep) {
this(groupId, msgId, data);
endpoint = ep;
}
public Message(int grpId, int msgId, Object data) {
this(grpId, msgId);
this.data = data;
}
public Message(int grpId, int msgId) {
if (grpId < 1 || msgId < 1) {
throw new ExceptionInInitializerError("invalid data given");
}
groupId = grpId;
messageId = msgId;
trigger = System.currentTimeMillis();
}
@Override
public int compareTo(Object o) {
long i = trigger;
long j = ((Message)o).trigger;
if(i < j) {
return -1;
}
if(i > j) {
return 1;
}
return 0;
}
public Endpoint getEndpoint() {
return endpoint;
}
public Object getData() {
return data;
}
public int getMessageId() {
return messageId;
}
public int getGroupId() {
return groupId;
}
public MessageType getMessageType() {
return messageType;
}
@Override
public String toString() {
String rv = "";
if(endpoint != null) {
rv = "<" + endpoint.getSocket().toString() + ">";
}
rv += "<" + Long.toString(groupId) + ":" + Long.toString(messageId) + ">";
if(data != null) {
rv += "<" + data.toString() + ">";
}
return rv;
}
}
|
package au.com.tyo.common.ui;
import android.annotation.TargetApi;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.FrameLayout;
import android.widget.TextView;
import java.util.List;
import au.com.tyo.common.ui.ImageViewAutoRefreshed.ImageItem;
public class PreviewBox extends FrameLayout {
private static final String LOG_TAG = "PreviewBox";
public enum PreviewType { HIGHLIGHT, CATEGORY, CATEGORY_ALL };
// UI components
private ImageViewAutoRefreshed imgView;
private TextView textView;
private PreviewType type;
/**
* @param context
*/
public PreviewBox(Context context) {
super(context);
init();
}
/**
* @param context
* @param attrs
*/
public PreviewBox(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
/**
* @param context
* @param attrs
* @param defStyleAttr
*/
public PreviewBox(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
/**
* @param context
* @param attrs
* @param defStyleAttr
* @param defStyleRes
*/
@TargetApi(21)
public PreviewBox(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init();
}
public PreviewType getType() {
return type;
}
public void setType(PreviewType type) {
this.type = type;
}
private void init() {
this.setClickable(true);
this.setType(PreviewType.HIGHLIGHT);
}
public boolean isCategoryType() {
return type == PreviewType.CATEGORY;
}
public boolean isCategoryAllType() {
return type == PreviewType.CATEGORY_ALL;
}
public boolean isHighlightType() {
return type == PreviewType.HIGHLIGHT;
}
public void addPreviewItem(ImageItem item) {
imgView.addImage(item);
}
public void setPreviewItems(List<ImageItem> items) {
imgView.setImages(items);
}
public ImageItem getCurrentItem() {
return (ImageItem) imgView.getCurrentImage();
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
imgView = (ImageViewAutoRefreshed) this.findViewById(R.id.preview_box_bg_img);
//imgView.setScaleType(ImageView.ScaleType.CENTER_CROP );
textView = (TextView) this.findViewById(R.id.preview_box_title);
setTitleResource(R.string.empty_string);
}
public void setBackgroudImageResource(int resId) {
imgView.setImageResource(resId);
}
public void setTitleResource(int resId) {
textView.setText(resId);
}
public void setTitle(CharSequence title) {
textView.setText(title);
}
public void start() {
try {
imgView.display();
}
catch (Exception ex) {
Log.e(LOG_TAG, ex.getMessage());
}
}
public void stop() {
imgView.pause();
}
}
|
package nl.sogeti.jct.java8party;
/**
* A car.
*/
class Car {
private String brand;
private String color;
/**
* A car.
*
* @param brand Brand
* @param color Color
*/
Car(String brand, String color) {
this.brand = brand;
this.color = color;
}
@Override
public String toString() {
return "Car{" +
"brand='" + brand + '\'' +
", color='" + color + '\'' +
'}';
}
/**
* @return Brand
*/
String getBrand() {
return brand;
}
/**
* @return Color
*/
String getColor() {
return color;
}
}
|
package org.c4sg.dao;
import java.util.List;
import java.util.Map;
import org.c4sg.entity.ProjectSkill;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
public interface ProjectSkillDAO extends CrudRepository<ProjectSkill, Long> {
ProjectSkill findByProject_IdAndSkill_Id(Integer projectId, Integer skillId);
List<ProjectSkill> findByProjectId(Integer ProjectId);
String FIND_SKILL_FOR_PROJECT ="select s.skillName as skillName "
+"from ProjectSkill ps inner join ps.skill s where ps.project.id= :id order by ps.displayOrder";
@Query(FIND_SKILL_FOR_PROJECT)
List<Map<String, Object>> findSkillsByProjectId(@Param("id") Integer id);
int countByProjectIdAndSkillId(Integer id, Integer skillId);
int countByProjectId(Integer id);
}
|
package org.cactoos.scalar;
import org.cactoos.Scalar;
import org.cactoos.iterable.IterableOf;
import org.cactoos.iterable.Mapped;
/**
* Find the highest item.
*
* <p>Here is how you can use it to
* find highest of {@link Comparable} items:</p>
*
* <pre>
* final String highest = new HighestOf<String>(
* () -> "Banana", () -> "Apple", () -> "Orange"
* ).value();
* // -> highest == "Orange"
*
* final Character highestChar = new HighestOf<>('B', 'U', 'G').value();
* // -> highestChar == 'U'
* </pre>
*
* <p>This class implements {@link Scalar}, which throws a checked
* {@link Exception}. This may not be convenient in many cases. To make
* it more convenient and get rid of the checked exception you can
* use {@link UncheckedScalar} or {@link IoCheckedScalar} decorators.</p>
*
* <p>There is no thread-safety guarantee.
*
* @author Fabricio Cabral (fabriciofx@gmail.com)
* @author Eduard Balovnev (bedward70@mail.ru)
* @version $Id$
* @param <T> Scalar type
* @see UncheckedScalar
* @see IoCheckedScalar
* @since 0.29
*/
public final class HighestOf<T extends Comparable<T>> implements Scalar<T> {
/**
* Result.
*/
private final Scalar<T> result;
/**
* Ctor.
* @param items The comparable items
*/
@SafeVarargs
public HighestOf(final T... items) {
this(
new Mapped<>(
item -> () -> item,
items
)
);
}
/**
* Ctor.
* @param scalars The scalars
*/
@SafeVarargs
public HighestOf(final Scalar<T>... scalars) {
this(new IterableOf<>(scalars));
}
/**
* Ctor.
* @param iterable The items
*/
public HighestOf(final Iterable<Scalar<T>> iterable) {
this.result = new Folded<>(
(first, second) -> {
final T value;
if (first.compareTo(second) > 0) {
value = first;
} else {
value = second;
}
return value;
},
iterable
);
}
@Override
public T value() throws Exception {
return this.result.value();
}
}
|
package org.dungeon.spells;
import org.dungeon.entity.creatures.Creature;
import org.dungeon.entity.creatures.Hero;
import org.dungeon.entity.creatures.HeroUtils;
import org.dungeon.entity.items.Item;
import org.dungeon.game.DungeonStringBuilder;
import org.dungeon.game.Engine;
import org.dungeon.game.Id;
import org.dungeon.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public final class SpellData {
private final static Map<Id, Spell> spellMap = new HashMap<Id, Spell>();
static {
putSpell(new Spell("HEAL", "Heal") {
private static final int HEALING_VALUE = 10;
private static final int SECONDS_TO_CAST_HEAL = 25;
@Override
public void operate(Hero hero, String[] targetMatcher) {
if (targetMatcher.length == 0) {
Engine.rollDateAndRefresh(SECONDS_TO_CAST_HEAL);
hero.getHealth().incrementBy(HEALING_VALUE);
writeHealCastOnSelf(hero);
} else {
Creature target = hero.findCreature(targetMatcher);
if (target != null) {
Engine.rollDateAndRefresh(SECONDS_TO_CAST_HEAL);
if (hero == target) { // The player used cast ... on <character name>.
writeHealCastOnSelf(hero);
} else {
writeHealCastOnTarget(target);
}
target.getHealth().incrementBy(HEALING_VALUE);
}
}
}
private void writeHealCastOnSelf(Hero hero) {
Writer.write("You casted " + getName() + " on yourself.");
if (hero.getHealth().isFull()) {
Writer.write("You are completely healed.");
}
}
private void writeHealCastOnTarget(Creature target) {
Writer.write("You casted " + getName() + " on " + target.getName().getSingular() + ".");
if (target.getHealth().isFull()) {
Writer.write(target.getName() + " is completely healed.");
}
}
});
putSpell(new Spell("REPAIR", "Repair") {
private static final int REPAIR_VALUE = 50;
private static final int SECONDS_TO_CAST_REPAIR = 10;
@Override
public void operate(Hero hero, String[] targetMatcher) {
Item selectedItem;
if (targetMatcher.length == 0) {
selectedItem = hero.getWeapon();
if (selectedItem == null) {
Writer.write("You are not equipping anything.");
}
} else {
selectedItem = HeroUtils.findItem(hero.getInventory().getItems(), targetMatcher);
}
if (selectedItem != null) {
effectivelyOperate(hero, selectedItem);
}
}
private void effectivelyOperate(Hero hero, Item item) {
if (!item.hasTag(Item.Tag.REPAIRABLE)) {
Writer.write(item.getName().getSingular() + " is not repairable.");
} else {
Engine.rollDateAndRefresh(SECONDS_TO_CAST_REPAIR); // Time passes before casting.
if (!hero.getInventory().hasItem(item)) { // If the item disappeared.
Writer.write(item.getName().getSingular() + " disappeared before you finished casting.");
} else {
boolean wasCompletelyRepaired = item.getIntegrity().isPerfect();
item.getIntegrity().incrementBy(REPAIR_VALUE);
Writer.write("You casted " + getName() + " on " + item.getName().getSingular() + ".");
if (wasCompletelyRepaired) {
Writer.write(item.getName().getSingular() + " was already completely repaired.");
} else {
if (item.getIntegrity().isPerfect()) { // The item became completely repaired.
Writer.write(item.getName().getSingular() + " is now completely repaired.");
}
}
}
}
}
});
putSpell(new Spell("PERCEIVE", "Perceive") {
private static final int SECONDS_TO_CAST_PERCEIVE = 15;
@Override
public void operate(Hero hero, String[] targetMatcher) {
Engine.rollDateAndRefresh(SECONDS_TO_CAST_PERCEIVE);
List<Creature> creatureList = new ArrayList<Creature>(hero.getLocation().getCreatures());
creatureList.remove(hero);
DungeonStringBuilder builder = new DungeonStringBuilder();
builder.append("You concentrate and allow your spells to show you what your eyes may have missed...\n");
Hero.writeCreatureSight(creatureList, builder);
Hero.writeItemSight(hero.getLocation().getItemList(), builder);
Writer.write(builder);
}
});
putSpell(new Spell("VEIL_OF_DARKNESS", "Veil Of Darkness") {
private static final int SECONDS_TO_CAST_VEIL_OF_DARKNESS = 60;
@Override
public void operate(Hero hero, String[] targetMatcher) {
if (targetMatcher.length == 0) {
Writer.write("Provide a target.");
} else {
Creature target = hero.findCreature(targetMatcher);
if (target != null) {
Engine.rollDateAndRefresh(SECONDS_TO_CAST_VEIL_OF_DARKNESS);
target.getLightSource().disable();
Writer.write("You casted " + getName() + " on " + target.getName().getSingular() + ".");
}
}
}
});
putSpell(new Spell("UNVEIL", "Unveil") {
public static final int SECONDS_TO_CAST_UNVEIL = 10;
@Override
public void operate(Hero hero, String[] targetMatcher) {
if (targetMatcher.length == 0) {
Writer.write("Provide a target.");
} else {
Creature target = hero.findCreature(targetMatcher);
if (target != null) {
Engine.rollDateAndRefresh(SECONDS_TO_CAST_UNVEIL);
target.getLightSource().enable();
Writer.write("You casted " + getName() + " on " + target.getName().getSingular() + ".");
}
}
}
});
}
private SpellData() {
}
public static Map<Id, Spell> getSpellMap() {
return spellMap;
}
private static void putSpell(Spell spell) {
spellMap.put(spell.getId(), spell);
}
}
|
package com.boundary.plugin.sdk.rpc;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.List;
import org.slf4j.LoggerFactory;
/**
*
* @author Santosh Patil
* @Date 16-05-2017
*/
public class RPC {
private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(RPC.class);
final static String HOSTNAME = "localhost";
final static int PORTNUMBER = 9192;
private static RPC rpc = new RPC();
private Socket socket;
private DataOutputStream dataOutputStream;
private RPC() {
super();
}
public static RPC getInstance() {
if (rpc == null) {
rpc = new RPC();
}
return rpc;
}
public boolean openConnection() {
if (this.socket == null) {
try {
this.socket = new Socket(HOSTNAME, PORTNUMBER);
this.dataOutputStream = new DataOutputStream(socket.getOutputStream());;
//socket.setKeepAlive(true);
return true;
} catch (UnknownHostException e) {
LOG.error("Unable to open socket connection to host", e);
} catch (IOException e) {
LOG.error("Unable to open Socket Connection", e);
}
}
return false;
}
public void send(final String content) {
try {
if (socket != null) {
dataOutputStream.writeBytes(content);
dataOutputStream.flush();
} else {
LOG.error("Unable to write the events, Socket connection is not open");
}
} catch (IOException ex) {
LOG.error("Exception occured while sending content to meter", ex);
}
}
public int sendList(final List<String> contentList) {
int totalRecordsWritten = 0;
try {
if (socket != null && dataOutputStream != null) {
for (String content : contentList) {
dataOutputStream.writeBytes(content);
totalRecordsWritten++;
}
dataOutputStream.flush();
} else {
LOG.error("Unable to write the events, Socket connection is not open");
}
} catch (IOException ex) {
LOG.error("Exception occured while sending content to meter", ex);
}
return totalRecordsWritten;
}
public boolean closeConnection() {
try {
if (dataOutputStream != null) {
dataOutputStream.close();
dataOutputStream = null;
}
if (socket != null) {
socket.close();
socket = null;
}
return true;
} catch (IOException e) {
LOG.error("Unable to close Socket Connection", e);
}
return false;
}
}
|
package org.grouplens.grapht;
import javax.annotation.Nullable;
import javax.inject.Qualifier;
import java.lang.annotation.Annotation;
/**
* <p>
* Context is the main entry point for configuring bind rules using the fluent
* API. The dependency injector uses the contexts to limit the scope of a
* binding. Every time a dependency is satisfied, that type (and possibly {@link Qualifier})
* is pushed onto the context stack. Thus, if two different types each require a
* Foo, there can be two different bindings activated depending on which first
* type is in the context stack.
* <p>
* The "root" context is an empty stack, and will always be matched. When
* creating bindings, the context stack can be configured by calling
* {@link #in(Class)} or {@link #in(Class, Class)}.
*
* @see org.grouplens.grapht.spi.ElementChainContextMatcher
* @author Michael Ludwig <mludwig@cs.umn.edu>
*/
public interface Context {
/**
* Start a new binding for the given type T within the scope of this
* context. The returned Binding instance can be configured and completed by
* invoking one of its various to() methods. By default, the resulting binding will
* apply to both qualified and unqualified uses of the type; see {@link Binding#withQualifier(Class)}
* to restrict to qualified types, and {@link Binding#unqualified()}} to restrict to only
* match unqualified types.
*
* @param <T> The matched source type
* @param type The raw class that is matched
* @return A new binding in this context for type T
*/
<T> Binding<T> bind(Class<T> type);
/**
* Start a new binding for a qualified type. A shortcut for {@code
* bind(type).withQualifier(qual)}, if {@code qual} is non-null, and {@code
* bind(type).unqualified()} if {@code qual} is null.
*
* @param qual The type's qualifier.
* @param type The type to bind.
* @param <T> The type to bind.
* @return A new binding in this context for T with qualifier qual.
* @see #bind(Class)
* @see Binding#withQualifier(Class)
* @see Binding#unqualified()
*/
<T> Binding<T> bind(Class<? extends Annotation> qual, Class<T> type);
/**
* @deprecated Use {@link #within(Class)}.
*/
@Deprecated
Context in(Class<?> type);
/**
* @deprecated Use {@link #within(Class, Class)}.
*/
@Deprecated
Context in(@Nullable Class<? extends Annotation> qualifier, Class<?> type);
/**
* @deprecated Use {@link #within(Annotation, Class)}.
*/
@Deprecated
Context in(@Nullable Annotation qualifier, Class<?> type);
/**
* Create a new Context that extends the current context stack with the
* given class type. This matches with the default {@link Qualifier}. This is equivalent
* to <code>within(null, type);</code>
*
* @param type The type to extend this context by
* @return A new Context with a longer context stack
*/
Context within(Class<?> type);
/**
* Create a new Context that extends the current context stack with the
* given class and {@link Qualifier} annotation. If the qualifier is null,
* the default or null qualifier is used.
*
* @param qualifier The qualifier type that must be matched along with the type
* @param type The type to extend this context by
* @return A new Context with a longer context stack
*/
Context within(@Nullable Class<? extends Annotation> qualifier, Class<?> type);
/**
* Create a new Context that extends the current context stack with the
* given class, qualified by the specific Annotation instance. If the
* qualifier is null, the default or null qualifier is used.
*
* <p>The annotation provided must be serializable. Annotations built by {@link
* org.grouplens.grapht.annotation.AnnotationBuilder} (recommended) or retrieved from the Java
* reflection API are serializable; if you use some other annotation implementation, it must be
* serializable.
*
* @param qualifier The qualifier instance that must be matched along with
* the type
* @param type The type to extend this context by
* @return A new Context with a longer context stack
*/
Context within(@Nullable Annotation qualifier, Class<?> type);
/**
* Create a new Context that extends the current context stack with the given class type as an
* anchored match. This matches with the default {@link Qualifier}. This is equivalent to
* <code>at(null, type);</code>
*
* @param type The type to extend this context by
* @return A new Context with a longer context stack
* @see #at(Class, Class)
*/
Context at(Class<?> type);
/**
* Create a new Context that extends the current context stack with the given class and {@link
* Qualifier} annotation as an anchored match. If the qualifier is null, the default or null
* qualifier is used.
* <p>
* Unlike {@link #in(Class,Class)}, this match is <em>anchored</em> — that is, it only
* matches at the end of a context chain. Context is matched if it ends with this or,
* if further context is opened inside this context, if the inner context matches immediately.
* </p>
*
* @param qualifier The qualifier type that must be matched along with the type
* @param type The type to extend this context by
* @return A new Context with a longer context stack
*/
Context at(@Nullable Class<? extends Annotation> qualifier, Class<?> type);
/**
* Create a new Context that extends the current context stack with the given class, qualified
* by the specific Annotation instance. as an anchored match. If the qualifier is null, the
* default or null qualifier is used.
*
* <p>The annotation provided must be serializable. Annotations built by {@link
* org.grouplens.grapht.annotation.AnnotationBuilder} (recommended) or retrieved from the Java
* reflection API are serializable; if you use some other annotation implementation, it must be
* serializable.
*
* @param qualifier The qualifier instance that must be matched along with the type
* @param type The type to extend this context by
* @return A new Context with a longer context stack
*/
Context at(@Nullable Annotation qualifier, Class<?> type);
}
|
package org.jtrfp.trcl;
import java.awt.Point;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;
import org.jtrfp.trcl.core.PortalTexture;
import org.jtrfp.trcl.core.TR;
import org.jtrfp.trcl.core.TextureDescription;
import org.jtrfp.trcl.file.DirectionVector;
import org.jtrfp.trcl.file.TDFFile;
import org.jtrfp.trcl.file.TDFFile.TunnelLogic;
import org.jtrfp.trcl.gpu.Model;
import org.jtrfp.trcl.miss.LoadingProgressReporter;
import org.jtrfp.trcl.obj.PortalEntrance;
import org.jtrfp.trcl.obj.PortalExit;
import org.jtrfp.trcl.obj.TerrainChunk;
public final class TerrainSystem extends RenderableSpacePartitioningGrid{
final double gridSquareSize;
//final double heightScalar;
final ArrayList<TerrainChunk> renderingCubes = new ArrayList<TerrainChunk>();
private final TR tr;
private final ExecutorService executor;
public static final double Y_NUDGE = -10000;
/*
* Y_NUDGE is a kludge. There is a tiny sliver of space
* between the ceiling and ground, likely caused by model
* vertex quantization in the rendering engine. I would
* rather put up with this quirk than re-design the engine,
* as the quantization exists as a side-effect of a
* memory-space optimization in the GPU and accommodating
* the fix of this bug could cause bigger problems further
* down the road.
*/
public TerrainSystem(final AltitudeMap altitude,
final TextureMesh textureMesh, final double gridSquareSize,
final RenderableSpacePartitioningGrid terrainMirror, final TR tr,
final TDFFile tdf, final boolean flatShading,
final LoadingProgressReporter terrainReporter, final String debugName) {
super();
final int numCores = Runtime.getRuntime().availableProcessors();
this.tr = tr;
final int width = (int) altitude.getWidth();
int height = (int) altitude.getHeight();
this.gridSquareSize = gridSquareSize;
executor = new ThreadPoolExecutor(numCores * 2, numCores * 2, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(),
new ThreadFactory(){
@Override
public Thread newThread(final Runnable runnable) {
final Thread result = new Thread("TerrainSystem "+hashCode()){
public void run(){
runnable.run();}
};
return result;
}});
final int chunkSideLength = TR.terrainChunkSideLengthInSquares;
final double u[] = { 0, 1, 1, 0 };
final double v[] = { 0, 0, 1, 1 };
final double cu[] = { 0, 1, 1, 0 };
final double cv[] = { 1, 1, 0, 0 };
final NormalMap normalMap = new NormalMap(altitude);
// Come up with a point list for tunnel entrances and exits
TDFFile.Tunnel[] tunnels = tdf.getTunnels();
final HashMap<Integer, TunnelPoint> points = new HashMap<Integer, TunnelPoint>();
final HashMap<String, TDFFile.Tunnel> tunnelsByName = new HashMap<String, TDFFile.Tunnel>();
final ArrayList<Future<Void>> rowTasks = new ArrayList<Future<Void>>();
if (tunnels != null) {// Null means no tunnels
for (int i = 0; i < tunnels.length; i++) {
final TDFFile.Tunnel tun = tunnels[i];
if (tun.getEntranceLogic() != TunnelLogic.invisible) {
final TunnelPoint tp = new TunnelPoint(tun, true);
points.put(tp.hashCode(), tp);
}
if (tun.getExitLogic() != TunnelLogic.invisible) {
final TunnelPoint tp = new TunnelPoint(tun, false);
points.put(tp.hashCode(), tp);
tunnelsByName.put(tun.getTunnelLVLFile(), tunnels[i]);
}//end if(invisible)
}// end for(tunnels)
}// end if(tunnels)
final LoadingProgressReporter[] reporters = terrainReporter
.generateSubReporters(256/chunkSideLength);
int reporterIndex=0;
final double worldCeiling = tr.getWorld().sizeY;
// For each chunk
for (int gZ = 0; gZ < height; gZ += chunkSideLength) {
reporters[reporterIndex++].complete();
final int _gZ = gZ;
rowTasks.add(executor.submit(new Callable<Void>(){
@Override
public Void call() throws Exception {
for (int gX = 0; gX < width; gX += chunkSideLength) {
// GROUND
{// Start scope
final double objectX = Math
.round(((double) gX + ((double) chunkSideLength / 2.))
* gridSquareSize);
final double objectZ = Math
.round(((double) _gZ + ((double) chunkSideLength / 2.))
* gridSquareSize);
final double objectY = Math.round(altitude
.heightAt(gX*gridSquareSize, _gZ*gridSquareSize));
final Model m = new Model(false, tr,"Terrain Chunk");
m.setDebugName(debugName);
// for each square
for (int cZ = _gZ; cZ < _gZ + chunkSideLength; cZ++) {
for (int cX = gX; cX < gX + chunkSideLength; cX++) {
final double xPos = cX * gridSquareSize;
final double zPos = cZ * gridSquareSize;
final double hTL = altitude.heightAt(xPos, cZ* gridSquareSize);
final double hTR = altitude.heightAt((cX + 1)* gridSquareSize, cZ* gridSquareSize);
final double hBR = altitude.heightAt((cX + 1)* gridSquareSize,
(cZ + 1)* gridSquareSize);
final double hBL = altitude.heightAt(xPos, (cZ + 1)* gridSquareSize);
Vector3D norm0, norm1, norm2, norm3;
norm3 = normalMap.normalAt(xPos, cZ* gridSquareSize);
/*norm3 = new Vector3D(norm.getX() * 3, norm.getY(),
norm.getZ() * 3).normalize();*/
norm2 = normalMap.normalAt((cX + 1)* gridSquareSize, cZ* gridSquareSize);
/*norm2 = new Vector3D(norm.getX() * 3, norm.getY(),
norm.getZ() * 3).normalize();*/
norm1 = normalMap.normalAt((cX + 1)* gridSquareSize, (cZ + 1)* gridSquareSize);
/*norm1 = new Vector3D(norm.getX() * 3, norm.getY(),
norm.getZ() * 3).normalize();*/
norm0 = normalMap.normalAt(xPos, (cZ + 1)* gridSquareSize);
/*norm0 = new Vector3D(norm.getX() * 3, norm.getY(),
norm.getZ() * 3).normalize();*/
if (flatShading)
norm0 = norm1 = norm2 = norm3 = normalMap
.normalAt((cX + .5)* gridSquareSize, (cZ + .5)* gridSquareSize);
final Integer tpi = cX + cZ * 256;
if(points.containsKey(tpi)){
final Model portalModel = new Model(false, tr,"PortalEntrance");
//Place a PortalEntrance
final int Y_OFFSET = -300;
final double portalX = xPos+gridSquareSize/2.;
final double portalY = (hBL+hBR+hTR+hTL)/4.;
final double portalZ = zPos+gridSquareSize/2.;
final PortalTexture portalTexture = new PortalTexture();
Triangle[] tris = Triangle
.quad2Triangles(
// COUNTER-CLOCKWISE
new double[] {
gridSquareSize/2,
-gridSquareSize/2,
-gridSquareSize/2,
gridSquareSize/2 },
new double[] {-gridSquareSize/2,-gridSquareSize/2,gridSquareSize/2,gridSquareSize/2},
new double[] {
0,
0,
0,
0 }, u, v, portalTexture,
RenderMode.STATIC,
new Vector3D[] { norm0, norm1,
norm2, norm3 }, cX + cZ % 4);
portalModel.addTriangles(tris);
final PortalExit exit = new PortalExit(tr);
final PortalEntrance entrance;
entrance = new PortalEntrance(tr,portalModel,exit,tr.getGame().getPlayer());
tr.getGame().getCurrentMission().registerTunnelEntrancePortal(new Point(cX,cZ), entrance);
entrance.setPortalTexture(portalTexture);
Vector3D heading = normalMap.normalAt(xPos, cZ* gridSquareSize).normalize().negate();
entrance.setHeading(heading);
if(heading.getY()>-.99&heading.getNorm()>0)//If the ground is flat this doesn't work.
entrance.setTop(Vector3D.PLUS_J.crossProduct(heading).crossProduct(heading).negate());
else entrance.setTop(Vector3D.PLUS_I);// ... so we create a clause for that.
entrance.setPosition(new Vector3D(portalX,portalY,portalZ).add(heading.scalarMultiply(2000)).toArray());
entrance.notifyPositionChange();
add(entrance);
}//end if(tunnel)
TextureDescription td = (TextureDescription) (points
.containsKey(tpi) ? points.get(tpi)
.getTexture() : textureMesh.textureAt(cX,
cZ));
Triangle[] tris = Triangle
.quad2Triangles(
// COUNTER-CLOCKWISE
new double[] {
xPos - objectX,
xPos + gridSquareSize
- objectX,
xPos + gridSquareSize
- objectX,
xPos - objectX },
new double[] { hBL - objectY,
hBR - objectY,
hTR - objectY,
hTL - objectY },
new double[] {
zPos + gridSquareSize
- objectZ,
zPos + gridSquareSize
- objectZ,
zPos - objectZ,
zPos - objectZ }, u, v, td,
RenderMode.STATIC,
new Vector3D[] { norm0, norm1,
norm2, norm3 }, cX + cZ % 4);
if(points.containsKey(tpi)){
tris[0].setAlphaBlended(true);
tris[1].setAlphaBlended(true);
}
m.addTriangle(tris[0]);
m.addTriangle(tris[1]);
}// end for(cX)
}// end for(cZ)
// Add to grid
if (m.finalizeModel().get().getTriangleList() != null || m.getTransparentTriangleList() != null) {
final TerrainChunk chunkToAdd = new TerrainChunk(tr, m,
altitude);
final double[] chunkPos = chunkToAdd.getPosition();
chunkPos[0] = objectX;
chunkPos[1] = objectY;
chunkPos[2] = objectZ;
chunkToAdd.notifyPositionChange();
add(chunkToAdd);
} else {
System.out.println("Rejected chunk: "
+ m.getDebugName());
}
}// end scope
{// start scope ///// CEILING
final double objectX = Math
.round(((double) gX + ((double) chunkSideLength / 2.))
* gridSquareSize);
final double objectZ = Math
.round(((double) _gZ + ((double) chunkSideLength / 2.))
* gridSquareSize);
final double objectY = Math.round((2. - altitude.heightAt(
gX* gridSquareSize, _gZ* gridSquareSize)) + Y_NUDGE);
final Model m = new Model(false, tr,"CeilingChunk");
// for each square
for (int cZ = _gZ; cZ < _gZ + chunkSideLength; cZ++) {
for (int cX = gX; cX < gX + chunkSideLength; cX++) {
final double xPos = cX * gridSquareSize;
final double zPos = cZ * gridSquareSize;
final double hTL = (worldCeiling - altitude.heightAt(xPos, cZ* gridSquareSize))
+ Y_NUDGE;
final double hTR = (worldCeiling - altitude.heightAt(
(cX + 1)* gridSquareSize, cZ* gridSquareSize)) + Y_NUDGE;
final double hBR = (worldCeiling - altitude.heightAt(
(cX + 1)* gridSquareSize, (cZ + 1)* gridSquareSize))
+ Y_NUDGE;
final double hBL = (worldCeiling - altitude.heightAt(xPos,
(cZ + 1)* gridSquareSize)) + Y_NUDGE;
Vector3D norm0, norm1, norm2, norm3;
norm3=norm2=norm1=norm0 = normalMap.normalAt(xPos, cZ* gridSquareSize);
/*
norm3 = altitude.heightAt(cX, cZ)<.9?
new Vector3D(norm.getX() * 3, norm.getY()*-1,
norm.getZ() * 3).normalize():
new Vector3D(norm.getX() * 3, norm.getY(),
norm.getZ() * 3).normalize();
norm = altitude.normalAt(cX + 1, cZ);
norm2 = altitude.heightAt(cX + 1, cZ)<.9?
new Vector3D(norm.getX() * 3, norm.getY()*-1,
norm.getZ() * 3).normalize():
new Vector3D(norm.getX() * 3, norm.getY(),
norm.getZ() * 3).normalize();
norm = altitude.normalAt(cX + 1, cZ + 1);
norm1 = altitude.heightAt(cX + 1 , cZ + 1)< .9?
new Vector3D(norm.getX() * 3, norm.getY()*-1,
norm.getZ() * 3).normalize():
new Vector3D(norm.getX() * 3, norm.getY(),
norm.getZ() * 3).normalize();
norm = altitude.normalAt(cX, cZ + 1);
norm0 = altitude.heightAt(cX, cZ + 1)<.9?
new Vector3D(norm.getX() * 3, norm.getY()*-1,
norm.getZ() * 3).normalize():
new Vector3D(norm.getX() * 3, norm.getY(),
norm.getZ() * 3).normalize();
*/
norm0 = norm1 = norm2 = norm3 = Vector3D.ZERO;
// Ceiling texture cell X (Z in this engine) value
// is offset by 10.
// No tunnelpoints on ceiling
TextureDescription td = (TextureDescription) (textureMesh
.textureAt(cX, cZ + 10));
// features.
Triangle[] tris = Triangle.quad2Triangles(
// CLOCKWISE (else backface culling will eat
new double[] { xPos - objectX,
xPos + gridSquareSize - objectX,
xPos + gridSquareSize - objectX,
xPos - objectX },
new double[] { hTL - objectY,
hTR - objectY, hBR - objectY,
hBL - objectY },
new double[] { zPos - objectZ,
zPos - objectZ,
zPos + gridSquareSize - objectZ,
zPos + gridSquareSize - objectZ },
cu,
cv,
td,
RenderMode.STATIC,
new Vector3D[] { norm3,
norm2, norm1,
norm0 }, cX + cZ % 4);
m.addTriangle(tris[0]);
m.addTriangle(tris[1]);
}// end for(cX)
}// end for(cZ)
// Add to grid
if (m.finalizeModel().get().getTriangleList() != null || m.getTransparentTriangleList() != null) {
final TerrainChunk chunkToAdd = new TerrainChunk(tr, m,
altitude);
final double[] chunkPos = chunkToAdd.getPosition();
chunkPos[0] = objectX;
chunkPos[1] = objectY;
chunkPos[2] = objectZ;
chunkToAdd.notifyPositionChange();
chunkToAdd.setCeiling(true);
terrainMirror.add(chunkToAdd);
} else {
System.out.println("Rejected chunk: "
+ m.getDebugName());
}
}// end scope(CEILING)
}// end for(gX)
return null;
}}));
}// end for(gZ)
for(Future<Void> task:rowTasks)
try{task.get();}catch(Exception e){throw new RuntimeException(e);}
}// end constructor
private class TunnelPoint{
final int x,z;
TextureDescription textureToInsert;
public TunnelPoint(TDFFile.Tunnel tun, boolean entrance){
try{final String texFile = entrance?tun.getEntranceTerrainTextureFile():tun.getExitTerrainTextureFile();
textureToInsert = tr.getResourceManager().getRAWAsTexture(texFile, tr.getGlobalPaletteVL(),null,false);}
catch(Exception e){e.printStackTrace();}
DirectionVector v = entrance?tun.getEntrance():tun.getExit();
x = (int)TR.legacy2MapSquare(v.getZ());
z = (int)TR.legacy2MapSquare(v.getX());
}
public TextureDescription getTexture(){return textureToInsert;}
@Override
public boolean equals(Object other){
return other.hashCode()==this.hashCode();
}
@Override
public int hashCode(){
return (int)(x+z*256);
}
}
/**
* @return the gridSquareSize
*/
public double getGridSquareSize(){
return gridSquareSize;
}
/**
* @return the renderingCubes
*/
public ArrayList<TerrainChunk> getRenderingCubes(){
return renderingCubes;
}
}//end TerrainSystem
|
package com.celements.web.sajson;
import java.io.IOException;
import java.io.StringReader;
import java.util.Stack;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonToken;
public class Parser {
private ILexicalParser<? extends IGenericLiteral> lexParser;
private JsonParser parser;
private static JsonFactory factory = new JsonFactory();
private Stack<ECommand> workerStack = new Stack<ECommand>();
private String lastKey = "";
private String lastValue = "";
public static <T extends IGenericLiteral> Parser createLexicalParser(
T initLiteral, IEventHandler<T> eventHandler) {
return new Parser(initLiteral, new LexicalParser<T>(initLiteral,
eventHandler));
}
<T extends IGenericLiteral> Parser(T initLiteral,
ILexicalParser<T> lexParser) {
this.lexParser = lexParser;
}
public void parse(String jsonExpression
) throws JsonParseException, IOException {
StringReader jsonReader = new StringReader(jsonExpression);
try {
parser = factory.createJsonParser(jsonReader);
workerStack.clear();
JsonToken nextToken = parser.nextToken();
lexParser.initEvent();
while (parser.hasCurrentToken()) {
switch (nextToken) {
case VALUE_STRING:
lastValue = parser.getText();
lexParser.stringEvent(lastValue);
impliciteCloseProperty();
break;
case START_ARRAY:
checkIllegalStackState(ECommand.DICTIONARY_COMMAND, nextToken);
workerStack.push(ECommand.ARRAY_COMMAND);
lexParser.openArrayEvent();
break;
case END_ARRAY:
checkStackState(ECommand.ARRAY_COMMAND);
lexParser.closeArrayEvent();
workerStack.pop();
impliciteCloseProperty();
break;
case START_OBJECT:
checkIllegalStackState(ECommand.DICTIONARY_COMMAND, nextToken);
workerStack.push(ECommand.DICTIONARY_COMMAND);
lexParser.openDictionaryEvent();
break;
case END_OBJECT:
checkStackState(ECommand.DICTIONARY_COMMAND);
lexParser.closeDictionaryEvent();
workerStack.pop();
impliciteCloseProperty();
break;
case FIELD_NAME:
checkStackState(ECommand.DICTIONARY_COMMAND);
workerStack.push(ECommand.PROPERTY_COMMAND);
lastKey = parser.getText();
lexParser.openPropertyEvent(lastKey);
break;
default:
break;
}
nextToken = parser.nextToken();
}
lexParser.finishEvent();
} finally {
jsonReader.close();
}
}
private void checkIllegalStackState(ECommand illegalCommand, JsonToken token) {
if (!workerStack.isEmpty()
&& workerStack.peek() == illegalCommand) {
throw new IllegalStateException("Found illegal " + token
+ " inside " + illegalCommand);
}
}
private void checkStackState(ECommand expectedCommand) {
if (workerStack.isEmpty()
|| workerStack.peek() != expectedCommand) {
throw new IllegalStateException("Expecting " + expectedCommand
+ " but found " + workerStack.peek() + " Last key [" + lastKey
+ "] last value [" + lastValue + "]");
}
}
private void impliciteCloseProperty() {
if (!workerStack.isEmpty()
&& workerStack.peek() == ECommand.PROPERTY_COMMAND) {
lexParser.closePropertyEvent();
workerStack.pop();
}
}
}
|
package org.jtrfp.trcl.obj;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.math3.exception.MathArithmeticException;
import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;
import org.jtrfp.jfdt.UnrecognizedFormatException;
import org.jtrfp.jtrfp.FileLoadException;
import org.jtrfp.trcl.beh.AdjustAltitudeToPlayerBehavior;
import org.jtrfp.trcl.beh.AutoFiring;
import org.jtrfp.trcl.beh.AutoLeveling;
import org.jtrfp.trcl.beh.AutoLeveling.LevelingAxis;
import org.jtrfp.trcl.beh.Behavior;
import org.jtrfp.trcl.beh.BehaviorNotFoundException;
import org.jtrfp.trcl.beh.Bobbing;
import org.jtrfp.trcl.beh.BuzzByPlayerSFX;
import org.jtrfp.trcl.beh.CollidesWithPlayer;
import org.jtrfp.trcl.beh.CollidesWithTerrain;
import org.jtrfp.trcl.beh.CustomDeathBehavior;
import org.jtrfp.trcl.beh.CustomNAVTargetableBehavior;
import org.jtrfp.trcl.beh.CustomPlayerWithinRangeBehavior;
import org.jtrfp.trcl.beh.DamageTrigger;
import org.jtrfp.trcl.beh.DamageableBehavior;
import org.jtrfp.trcl.beh.DamageableBehavior.SupplyNotNeededException;
import org.jtrfp.trcl.beh.DamagedByCollisionWithDEFObject;
import org.jtrfp.trcl.beh.DamagedByCollisionWithPlayer;
import org.jtrfp.trcl.beh.DamagedByCollisionWithSurface;
import org.jtrfp.trcl.beh.DeathBehavior;
import org.jtrfp.trcl.beh.DebrisOnDeathBehavior;
import org.jtrfp.trcl.beh.ExecuteOnInterval;
import org.jtrfp.trcl.beh.ExecuteOnInterval.OneShotIntervalLogic;
import org.jtrfp.trcl.beh.ExplodesOnDeath;
import org.jtrfp.trcl.beh.FireOnFrame;
import org.jtrfp.trcl.beh.HorizAimAtPlayerBehavior;
import org.jtrfp.trcl.beh.LeavesPowerupOnDeathBehavior;
import org.jtrfp.trcl.beh.LoopingPositionBehavior;
import org.jtrfp.trcl.beh.MissileSiloBehavior;
import org.jtrfp.trcl.beh.NewSmartPlaneBehavior;
import org.jtrfp.trcl.beh.PositionLimit;
import org.jtrfp.trcl.beh.ProjectileFiringBehavior;
import org.jtrfp.trcl.beh.RandomSFXPlayback;
import org.jtrfp.trcl.beh.ResetsRandomlyAfterDeath;
import org.jtrfp.trcl.beh.SmartPlaneBehavior;
import org.jtrfp.trcl.beh.SpawnsRandomSmoke;
import org.jtrfp.trcl.beh.SpinAccellerationBehavior;
import org.jtrfp.trcl.beh.SpinAccellerationBehavior.SpinMode;
import org.jtrfp.trcl.beh.SteadilyRotating;
import org.jtrfp.trcl.beh.TerrainLocked;
import org.jtrfp.trcl.beh.TunnelRailed;
import org.jtrfp.trcl.beh.phy.AccelleratedByPropulsion;
import org.jtrfp.trcl.beh.phy.HasPropulsion;
import org.jtrfp.trcl.beh.phy.MovesByVelocity;
import org.jtrfp.trcl.beh.phy.PulledDownByGravityBehavior;
import org.jtrfp.trcl.beh.phy.RotationalDragBehavior;
import org.jtrfp.trcl.beh.phy.RotationalMomentumBehavior;
import org.jtrfp.trcl.beh.phy.VelocityDragBehavior;
import org.jtrfp.trcl.core.Features;
import org.jtrfp.trcl.core.ResourceManager;
import org.jtrfp.trcl.core.TRFactory;
import org.jtrfp.trcl.core.TRFactory.TR;
import org.jtrfp.trcl.ext.tr.GPUFactory.GPUFeature;
import org.jtrfp.trcl.ext.tr.SoundSystemFactory.SoundSystemFeature;
import org.jtrfp.trcl.file.BINFile.AnimationControl;
import org.jtrfp.trcl.file.DEFFile.EnemyDefinition;
import org.jtrfp.trcl.file.DEFFile.EnemyDefinition.EnemyLogic;
import org.jtrfp.trcl.file.DEFFile.EnemyPlacement;
import org.jtrfp.trcl.flow.GameVersion;
import org.jtrfp.trcl.game.TVF3Game;
import org.jtrfp.trcl.game.TVF3Game.Difficulty;
import org.jtrfp.trcl.gpu.BINFileExtractor;
import org.jtrfp.trcl.gpu.BasicModelSource;
import org.jtrfp.trcl.gpu.BufferedModelTarget;
import org.jtrfp.trcl.gpu.GL33Model;
import org.jtrfp.trcl.gpu.InterpolatedAnimatedModelSource;
import org.jtrfp.trcl.gpu.RotatedModelSource;
import org.jtrfp.trcl.miss.Mission;
import org.jtrfp.trcl.obj.Explosion.ExplosionType;
import org.jtrfp.trcl.shell.GameShellFactory.GameShell;
import org.jtrfp.trcl.snd.SoundSystem;
import org.jtrfp.trcl.snd.SoundTexture;
import org.jtrfp.trcl.tools.Util;
//import org.jtrfp.trcl.beh.NewSmartPlaneBehavior;
public class DEFObject extends WorldObject {
private static final boolean NEW_SMART_PLANE_BEHAVIOR = true;
// PROPERTIES
public static final String ENEMY_DEFINITION = "enemyDefinition",
ENEMY_PLACEMENT = "enemyPlacement";
private Double boundingHeight, boundingWidth;
private HitBox[] hitBoxes;
// private WorldObject ruinObject;
private ArrayList<WorldObject> subObjects = null;
private EnemyLogic logic;
private EnemyDefinition enemyDefinition;
private EnemyPlacement enemyPlacement;
private boolean mobile, canTurn, foliage, boss, shieldGen, isRuin,
spinCrash, ignoringProjectiles;
private Anchoring anchoring;
private RotatedModelSource rotatedModelSource;
public static final String[] BIG_EXP_SOUNDS = new String[] { "EXP3.WAV",
"EXP4.WAV", "EXP5.WAV" };
public static final String[] MED_EXP_SOUNDS = new String[] { "EXP1.WAV",
"EXP2.WAV" };
private final ArrayList<Object> hardReferences = new ArrayList<Object>();
private GameShell gameShell;
private boolean evaluated = false;
//// INTROSPECTOR
static {
try {
final Set<String> persistentProperties = new HashSet<String>();
persistentProperties.addAll(Arrays.asList(ENEMY_DEFINITION,
ENEMY_PLACEMENT, POSITION, HEADING_ARRAY, TOP_ARRAY, ACTIVE,
VISIBLE, IN_GRID));
BeanInfo info = Introspector.getBeanInfo(DEFObject.class);
PropertyDescriptor[] propertyDescriptors = info
.getPropertyDescriptors();
for (int i = 0; i < propertyDescriptors.length; ++i) {
PropertyDescriptor pd = propertyDescriptors[i];
System.out.println(
"DEFObject property descriptor: " + pd.getName());
if (!persistentProperties.contains(pd.getName()))
pd.setValue("transient",
persistentProperties.contains(pd.getName())
? Boolean.FALSE : Boolean.TRUE);
}
} catch (Exception e) {
e.printStackTrace();
}
}// end static{}
public void proposeEvaluate() {
try {
if (!isEvaluated())
setEvaluated(evaluate());
} catch (Exception e) {
e.printStackTrace();
} // TODO: Handle this better?
}// end proposeEvaluate()
protected boolean evaluate() throws Exception {
try {
Util.assertPropertiesNotNull(this, ENEMY_DEFINITION,
ENEMY_PLACEMENT);
} catch (RuntimeException e) {
return false;
} // TODO: More specific exception
final TR tr = getTr();
final EnemyDefinition def = getEnemyDefinition();
final EnemyPlacement pl = getEnemyPlacement();
anchoring = Anchoring.floating;
logic = def.getLogic();
mobile = true;
canTurn = true;
foliage = false;
boss = def.isObjectIsBoss();
// XXX KLUDGE: GEIGER.DEF specifies an out-of-range firing vertex and it crashes the engine. Sanitize this data.
{final BasicModelSource modelSource = getModelSource();
Integer[] firingVertices = def.getFiringVertices();
int numVerts = def.getNumRandomFiringVertices();
for(int index = 0; index < numVerts; index++)
try{modelSource.getVertex(firingVertices[index]);}
catch(IndexOutOfBoundsException e){firingVertices[index]=0;}
}
final GameShell gameShell = getGameShell();
final TVF3Game game = (TVF3Game) gameShell.getGame();
final Player player = game.getPlayer();
final Mission mission = game.getCurrentMission();
final int numHitBoxes = def.getNumNewHBoxes();
final int[] rawHBoxData = def.getHboxVertices();
if (numHitBoxes != 0) {
final HitBox[] boxes = new HitBox[numHitBoxes];
for (int i = 0; i < numHitBoxes; i++) {
final HitBox hb = new HitBox();
hb.setVertexID(rawHBoxData[i * 2]);
hb.setSize(
rawHBoxData[i * 2 + 1] / TRFactory.crossPlatformScalar);
boxes[i] = hb;
} // end for(boxes)
setHitBoxes(boxes);
} // end if(hitboxes)
// Default Direction
setDirection(new ObjectDirection(pl.getRoll(), pl.getPitch(),
pl.getYaw() + 65536));
boolean customExplosion = false;
this.setModelOffset(TRFactory.legacy2Modern(def.getPivotX()),
TRFactory.legacy2Modern(def.getPivotY()),
TRFactory.legacy2Modern(def.getPivotZ()));
// UNIVERSAL
final DamageableBehavior damageableBehavior = new DamageableBehavior();
addBehavior(damageableBehavior);
// LOGIC
if (logic == null)
return false;
switch (logic) {
case groundStatic:
mobile = false;
canTurn = false;
anchoring = Anchoring.terrain;
defaultModelAssignment();
break;
case groundTargeting:// Ground turrets
{
mobile = false;
canTurn = true;
addBehavior(new HorizAimAtPlayerBehavior(
getGameShell().getGame().getPlayer()));
ProjectileFiringBehavior pfb;
Integer[] firingVertices = Arrays.copyOf(def.getFiringVertices(),
def.getNumRandomFiringVertices());
addBehavior(pfb = new ProjectileFiringBehavior()
.setProjectileFactory(
tr.getResourceManager().getProjectileFactories()[def
.getWeapon().ordinal()])
.setFiringPositions(getModelSource(), firingVertices));
try {
pfb.addSupply(9999999);
} catch (SupplyNotNeededException e) {
}
addBehavior(new AutoFiring().setProjectileFiringBehavior(pfb)
.setPatternOffsetMillis((int) (Math.random() * 2000))
.setMaxFiringDistance(TRFactory.mapSquareSize * 3)
.setSmartFiring(false).setMaxFireVectorDeviation(.7)
.setTimePerPatternEntry(def.getFireSpeed() / 66));
anchoring = Anchoring.terrain;
defaultModelAssignment();
break;
}
case flyingDumb:
canTurn = false;
defaultModelAssignment();
break;
case groundTargetingDumb:
addBehavior(new HorizAimAtPlayerBehavior(
getGameShell().getGame().getPlayer()));
anchoring = Anchoring.terrain;
defaultModelAssignment();
break;
case flyingSmart:
newSmartPlaneBehavior(tr, def, false);
defaultModelAssignment();
break;
case bankSpinDrill:
addBehavior(new HorizAimAtPlayerBehavior(
getGameShell().getGame().getPlayer()));
unhandled(def);
defaultModelAssignment();
break;
case sphereBoss:{
projectileFiringBehavior();
mobile = false;
//TODO: Simple model likely the secondary mode model
final EnemyDefinition ed = getEnemyDefinition();
final String secondaryModelName = ed.getSimpleModel();
final GL33Model secondaryModel = getTr().getResourceManager().getBINModel(
secondaryModelName,
getTr().getGlobalPaletteVL(), null, null);
//Speculative: Secondary mode doubles the shield?
final EnemyPlacement ep = getEnemyPlacement();
final int secondaryModeShield = ep.getStrength() * 2;
//XXX KLUDGE: Force boss mode on
//TODO: Boss mode should only involve NAV targeting
boss = true;
damageableBehavior.setDieOnZeroHealth(false);
final DamageTrigger newSphereMode = new DamageTrigger(){
@Override
public void healthBelowThreshold() {
final WorldObject parent = getParent();
//Set the new health
final DamageableBehavior db = parent.probeForBehavior(DamageableBehavior.class);
db.setMaxHealth(secondaryModeShield);
db.setHealth (secondaryModeShield);
//Set the new model
parent.setModel(secondaryModel);
//Start the spinny action.
final RotationalMomentumBehavior rmb = parent.probeForBehavior(RotationalMomentumBehavior.class);
rmb.setLateralMomentum (.05);
rmb.setEquatorialMomentum(.05);
rmb.setPolarMomentum (.05);
parent.probeForBehavior(RotationalDragBehavior.class).setEnable(false);
damageableBehavior.setDieOnZeroHealth(true);
}}.setThreshold(65537);
addBehavior(newSphereMode);
/*setModel(getTr().getResourceManager().getBINModel(
enemyDefinition.getSimpleModel(),
getTr().getGlobalPaletteVL(), null, null));*/
defaultModelAssignment();
break;}
case flyingAttackRetreatSmart:
newSmartPlaneBehavior(tr, def, false);
// addBehavior(new
// HorizAimAtPlayerBehavior(getGameShell().getGame().getPlayer()));
defaultModelAssignment();
break;
case splitShipSmart:// TODO
newSmartPlaneBehavior(tr, def, false);
// addBehavior(new
// HorizAimAtPlayerBehavior(getGameShell().getGame().getPlayer()));
defaultModelAssignment();
break;
case groundStaticRuin:// Destroyed object is replaced with another using
// SimpleModel i.e. weapons bunker
mobile = false;
canTurn = false;
anchoring = Anchoring.terrain;
defaultModelAssignment();
defaultRuinObject(pl);
break;
case targetHeadingSmart:
mobile = false;// Belazure's crane bots
addBehavior(new HorizAimAtPlayerBehavior(
getGameShell().getGame().getPlayer()));
projectileFiringBehavior();
anchoring = Anchoring.terrain;
defaultModelAssignment();
break;
case targetPitchSmart:
mobile = false;
addBehavior(new HorizAimAtPlayerBehavior(
getGameShell().getGame().getPlayer()));
projectileFiringBehavior();
anchoring = Anchoring.terrain;
defaultModelAssignment();
break;
case coreBossSmart:
mobile = false;
addBehavior(new HorizAimAtPlayerBehavior(
getGameShell().getGame().getPlayer()));
projectileFiringBehavior();
defaultModelAssignment();
//defaultBossNAVTargetingResponse();
break;
case cityBossSmart:
mobile = false;
projectileFiringBehavior();
defaultModelAssignment();
//defaultBossNAVTargetingResponse();
addBehavior(new SteadilyRotating().setRotationPeriodMillis(1000));
break;
case staticFiringSmart: {
if (boss)
addBehavior(new HorizAimAtPlayerBehavior(
getGameShell().getGame().getPlayer()));// ATMOS Boss
// uses this!
final ProjectileFiringBehavior pfb = new ProjectileFiringBehavior();
try {
pfb.addSupply(99999999);
} catch (SupplyNotNeededException e) {
}
Integer[] firingVertices = Arrays.copyOf(def.getFiringVertices(),
def.getNumRandomFiringVertices());
pfb.setProjectileFactory(tr.getResourceManager()
.getProjectileFactories()[def.getWeapon().ordinal()])
.setFiringPositions(getModelSource(), firingVertices);
addBehavior(pfb);
addBehavior(new AutoFiring().setProjectileFiringBehavior(pfb)
.setPatternOffsetMillis((int) (Math.random() * 2000))
.setMaxFiringDistance(TRFactory.mapSquareSize * 8)
.setSmartFiring(true));
mobile = false;
canTurn = true;
defaultModelAssignment();
break;
}
case sittingDuck:
canTurn = false;
mobile = false;
defaultModelAssignment();
break;
case tunnelAttack: {
final ProjectileFiringBehavior pfb = new ProjectileFiringBehavior();
try {
pfb.addSupply(99999999);
} catch (SupplyNotNeededException e) {
}
Integer[] firingVertices = Arrays.copyOf(def.getFiringVertices(),
def.getNumRandomFiringVertices());
pfb.setProjectileFactory(tr.getResourceManager()
.getProjectileFactories()[def.getWeapon().ordinal()])
.setFiringPositions(getModelSource(), firingVertices);
addBehavior(pfb);
// addBehavior(new
// HorizAimAtPlayerBehavior(getGameShell().getGame().getPlayer()));
addBehavior(new AutoFiring().setProjectileFiringBehavior(pfb)
.setPatternOffsetMillis((int) (Math.random() * 2000))
.setMaxFiringDistance(TRFactory.mapSquareSize * .2)
.setSmartFiring(false).setMaxFireVectorDeviation(.3)
.setTimePerPatternEntry((int) (def.getFireSpeed() / 66)));
/*
* addBehavior(new Bobbing(). setPhase(Math.random()).
* setBobPeriodMillis(10*1000+Math.random()*3000).setAmplitude(2000)
* . setAdditionalHeight(0));
*/ // Conflicts with TunnelRailed
mobile = false;
defaultModelAssignment();
break;
}
case takeoffAndEscape:
addBehavior(new MovesByVelocity());
addBehavior((Behavior) (new HasPropulsion().setMinPropulsion(0)
.setPropulsion(def.getThrustSpeed() / 1.2)));
addBehavior(new AccelleratedByPropulsion().setEnable(false));
addBehavior(new VelocityDragBehavior().setDragCoefficient(.86));
addBehavior(new CustomPlayerWithinRangeBehavior() {
@Override
public void withinRange() {
DEFObject.this
.probeForBehavior(AccelleratedByPropulsion.class)
.setThrustVector(Vector3D.PLUS_J).setEnable(true);
}
}).setRange(TRFactory.mapSquareSize * 10);
addBehavior(new LoopingPositionBehavior());
addBehavior(new ExplodesOnDeath(ExplosionType.Blast,
BIG_EXP_SOUNDS[(int) (Math.random() * 3)]));
customExplosion = true;
canTurn = false;
mobile = false;
defaultModelAssignment();
break;
case fallingAsteroid:
anchoring = Anchoring.floating;
fallingObjectBehavior();
customExplosion = true;
addBehavior(new ExplodesOnDeath(ExplosionType.BigExplosion,
MED_EXP_SOUNDS[(int) (Math.random() * 2)]));
// setVisible(false);
// addBehavior(new FallingDebrisBehavior(tr,model));
defaultModelAssignment();
break;
case cNome:// Walky bot?
anchoring = Anchoring.terrain;
addBehavior(new HorizAimAtPlayerBehavior(
getGameShell().getGame().getPlayer()));
defaultModelAssignment();
// In TV, C-NOMEs spawn legs on death. In F3, this doesn't appear to happen
if(game.getGameVersion() == GameVersion.TV){
final DEFObject cNomeLegs = new DEFObject();
EnemyDefinition ed = new EnemyDefinition();
ed.setLogic(EnemyLogic.cNomeLegs);
ed.setDescription("auto-generated c-Nome legs");
ed.setPowerupProbability(0);
ed.setComplexModelFile("LEGS.BIN");
ed.setThrustSpeed(0);
EnemyPlacement simplePlacement = pl.clone();
simplePlacement.setStrength(1024 * 32);
simplePlacement.setYaw(DEFObject.this.getEnemyPlacement().getYaw());
cNomeLegs.setRuin(true);
cNomeLegs.setEnemyDefinition(ed);
cNomeLegs.setEnemyPlacement(simplePlacement);
cNomeLegs.setActive(false);
cNomeLegs.setVisible(false);
cNomeLegs.setPosition(new double[] { -999999999999999999.,
-9999999999999999999., -999999999999999999. });// Relevant
// nowhere
cNomeLegs.notifyPositionChange();
getSubObjects().add(cNomeLegs);
//cNome.addBehavior(new HorizAimAtPlayerBehavior(
// getGameShell().getGame().getPlayer()));
final Runnable cNomeDeathTask = new Runnable(){
@Override
public void run() {
cNomeLegs.setActive(true);
cNomeLegs.setVisible(true);
final double [] parentPos = getPosition();
cNomeLegs.setPosition(new double[] { parentPos[0],
0, parentPos[2] });
cNomeLegs.notifyPositionChange();
}};
addBehavior(new CustomDeathBehavior(cNomeDeathTask));
}//end if(TV)
break;
case cNomeLegs:// Walky bot?
anchoring = Anchoring.terrain;
mobile = false;
defaultModelAssignment();
break;
case cNomeFactory:
mobile = false;
boss = true;//This is because NAVObjective sets ignoringProjecitles to true
defaultModelAssignment();
final Runnable cNomeSpawnTask = new Runnable(){
@Override
public void run() {
final DEFObject cNome = new DEFObject();
EnemyDefinition ed = new EnemyDefinition();
ed.setLogic(EnemyLogic.cNome);
ed.setDescription("auto-generated c-Nome");
ed.setPowerupProbability(0);
ed.setComplexModelFile("CNOME.BIN");//Is this hard-coded in the original?
ed.setThrustSpeed(250000);
EnemyPlacement simplePlacement = pl.clone();
simplePlacement.setStrength(4096);
simplePlacement.setYaw((int)(Math.random() * 65535.));
cNome.setRuin(false);
cNome.setEnemyDefinition(ed);
cNome.setEnemyPlacement(simplePlacement);
cNome.setActive(true);
cNome.setVisible(true);
final double [] parentPos = getPosition();
cNome.setPosition(new double[] { parentPos[0],
0, parentPos[2] });
cNome.notifyPositionChange();
//cNome.addBehavior(new HorizAimAtPlayerBehavior(
// getGameShell().getGame().getPlayer()));
getContainingGrid().add(cNome);
}};
addBehavior(new ExecuteOnInterval(5000, cNomeSpawnTask));
break;
case geigerBoss:
addBehavior(new HorizAimAtPlayerBehavior(
getGameShell().getGame().getPlayer()));
projectileFiringBehavior();
boss = true;
anchoring = Anchoring.terrain;
mobile = false;
defaultModelAssignment();
//defaultBossNAVTargetingResponse();
break;
case volcanoBoss:
addBehavior(new HorizAimAtPlayerBehavior(
getGameShell().getGame().getPlayer()));
projectileFiringBehavior();
anchoring = Anchoring.terrain;
mobile = false;
defaultModelAssignment();
//defaultBossNAVTargetingResponse();
break;
case volcano:// Wat.
unhandled(def);
canTurn = false;
mobile = false;
anchoring = Anchoring.terrain;
defaultModelAssignment();
//defaultBossNAVTargetingResponse();
break;
case missile: {// Silo
mobile = true;
anchoring = Anchoring.none;
defaultModelAssignment();
final MissileSiloBehavior silo = new MissileSiloBehavior();
silo.setSequenceOffsetMillis((long) (Math.random() * 5000.));
silo.setInitialRestTimeMillis(
1000L + (long) (Math.random() * 3000));
addBehavior(silo);
break;
}
case bob:
addBehavior(new Bobbing()
.setAdditionalHeight(TRFactory.mapSquareSize * 1));
// Apparently the rotation rates are only for manuevering and not for rotation rate of bobbing.
//int rotationSpeed = def.getRotationSpeed();
//if(rotationSpeed <= 0)
//rotationSpeed = 65535 * 5;
//XXX 7-second rotation period looks about right.
addBehavior(new SteadilyRotating().setRotationPeriodMillis(7. * 1000));
addBehavior(new ExplodesOnDeath(ExplosionType.Blast,
MED_EXP_SOUNDS[(int) (Math.random() * 2)]));
possibleBobbingSpinAndCrashOnDeath(.5, def);
customExplosion = true;
anchoring = Anchoring.floating;
mobile = false;
canTurn = false;// ironic?
defaultModelAssignment();
break;
case alienBoss:
mobile = false;
alienModelAssignment();
alienBoss(pl);
//bossWarningSiren();
break;
case canyonBoss1:
newSmartPlaneBehavior(tr, def, false);
probeForBehavior(NewSmartPlaneBehavior.class).setEnable(false);
final SteadilyRotating rotating = new SteadilyRotating().setRotationPeriodMillis(12000);
rotating.setEnable(false);
addBehavior(rotating);
final ExecuteOnInterval eoiRise = new ExecuteOnInterval();
eoiRise.setEnable(false);
addBehavior(eoiRise);
final MovesByVelocity velocible = new MovesByVelocity();
velocible.setEnable(false);
addBehavior(velocible);
eoiRise.setTaskToExecute(new Runnable(){
@Override
public void run() {//ATTACK
DEFObject.this.probeForBehavior(AccelleratedByPropulsion.class).setEnable(true);
DEFObject.this.probeForBehavior(VelocityDragBehavior.class) .setEnable(true);
rotating.setEnable(false);
DEFObject.this.probeForBehavior(NewSmartPlaneBehavior.class).setEnable(true);
}});
final CustomNAVTargetableBehavior navTargBehavior = new CustomNAVTargetableBehavior(new Runnable(){
@Override
public void run() {//RISE
DEFObject.this.probeForBehavior(AccelleratedByPropulsion.class).setEnable(false);
DEFObject.this.probeForBehavior(VelocityDragBehavior.class) .setEnable(false);
velocible.setEnable(true);
velocible.setVelocity(new double [] {0,10240,0});
rotating.setEnable(true);
eoiRise.setIntervalLogic(new OneShotIntervalLogic(System.currentTimeMillis()+10000));
eoiRise.setEnable(true);
}});
addBehavior(navTargBehavior);
defaultModelAssignment();
//defaultBossNAVTargetingResponse();
break;
case canyonBoss2:
addBehavior(new HorizAimAtPlayerBehavior(
getGameShell().getGame().getPlayer()));
projectileFiringBehavior();
mobile = false;
defaultModelAssignment();
//defaultBossNAVTargetingResponse();
break;
case lavaMan:// Also terraform-o-bot
addBehavior(new HorizAimAtPlayerBehavior(
getGameShell().getGame().getPlayer()));
projectileFiringBehavior();
mobile = false;
defaultModelAssignment();
//defaultBossNAVTargetingResponse();
break;
case arcticBoss:
// ARTIC / Ymir. Hangs from ceiling.
addBehavior(new HorizAimAtPlayerBehavior(
getGameShell().getGame().getPlayer()));
projectileFiringBehavior();
mobile = false;
anchoring = Anchoring.ceiling;
defaultModelAssignment();
//defaultBossNAVTargetingResponse();
break;
case helicopter:
defaultModelAssignment();
break;
case tree:
canTurn = false;
mobile = false;
foliage = true;
anchoring = Anchoring.terrain;
defaultModelAssignment();
break;
case ceilingStatic:
canTurn = false;
mobile = false;
setTop(Vector3D.MINUS_J);
anchoring = Anchoring.ceiling;
defaultModelAssignment();
break;
case bobAndAttack: {
addBehavior(new SteadilyRotating()
.setRotationPhase(2 * Math.PI * Math.random()));
final ProjectileFiringBehavior pfb = new ProjectileFiringBehavior();
try {
pfb.addSupply(99999999);
} catch (SupplyNotNeededException e) {
}
pfb.setProjectileFactory(tr.getResourceManager()
.getProjectileFactories()[def.getWeapon().ordinal()]);
Integer[] firingVertices = Arrays.copyOf(def.getFiringVertices(),
def.getNumRandomFiringVertices());
pfb.setFiringPositions(getModelSource(), firingVertices);
addBehavior(pfb);// Bob and attack don't have the advantage of
// movement, so give them the advantage of range.
addBehavior(new AutoFiring().setProjectileFiringBehavior(pfb)
.setPatternOffsetMillis((int) (Math.random() * 2000))
.setMaxFiringDistance(TRFactory.mapSquareSize * 17)
.setSmartFiring(true));
addBehavior(new Bobbing().setPhase(Math.random())
.setBobPeriodMillis(10 * 1000 + Math.random() * 3000));
addBehavior(new ExplodesOnDeath(ExplosionType.Blast,
BIG_EXP_SOUNDS[(int) (Math.random() * 3)]));
possibleBobbingSpinAndCrashOnDeath(.5, def);
//if (isBoss())
// defaultBossNAVTargetingResponse();
customExplosion = true;
mobile = false;
canTurn = false;
anchoring = Anchoring.floating;
defaultModelAssignment();
break;
}
case forwardDrive:
canTurn = false;
anchoring = Anchoring.terrain;
defaultModelAssignment();
break;
case fallingStalag:
fallingObjectBehavior();
customExplosion = true;
addBehavior(new ExplodesOnDeath(ExplosionType.BigExplosion,
MED_EXP_SOUNDS[(int) (Math.random() * 2)]));
// canTurn=false;
// mobile=false;
anchoring = Anchoring.floating;
defaultModelAssignment();
break;
case attackRetreatBelowSky:
newSmartPlaneBehavior(tr, def, false);
anchoring = Anchoring.floating;
defaultModelAssignment();
break;
case attackRetreatAboveSky:
newSmartPlaneBehavior(tr, def, true);
anchoring = Anchoring.floating;
defaultModelAssignment();
break;
case bobAboveSky:
addBehavior(new Bobbing()
.setAdditionalHeight(TRFactory.mapSquareSize * 5));
addBehavior(new SteadilyRotating());
possibleBobbingSpinAndCrashOnDeath(.5, def);
mobile = false;
canTurn = false;
anchoring = Anchoring.floating;
defaultModelAssignment();
break;
case factory:
canTurn = false;
mobile = false;
anchoring = Anchoring.floating;
defaultModelAssignment();
break;
case shootOnThrustFrame:
defaultModelAssignment();
projectileFiringBehavior();
addBehavior(
new FireOnFrame().setController(getModel().getController())
.setFrame(def.getThrustSpeed()).setNumShots(5)
.setTimeBetweenShotsMillis(200));
addBehavior(new HorizAimAtPlayerBehavior(
getGameShell().getGame().getPlayer()));
//defaultBossNAVTargetingResponse();
break;
}// end switch(logic)
// Position Limit
{
final PositionLimit posLimit = new PositionLimit();
posLimit.getPositionMaxima()[1] = tr.getWorld().sizeY;
posLimit.getPositionMinima()[1] = -tr.getWorld().sizeY;
addBehavior(posLimit);
}
if (anchoring == Anchoring.terrain) {
addBehavior(new CustomDeathBehavior(new Runnable() {
@Override
public void run() {
getGameShell().getGame().getCurrentMission()
.notifyGroundTargetDestroyed();
}
}));
addBehavior(new TerrainLocked());
} else if (anchoring == Anchoring.ceiling) {
addBehavior(new TerrainLocked().setLockedToCeiling(true));
} else
addBehavior(new CustomDeathBehavior(new Runnable() {
@Override
public void run() {
getGameShell().getGame().getCurrentMission()
.notifyAirTargetDestroyed();
}// end run()
}));
// Misc
if (isBoss())
defaultBossNAVTargetingResponse();
addBehavior(new TunnelRailed(tr));// Centers in tunnel when appropriate
addBehavior(new DeathBehavior());
final int newHealth = (int) ((pl.getStrength() + (spinCrash ? 16 : 0)));
damageableBehavior.setHealth(newHealth)
.setMaxHealth(newHealth).setEnable(!boss);
setActive(!boss);
addBehavior(new DamagedByCollisionWithDEFObject());
if (!foliage)
addBehavior(new DebrisOnDeathBehavior());
else {
addBehavior(new CustomDeathBehavior(new Runnable() {
@Override
public void run() {
getGameShell().getGame().getCurrentMission()
.notifyFoliageDestroyed();
}
}));
}
if (canTurn || boss) {
addBehavior(new RotationalMomentumBehavior());
addBehavior(new RotationalDragBehavior()).setDragCoefficient(.86);
addBehavior(new AutoLeveling());
}
if (foliage) {
addBehavior(new ExplodesOnDeath(ExplosionType.Billow));
} else if ((anchoring == Anchoring.terrain) && !customExplosion) {
addBehavior(new ExplodesOnDeath(ExplosionType.BigExplosion,
BIG_EXP_SOUNDS[(int) (Math.random() * 3)]));
} else if (!customExplosion) {
addBehavior(new ExplodesOnDeath(ExplosionType.Blast,
MED_EXP_SOUNDS[(int) (Math.random() * 2)]));
}
if (mobile) {
addBehavior(new MovesByVelocity());
addBehavior(new HasPropulsion());
addBehavior(new AccelleratedByPropulsion());
addBehavior(new VelocityDragBehavior());
if (anchoring == Anchoring.terrain) {
} else if (anchoring == Anchoring.none) {
} else {// addBehavior(new
// BouncesOffSurfaces().setReflectHeading(false));
addBehavior(new CollidesWithTerrain().setAutoNudge(true)
.setNudgePadding(40000));
}
probeForBehavior(VelocityDragBehavior.class)
.setDragCoefficient(.86);
probeForBehavior(Propelled.class).setMinPropulsion(0);
probeForBehavior(Propelled.class)
.setPropulsion(def.getThrustSpeed() / 1.2);
addBehavior(new LoopingPositionBehavior());
} // end if(mobile)
if (def.getPowerup() != null
&& Math.random() * 100. < def.getPowerupProbability()) {
addBehavior(new LeavesPowerupOnDeathBehavior(def.getPowerup()));
}
addBehavior(new CollidesWithPlayer());
if (!boss)// Boss is too easy to beat by just colliding into it.
addBehavior(new DamagedByCollisionWithPlayer(8024, 250));
proposeRandomYell();
return true;
}// end evaluate()
public DEFObject() {
super();
}// end DEFObject
/*
* @Override public void destroy(){ if(ruinObject!=null){ //Give the
* ruinObject is own position because it is sharing positions with the
* original WorldObject, //which is going to be sent to xyz=Double.INFINITY
* soon. ruinObject.setPosition(Arrays.copyOf(getPosition(), 3));
* ruinObject.setVisible(true); ruinObject.setActive(true);}
* super.destroy(); }
*/
private void defaultModelAssignment()
throws IllegalAccessException, FileLoadException, IOException {
setModel(getTr().getResourceManager().getBINModel(
enemyDefinition.getComplexModelFile(),
getTr().getGlobalPaletteVL(), null, null));
}
private void alienModelAssignment()
throws FileLoadException, IOException, IllegalAccessException {
setModel(getTr().getResourceManager().getBINModel(
enemyDefinition.getSimpleModel(), getTr().getGlobalPaletteVL(),
null, null));
}
private void defaultRuinObject(EnemyPlacement pl)
throws IOException, IllegalArgumentException,
IllegalAccessException, FileLoadException {
// Spawn a second, powerup-free model using the simplemodel
// Model simpleModel=null;
// try{simpleModel =
// tr.getResourceManager().getBINModel(def.getSimpleModel(),tr.getGlobalPaletteVL(),null,tr.gpu.get().getGl());}
// catch(Exception e){e.printStackTrace();}
EnemyDefinition ed = new EnemyDefinition();
ed.setLogic(EnemyLogic.groundStatic);
ed.setDescription("auto-generated enemy rubble def");
ed.setPowerupProbability(0);
ed.setComplexModelFile(enemyDefinition.getSimpleModel());
EnemyPlacement simplePlacement = pl.clone();
// if(ed.getComplexModelFile()!=null){
final DEFObject ruin = new DEFObject();
ruin.setEnemyDefinition(ed);
ruin.setEnemyPlacement(simplePlacement);
ruin.setActive(false);
ruin.setVisible(false);
ruin.setRuin(true);
getSubObjects().add(ruin);
ruin.setPosition(new double[] { -999999999999999999.,
-9999999999999999999., -999999999999999999. });// Relevant
// nowhere
ruin.notifyPositionChange();
addBehavior(new CustomDeathBehavior(new Runnable() {
@Override
public void run() {
ruin.setPosition(Arrays.copyOf(getPosition(), 3));
ruin.notifyPositionChange();
ruin.setActive(true);
ruin.setVisible(true);
}
}));
try {
ruin.setDirection(new ObjectDirection(pl.getRoll(), pl.getPitch(),
pl.getYaw() + 65536));
} catch (MathArithmeticException e) {
e.printStackTrace();
}
// }//end if(!null)
}// end setRuinObject(...)
private void proposeRandomYell() {
final String sfxFile = enemyDefinition.getBossYellSFXFile();
if (sfxFile != null && !sfxFile.toUpperCase().contentEquals("NULL")) {
final SoundTexture soundTexture = getTr()
.getResourceManager().soundTextures.get(sfxFile);
final RandomSFXPlayback randomSFXPlayback = new RandomSFXPlayback()
.setSoundTexture(soundTexture).setDisableOnDeath(true)
.setVolumeScalar(SoundSystem.DEFAULT_SFX_VOLUME * 1.5);
addBehavior(randomSFXPlayback);
} // end if(!NULL)
}// end proposeRandomYell()
private void projectileFiringBehavior() {
ProjectileFiringBehavior pfb;
Integer[] firingVertices = Arrays.copyOf(
enemyDefinition.getFiringVertices(),
enemyDefinition.getNumRandomFiringVertices());
addBehavior(pfb = new ProjectileFiringBehavior()
.setProjectileFactory(getTr().getResourceManager()
.getProjectileFactories()[enemyDefinition.getWeapon()
.ordinal()])
.setFiringPositions(getModelSource(), firingVertices));
final String fireSfxFile = enemyDefinition.getBossFireSFXFile();
if (!fireSfxFile.toUpperCase().contentEquals("NULL"))
pfb.setFiringSFX(getTr().getResourceManager().soundTextures
.get(fireSfxFile));
try {
pfb.addSupply(99999999);
} catch (SupplyNotNeededException e) {
}
final AutoFiring af;
addBehavior(af = new AutoFiring().setProjectileFiringBehavior(pfb)
.setPatternOffsetMillis((int) (Math.random() * 2000))
.setMaxFiringDistance(TRFactory.mapSquareSize * 5)
.setSmartFiring(true).setMaxFireVectorDeviation(2.)
.setTimePerPatternEntry(
Math.max(1, getEnemyDefinition().getFireSpeed() / 66)));
if (boss)
af.setFiringPattern(new boolean[] { true }).setAimRandomness(.07);
}
private void unhandled(EnemyDefinition def) {
System.err.println("UNHANDLED DEF LOGIC: " + def.getLogic() + ". MODEL="
+ def.getComplexModelFile() + " DESC=" + def.getDescription());
}
private void fallingObjectBehavior() {
canTurn = false;
mobile = false;// Technically wrong but propulsion is unneeded.
// addBehavior(new PulledDownByGravityBehavior());
final MovesByVelocity mbv = new MovesByVelocity();
mbv.setVelocity(new double[] { 3500, -100000, 5000 });
addBehavior(mbv);
// addBehavior(new VelocityDragBehavior().setDragCoefficient(.99)); //
// For some reason it falls like pine tar
probeForBehavior(DamageableBehavior.class).setMaxHealth(10).setHealth(10);
addBehavior(new DeathBehavior());
addBehavior(new CollidesWithTerrain().setIgnoreCeiling(true));
addBehavior(new DamagedByCollisionWithSurface());
addBehavior(new RotationalMomentumBehavior().setEquatorialMomentum(.01)
.setLateralMomentum(.02).setPolarMomentum(.03));
{
final DEFObject thisObject = this;
final TR thisTr = getTr();
addBehavior(new ResetsRandomlyAfterDeath().setMinWaitMillis(1000)
.setMaxWaitMillis(5000).setRunOnReset(new Runnable() {
@Override
public void run() {
final Vector3D centerPos = thisObject
.probeForBehavior(DeathBehavior.class)
.getLocationOfLastDeath();
thisObject.probeForBehavior(MovesByVelocity.class)
.setVelocity(new double[] { 7000, -200000,
1000 });
final double[] pos = thisObject.getPosition();
pos[0] = centerPos.getX() + Math.random()
* TRFactory.mapSquareSize * 3
- TRFactory.mapSquareSize * 1.5;
pos[1] = thisTr.getWorld().sizeY / 2
+ thisTr.getWorld().sizeY * (Math.random())
* .3;
pos[2] = centerPos.getZ() + Math.random()
* TRFactory.mapSquareSize * 3
- TRFactory.mapSquareSize * 1.5;
thisObject.notifyPositionChange();
}// end run()
}));
}
}
private void possibleSpinAndCrashOnDeath(double probability,
final EnemyDefinition def) {
spinCrash = Math.random() < probability;
if (spinCrash) {
final DamageTrigger spinAndCrash = new DamageTrigger() {
@Override
public void healthBelowThreshold() {// Spinout and crash
final WorldObject parent = getParent();
if (probeForBehavior(DamageableBehavior.class)
.getHealth() < 1)
return;// No point; already dying.
// Trigger small boom
final TR tr = parent.getTr();
Features.get(tr, SoundSystemFeature.class)
.getPlaybackFactory()
.create(tr.getResourceManager().soundTextures
.get("EXP2.WAV"),
new double[] {
.5 * SoundSystem.DEFAULT_SFX_VOLUME
* 2,
.5 * SoundSystem.DEFAULT_SFX_VOLUME
* 2 });
addBehavior(
new PulledDownByGravityBehavior().setEnable(true));
probeForBehavior(DamagedByCollisionWithSurface.class)
.setEnable(true);
probeForBehavior(CollidesWithTerrain.class)
.setNudgePadding(0);
probeForBehavior(DamageableBehavior.class)
.setAcceptsProjectileDamage(true);
probeForBehavior(ExplodesOnDeath.class)
.setExplosionType(ExplosionType.Blast)
.setExplosionSound(
BIG_EXP_SOUNDS[(int) (Math.random() * 3)]);
if (def.getThrustSpeed() < 800000) {
probeForBehavior(HasPropulsion.class).setPropulsion(0);
probeForBehavior(VelocityDragBehavior.class)
.setEnable(false);
}
// Catastrophy
final double spinSpeedCoeff = Math
.max(def.getThrustSpeed() != 0
? def.getThrustSpeed() / 1600000 : .3, .4);
addBehavior(new SpinAccellerationBehavior()
.setSpinMode(SpinMode.LATERAL)
.setSpinAccelleration(.009 * spinSpeedCoeff));
addBehavior(new SpinAccellerationBehavior()
.setSpinMode(SpinMode.EQUATORIAL)
.setSpinAccelleration(.006 * spinSpeedCoeff));
addBehavior(new SpinAccellerationBehavior()
.setSpinMode(SpinMode.POLAR)
.setSpinAccelleration(.007 * spinSpeedCoeff));
// TODO: Sparks, and other fun stuff.
addBehavior(new SpawnsRandomExplosionsAndDebris(
parent.getTr()));
addBehavior(new SpawnsRandomSmoke(parent.getTr()));
}// end healthBelowThreshold
}.setThreshold(2048);
addBehavior(new DamagedByCollisionWithSurface()
.setCollisionDamage(65535).setEnable(false));
addBehavior(spinAndCrash);
}
}
private void possibleBobbingSpinAndCrashOnDeath(double probability,
EnemyDefinition def) {
possibleSpinAndCrashOnDeath(probability, def);
if (spinCrash) {
addBehavior(new CollidesWithTerrain());
addBehavior(new MovesByVelocity()).setEnable(false);
addBehavior(new HasPropulsion()).setEnable(false);
addBehavior(new AccelleratedByPropulsion()).setEnable(false);
addBehavior(new VelocityDragBehavior()).setEnable(false);
addBehavior(new RotationalMomentumBehavior()).setEnable(false);
addBehavior(new RotationalDragBehavior()).setDragCoefficient(.86);
final DamageTrigger spinAndCrashAddendum = new DamageTrigger() {
@Override
public void healthBelowThreshold() {
final WorldObject parent = getParent();
parent.probeForBehavior(MovesByVelocity.class)
.setEnable(true);
parent.probeForBehavior(HasPropulsion.class)
.setEnable(true);
parent.probeForBehavior(AccelleratedByPropulsion.class)
.setEnable(true);
parent.probeForBehavior(VelocityDragBehavior.class)
.setEnable(true);
parent.probeForBehavior(RotationalMomentumBehavior.class)
.setEnable(true);
parent.probeForBehavior(SteadilyRotating.class)
.setEnable(false);
parent.probeForBehavior(Bobbing.class).setEnable(false);
// parent.getBehavior().probeForBehavior(AutoFiring.class).setBerzerk(true)
// .setFiringPattern(new
// boolean[]{true}).setTimePerPatternEntry(100);
}
};
addBehavior(spinAndCrashAddendum);
} // end if(spinCrash)
}// end possibleBobbingSpinAndCrashOnDeath
private void newSmartPlaneBehavior(TR tr, EnemyDefinition def,
boolean retreatAboveSky) {
if (!DEFObject.NEW_SMART_PLANE_BEHAVIOR) {
smartPlaneBehavior(tr, def, retreatAboveSky);
return;
}
final ProjectileFiringBehavior pfb = new ProjectileFiringBehavior()
.setProjectileFactory(tr.getResourceManager()
.getProjectileFactories()[def.getWeapon().ordinal()]);
final ProjectileFiringBehavior secondaryPFB = new ProjectileFiringBehavior()
.setProjectileFactory(tr.getResourceManager()
.getProjectileFactories()[def.getSecondaryWeapon().ordinal()]);
try {
pfb.addSupply(99999999);
secondaryPFB.addSupply(99999999);
} catch (SupplyNotNeededException e) {
}
Integer[] firingVertices = Arrays.copyOf(def.getFiringVertices(),
def.getNumRandomFiringVertices());
pfb.setFiringPositions(getModelSource(), firingVertices);
addBehavior(pfb);
addBehavior(secondaryPFB);
possibleSpinAndCrashOnDeath(.4, def);
if (spinCrash) {
final DamageTrigger spinAndCrashAddendum = new DamageTrigger() {
@Override
public void healthBelowThreshold() {
final WorldObject parent = getParent();
final HasPropulsion hp = probeForBehavior(
HasPropulsion.class);
try {
probeForBehavior(NewSmartPlaneBehavior.class)
.setEnable(false);
} catch (BehaviorNotFoundException e) {
}
hp.setPropulsion(hp.getPropulsion() / 1);
hp.setEnable(false);
probeForBehavior(AutoLeveling.class)
.setLevelingAxis(LevelingAxis.HEADING)
.setLevelingVector(Vector3D.MINUS_J)
.setRetainmentCoeff(.987, .987, .987)
.setEnable(true);
System.out.println("spinAndCrashAddendum()");
}
};
addBehavior(spinAndCrashAddendum);
} // end if(spinCrash)
final AutoFiring afb = new AutoFiring();
final AutoFiring secondaryAFB = new AutoFiring();
final double secondWeaponDistance = TRFactory.legacy2Modern(def.getSecondWeaponDistance()) * TRFactory.mapSquareSize;
afb.setMaxFiringDistance(TRFactory.legacy2Modern(def.getAttackDistance()) * TRFactory.mapSquareSize);
afb.setMinFiringDistance(secondWeaponDistance);
secondaryAFB.setMaxFiringDistance(secondWeaponDistance);
afb.setMaxFireVectorDeviation(.7);
secondaryAFB.setMaxFireVectorDeviation(2);
//Fires 3 out of 7 times
afb.setFiringPattern(
new boolean[] { true, false, false, false, true, true, false });
secondaryAFB.setFiringPattern(
new boolean[] { true, false, false, false, true, true, false });
//Use the 3/7 ratio to compensate for the staggered shooting pattern in TRCL
afb.setTimePerPatternEntry(
Math.max(1, (int) (getEnemyDefinition().getFireSpeed() / 66 * (3./7.))));
secondaryAFB.setTimePerPatternEntry(
Math.max(1, (int) (getEnemyDefinition().getFireSpeed() / 66 * (3./7.))));
afb.setPatternOffsetMillis((int) (Math.random() * 1000));
secondaryAFB.setPatternOffsetMillis((int) (Math.random() * 1000));
afb.setProjectileFiringBehavior(pfb);
secondaryAFB.setProjectileFiringBehavior(secondaryPFB);
try {
final TVF3Game tvf3 = (TVF3Game) getGameShell().getGame();
if (tvf3.getDifficulty() != Difficulty.EASY)
afb.setSmartFiring(true);
} catch (ClassCastException e) {
} // Not a TVF3 Game
addBehavior(afb);
addBehavior(secondaryAFB);
/*
* addBehavior(new BuzzByPlayerSFX().setBuzzSounds(new String[]{
* "FLYBY56.WAV","FLYBY60.WAV","FLYBY80.WAV","FLYBY81.WAV"}));
*/
// addBehavior(new RollPitchYawBehavior());
// addBehavior(new RollBasedTurnBehavior());
final NewSmartPlaneBehavior nspb = new NewSmartPlaneBehavior();
nspb.setRotationScalar(getEnemyDefinition().getThrustSpeed() / 1000000);
System.out
.println("THRUST " + getEnemyDefinition().getComplexModelFile()
+ " " + getEnemyDefinition().getThrustSpeed());
addBehavior(nspb);
}// end newSmartPlaneBehavior
private void smartPlaneBehavior(TR tr, EnemyDefinition def,
boolean retreatAboveSky) {
final HorizAimAtPlayerBehavior haapb = new HorizAimAtPlayerBehavior(
getGameShell().getGame().getPlayer())
.setLeftHanded(Math.random() >= .5);
addBehavior(haapb);
final AdjustAltitudeToPlayerBehavior aatpb = new AdjustAltitudeToPlayerBehavior(
getGameShell().getGame().getPlayer()).setAccelleration(1000);
addBehavior(aatpb);
final ResourceManager resourceManager = tr.getResourceManager();
final ProjectileFiringBehavior pfb = new ProjectileFiringBehavior()
.setProjectileFactory(resourceManager
.getProjectileFactories()[def.getWeapon().ordinal()]);
final ProjectileFiringBehavior secondaryPFB = new ProjectileFiringBehavior()
.setProjectileFactory(resourceManager
.getProjectileFactories()[def.getSecondaryWeapon().ordinal()]);
try {
pfb.addSupply(99999999);
secondaryPFB.addSupply(99999999);
} catch (SupplyNotNeededException e) {
}
Integer[] firingVertices = Arrays.copyOf(def.getFiringVertices(),
def.getNumRandomFiringVertices());
pfb.setFiringPositions(getModelSource(), firingVertices);
addBehavior(pfb);
addBehavior(secondaryPFB);
possibleSpinAndCrashOnDeath(.4, def);
if (spinCrash) {
final DamageTrigger spinAndCrashAddendum = new DamageTrigger() {
@Override
public void healthBelowThreshold() {
final WorldObject parent = getParent();
final HasPropulsion hp = probeForBehavior(
HasPropulsion.class);
hp.setPropulsion(hp.getPropulsion() / 1);
probeForBehavior(AutoLeveling.class)
.setLevelingAxis(LevelingAxis.HEADING)
.setLevelingVector(Vector3D.MINUS_J)
.setRetainmentCoeff(.985, .985, .985);
}
};
addBehavior(spinAndCrashAddendum);
} // end if(spinCrash)
AccelleratedByPropulsion escapeProp = null;
if (retreatAboveSky) {
escapeProp = new AccelleratedByPropulsion();
escapeProp.setThrustVector(new Vector3D(0, .1, 0)).setEnable(false);
addBehavior(escapeProp);
}
final AutoFiring secondaryAFB = new AutoFiring();
final AutoFiring afb = new AutoFiring();
afb .setMaxFireVectorDeviation(.7);
secondaryAFB.setMaxFireVectorDeviation(2);
afb.setFiringPattern(
new boolean[] { true, false, false, false, true, true, false });
secondaryAFB.setFiringPattern(
new boolean[] { true, false, true, false, false, false, false });
afb.setTimePerPatternEntry((int) ((200 + Math.random() * 200)));//TODO: Use firing rate!
secondaryAFB.setTimePerPatternEntry((int) ((200 + Math.random() * 200)));//TODO: Use firing rate!
afb.setPatternOffsetMillis((int) (Math.random() * 1000));
secondaryAFB.setPatternOffsetMillis((int) (Math.random() * 1000));
afb.setProjectileFiringBehavior(pfb);
secondaryAFB.setProjectileFiringBehavior(pfb);
try {
final TVF3Game tvf3 = (TVF3Game) getGameShell().getGame();
Difficulty difficulty = tvf3.getDifficulty();
if (difficulty != Difficulty.EASY)
afb.setSmartFiring(true);
if (difficulty == Difficulty.HARD || difficulty == Difficulty.FURIOUS)
secondaryAFB.setSmartFiring(true);
} catch (ClassCastException e) {
} // Not a TVF3 Game
addBehavior(afb);
addBehavior(secondaryAFB);
final SpinAccellerationBehavior sab = (SpinAccellerationBehavior) new SpinAccellerationBehavior()
.setEnable(false);
addBehavior(sab);
addBehavior(new SmartPlaneBehavior(haapb, afb, sab, aatpb, escapeProp,
retreatAboveSky));
// addBehavior(new NewSmartPlaneBehavior());
addBehavior(new BuzzByPlayerSFX().setBuzzSounds(new String[] {
"FLYBY56.WAV", "FLYBY60.WAV", "FLYBY80.WAV", "FLYBY81.WAV" }));
}// end smartPlaneBehavior()
private void alienBoss(EnemyPlacement pl)
throws FileLoadException, IllegalAccessException, IOException {
addBehavior(new HorizAimAtPlayerBehavior(
getGameShell().getGame().getPlayer())).setEnable(false);
projectileFiringBehavior();
setVisible(false);
final ResourceManager rm = getTr().getResourceManager();
setModel(rm.getBINModel(enemyDefinition.getSimpleModel(),
getTr().getGlobalPaletteVL(), null, null));
final int towerShields = pl.getStrength();// Not sure exactly what
// should go here.
final int alienShields = pl.getStrength();
final int totalShields = towerShields + alienShields;
// BOSS
final DamageTrigger damageTrigger = new DamageTrigger() {
@Override
public void healthBelowThreshold() {
final GL33Model oldModel = getModel();
try {
setModel(rm.getBINModel(
enemyDefinition.getComplexModelFile(),
getTr().getGlobalPaletteVL(), null, null));
} catch (Exception e) {
e.printStackTrace();
}
probeForBehavior(ProjectileFiringBehavior.class)
.setEnable(true);
probeForBehavior(HorizAimAtPlayerBehavior.class)
.setEnable(true);
final Vector3D pos = new Vector3D(getPosition());
getTr().getResourceManager().getExplosionFactory()
.triggerExplosion(pos, Explosion.ExplosionType.Blast);
final Vector3D dims = oldModel.getMaximumVertexDims();
final DebrisSystem debrisSystem = getTr().getResourceManager()
.getDebrisSystem();
for (int i = 0; i < 20; i++) {
final Vector3D rPos = new Vector3D(
(Math.random() - .5) * dims.getX(),
(Math.random() - .5) * dims.getY(),
(Math.random() - .5) * dims.getZ())
.scalarMultiply(2)
.add(new Vector3D(getPosition()));
final double velocity = 1000;
final Vector3D rVel = new Vector3D(
(Math.random() - .5) * velocity,
(Math.random() - .5) * velocity,
(Math.random() - .5) * velocity).scalarMultiply(2);
debrisSystem.spawn(rPos, rVel);
} // end for(200)
getTr().getResourceManager().getDebrisSystem().spawn(pos,
new Vector3D(Math.random() * 10000,
Math.random() * 10000, Math.random() * 10000));
}
};
damageTrigger.setThreshold(alienShields);
addBehavior(damageTrigger);
// TOWER
final PropertyChangeListener alienPCL;
addPropertyChangeListener(ACTIVE,
alienPCL = new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getNewValue() == Boolean.TRUE) {
probeForBehavior(DamageableBehavior.class)
.setMaxHealth(totalShields);
probeForBehavior(DamageableBehavior.class)
.setHealth(totalShields);
probeForBehavior(ProjectileFiringBehavior.class)
.setEnable(false);
DEFObject.this.setVisible(true);
}
}
});
// DAMAGEABLE TOOWER
addBehavior(new CustomNAVTargetableBehavior(new Runnable() {
@Override
public void run() {
probeForBehavior(DamageableBehavior.class).setEnable(true);
DEFObject.this.setIgnoringProjectiles(false);
}
}));
hardReferences.add(alienPCL);
}// end alienBoss(...)
/*
private void bossWarningSiren() {
final PropertyChangeListener alienPCL;
addPropertyChangeListener(ACTIVE,
alienPCL = new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getNewValue() == Boolean.TRUE) {
final TR tr = getTr();
SoundSystem ss = Features.get(getTr(),
SoundSystemFeature.class);
final SoundTexture st = tr
.getResourceManager().soundTextures
.get("WARNING.WAV");
final SoundEvent se = ss.getPlaybackFactory()
.create(st, new double[] {
SoundSystem.DEFAULT_SFX_VOLUME,
SoundSystem.DEFAULT_SFX_VOLUME });
ss.enqueuePlaybackEvent(se);
}
}
});
hardReferences.add(alienPCL);
}// end bossWarningSiren()
*/
private void defaultBossNAVTargetingResponse() {
addBehavior(new CustomNAVTargetableBehavior(new Runnable() {
@Override
public void run() {
probeForBehavior(DamageableBehavior.class).setEnable(true);
setIgnoringProjectiles(false);
}
}));
//bossWarningSiren();
}// end defaultBossNAVTargetingResponse()
@Override
public void setTop(Vector3D top) {
super.setTop(top);
}
/**
* @return the logic
*/
public EnemyLogic getLogic() {
return logic;
}
/**
* @return the mobile
*/
public boolean isMobile() {
return mobile;
}
/**
* @return the canTurn
*/
public boolean isCanTurn() {
return canTurn;
}
/**
* @return the foliage
*/
public boolean isFoliage() {
return foliage;
}
/**
* @return the boss
*/
public boolean isBoss() {
return boss;
}
/**
* @return the groundLocked
*/
public boolean isGroundLocked() {
return anchoring == Anchoring.terrain;
}
/**
* @return the ignoringProjectiles
*/
public boolean isIgnoringProjectiles() {
return ignoringProjectiles;
}
/**
* @param ignoringProjectiles
* the ignoringProjectiles to set
*/
public void setIgnoringProjectiles(boolean ignoringProjectiles) {
this.ignoringProjectiles = ignoringProjectiles;
}
/**
* @return the isRuin
*/
public boolean isRuin() {
return isRuin;
}
/**
* @param isRuin
* the isRuin to set
*/
public void setRuin(boolean isRuin) {
this.isRuin = isRuin;
}
/**
* @return the shieldGen
*/
public boolean isShieldGen() {
return shieldGen;
}
/**
* @param shieldGen
* the shieldGen to set
*/
public void setShieldGen(boolean shieldGen) {
this.shieldGen = shieldGen;
}
@Override
public String toString() {
final StringBuilder attachedObjects = new StringBuilder();
attachedObjects.append("\n\tAttached objects: ");
for (WorldObject wo : getSubObjects())
attachedObjects.append("\n\t " + wo.toString() + " ");
return "DEFObject Model=" + getModel() + " Logic=" + logic
+ " Anchoring=" + anchoring + "\n\tmobile=" + mobile
+ " isRuin=" + isRuin + " foliage=" + foliage + " boss=" + boss
+ " spinCrash=" + spinCrash + "\n\tignoringProjectiles="
+ ignoringProjectiles + "\n" + "\tRuinObject="
+ attachedObjects.toString();
}
enum Anchoring {
floating(false), terrain(true), ceiling(true), none(false);
private final boolean locked;
private Anchoring(boolean locked) {
this.locked = locked;
}
public boolean isLocked() {
return locked;
}
}// end Anchoring
public BasicModelSource getModelSource() {
if (rotatedModelSource == null) {// Assemble our decorator sandwich.
final String complexModel = enemyDefinition.getComplexModelFile();
if (complexModel == null)
return null;
final ResourceManager rm = getTr().getResourceManager();
BasicModelSource bmt = null;
final BINFileExtractor bfe = new BINFileExtractor(rm);
bfe.setDefaultTexture(
Features.get(getTr(), GPUFeature.class).textureManager.get()
.getFallbackTexture());
try {
bmt = new BufferedModelTarget();
bfe.extract(
rm.getBinFileModel(
enemyDefinition.getComplexModelFile()),
(BufferedModelTarget) bmt);
} catch (UnrecognizedFormatException e) {// Animated BIN
try {
final AnimationControl ac = rm.getAnimationControlBIN(
enemyDefinition.getComplexModelFile());
List<String> bins = ac.getBinFiles();
bmt = new InterpolatedAnimatedModelSource();
for (String name : bins) {
BufferedModelTarget bufferedTarget = new BufferedModelTarget();
bfe.extract(rm.getBinFileModel(name), bufferedTarget);
((InterpolatedAnimatedModelSource) bmt)
.addModelFrame(bufferedTarget);
}
((InterpolatedAnimatedModelSource) bmt)
.setDelayBetweenFramesMillis(ac.getDelay());
} catch (Exception ee) {
ee.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
rotatedModelSource = new RotatedModelSource(bmt);
rotatedModelSource.setRotatableSource(this);
}
return rotatedModelSource;
}
/**
* @return the boundingHeight
*/
public double getBoundingHeight() {
if (boundingHeight == null) {
calcBoundingDims();
}
return boundingHeight;
}// end getBoundingHeight()
public double getBoundingWidth() {
if (boundingWidth == null) {
calcBoundingDims();
}
return boundingWidth;
}// end getBoundingHeight()
private void calcBoundingDims() {
final GL33Model model = getModel();
Vector3D max = Vector3D.ZERO;
if (model != null)
max = model.getMaximumVertexDims();
else {
max = new Vector3D(
(enemyDefinition.getBoundingBoxRadius()
/ TRFactory.crossPlatformScalar),
(enemyDefinition.getBoundingBoxRadius()
/ TRFactory.crossPlatformScalar),
0).scalarMultiply(1. / 1.5);
// max = Vector3D.ZERO;
}
boundingWidth = max.getX();
boundingHeight = max.getY();
}// end calcBoundingDims()
public static class HitBox {
private int vertexID;
private double size;
public int getVertexID() {
return vertexID;
}
public void setVertexID(int vertexID) {
this.vertexID = vertexID;
}
/**
*
* @return size in modern units
* @since Jul 6, 2016
*/
public double getSize() {
return size;
}
/**
* Size in modern units
*
* @param size
* @since Jul 6, 2016
*/
public void setSize(double size) {
this.size = size;
}
}// end HitBox
public HitBox[] getHitBoxes() {
return hitBoxes;
}
public void setHitBoxes(HitBox[] hitBoxes) {
this.hitBoxes = hitBoxes;
}
public ArrayList<WorldObject> getSubObjects() {
if (subObjects == null)
subObjects = new ArrayList<WorldObject>();
return subObjects;
}
protected void setSubObjects(ArrayList<WorldObject> attachedObjects) {
this.subObjects = attachedObjects;
}
public GameShell getGameShell() {
if (gameShell == null) {
gameShell = Features.get(getTr(), GameShell.class);
}
return gameShell;
}
public void setGameShell(GameShell gameShell) {
this.gameShell = gameShell;
}
public EnemyDefinition getEnemyDefinition() {
return enemyDefinition;
}
public EnemyPlacement getEnemyPlacement() {
return enemyPlacement;
}
public void setEnemyPlacement(EnemyPlacement enemyPlacement) {
this.enemyPlacement = enemyPlacement;
proposeEvaluate();
}
public void setEnemyDefinition(EnemyDefinition enemyDefinition) {
this.enemyDefinition = enemyDefinition;
proposeEvaluate();
}
public boolean isEvaluated() {
return evaluated;
}
public void setEvaluated(boolean evaluated) {
this.evaluated = evaluated;
}
}// end DEFObject
|
package com.chaos.services;
import com.chaos.model.EmailEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.context.ApplicationListener;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
@Component
public class EmailService implements ApplicationEventPublisherAware,ApplicationListener<EmailEvent>{
private ApplicationEventPublisher publisher;
@Value("${support.email}")
private String supportEmail;
@Autowired
private JavaMailSender javaMailSender;
public void setApplicationEventPublisher(ApplicationEventPublisher publisher) {
this.publisher = publisher;
}
@Override
public void onApplicationEvent(EmailEvent event) {
this.send(event.getSubject(), event.getContent());
}
private void send(String subject, String content) {
SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setTo(supportEmail);
mailMessage.setReplyTo(supportEmail);
mailMessage.setFrom(supportEmail);
mailMessage.setSubject(subject);
mailMessage.setText(content);
try {
javaMailSender.send(mailMessage);
} catch (MailException e)
{
e.printStackTrace();
}
}
public void sendEmail(String subject, String content) {
EmailEvent event = new EmailEvent(this, subject, content);
publisher.publishEvent(event);
}
}
|
package org.jtrfp.trcl.obj;
import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;
import org.jtrfp.trcl.Model;
import org.jtrfp.trcl.beh.AdjustAltitudeToPlayerBehavior;
import org.jtrfp.trcl.beh.AutoFiring;
import org.jtrfp.trcl.beh.AutoLeveling;
import org.jtrfp.trcl.beh.AutoLeveling.LevelingAxis;
import org.jtrfp.trcl.beh.Behavior;
import org.jtrfp.trcl.beh.Bobbing;
import org.jtrfp.trcl.beh.CollidesWithTerrain;
import org.jtrfp.trcl.beh.CustomPlayerWithinRangeBehavior;
import org.jtrfp.trcl.beh.DamageTrigger;
import org.jtrfp.trcl.beh.DamageableBehavior;
import org.jtrfp.trcl.beh.DamagedByCollisionWithGameplayObject;
import org.jtrfp.trcl.beh.DamagedByCollisionWithSurface;
import org.jtrfp.trcl.beh.DeathBehavior;
import org.jtrfp.trcl.beh.DebrisOnDeathBehavior;
import org.jtrfp.trcl.beh.ExplodesOnDeath;
import org.jtrfp.trcl.beh.HorizAimAtPlayerBehavior;
import org.jtrfp.trcl.beh.LeavesPowerupOnDeathBehavior;
import org.jtrfp.trcl.beh.LoopingPositionBehavior;
import org.jtrfp.trcl.beh.PositionLimit;
import org.jtrfp.trcl.beh.ProjectileFiringBehavior;
import org.jtrfp.trcl.beh.ResetsRandomlyAfterDeath;
import org.jtrfp.trcl.beh.SmartPlaneBehavior;
import org.jtrfp.trcl.beh.SpinAccellerationBehavior;
import org.jtrfp.trcl.beh.SpinAccellerationBehavior.SpinMode;
import org.jtrfp.trcl.beh.SteadilyRotating;
import org.jtrfp.trcl.beh.TerrainLocked;
import org.jtrfp.trcl.beh.phy.AccelleratedByPropulsion;
import org.jtrfp.trcl.beh.phy.BouncesOffSurfaces;
import org.jtrfp.trcl.beh.phy.HasPropulsion;
import org.jtrfp.trcl.beh.phy.MovesByVelocity;
import org.jtrfp.trcl.beh.phy.PulledDownByGravityBehavior;
import org.jtrfp.trcl.beh.phy.RotationalDragBehavior;
import org.jtrfp.trcl.beh.phy.RotationalMomentumBehavior;
import org.jtrfp.trcl.beh.phy.VelocityDragBehavior;
import org.jtrfp.trcl.core.TR;
import org.jtrfp.trcl.file.DEFFile.EnemyDefinition;
import org.jtrfp.trcl.file.DEFFile.EnemyDefinition.EnemyLogic;
import org.jtrfp.trcl.file.DEFFile.EnemyPlacement;
import org.jtrfp.trcl.obj.Explosion.ExplosionType;
public class DEFObject extends WorldObject {
private final double boundingRadius;
private WorldObject ruinObject;
private final EnemyLogic logic;
private boolean mobile,canTurn,foliage,boss,groundLocked;
boolean spinCrash=false;
public DEFObject(TR tr,Model model, EnemyDefinition def, EnemyPlacement pl){
super(tr,model);
boundingRadius = TR.legacy2Modern(def.getBoundingBoxRadius())/1.5;
logic = def.getLogic();
mobile=true;
canTurn=true;
foliage=false;
boss=def.isObjectIsBoss();
groundLocked=false;
boolean customExplosion=false;
switch(logic){
case groundDumb:
mobile=false;
canTurn=false;
break;
case groundTargeting://Ground turrets
mobile=false;
canTurn=true;
addBehavior(new HorizAimAtPlayerBehavior(tr.getPlayer()));
//TODO: def.getFiringVertices() needs actual vertex lookup.
addBehavior(new ProjectileFiringBehavior().setFiringPositions(new Vector3D[]{
new Vector3D(0,0,0)
}));
break;
case flyingDumb:
canTurn=false;
break;
case groundTargetingDumb:
groundLocked=true;
break;
case flyingSmart:
smartPlaneBehavior(tr,def,false);
break;
case bankSpinDrill:
unhandled(def);
break;
case sphereBoss:
unhandled(def);
mobile=true;
break;
case flyingAttackRetreatSmart:
smartPlaneBehavior(tr,def,false);
//addBehavior(new HorizAimAtPlayerBehavior(tr.getPlayer()));
break;
case splitShipSmart://TODO
smartPlaneBehavior(tr,def,false);
//addBehavior(new HorizAimAtPlayerBehavior(tr.getPlayer()));
break;
case groundStaticRuin://Destroyed object is replaced with another using SimpleModel i.e. weapons bunker
mobile=false;
canTurn=false;
break;
case targetHeadingSmart:
mobile=false;//Belazure's crane bots
addBehavior(new HorizAimAtPlayerBehavior(tr.getPlayer()));
break;
case targetPitchSmart:
mobile=false;
addBehavior(new HorizAimAtPlayerBehavior(tr.getPlayer()));
break;
case coreBossSmart:
mobile=false;
break;
case cityBossSmart:
mobile=false;
break;
case staticFiringSmart:{
//addBehavior(new HorizAimAtPlayerBehavior(tr.getPlayer()));
final ProjectileFiringBehavior pfb = new ProjectileFiringBehavior();
pfb.addSupply(99999999);
pfb.setProjectileFactory(tr.getResourceManager().getProjectileFactories()[def.getWeapon().ordinal()]);
addBehavior(pfb);
addBehavior(new AutoFiring().
setProjectileFiringBehavior(pfb).
setPatternOffsetMillis((int)(Math.random()*2000)).
setMaxFiringDistance(TR.mapSquareSize*8).
setSmartFiring(true));
mobile=false;
canTurn=false;
break;}
case sittingDuck:
canTurn=false;
mobile=false;
break;
case tunnelAttack:{
final ProjectileFiringBehavior pfb = new ProjectileFiringBehavior();
pfb.addSupply(99999999);
pfb.setProjectileFactory(tr.getResourceManager().getProjectileFactories()[def.getWeapon().ordinal()]);
addBehavior(pfb);
//addBehavior(new HorizAimAtPlayerBehavior(tr.getPlayer()));
addBehavior(new AutoFiring().
setProjectileFiringBehavior(pfb).
setPatternOffsetMillis((int)(Math.random()*2000)).
setMaxFiringDistance(TR.mapSquareSize*.2).
setSmartFiring(false).
setMaxFireVectorDeviation(.3).
setTimePerPatternEntry(2000));
addBehavior(new Bobbing().
setPhase(Math.random()).
setBobPeriodMillis(10*1000+Math.random()*3000).setAmplitude(2000));
mobile=false;
break;}
case takeoffAndEscape:
addBehavior(new MovesByVelocity());
addBehavior((Behavior)(new HasPropulsion().setMinPropulsion(0).setPropulsion(def.getThrustSpeed())));
addBehavior(new AccelleratedByPropulsion().setEnable(false));
addBehavior(new VelocityDragBehavior().setDragCoefficient(.86));
addBehavior(new CustomPlayerWithinRangeBehavior(){
@Override
public void withinRange(){
DEFObject.this.getBehavior().
probeForBehavior(AccelleratedByPropulsion.class).
setThrustVector(Vector3D.PLUS_J).
setEnable(true);
}
}).setRange(TR.mapSquareSize*10);
addBehavior(new LoopingPositionBehavior());
addBehavior(new ExplodesOnDeath(ExplosionType.Blast));
customExplosion=true;
canTurn=false;
mobile=false;
break;
case fallingAsteroid:
fallingObjectBehavior();
addBehavior(new RotationalMomentumBehavior()
.accellerateEquatorialMomentum(1)
.accellerateLateralMomentum(1)
.accelleratePolarMomentum(1));
{ final DEFObject thisObject = this;
final Vector3D centerPos = new Vector3D(this.getPosition());
final TR thisTr = tr;
addBehavior(new ResetsRandomlyAfterDeath()
.setMinWaitMillis(100)
.setMaxWaitMillis(1000)
.setRunOnReset(new Runnable(){
@Override
public void run(){
final double [] pos = thisObject.getPosition();
pos[0]=centerPos.getX()+Math.random()*TR.mapSquareSize*10;
pos[1]=thisTr.getWorld().sizeY/1.5;
pos[2]=centerPos.getZ()+Math.random()*TR.mapSquareSize*10;
thisObject.notifyPositionChange();
}//end run()
}));}
break;
case cNome://Walky bot?
groundLocked=true;
break;
case cNomeLegs://Walky bot?
groundLocked=true;
break;
case cNomeFactory:
mobile=false;
break;
case geigerBoss:
addBehavior(new HorizAimAtPlayerBehavior(tr.getPlayer()));
mobile=false;
break;
case volcanoBoss:
addBehavior(new HorizAimAtPlayerBehavior(tr.getPlayer()));
mobile=false;
break;
case volcano://Wat.
unhandled(def);
canTurn=false;
mobile=false;
break;
case missile://Silo?
mobile=false;//TODO
break;
case bob:
addBehavior(new Bobbing());
addBehavior(new SteadilyRotating());
addBehavior(new ExplodesOnDeath(ExplosionType.Blast));
possibleBobbingSpinAndCrashOnDeath(.5);
customExplosion=true;
mobile=false;
canTurn=false;//ironic?
break;
case alienBoss:
break;
case canyonBoss1:
mobile=false;
break;
case canyonBoss2:
mobile=false;
break;
case lavaMan://Also terraform-o-bot
mobile=false;
break;
case arcticBoss:
mobile=false;
break;
case helicopter://TODO
break;
case tree:
canTurn=false;
mobile=false;
foliage=true;
break;
case ceilingStatic:
canTurn=false;
mobile=false;
break;
case bobAndAttack:{
addBehavior(new SteadilyRotating().setRotationPhase(2*Math.PI*Math.random()));
final ProjectileFiringBehavior pfb = new ProjectileFiringBehavior();
pfb.addSupply(99999999);
pfb.setProjectileFactory(tr.getResourceManager().getProjectileFactories()[def.getWeapon().ordinal()]);
addBehavior(pfb);//Bob and attack don't have the advantage of movement, so give them the advantage of range.
addBehavior(new AutoFiring().
setProjectileFiringBehavior(pfb).
setPatternOffsetMillis((int)(Math.random()*2000)).
setMaxFiringDistance(TR.mapSquareSize*17).
setSmartFiring(true));
addBehavior(new Bobbing().
setPhase(Math.random()).
setBobPeriodMillis(10*1000+Math.random()*3000));
addBehavior(new ExplodesOnDeath(ExplosionType.Blast));
possibleBobbingSpinAndCrashOnDeath(.5);
customExplosion=true;
mobile=false;
canTurn=false;
break;}
case forwardDrive:
canTurn=false;
groundLocked=true;
break;
case fallingStalag:
fallingObjectBehavior();
{final DEFObject thisObject = this;
final Vector3D centerPos = new Vector3D(this.getPosition());
final TR thisTr = tr;
addBehavior(new ResetsRandomlyAfterDeath()
.setMinWaitMillis(100)
.setMaxWaitMillis(1000)
.setRunOnReset(new Runnable(){
@Override
public void run(){
final double [] pos = thisObject.getPosition();
pos[0]=centerPos.getX()+Math.random()*TR.mapSquareSize*10;
pos[1]=thisTr.getWorld().sizeY/1.5;
pos[2]=centerPos.getZ()+Math.random()*TR.mapSquareSize*10;
thisObject.notifyPositionChange();
}//end run()
}));}
canTurn=false;
mobile=false;
break;
case attackRetreatBelowSky:
smartPlaneBehavior(tr,def,false);
break;
case attackRetreatAboveSky:
smartPlaneBehavior(tr,def,true);
break;
case bobAboveSky:
addBehavior(new Bobbing());
addBehavior(new SteadilyRotating());
possibleBobbingSpinAndCrashOnDeath(.5);
mobile=false;
canTurn=false;
break;
case factory:
canTurn=false;
mobile=false;
break;
}//end switch(logic)
//Position Limit
{final PositionLimit posLimit = new PositionLimit();
posLimit.getPositionMaxima()[1]=TR.mapSquareSize*10;
posLimit.getPositionMinima()[1]=-TR.mapSquareSize;
addBehavior(posLimit);}
//Misc
addBehavior(new DeathBehavior());
addBehavior(new DamageableBehavior().setHealth(pl.getStrength()+(spinCrash?16:0)).setMaxHealth(pl.getStrength()+(spinCrash?16:0)).setEnable(!boss));
setActive(!boss);
addBehavior(new DamagedByCollisionWithGameplayObject());
if(!foliage)addBehavior(new DebrisOnDeathBehavior());
if(canTurn||boss){
addBehavior(new RotationalMomentumBehavior());
addBehavior(new RotationalDragBehavior()).setDragCoefficient(.86);
addBehavior(new AutoLeveling());
}
if(foliage){
addBehavior(new ExplodesOnDeath(ExplosionType.Billow));
}else if((!mobile || groundLocked) && !customExplosion){
addBehavior(new ExplodesOnDeath(ExplosionType.BigExplosion));
}else if(!customExplosion){
addBehavior(new ExplodesOnDeath(ExplosionType.Blast));
}
if(mobile){
addBehavior(new MovesByVelocity());
addBehavior(new HasPropulsion());
addBehavior(new AccelleratedByPropulsion());
addBehavior(new VelocityDragBehavior());
if(groundLocked){
addBehavior(new TerrainLocked());}
else {addBehavior(new BouncesOffSurfaces().setReflectHeading(false));
addBehavior(new CollidesWithTerrain());
}
getBehavior().probeForBehavior(VelocityDragBehavior.class).setDragCoefficient(.86);
getBehavior().probeForBehavior(Propelled.class).setMinPropulsion(0);
getBehavior().probeForBehavior(Propelled.class).setPropulsion(def.getThrustSpeed());
addBehavior(new LoopingPositionBehavior());
}//end if(mobile)
if(boss){bossBehavior(tr,def);}
if(def.getPowerup()!=null && Math.random()*100. < def.getPowerupProbability()){addBehavior(new LeavesPowerupOnDeathBehavior(def.getPowerup()));}
}//end DEFObject
@Override
public void destroy(){
if(ruinObject!=null)ruinObject.setVisible(true);//TODO: Switch to setActive later.
super.destroy();
}
private void unhandled(EnemyDefinition def){
System.err.println("UNHANDLED DEF LOGIC: "+def.getLogic()+". MODEL="+def.getComplexModelFile()+" DESC="+def.getDescription());
}
private void bossBehavior(TR tr, EnemyDefinition def){//Don't include hitzones for aiming.
if(!def.getComplexModelFile().toUpperCase().contains("HITZO"))addBehavior(new HorizAimAtPlayerBehavior(tr.getPlayer()));
}
private void fallingObjectBehavior(){
canTurn=false;
addBehavior(new PulledDownByGravityBehavior());
addBehavior(new DamageableBehavior().setHealth(1));
addBehavior(new CollidesWithTerrain());
}
private void possibleSpinAndCrashOnDeath(double probability, final double spinSpeedCoeff){
spinCrash=Math.random()<probability;
if(spinCrash){
final DamageTrigger spinAndCrash = new DamageTrigger(){
@Override
public void healthBelowThreshold(){// Spinout and crash
final WorldObject parent = getParent();
final Behavior beh = parent.getBehavior();
addBehavior(new PulledDownByGravityBehavior());
beh.probeForBehavior(DamagedByCollisionWithSurface.class).setEnable(true);
beh.probeForBehavior(DamageableBehavior.class).setAcceptsProjectileDamage(false);
beh.probeForBehavior(ExplodesOnDeath.class).setExplosionType(ExplosionType.BigExplosion);
//Catastrophy
addBehavior(new SpinAccellerationBehavior().setSpinMode(SpinMode.LATERAL).setSpinAccelleration(.009*spinSpeedCoeff));
addBehavior(new SpinAccellerationBehavior().setSpinMode(SpinMode.EQUATORIAL).setSpinAccelleration(.006*spinSpeedCoeff));
addBehavior(new SpinAccellerationBehavior().setSpinMode(SpinMode.POLAR).setSpinAccelleration(.007*spinSpeedCoeff));
//TODO: Smoke, sparks, and other fun stuff.
addBehavior(new SpawnsRandomExplosionsAndDebris(parent.getTr()));
}//end healthBelowThreshold
}.setThreshold(2048);
addBehavior(new DamagedByCollisionWithSurface().setCollisionDamage(65535).setEnable(false));
addBehavior(spinAndCrash);}
}
private void possibleBobbingSpinAndCrashOnDeath(double probability){
possibleSpinAndCrashOnDeath(probability,.3);
if(spinCrash){
addBehavior(new CollidesWithTerrain());
addBehavior(new MovesByVelocity()).setEnable(false);
addBehavior(new HasPropulsion()).setEnable(false);
addBehavior(new AccelleratedByPropulsion()).setEnable(false);
addBehavior(new VelocityDragBehavior()).setEnable(false);
addBehavior(new RotationalMomentumBehavior()).setEnable(false);
addBehavior(new RotationalDragBehavior()).setDragCoefficient(.86);
final DamageTrigger spinAndCrashAddendum = new DamageTrigger(){
@Override
public void healthBelowThreshold(){
final WorldObject parent = getParent();
parent.getBehavior().probeForBehavior(MovesByVelocity.class).setEnable(true);
parent.getBehavior().probeForBehavior(HasPropulsion.class).setEnable(true);
parent.getBehavior().probeForBehavior(AccelleratedByPropulsion.class).setEnable(true);
parent.getBehavior().probeForBehavior(VelocityDragBehavior.class).setEnable(true);
parent.getBehavior().probeForBehavior(RotationalMomentumBehavior.class).setEnable(true);
parent.getBehavior().probeForBehavior(SteadilyRotating.class).setEnable(false);
parent.getBehavior().probeForBehavior(Bobbing.class).setEnable(false);
// parent.getBehavior().probeForBehavior(AutoFiring.class).setBerzerk(true)
// .setFiringPattern(new boolean[]{true}).setTimePerPatternEntry(100);
}};
addBehavior(spinAndCrashAddendum);
}//end if(spinCrash)
}
private void smartPlaneBehavior(TR tr, EnemyDefinition def, boolean retreatAboveSky){
final HorizAimAtPlayerBehavior haapb =new HorizAimAtPlayerBehavior(tr.getPlayer()).setLeftHanded(Math.random()>=.5);
addBehavior(haapb);
final AdjustAltitudeToPlayerBehavior aatpb = new AdjustAltitudeToPlayerBehavior(tr.getPlayer()).setAccelleration(1000);
addBehavior(aatpb);
final ProjectileFiringBehavior pfb = new ProjectileFiringBehavior().setProjectileFactory(tr.getResourceManager().getProjectileFactories()[def.getWeapon().ordinal()]);
pfb.addSupply(99999999);
addBehavior(pfb);
possibleSpinAndCrashOnDeath(.4,1.);
if(spinCrash){
final DamageTrigger spinAndCrashAddendum = new DamageTrigger(){
@Override
public void healthBelowThreshold(){
final WorldObject parent = getParent();
final Behavior beh = parent.getBehavior();
final HasPropulsion hp = beh.probeForBehavior(HasPropulsion.class);
hp.setPropulsion(hp.getPropulsion()/1);
beh.probeForBehavior(AutoLeveling.class).
setLevelingAxis(LevelingAxis.HEADING).
setLevelingVector(Vector3D.MINUS_J).setRetainmentCoeff(.985);
}};
addBehavior(spinAndCrashAddendum);
}//end if(spinCrash)
AccelleratedByPropulsion escapeProp=null;
if(retreatAboveSky){
escapeProp = new AccelleratedByPropulsion();
escapeProp.setThrustVector(new Vector3D(0,.1,0)).setEnable(false);
addBehavior(escapeProp);}
final AutoFiring afb = new AutoFiring();
afb.setMaxFireVectorDeviation(.3);
afb.setFiringPattern(new boolean [] {true,false,false,false,true,true,false});
afb.setTimePerPatternEntry((int)(400+Math.random()*300));
afb.setPatternOffsetMillis((int)(Math.random()*1000));
afb.setProjectileFiringBehavior(pfb);
addBehavior(afb);
//final EnsureUpright eu = new EnsureUpright();
//addBehavior(eu);
final SpinAccellerationBehavior sab = (SpinAccellerationBehavior)new SpinAccellerationBehavior().setEnable(false);
addBehavior(sab);
addBehavior(new SmartPlaneBehavior(haapb,afb,sab,aatpb,escapeProp,retreatAboveSky));
}
/**
* @return the boundingRadius
*/
public double getBoundingRadius() {
return boundingRadius;
}
public void setRuinObject(DEFObject ruin) {
ruinObject=ruin;
}
/**
* @return the logic
*/
public EnemyLogic getLogic() {
return logic;
}
/**
* @return the mobile
*/
public boolean isMobile() {
return mobile;
}
/**
* @return the canTurn
*/
public boolean isCanTurn() {
return canTurn;
}
/**
* @return the foliage
*/
public boolean isFoliage() {
return foliage;
}
/**
* @return the boss
*/
public boolean isBoss() {
return boss;
}
/**
* @return the groundLocked
*/
public boolean isGroundLocked() {
return groundLocked;
}
}//end DEFObject
|
package org.jtrfp.trcl.obj;
import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;
import org.jtrfp.trcl.Model;
import org.jtrfp.trcl.beh.AdjustAltitudeToPlayerBehavior;
import org.jtrfp.trcl.beh.AutoFiring;
import org.jtrfp.trcl.beh.AutoLeveling;
import org.jtrfp.trcl.beh.Bobbing;
import org.jtrfp.trcl.beh.CollidesWithTerrain;
import org.jtrfp.trcl.beh.DamageableBehavior;
import org.jtrfp.trcl.beh.DamagedByCollisionWithGameplayObject;
import org.jtrfp.trcl.beh.DeathBehavior;
import org.jtrfp.trcl.beh.DebrisOnDeathBehavior;
import org.jtrfp.trcl.beh.ExplodesOnDeath;
import org.jtrfp.trcl.beh.HorizAimAtPlayerBehavior;
import org.jtrfp.trcl.beh.LeavesPowerupOnDeathBehavior;
import org.jtrfp.trcl.beh.LoopingPositionBehavior;
import org.jtrfp.trcl.beh.ProjectileFiringBehavior;
import org.jtrfp.trcl.beh.ResetsRandomlyAfterDeath;
import org.jtrfp.trcl.beh.SmartPlaneBehavior;
import org.jtrfp.trcl.beh.SpinAccellerationBehavior;
import org.jtrfp.trcl.beh.SteadilyRotating;
import org.jtrfp.trcl.beh.TerrainLocked;
import org.jtrfp.trcl.beh.phy.AccelleratedByPropulsion;
import org.jtrfp.trcl.beh.phy.BouncesOffSurfaces;
import org.jtrfp.trcl.beh.phy.HasPropulsion;
import org.jtrfp.trcl.beh.phy.MovesByVelocity;
import org.jtrfp.trcl.beh.phy.PulledDownByGravityBehavior;
import org.jtrfp.trcl.beh.phy.RotationalDragBehavior;
import org.jtrfp.trcl.beh.phy.RotationalMomentumBehavior;
import org.jtrfp.trcl.beh.phy.VelocityDragBehavior;
import org.jtrfp.trcl.core.TR;
import org.jtrfp.trcl.file.DEFFile.EnemyDefinition;
import org.jtrfp.trcl.file.DEFFile.EnemyDefinition.EnemyLogic;
import org.jtrfp.trcl.file.DEFFile.EnemyPlacement;
import org.jtrfp.trcl.obj.Explosion.ExplosionType;
public class DEFObject extends WorldObject {
private final double boundingRadius;
private WorldObject ruinObject;
private final EnemyLogic logic;
private boolean mobile,canTurn,foliage,boss,groundLocked;
public DEFObject(TR tr,Model model, EnemyDefinition def, EnemyPlacement pl){
super(tr,model);
boundingRadius = TR.legacy2Modern(def.getBoundingBoxRadius())/1.5;
logic = def.getLogic();
mobile=true;
canTurn=true;
foliage=false;
boss=def.isObjectIsBoss();
groundLocked=false;
switch(logic){
case groundDumb:
mobile=false;
canTurn=false;
break;
case groundTargeting://Ground turrets
mobile=false;
canTurn=true;
addBehavior(new HorizAimAtPlayerBehavior(tr.getPlayer()));
//TODO: def.getFiringVertices() needs actual vertex lookup.
addBehavior(new ProjectileFiringBehavior().setFiringPositions(new Vector3D[]{
new Vector3D(0,0,0)
}));
break;
case flyingDumb:
canTurn=false;
break;
case groundTargetingDumb:
groundLocked=true;
break;
case flyingSmart:
smartPlaneBehavior(tr,def);
break;
case bankSpinDrill:
unhandled(def);
break;
case sphereBoss:
unhandled(def);
mobile=true;
break;
case flyingAttackRetreatSmart:
smartPlaneBehavior(tr,def);
//addBehavior(new HorizAimAtPlayerBehavior(tr.getPlayer()));
break;
case splitShipSmart://TODO
smartPlaneBehavior(tr,def);
//addBehavior(new HorizAimAtPlayerBehavior(tr.getPlayer()));
break;
case groundStaticRuin://Destroyed object is replaced with another using SimpleModel i.e. weapons bunker
mobile=false;
canTurn=false;
break;
case targetHeadingSmart:
mobile=false;//Belazure's crane bots
addBehavior(new HorizAimAtPlayerBehavior(tr.getPlayer()));
break;
case targetPitchSmart:
unhandled(def);
break;
case coreBossSmart:
mobile=false;
break;
case cityBossSmart:
mobile=false;
break;
case staticFiringSmart:
addBehavior(new HorizAimAtPlayerBehavior(tr.getPlayer()));
mobile=false;
break;
case sittingDuck:
canTurn=false;
mobile=false;
break;
case tunnelAttack://TODO
mobile=false;
break;
case takeoffAndEscape://TODO
canTurn=false;
break;
case fallingAsteroid:
fallingObjectBehavior();
addBehavior(new RotationalMomentumBehavior()
.accellerateEquatorialMomentum(1)
.accellerateLateralMomentum(1)
.accelleratePolarMomentum(1));
{ final DEFObject thisObject = this;
final Vector3D centerPos = new Vector3D(this.getPosition());
final TR thisTr = tr;
addBehavior(new ResetsRandomlyAfterDeath()
.setMinWaitMillis(100)
.setMaxWaitMillis(1000)
.setRunOnReset(new Runnable(){
@Override
public void run(){
final double [] pos = thisObject.getPosition();
pos[0]=centerPos.getX()+Math.random()*TR.mapSquareSize*10;
pos[1]=thisTr.getWorld().sizeY/1.5;
pos[2]=centerPos.getZ()+Math.random()*TR.mapSquareSize*10;
thisObject.notifyPositionChange();
}//end run()
}));}
break;
case cNome://Walky bot?
groundLocked=true;
break;
case cNomeLegs://Walky bot?
groundLocked=true;
break;
case cNomeFactory:
mobile=false;
break;
case geigerBoss:
addBehavior(new HorizAimAtPlayerBehavior(tr.getPlayer()));
mobile=false;
break;
case volcanoBoss:
addBehavior(new HorizAimAtPlayerBehavior(tr.getPlayer()));
mobile=false;
break;
case volcano://Wat.
unhandled(def);
canTurn=false;
mobile=false;
break;
case missile://Silo?
mobile=false;//TODO
break;
case bob:
addBehavior(new Bobbing());
addBehavior(new SteadilyRotating());
mobile=false;
canTurn=false;//ironic?
break;
case alienBoss:
break;
case canyonBoss1:
mobile=false;
break;
case canyonBoss2:
mobile=false;
break;
case lavaMan://Also terraform-o-bot
mobile=false;
break;
case arcticBoss:
mobile=false;
break;
case helicopter://TODO
break;
case tree:
canTurn=false;
mobile=false;
foliage=true;
break;
case ceilingStatic:
canTurn=false;
mobile=false;
break;
case bobAndAttack:{
addBehavior(new SteadilyRotating().setRotationPhase(2*Math.PI*Math.random()));
final ProjectileFiringBehavior pfb = new ProjectileFiringBehavior();
pfb.addSupply(99999999);
pfb.setProjectileFactory(tr.getResourceManager().getProjectileFactories()[def.getWeapon().ordinal()]);
addBehavior(pfb);//Bob and attack don't have the advantage of movement, so give them the advantage of range.
addBehavior(new AutoFiring().
setProjectileFiringBehavior(pfb).
setPatternOffsetMillis((int)(Math.random()*2000)).
setMaxFiringDistance(TR.mapSquareSize*17).
setSmartFiring(true));
addBehavior(new Bobbing().
setPhase(Math.random()).
setBobPeriodMillis(10*1000+Math.random()*3000));
mobile=false;
canTurn=false;
break;}
case forwardDrive:
canTurn=false;
groundLocked=true;
break;
case fallingStalag:
fallingObjectBehavior();
{final DEFObject thisObject = this;
final Vector3D centerPos = new Vector3D(this.getPosition());
final TR thisTr = tr;
addBehavior(new ResetsRandomlyAfterDeath()
.setMinWaitMillis(100)
.setMaxWaitMillis(1000)
.setRunOnReset(new Runnable(){
@Override
public void run(){
final double [] pos = thisObject.getPosition();
pos[0]=centerPos.getX()+Math.random()*TR.mapSquareSize*10;
pos[1]=thisTr.getWorld().sizeY/1.5;
pos[2]=centerPos.getZ()+Math.random()*TR.mapSquareSize*10;
thisObject.notifyPositionChange();
}//end run()
}));}
canTurn=false;
mobile=false;
break;
case attackRetreatBelowSky:
smartPlaneBehavior(tr,def);
break;
case attackRetreatAboveSky:
smartPlaneBehavior(tr,def);
break;
case bobAboveSky:
mobile=false;
break;
case factory:
canTurn=false;
mobile=false;
break;
}//end switch(logic)
addBehavior(new DeathBehavior());
addBehavior(new DamageableBehavior().setHealth(pl.getStrength()).setMaxHealth(pl.getStrength()).setEnable(!boss));
setActive(!boss);
addBehavior(new DamagedByCollisionWithGameplayObject());
if(!foliage)addBehavior(new DebrisOnDeathBehavior());
if(canTurn||boss){
addBehavior(new RotationalMomentumBehavior());
addBehavior(new RotationalDragBehavior()).setDragCoefficient(.86);
addBehavior(new AutoLeveling());
}
if(!mobile || groundLocked){
addBehavior(new ExplodesOnDeath(ExplosionType.BigExplosion));
}else{
addBehavior(new ExplodesOnDeath(ExplosionType.Blast));
}
if(mobile){
addBehavior(new MovesByVelocity());
addBehavior(new HasPropulsion());
addBehavior(new AccelleratedByPropulsion());
addBehavior(new VelocityDragBehavior());
if(groundLocked){
addBehavior(new TerrainLocked());}
else {addBehavior(new BouncesOffSurfaces());
addBehavior(new CollidesWithTerrain());
}
getBehavior().probeForBehavior(VelocityDragBehavior.class).setDragCoefficient(.86);
getBehavior().probeForBehavior(Propelled.class).setMinPropulsion(0);
getBehavior().probeForBehavior(Propelled.class).setPropulsion(def.getThrustSpeed());
addBehavior(new LoopingPositionBehavior());
}//end if(mobile)
if(boss){bossBehavior(tr,def);}
if(def.getPowerup()!=null && Math.random()*100. < def.getPowerupProbability()){addBehavior(new LeavesPowerupOnDeathBehavior(def.getPowerup()));}
}//end DEFObject
@Override
public void destroy(){
if(ruinObject!=null)ruinObject.setVisible(true);//TODO: Switch to setActive later.
super.destroy();
}
private void unhandled(EnemyDefinition def){
System.err.println("UNHANDLED DEF LOGIC: "+def.getLogic()+". MODEL="+def.getComplexModelFile()+" DESC="+def.getDescription());
}
private void bossBehavior(TR tr, EnemyDefinition def){//Don't include hitzones for aiming.
if(!def.getComplexModelFile().toUpperCase().contains("HITZO"))addBehavior(new HorizAimAtPlayerBehavior(tr.getPlayer()));
}
private void fallingObjectBehavior(){
canTurn=false;
addBehavior(new PulledDownByGravityBehavior());
addBehavior(new DamageableBehavior().setHealth(1));
addBehavior(new CollidesWithTerrain());
}
private void smartPlaneBehavior(TR tr, EnemyDefinition def){
final HorizAimAtPlayerBehavior haapb =new HorizAimAtPlayerBehavior(tr.getPlayer()).setLeftHanded(Math.random()>=.5);
addBehavior(haapb);
final AdjustAltitudeToPlayerBehavior aatpb = new AdjustAltitudeToPlayerBehavior(tr.getPlayer()).setAccelleration(1000);
addBehavior(aatpb);
final ProjectileFiringBehavior pfb = new ProjectileFiringBehavior().setProjectileFactory(tr.getResourceManager().getProjectileFactories()[def.getWeapon().ordinal()]);
pfb.addSupply(99999999);
addBehavior(pfb);
final AutoFiring afb = new AutoFiring();
afb.setFiringPattern(new boolean [] {true,false,false,false,true,true,false});
afb.setTimePerPatternEntry((int)(400+Math.random()*300));
afb.setPatternOffsetMillis((int)(Math.random()*1000));
afb.setProjectileFiringBehavior(pfb);
addBehavior(afb);
//final EnsureUpright eu = new EnsureUpright();
//addBehavior(eu);
final SpinAccellerationBehavior sab = (SpinAccellerationBehavior)new SpinAccellerationBehavior().setEnable(false);
addBehavior(sab);
addBehavior(new SmartPlaneBehavior(haapb,afb,sab,aatpb));
}
/**
* @return the boundingRadius
*/
public double getBoundingRadius() {
return boundingRadius;
}
public void setRuinObject(DEFObject ruin) {
ruinObject=ruin;
}
/**
* @return the logic
*/
public EnemyLogic getLogic() {
return logic;
}
/**
* @return the mobile
*/
public boolean isMobile() {
return mobile;
}
/**
* @return the canTurn
*/
public boolean isCanTurn() {
return canTurn;
}
/**
* @return the foliage
*/
public boolean isFoliage() {
return foliage;
}
/**
* @return the boss
*/
public boolean isBoss() {
return boss;
}
/**
* @return the groundLocked
*/
public boolean isGroundLocked() {
return groundLocked;
}
}//end DEFObject
|
package com.clevertap.apns;
import com.clevertap.apns.clients.AsyncOkHttpApnsClient;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
/**
* An entity containing the payload and the token.
*/
public class Notification {
private final String payload;
private final String token;
private final String topic;
private final String collapseId;
/**
* Constructs a new Notification with a payload and token.
*
* @param payload The JSON body (which is used for the request)
* @param token The device token
* @param topic The topic for this notification
* @param collapseId The collapse ID
*/
protected Notification(String payload, String token, String topic, String collapseId) {
this.payload = payload;
this.token = token;
this.topic = topic;
this.collapseId = collapseId;
}
/**
* Retrieves the topic.
*
* @return The topic
*/
public String getTopic() {
return topic;
}
/**
* Retrieves the collapseId.
*
* @return The collapseId
*/
public String getCollapseId() {
return collapseId;
}
/**
* Retrieves the payload.
*
* @return The payload
*/
public String getPayload() {
return payload;
}
/**
* Retrieves the token.
*
* @return The device token
*/
public String getToken() {
return token;
}
/**
* Builds a notification to be sent to APNS.
*/
public static class Builder {
private final ObjectMapper mapper = new ObjectMapper();
private final HashMap<String, Object> root, aps, alert;
private final String token;
private String topic = null;
private String collapseId = null;
private boolean contentAvailable = false;
/**
* Creates a new notification builder.
*
* @param token The device token
*/
public Builder(String token) {
this.token = token;
root = new HashMap<>();
aps = new HashMap<>();
alert = new HashMap<>();
}
public Builder mutableContent(boolean mutable) {
if (mutable) {
aps.put("mutable-content", 1);
} else {
aps.remove("mutable-content");
}
return this;
}
public Builder mutableContent() {
return this.mutableContent(true);
}
public Builder contentAvailable(boolean contentAvailable) {
if (contentAvailable) {
aps.put("content-available", 1);
} else {
aps.remove("content-available");
}
this.contentAvailable = contentAvailable;
return this;
}
public Builder contentAvailable() {
return this.contentAvailable(true);
}
public Builder alertBody(String body) {
alert.put("body", body);
return this;
}
public Builder alertTitle(String title) {
alert.put("title", title);
return this;
}
public Builder sound(String sound) {
if (sound != null) {
aps.put("sound", sound);
} else {
aps.remove("sound");
}
return this;
}
public Builder category(String category) {
if (category != null) {
aps.put("category", category);
} else {
aps.remove("category");
}
return this;
}
public Builder badge(int badge) {
aps.put("badge", badge);
return this;
}
public Builder customField(String key, Object value) {
root.put(key, value);
return this;
}
public Builder topic(String topic) {
this.topic = topic;
return this;
}
public Builder collapseId(String collapseId) {
this.collapseId = collapseId;
return this;
}
public int size() {
try {
return build().getPayload().getBytes("UTF-8").length;
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
/**
* Builds the notification.
* Also see {@link AsyncOkHttpApnsClient#push(Notification, NotificationResponseListener)}
*
* @return The notification
*/
public Notification build() {
root.put("aps", aps);
aps.put("alert", alert);
// Clean up the aps dictionary for content-available notifications
if (contentAvailable) {
aps.remove("alert");
aps.remove("sound");
aps.remove("badge");
}
final String payload;
try {
payload = mapper.writeValueAsString(root);
} catch (JsonProcessingException e) {
// Should not happen
throw new RuntimeException(e);
}
return new Notification(payload, token, topic, collapseId);
}
}
}
|
package org.lantern;
import java.io.File;
import java.util.Map;
import org.apache.commons.lang3.SystemUtils;
import org.lantern.event.Events;
import org.lantern.event.GoogleTalkStateEvent;
import org.lantern.event.ProxyConnectionEvent;
import org.lantern.event.QuitEvent;
import org.lantern.linux.AppIndicator;
import org.lantern.linux.Glib;
import org.lantern.linux.Gobject;
import org.lantern.linux.Gtk;
import org.lantern.state.Mode;
import org.lantern.state.Model;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.eventbus.Subscribe;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.sun.jna.Native;
import com.sun.jna.Pointer;
/**
* Class for handling all system tray interactions.
* specialization for using app indicators in ubuntu.
*/
@Singleton
public class AppIndicatorTray implements SystemTray {
private static final Logger LOG = LoggerFactory.getLogger(AppIndicatorTray.class);
private final static String LABEL_DISCONNECTED = "Lantern: Not connected";
private final static String LABEL_CONNECTING = "Lantern: Connecting...";
private final static String LABEL_CONNECTED = "Lantern: Connected";
private final static String LABEL_DISCONNECTING = "Lantern: Disconnecting...";
// could be changed to red/yellow/green
private final static String ICON_DISCONNECTED = "16off.png";
private final static String ICON_CONNECTING = "16off.png";
private final static String ICON_CONNECTED = "16on.png";
private final static String ICON_DISCONNECTING = "16off.png";
private static Glib libglib = null;
private static Gobject libgobject = null;
private static Gtk libgtk = null;
private static AppIndicator libappindicator = null;
static {
if (SystemUtils.IS_OS_LINUX) {
try {
libappindicator = (AppIndicator) Native.loadLibrary("appindicator", AppIndicator.class);
libgtk = (Gtk) Native.loadLibrary("gtk-x11-2.0", Gtk.class);
libgobject = (Gobject) Native.loadLibrary("gobject-2.0", Gobject.class);
libglib = (Glib) Native.loadLibrary("glib-2.0", Glib.class);
//libunique = (Unique) Native.loadLibrary("unique-3.0", Unique.class);
libgtk.gtk_init(0, null);
}
catch (final Throwable ex) {
LOG.warn("no supported version of appindicator libs found", ex);
}
}
}
@Override
public boolean isSupported() {
return (libglib != null && libgtk != null && libappindicator != null);
}
public interface FailureCallback {
public void createTrayFailed();
};
private AppIndicator.AppIndicatorInstanceStruct appIndicator;
private Pointer menu;
private Pointer connectionStatusItem;
private Pointer dashboardItem;
private Pointer updateItem;
private Pointer quitItem;
// need to hang on to these to prevent gc
private Gobject.GCallback connectionStatusItemCallback;
private Gobject.GCallback dashboardItemCallback;
private Gobject.GCallback updateItemCallback;
private Gobject.GCallback quitItemCallback;
private FailureCallback failureCallback;
private Map<String, Object> updateData;
private boolean active = false;
private final BrowserService browserService;
private final Model model;
@Inject
public AppIndicatorTray(final BrowserService jettyLauncher,
final Model model) {
this.browserService = jettyLauncher;
this.model = model;
}
@Override
public void start() {
createTray();
}
@Override
public void stop() {
}
@Override
public void createTray() {
// TODO share menu item strings with SystemTrayImpl.java
/*uniqueApp = libunique.unique_app_new("org.lantern.lantern", null);
if (libunique.unique_app_is_running(uniqueApp)) {
LOG.error("Already running!");
System.exit(0);
// could signal to open dashboard
}*/
menu = libgtk.gtk_menu_new();
connectionStatusItem = libgtk.gtk_menu_item_new_with_label(LABEL_DISCONNECTED);
libgtk.gtk_widget_set_sensitive(connectionStatusItem, Gtk.FALSE);
libgtk.gtk_menu_shell_append(menu, connectionStatusItem);
libgtk.gtk_widget_show_all(connectionStatusItem);
dashboardItem = libgtk.gtk_menu_item_new_with_label("Show Lantern"); // XXX i18n
dashboardItemCallback = new Gobject.GCallback() {
@Override
public void callback(Pointer instance, Pointer data) {
LOG.debug("openDashboardItem callback called");
openDashboard();
}
};
libgobject.g_signal_connect_data(dashboardItem, "activate", dashboardItemCallback,null, null, 0);
libgtk.gtk_menu_shell_append(menu, dashboardItem);
libgtk.gtk_widget_show_all(dashboardItem);
//updateItem = Gtk.gtk_menu_item_new_with_label();
quitItem = libgtk.gtk_menu_item_new_with_label("Quit Lantern"); // XXX i18n
quitItemCallback = new Gobject.GCallback() {
@Override
public void callback(Pointer instance, Pointer data) {
LOG.debug("quitItemCallback called");
quit();
}
};
libgobject.g_signal_connect_data(quitItem, "activate", quitItemCallback,null, null, 0);
libgtk.gtk_menu_shell_append(menu, quitItem);
libgtk.gtk_widget_show_all(quitItem);
appIndicator = libappindicator.app_indicator_new(
"lantern", "indicator-messages-new",
AppIndicator.CATEGORY_APPLICATION_STATUS);
/* XXX basically a hack -- we should subclass the AppIndicator
type and override the fallback entry in the 'vtable', instead we just
hack the app indicator class itself. Not an issue unless we need other
appindicators.
*/
AppIndicator.AppIndicatorClassStruct aiclass =
new AppIndicator.AppIndicatorClassStruct(appIndicator.parent.g_type_instance.g_class);
AppIndicator.Fallback replacementFallback = new AppIndicator.Fallback() {
@Override
public Pointer callback(
final AppIndicator.AppIndicatorInstanceStruct self) {
fallback();
return null;
}
};
aiclass.fallback = replacementFallback;
aiclass.write();
libappindicator.app_indicator_set_menu(appIndicator, menu);
changeIcon(ICON_DISCONNECTED, LABEL_DISCONNECTED);
libappindicator.app_indicator_set_status(appIndicator, AppIndicator.STATUS_ACTIVE);
Events.register(this);
new Thread() {
public void run() {
try {
libgtk.gtk_main();
} catch (Throwable t) {
LOG.warn("Unable to run main loop", t);
}
}
}.start();
this.active = true;
}
private String iconPath(final String fileName) {
final File iconTest = new File(ICON_DISCONNECTED);
if (iconTest.isFile()) {
return new File(new File("."), fileName).getAbsolutePath();
}
// Running from main line.
return new File(new File("install/common"), fileName).getAbsolutePath();
}
protected void fallback() {
LOG.warn("Failed to create appindicator system tray.");
if (this.failureCallback != null) {
this.failureCallback.createTrayFailed();
}
}
private void openDashboard() {
LOG.debug("openDashboard called.");
this.browserService.reopenBrowser();
}
private void quit() {
LOG.debug("quit called.");
Events.eventBus().post(new QuitEvent());
//LanternHub.display().dispose();
//this.xmppHandler.disconnect();
System.exit(0);
}
@Override
public void addUpdate(final Map<String, Object> data) {
LOG.info("Adding update data: {}", data);
if (this.updateData != null && this.updateData.equals(data)) {
LOG.info("Ignoring duplicate update data");
return;
}
this.updateData = data;
final String label = Tr.tr("Update to Lantern ") +
data.get(LanternConstants.UPDATE_KEY);
updateItem = libgtk.gtk_menu_item_new_with_label(label);
updateItemCallback = new Gobject.GCallback() {
@Override
public void callback(Pointer instance, Pointer pointer) {
LOG.debug("updateItemCallback called");
NativeUtils.openUri(
(String)data.get("installerUrl"));
}
};
libgobject.g_signal_connect_data(updateItem, "activate", updateItemCallback,null, null, 0);
libgtk.gtk_menu_shell_append(menu, updateItem);
libgtk.gtk_widget_show_all(updateItem);
}
@Override
public boolean isActive() {
return isSupported() && this.active;
}
@Subscribe
public void onConnectivityStateChanged(final ProxyConnectionEvent csce) {
final ConnectivityStatus cs = csce.getConnectivityStatus();
LOG.debug("Got connectivity state changed {}", cs);
onConnectivityStatus(cs);
}
@Subscribe
public void onGoogleTalkState(final GoogleTalkStateEvent event) {
if (model.getSettings().getMode() == Mode.get) {
LOG.debug("Not linking Google Talk state to connectivity " +
"state in get mode");
return;
}
final GoogleTalkState state = event.getState();
final ConnectivityStatus cs;
switch (state) {
case connected:
cs = ConnectivityStatus.CONNECTED;
break;
case notConnected:
cs = ConnectivityStatus.DISCONNECTED;
break;
case LOGIN_FAILED:
cs = ConnectivityStatus.DISCONNECTED;
break;
case connecting:
cs = ConnectivityStatus.CONNECTING;
break;
default:
LOG.error("Should never get here...");
cs = ConnectivityStatus.DISCONNECTED;
break;
}
onConnectivityStatus(cs);
}
private void onConnectivityStatus(final ConnectivityStatus cs) {
switch (cs) {
case DISCONNECTED: {
changeIcon(ICON_DISCONNECTED, LABEL_DISCONNECTED);
break;
}
case CONNECTING: {
changeIcon(ICON_CONNECTING, LABEL_CONNECTING);
break;
}
case CONNECTED: {
changeIcon(ICON_CONNECTED, LABEL_CONNECTED);
break;
}
}
}
private void changeIcon(final String fileName, final String label) {
libappindicator.app_indicator_set_icon_full(appIndicator, iconPath(fileName), "Lantern");
libgtk.gtk_menu_item_set_label(connectionStatusItem, label);
}
public void setFailureCallback(FailureCallback failureCallback) {
this.failureCallback = failureCallback;
}
};
|
package com.couchbase.cblite;
import android.content.Context;
import android.util.Log;
import com.couchbase.cblite.auth.CBLAuthorizer;
import com.couchbase.cblite.auth.CBLFacebookAuthorizer;
import com.couchbase.cblite.auth.CBLPersonaAuthorizer;
import com.couchbase.cblite.internal.InterfaceAudience;
import com.couchbase.cblite.replicator.CBLPuller;
import com.couchbase.cblite.replicator.CBLPusher;
import com.couchbase.cblite.replicator.CBLReplicator;
import com.couchbase.cblite.support.FileDirUtils;
import com.couchbase.cblite.support.HttpClientFactory;
import org.codehaus.jackson.map.ObjectMapper;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Top-level CouchbaseLite object; manages a collection of databases as a CouchDB server does.
*/
public class CBLManager {
private static final ObjectMapper mapper = new ObjectMapper();
public static final String DATABASE_SUFFIX_OLD = ".touchdb";
public static final String DATABASE_SUFFIX = ".cblite";
public static final CBLManagerOptions DEFAULT_OPTIONS = new CBLManagerOptions(false, false);
private static CBLManager sharedInstance;
public static final String LEGAL_CHARACTERS = "[^a-z]{1,}[^a-z0-9_$()/+-]*$";
private CBLManagerOptions options;
private File directoryFile;
private Map<String, CBLDatabase> databases;
private List<CBLReplicator> replications;
private ScheduledExecutorService workExecutor;
private HttpClientFactory defaultHttpClientFactory;
public static ObjectMapper getObjectMapper() {
return mapper;
}
public CBLManager(Context androidContext, String directoryName) {
this(androidContext, directoryName, DEFAULT_OPTIONS);
}
public CBLManager(Context androidContext, String directoryName, CBLManagerOptions options) {
this.directoryFile = new File(androidContext.getFilesDir(), directoryName);
this.options = (options != null) ? options : DEFAULT_OPTIONS;
this.databases = new HashMap<String, CBLDatabase>();
this.replications = new ArrayList<CBLReplicator>();
//create the directory, but don't fail if it already exists
if(!directoryFile.exists()) {
boolean result = directoryFile.mkdir();
if(!result) {
throw new RuntimeException("Unable to create directory " + directoryFile);
}
}
upgradeOldDatabaseFiles(directoryFile);
workExecutor = Executors.newSingleThreadScheduledExecutor();
// TODO: in the iOS code it starts persistent replications here (using runloop trick)
}
public synchronized static CBLManager createSharedInstance(Context androidContext, String directoryName, CBLManagerOptions options) {
if (sharedInstance == null) {
sharedInstance = new CBLManager(androidContext, directoryName, options);
}
return sharedInstance;
}
public synchronized static CBLManager createSharedInstance(Context androidContext, String directoryName) {
return createSharedInstance(androidContext, directoryName, DEFAULT_OPTIONS);
}
public static CBLManager getSharedInstance() {
return sharedInstance;
}
/**
* Returns YES if the given name is a valid database name.
* (Only the characters in "abcdefghijklmnopqrstuvwxyz0123456789_$()+-/" are allowed.)
*/
public static boolean isValidDatabaseName(String databaseName) {
if (databaseName.length() > 0 && databaseName.length() < 240 &&
containsOnlyLegalCharacters(databaseName) &&
Character.isLowerCase(databaseName.charAt(0))) {
return true;
}
return databaseName.equals(CBLReplicator.REPLICATOR_DATABASE_NAME);
}
private static boolean containsOnlyLegalCharacters(String databaseName) {
Pattern p = Pattern.compile("^[abcdefghijklmnopqrstuvwxyz0123456789_$()+-/]+$");
Matcher matcher = p.matcher(databaseName);
return matcher.matches();
}
private void upgradeOldDatabaseFiles(File directory) {
File[] files = directory.listFiles(new FilenameFilter() {
@Override
public boolean accept(File file, String name) {
return name.endsWith(DATABASE_SUFFIX_OLD);
}
});
for (File file : files) {
String oldFilename = file.getName();
String newFilename = filenameWithNewExtension(oldFilename, DATABASE_SUFFIX_OLD, DATABASE_SUFFIX);
File newFile = new File(directory, newFilename);
if (newFile.exists()) {
String msg = String.format("Cannot rename %s to %s, %s already exists", oldFilename, newFilename, newFilename);
Log.w(CBLDatabase.TAG, msg);
continue;
}
boolean ok = file.renameTo(newFile);
if (!ok) {
String msg = String.format("Unable to rename %s to %s", oldFilename, newFilename);
throw new IllegalStateException(msg);
}
}
}
private String filenameWithNewExtension(String oldFilename, String oldExtension, String newExtension) {
String oldExtensionRegex = String.format("%s$",oldExtension);
return oldFilename.replaceAll(oldExtensionRegex, newExtension);
}
/**
* Releases all resources used by the CBLManager instance and closes all its databases.
*/
public void close() {
// TODO: review this code, especially call to server.close()
Log.i(CBLDatabase.TAG, "Closing " + this);
for (CBLDatabase database : databases.values()) {
List<CBLReplicator> replicators = database.getAllReplications();
if (replicators != null) {
for (CBLReplicator replicator : replicators) {
replicator.stop();
}
}
database.close();
}
databases.clear();
Log.i(CBLDatabase.TAG, "Closed " + this);
}
/**
* The root directory of this manager (as specified at initialization time.)
*/
public String getDirectory() {
return directoryFile.getAbsolutePath();
}
/**
* Returns the database with the given name, or creates it if it doesn't exist.
* Multiple calls with the same name will return the same CBLDatabase instance.
*/
public CBLDatabase getDatabase(String name) {
CBLDatabase db = databases.get(name);
if(db == null) {
if (!isValidDatabaseName(name)) {
throw new IllegalArgumentException("Invalid database name: " + name);
}
String path = pathForName(name);
if(path == null) {
return null;
}
db = new CBLDatabase(path, this);
db.setName(name);
databases.put(name, db);
}
return db;
}
/**
* Returns the database with the given name, or null if it doesn't exist.
* Multiple calls with the same name will return the same CBLDatabase instance.
*/
public CBLDatabase getExistingDatabase(String name) {
return databases.get(name);
}
/**
* An array of the names of all existing databases.
*/
public List<String> getAllDatabaseNames() {
String[] databaseFiles = directoryFile.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String filename) {
if(filename.endsWith(CBLManager.DATABASE_SUFFIX)) {
return true;
}
return false;
}
});
List<String> result = new ArrayList<String>();
for (String databaseFile : databaseFiles) {
String trimmed = databaseFile.substring(0, databaseFile.length() - CBLManager.DATABASE_SUFFIX.length());
String replaced = trimmed.replace(':', '/');
result.add(replaced);
}
Collections.sort(result);
return Collections.unmodifiableList(result);
}
public Collection<CBLDatabase> allOpenDatabases() {
return databases.values();
}
/**
* Replaces or installs a database from a file.
*
* This is primarily used to install a canned database on first launch of an app, in which case
* you should first check .exists to avoid replacing the database if it exists already. The
* canned database would have been copied into your app bundle at build time.
*
* @param databaseName The name of the database to replace.
* @param databasePath Path of the database file that should replace it.
* @param attachmentsPath Path of the associated attachments directory, or nil if there are no attachments.
**/
public void replaceDatabase(String databaseName, String databasePath, String attachmentsPath) throws IOException {
CBLDatabase database = getDatabase(databaseName);
String dstAttachmentsPath = database.getAttachmentStorePath();
File sourceFile = new File(databasePath);
File destFile = new File(database.getPath());
FileDirUtils.copyFile(sourceFile, destFile);
File attachmentsFile = new File(dstAttachmentsPath);
FileDirUtils.deleteRecursive(attachmentsFile);
attachmentsFile.mkdirs();
if(attachmentsPath != null) {
FileDirUtils.copyFolder(new File(attachmentsPath), attachmentsFile);
}
database.replaceUUIDs();
}
/**
* Asynchronously dispatches a callback to run on a background thread. The callback will be passed
* CBLDatabase instance. There is not currently a known reason to use it, it may not make
* sense on the Android API, but it was added for the purpose of having a consistent API with iOS.
*/
public void runAsync(String databaseName, final CBLDatabaseAsyncFunction function) {
final CBLDatabase database = getDatabase(databaseName);
Thread t = new Thread(new Runnable() {
@Override
public void run() {
function.performFunction(database);
}
});
t.start();
}
private String pathForName(String name) {
if((name == null) || (name.length() == 0) || Pattern.matches(LEGAL_CHARACTERS, name)) {
return null;
}
name = name.replace('/', ':');
String result = directoryFile.getPath() + File.separator + name + CBLManager.DATABASE_SUFFIX;
return result;
}
private Map<String, Object> parseSourceOrTarget(Map<String,Object> properties, String key) {
Map<String, Object> result = new HashMap<String, Object>();
Object value = properties.get(key);
if (value instanceof String) {
result.put("url", (String)value);
}
else if (value instanceof Map) {
result = (Map<String, Object>) value;
}
return result;
}
@InterfaceAudience.Private
CBLReplicator replicationWithDatabase(CBLDatabase db, URL remote, boolean push, boolean create, boolean start) {
for (CBLReplicator replicator : replications) {
if (replicator.getDb() == db && replicator.getRemote().equals(remote) && replicator.isPush() == push) {
return replicator;
}
}
if (!create) {
return null;
}
CBLReplicator replicator = null;
if (push) {
replicator = new CBLPusher(db, remote, true, getWorkExecutor());
}
else {
replicator = new CBLPuller(db, remote, true, getWorkExecutor());
}
replications.add(replicator);
if (start) {
replicator.start();
}
return replicator;
}
@InterfaceAudience.Private
public CBLReplicator getReplicator(Map<String,Object> properties) throws CBLiteException {
CBLAuthorizer authorizer = null;
CBLReplicator repl = null;
URL remote = null;
Map<String, Object> remoteMap;
Map<String, Object> sourceMap = parseSourceOrTarget(properties, "source");
Map<String, Object> targetMap = parseSourceOrTarget(properties, "target");
String source = (String)sourceMap.get("url");
String target = (String)targetMap.get("url");
Boolean createTargetBoolean = (Boolean)properties.get("create_target");
boolean createTarget = (createTargetBoolean != null && createTargetBoolean.booleanValue());
Boolean continuousBoolean = (Boolean)properties.get("continuous");
boolean continuous = (continuousBoolean != null && continuousBoolean.booleanValue());
Boolean cancelBoolean = (Boolean)properties.get("cancel");
boolean cancel = (cancelBoolean != null && cancelBoolean.booleanValue());
// Map the 'source' and 'target' JSON params to a local database and remote URL:
if(source == null || target == null) {
throw new CBLiteException("source and target are both null", new CBLStatus(CBLStatus.BAD_REQUEST));
}
boolean push = false;
CBLDatabase db = getExistingDatabase(source);
String remoteStr = null;
if(db != null) {
remoteStr = target;
push = true;
remoteMap = targetMap;
} else {
remoteStr = source;
if(createTarget && !cancel) {
db = getDatabase(target);
if(!db.open()) {
throw new CBLiteException("cannot open database: " + db, new CBLStatus(CBLStatus.INTERNAL_SERVER_ERROR));
}
} else {
db = getExistingDatabase(target);
}
if(db == null) {
throw new CBLiteException("database is null", new CBLStatus(CBLStatus.NOT_FOUND));
}
remoteMap = sourceMap;
}
Map<String, Object> authMap = (Map<String, Object>) remoteMap.get("auth");
if (authMap != null) {
Map<String, Object> persona = (Map<String, Object>) authMap.get("persona");
if (persona != null) {
String email = (String) persona.get("email");
authorizer = new CBLPersonaAuthorizer(email);
}
Map<String, Object> facebook = (Map<String, Object>) authMap.get("facebook");
if (facebook != null) {
String email = (String) facebook.get("email");
authorizer = new CBLFacebookAuthorizer(email);
}
}
try {
remote = new URL(remoteStr);
} catch (MalformedURLException e) {
throw new CBLiteException("malformed remote url: " + remoteStr, new CBLStatus(CBLStatus.BAD_REQUEST));
}
if(remote == null || !remote.getProtocol().startsWith("http")) {
throw new CBLiteException("remote URL is null or non-http: " + remoteStr, new CBLStatus(CBLStatus.BAD_REQUEST));
}
if(!cancel) {
repl = db.getReplicator(remote, getDefaultHttpClientFactory(), push, continuous, getWorkExecutor());
if(repl == null) {
throw new CBLiteException("unable to create replicator with remote: " + remote, new CBLStatus(CBLStatus.INTERNAL_SERVER_ERROR));
}
if (authorizer != null) {
repl.setAuthorizer(authorizer);
}
String filterName = (String)properties.get("filter");
if(filterName != null) {
repl.setFilterName(filterName);
Map<String,Object> filterParams = (Map<String,Object>)properties.get("query_params");
if(filterParams != null) {
repl.setFilterParams(filterParams);
}
}
if(push) {
((CBLPusher)repl).setCreateTarget(createTarget);
}
} else {
// Cancel replication:
repl = db.getActiveReplicator(remote, push);
if(repl == null) {
throw new CBLiteException("unable to lookup replicator with remote: " + remote, new CBLStatus(CBLStatus.NOT_FOUND));
}
}
return repl;
}
public ScheduledExecutorService getWorkExecutor() {
return workExecutor;
}
public HttpClientFactory getDefaultHttpClientFactory() {
return defaultHttpClientFactory;
}
public void setDefaultHttpClientFactory(
HttpClientFactory defaultHttpClientFactory) {
this.defaultHttpClientFactory = defaultHttpClientFactory;
}
}
|
package org.lightmare.cache;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Stack;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.ejb.TransactionAttributeType;
import javax.ejb.TransactionManagementType;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceUnit;
import org.lightmare.ejb.handlers.BeanHandler;
import org.lightmare.utils.CollectionUtils;
/**
* Container class to save bean {@link Field} with annotation
* {@link PersistenceContext} and bean class
*
* @author Levan Tsinadze
* @since 0.0.45-SNAPSHOT
* @see org.lightmare.deploy.BeanLoader#loadBean(org.lightmare.deploy.BeanLoader.BeanParameters)
* @see org.lightmare.ejb.EjbConnector#connectToBean(MetaData)
* @see org.lightmare.ejb.EjbConnector#createRestHandler(MetaData)
* @see org.lightmare.ejb.handlers.BeanHandler
*/
public class MetaData {
// EJB bean class
private Class<?> beanClass;
// EJB bean implementation interfaces
private Class<?>[] interfaceClasses;
// All EJB local interfaces
private Class<?>[] localInterfaces;
// All EJB remote interfaces
private Class<?>[] remoteInterfaces;
// EJB bean's Field to set JTA UserTransaction instance
private Field transactionField;
// All connections for appropriated EJB bean
private Collection<ConnectionData> connections;
// Appropriated ClassLoader with loaded EJB bean class
private ClassLoader loader;
// Check if appropriated EJB bean is in deployment progress
private AtomicBoolean inProgress = new AtomicBoolean();
// Check if appropriated EJB bean has bean managed or container managed
// transactions
private boolean transactional;
// Transaction attribute type annotation or default value for appropriated
// EJB bean
private TransactionAttributeType transactionAttrType;
//TransactionManagementType annotation or defaulr value for appropriated EJB bean
private TransactionManagementType transactionManType;
private List<InjectionData> injects;
private Collection<Field> unitFields;
private Queue<InterceptorData> interceptors;
private BeanHandler handler;
public Class<?> getBeanClass() {
return beanClass;
}
public void setBeanClass(Class<?> beanClass) {
this.beanClass = beanClass;
}
public Class<?>[] getInterfaceClasses() {
return interfaceClasses;
}
public void setInterfaceClasses(Class<?>[] interfaceClasses) {
this.interfaceClasses = interfaceClasses;
}
public Class<?>[] getLocalInterfaces() {
return localInterfaces;
}
public void setLocalInterfaces(Class<?>[] localInterfaces) {
this.localInterfaces = localInterfaces;
}
public Class<?>[] getRemoteInterfaces() {
return remoteInterfaces;
}
public void setRemoteInterfaces(Class<?>[] remoteInterfaces) {
this.remoteInterfaces = remoteInterfaces;
}
public Field getTransactionField() {
return transactionField;
}
public void setTransactionField(Field transactionField) {
this.transactionField = transactionField;
}
public Collection<ConnectionData> getConnections() {
return connections;
}
public void setConnections(Collection<ConnectionData> connections) {
this.connections = connections;
}
/**
* Caches passed connection information
*
* @param connection
*/
public void addConnection(ConnectionData connection) {
if (connections == null) {
connections = new ArrayList<ConnectionData>();
}
connections.add(connection);
}
/**
* Caches {@link javax.persistence.PersistenceUnit} annotated field and unit
* name to cache
*
* @param unitName
* @param unitField
*/
private void addUnitField(String unitName, Field unitField) {
for (ConnectionData connection : connections) {
if (unitName.equals(connection.getUnitName())) {
connection.setUnitField(unitField);
}
}
}
/**
* Adds {@link javax.ejb.PersistenceUnit} annotated field to
* {@link MetaData} for cache
*
* @param unitFields
*/
public void addUnitFields(Collection<Field> unitFields) {
if (CollectionUtils.validAll(connections, unitFields)) {
String unitName;
for (Field unitField : unitFields) {
unitName = unitField.getAnnotation(PersistenceUnit.class)
.unitName();
addUnitField(unitName, unitField);
}
this.unitFields = unitFields;
}
}
public ClassLoader getLoader() {
return loader;
}
public void setLoader(ClassLoader loader) {
this.loader = loader;
}
public boolean isInProgress() {
return inProgress.get();
}
public void setInProgress(boolean inProgress) {
this.inProgress.getAndSet(inProgress);
}
public boolean isTransactional() {
return transactional;
}
public void setTransactional(boolean transactional) {
this.transactional = transactional;
}
public TransactionAttributeType getTransactionAttrType() {
return transactionAttrType;
}
public void setTransactionAttrType(
TransactionAttributeType transactionAttrType) {
this.transactionAttrType = transactionAttrType;
}
public TransactionManagementType getTransactionManType() {
return transactionManType;
}
public void setTransactionManType(
TransactionManagementType transactionManType) {
this.transactionManType = transactionManType;
}
public List<InjectionData> getInjects() {
return injects;
}
/**
* Adds passed {@link InjectionData} to cache
*
* @param inject
*/
public void addInject(InjectionData inject) {
if (injects == null) {
injects = new ArrayList<InjectionData>();
}
injects.add(inject);
}
public Collection<Field> getUnitFields() {
return this.unitFields;
}
/**
* Offers {@link InterceptorData} to {@link Stack} to process request by
* order
*
* @param interceptor
*/
public void addInterceptor(InterceptorData interceptor) {
if (interceptors == null) {
interceptors = new LinkedList<InterceptorData>();
}
interceptors.offer(interceptor);
}
public Collection<InterceptorData> getInterceptors() {
return interceptors;
}
public BeanHandler getHandler() {
return handler;
}
public void setHandler(BeanHandler handler) {
this.handler = handler;
}
}
|
package org.myrobotlab.service;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.PullCommand;
import org.eclipse.jgit.api.errors.CanceledException;
import org.eclipse.jgit.api.errors.DetachedHeadException;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.api.errors.InvalidConfigurationException;
import org.eclipse.jgit.api.errors.InvalidRemoteException;
import org.eclipse.jgit.api.errors.NoHeadException;
import org.eclipse.jgit.api.errors.RefNotFoundException;
import org.eclipse.jgit.api.errors.TransportException;
import org.eclipse.jgit.api.errors.WrongRepositoryStateException;
import org.eclipse.jgit.errors.AmbiguousObjectException;
import org.eclipse.jgit.errors.IncorrectObjectTypeException;
import org.eclipse.jgit.errors.MissingObjectException;
import org.eclipse.jgit.errors.RevisionSyntaxException;
import org.eclipse.jgit.lib.BranchTrackingStatus;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.lib.TextProgressMonitor;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.storage.file.FileRepositoryBuilder;
import org.myrobotlab.codec.CodecJson;
import org.myrobotlab.framework.MrlException;
import org.myrobotlab.framework.Platform;
import org.myrobotlab.framework.ProcessData;
import org.myrobotlab.framework.Service;
import org.myrobotlab.framework.ServiceType;
import org.myrobotlab.framework.Status;
import org.myrobotlab.lang.NameGenerator;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.net.Http;
import org.myrobotlab.service.Runtime.CmdOptions;
import org.slf4j.Logger;
import picocli.CommandLine;
/**
* <pre>
*
* Agent is responsible for managing running instances of myrobotlab. It
* can start, stop and update myrobotlab.
*
*
* FIXME - test switching branches and remaining on the branch for multiple updates
* FIXME - tes multiple instances on different branches
* FIXME - ws client connectivity and communication !!!
* FIXME - Cli client ws enabled !!
* FIXME - capability to update Agent from child
* FIXME - move CmdLine defintion to Runtime
* FIXME - convert Runtime's cmdline processing to CmdOptions Fixme - remove CmdLine
* FIXME !!! - remove stdin/stdout !!!! use sockets only
*
* FIXME - there are at least 3 different levels of updating
* 1. a global thread which only "checks" for updates
* 2. the possibility of just downloading an update (per instance)
* 3. the possibility of auto-restarting after a download is completed (per instance)
*
* FIXME - auto update log .. sparse log of only updates and their results ...
* FIXME - test changing version prefix .. e.g. 1.2.
* FIXME - testing test - without version test - remote unaccessable
* FIXME - spawn must be synchronized 2 threads (the timer and the user)
* FIXME - test naming an instance FIXME - test starting an old version
* FIXME - make hidden check latest version interval and make default interval check large
* FIXME - change Runtime's cli !!!
* FIXME - check user define services for Agent
*
* </pre>
*/
public class Agent extends Service {
private static final long serialVersionUID = 1L;
public final static Logger log = LoggerFactory.getLogger(Agent.class);
final Map<String, ProcessData> processes = new ConcurrentHashMap<String, ProcessData>();
transient static SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd.HHmmssSSS");
Platform platform = Platform.getLocalInstance();
transient WebGui webgui = null;
int port = 8887;
String address = "127.0.0.1";
String currentBranch;
String currentVersion;
/**
* auto update - automatically checks for updates and WILL update any running
* mrl instance automatically
*/
boolean autoUpdate = false;
/**
* autoCheckForUpdate - checks automatically checks for updates after some
* interval but does not automatically update - it publishes events of new
* availability of updates but does not update
*/
boolean autoCheckForUpdate = false;
Set<String> possibleVersions = new TreeSet<String>();
final static String REMOTE_BUILDS_URL_HOME = "http://build.myrobotlab.org:8080/job/myrobotlab-multibranch/";
// for more info -
// myrobotlab-multibranch/job/develop/api/json
// WARNING Jenkins url api format for multi-branch pipelines is different from
// maven builds !
final static String REMOTE_BUILDS_URL = "job/%s/api/json?tree=builds[number,status,timestamp,id,result]";
final static String REMOTE_JAR_URL = "job/%s/%s/artifact/target/myrobotlab.jar";
final static String REMOTE_MULTI_BRANCH_JOBS = "api/json";
boolean checkRemoteVersions = false;
/**
* command line options for the agent
*/
static CmdOptions options;
String versionPrefix = "1.1.";
static String banner = " _____ __________ ___. __ .____ ___. \n"
+ " / \\ ___.__.\\______ \\ ____\\_ |__ _____/ |_| | _____ \\_ |__ \n"
+ " / \\ / < | | | _
+ "/ Y \\___ | | | ( <_> ) \\_\\ ( <_> ) | | |___ / __ \\| \\_\\ \\\n" + "\\____|__ / ____| |____|_ /\\____/|___ /\\____/|__| |_______ (____ /___ /\n"
+ " \\/\\/ \\/ \\/ \\/ \\/ \\/ \n resistance is futile, we have cookies and robots ...";
/**
* singleton for security purposes
*/
transient static Agent agent;
/**
* development variable to force version "unknown" to be either greatest or
* smallest version for development
*/
private boolean unknownIsGreatest = false;
public static class WorkflowMultiBranchProject {
String name;
WorkflowJob[] jobs;
}
/**
* Jenkins data structure to describe jobs
*/
public static class WorkflowJob {
String name;
String url;
String color;
WorkflowRun lastSuccessfulBuild;
WorkflowRun[] builds;
}
/**
* Jenkins data structure to describe builds
*/
public static class WorkflowRun {
String id;
Integer number;
String result;
Long timestamp;
}
// FIXME - change this to hour for production ...
// long updateCheckIntervalMs = 60 * 60 * 1000; // every hour
long updateCheckIntervalMs = 60 * 1000; // every minute
List<Status> updateLog = new ArrayList<>();
/**
* Update thread - we cannot use addTask as a long update could pile up a
* large set of updates to process quickly in series. Instead, we have a
* simple single class which is always single threaded to process updates.
*
*/
class Updater implements Runnable {
transient Agent agent = null;
transient Thread thread = null;
ProcessData.stateType state = ProcessData.stateType.stopped;
public Updater(Agent agent) {
this.agent = agent;
}
@Override
public void run() {
state = ProcessData.stateType.running;
updateLog("info", "updater running");
autoUpdate = true;
broadcastState();
try {
while (true) {
state = ProcessData.stateType.sleeping;
updateLog("info", "updater sleeping");
Thread.sleep(updateCheckIntervalMs);
state = ProcessData.stateType.updating;
updateLog("info", "updater updating");
agent.update();
}
} catch (Exception e) {
log.info("updater threw", e);
}
log.info("updater stopping");
updateLog("info", "updater stopping");
autoUpdate = false;
state = ProcessData.stateType.stopped;
broadcastState();
}
synchronized public void start() {
if (state == ProcessData.stateType.stopped) {
thread = new Thread(this, getName() + ".updater");
thread.start();
updateLog("info", "updater starting");
} else {
log.warn("updater busy in state = {}", state);
}
}
synchronized public void stop() {
if (state != ProcessData.stateType.stopped) {
// we'll wait if its in the middle of an update
while (state == ProcessData.stateType.updating) {
log.warn("updater currently updating, waiting for 5 seconds...");
sleep(5000);
}
// most likely the thread is a sleeping state
// so, we wake it up quickly to die ;)
thread.interrupt();
}
}
}
public static String BRANCHES_ROOT = "branches";
Updater updater;
public Agent(String n) throws IOException {
super(n);
updater = new Updater(this);
currentBranch = Platform.getLocalInstance().getBranch();
currentVersion = Platform.getLocalInstance().getVersion();
log.info("Agent {} Pid {} is alive", n, Platform.getLocalInstance().getPid());
// basic setup - minimally we make a directory
// and instance folder of the same branch & version as the
// agent jar
setup();
// user has decided to look for updates ..
if (autoUpdate || checkRemoteVersions) {
invoke("getVersions", currentBranch);
}
}
public String getDir(String branch, String version) {
if (branch == null) {
branch = Platform.getLocalInstance().getBranch();
}
if (version == null) {
try {
version = getLatestVersion(branch, autoUpdate);
} catch (Exception e) {
log.error("getDir threw", e);
}
}
return BRANCHES_ROOT + File.separator + branch + "-" + version;
}
public String getJarName(String branch, String version) {
return getDir(branch, version) + File.separator + "myrobotlab.jar";
}
private void setup() throws IOException {
String agentBranch = Platform.getLocalInstance().getBranch();
String agentVersion = Platform.getLocalInstance().getVersion();
// location of the agent's branch (and version)
String agentVersionPath = getDir(agentBranch, agentVersion);
if (!new File(agentVersionPath).exists()) {
File branchDir = new File(agentVersionPath);
branchDir.mkdirs();
}
String agentMyRobotLabJar = getJarName(agentBranch, agentVersion);
if (!new File(agentMyRobotLabJar).exists()) {
String agentJar = new java.io.File(Agent.class.getProtectionDomain().getCodeSource().getLocation().getPath()).getName();
if (!new File(agentJar).exists() || !agentJar.endsWith(".jar")) {
// not operating in released runtime mode - probably operating in ide
String ideTargetJar = new File(System.getProperty("user.dir") + File.separator + "target" + File.separator + "myrobotlab.jar").getAbsolutePath();
if (!new File(ideTargetJar).exists()) {
error("no source agent jar can be found checked:\n%s\n%s\nare you using ide? please package a build (mvn package -DskipTest)", agentJar, ideTargetJar);
} else {
agentJar = ideTargetJar;
}
}
log.info("on branch {} copying agent's current jar to appropriate location {} -> {}", currentBranch, agentJar, agentMyRobotLabJar);
Files.copy(Paths.get(agentJar), Paths.get(agentMyRobotLabJar), StandardCopyOption.REPLACE_EXISTING);
}
}
public void startWebGui() {
startWebGui(null);
}
public void startWebGui(String addressPort) {
if (addressPort == null) {
startWebGui(null, null);
}
Integer port = null;
String address = null;
try {
port = Integer.parseInt(addressPort);
} catch (Exception e) {
}
try {
if (addressPort.contains(":")) {
String[] anp = addressPort.split(":");
port = Integer.parseInt(anp[1]);
addressPort = anp[0];
}
InetAddress ip = InetAddress.getByName(addressPort);
address = ip.getHostAddress();
} catch (Exception e2) {
}
startWebGui(address, port);
}
public void startWebGui(String address, Integer port) {
try {
if (webgui == null) {
if (address != null) {
this.address = address;
}
if (port != null) {
this.port = port;
} else {
port = 8887;
}
webgui = (WebGui) Runtime.create("webgui", "WebGui");
webgui.autoStartBrowser(false);
webgui.setPort(port);
webgui.setAddress(address);
webgui.startService();
} else {
log.info("webgui already started");
}
} catch (Exception e) {
log.error("startWebGui threw", e);
}
}
public void autoUpdate(boolean b) {
if (b) {
// addTask("update", 1000 * 60, 0, "update");
updater.start();
} else {
// purgeTask("update");
updater.stop();
}
}
/**
* FIXME !!! - i believe in task for these pipe up !!! NOT GOOD _ must have
* its own thread then !!
*
* called by the autoUpdate task which is scheduled every minute to look for
* updates from the build server
*/
public void update() {
log.info("looking for updates");
for (String key : processes.keySet()) {
ProcessData process = processes.get(key);
if (!process.options.autoUpdate) {
log.info("not autoUpdate");
continue;
}
try {
// FIXME - if options.src != null GITHUB
if (options.src != null) {
log.info("USING SRC LOOKING FOR GITHUB FOR UPDATES");
getLatestSrc(process.options.branch);
if (process.isRunning()) {
log.info("its running - we should restart");
restart(process.options.id);
log.info("restarted");
}
/*
CmdOptions options = new CmdOptions();
options.branch = branch;
options.version = version;
agent.spawn(options);
*/
} else {
/**<pre> OLD WAY - checking Jenkins ! FIXME - else JENKINS
// getRemoteVersions
log.info("getting version");
String version = getLatestVersion(process.options.branch, true);
if (version == null || version.equals(process.options.version)) {
log.info("same version {}", version);
continue;
}
// we have a possible update
log.info("WOOHOO ! updating to version {}", version);
process.options.version = version;
process.jarPath = new File(getJarName(process.options.branch, process.options.version)).getAbsolutePath();
getLatestJar(process.options.branch);
log.info("WOOHOO ! updated !");
if (process.isRunning()) {
log.info("its running - we should restart");
restart(process.options.id);
log.info("restarted");
}
</pre>
*/
}
} catch (Exception e) {
log.error("proccessing updates from scheduled task threw", e);
}
}
}
/**
* gets the latest jar if allowed to check remote ....
*
* @param branch
*/
public void getLatestJar(String branch) {
try {
// check for latest
String version = getLatestVersion(branch, true);
// check if branch and version exist locally
if (!existsLocally(branch, version)) {
log.info("found update - getting new jar {} {}", branch, version);
getJar(branch, version);
// download latest to the appropriate directory
// mkdirs
// download file
if (!verifyJar(branch, version)) {
}
log.info("successfully downloaded {} {}", branch, version);
}
} catch (Exception e) {
error(e);
}
}
// FIXME - implement :)
private boolean verifyJar(String branch, String version) {
return true;
}
synchronized public void getJar(String branch, String version) {
new File(getDir(branch, version)).mkdirs();
String build = getBuildId(version);
// this
Http.getSafePartFile(String.format(REMOTE_BUILDS_URL_HOME + REMOTE_JAR_URL, branch, build), getJarName(branch, version));
}
public String getBuildId(String version) {
String[] parts = version.split("\\.");
return parts[2];
}
public String getLatestVersion(String branch, Boolean allowRemote) throws MrlException {
Set<String> versions = getVersions(branch, allowRemote);
return getLatestVersion(versions);
}
public String getLatestVersion(Set<String> versions) throws MrlException {
String latest = null;
for (String version : versions) {
if (latest == null) {
latest = version;
continue;
}
if (isGreaterThan(version, latest)) {
latest = version;
}
}
return latest;
}
/**
* checks to see if a branch / version jar exists on the local filesystem
*
* @param branch
* @param version
* @return
*/
public boolean existsLocally(String branch, String version) {
return new File(getJarName(branch, version)).exists();
}
/**
* if there is a single instance - just restart it ...
*
* @throws IOException
* e
* @throws URISyntaxException
* e
* @throws InterruptedException
* e
*
*/
public synchronized void restart(String id) throws IOException, URISyntaxException, InterruptedException {
log.info("restarting process {}", id);
kill(id); // FIXME - kill should include prepare to shutdown ...
sleep(2000);
spawnId(id);
}
/**
* For respawning an existing ProcessData object
*
* @param id
*/
public void spawnId(String id) {
try {
if (processes.containsKey(id)) {
spawn(processes.get(id));
} else {
log.error("agent does not know about process id {}", id);
}
} catch (Exception e) {
log.error("spawn({}) threw ", id, e);
}
}
/**
* Will spawn a new process of mrl using defaults.
*
* @return
* @throws IOException
* @throws URISyntaxException
* @throws InterruptedException
*/
public Process spawn() throws IOException, URISyntaxException, InterruptedException {
CmdOptions options = new CmdOptions();
new CommandLine(options).parseArgs(new String[] {});
return spawn(options);
}
/**
* Spawn a process give a argument command line in single string form
*
* @param args
* @return
* @throws IOException
* @throws URISyntaxException
* @throws InterruptedException
*/
public Process spawn(String args) throws IOException, URISyntaxException, InterruptedException {
CmdOptions options = new CmdOptions();
new CommandLine(options).parseArgs(args.split(" "));
return spawn(options);
}
/**
* return a non-running process structure from an existing one with a new id
*
* @param id
* id
* @return process data
*
*/
public ProcessData copy(String id) {
if (!processes.containsKey(id)) {
log.error("cannot copy %s does not exist", id);
return null;
}
ProcessData pd = processes.get(id);
ProcessData pd2 = new ProcessData(pd);
pd2.startTs = null;
pd2.stopTs = null;
String[] parts = id.split("\\.");
if (parts.length == 4) {
try {
int instance = Integer.parseInt(parts[3]);
++instance;
} catch (Exception e) {
}
} else {
pd2.options.id = id + ".0";
}
processes.put(pd2.options.id, pd2);
if (agent != null) {
agent.broadcastState();
}
return pd2;
}
/**
* Copies an existing ProcessData, makes a new id and spawns it.
*
* @param id
* @throws IOException
*/
public void copyAndStart(String id) throws IOException {
// returns a non running copy with new process id
// on the processes list
ProcessData pd2 = copy(id);
spawn(pd2);
if (agent != null) {
agent.broadcastState();
}
}
/**
* get the current branches being built in a Jenkins multi-branch pipeline job
*
* @return
*/
static public Set<String> getBranches() {
Set<String> possibleBranches = new TreeSet<String>();
try {
byte[] r = Http.get(REMOTE_BUILDS_URL_HOME + REMOTE_MULTI_BRANCH_JOBS);
if (r != null) {
String json = new String(r);
CodecJson decoder = new CodecJson();
WorkflowMultiBranchProject project = (WorkflowMultiBranchProject) decoder.decode(json, WorkflowMultiBranchProject.class);
for (WorkflowJob job : project.jobs) {
possibleBranches.add(job.name);
}
}
} catch (Exception e) {
log.error("getRemoteBranches threw", e);
}
return possibleBranches;
}
/**
* Used to compare semantic versions
*
* @param version1
* @param version2
* @return
* @throws MrlException
*/
boolean isGreaterThan(String version1, String version2) throws MrlException {
if (version1 == null) {
return false;
}
if (version2 == null) {
return true;
}
// special development behavior
if (version1.equals("unknown")) {
return (unknownIsGreatest) ? true : false;
}
if (version2.equals("unknown")) {
return !((unknownIsGreatest) ? true : false);
}
String[] parts1 = version1.split("\\.");
String[] parts2 = version2.split("\\.");
if (parts1.length != 3 || parts2.length != 3) {
throw new MrlException("invalid version isGreaterThan(%s, %s)", version1, version2);
}
for (int i = 0; i < 3; ++i) {
int v1 = Integer.parseInt(parts1[i]);
int v2 = Integer.parseInt(parts2[i]);
if (v1 != v2) {
return v1 > v2;
}
}
throw new MrlException("invalid isGreaterThan(%s, %s)", version1, version2);
}
/**
* This method gets all the version on a particular branch, if allowed remote
* access it will ask the build server what successful builds exist
*
* @param branch
* @param allowRemote
* @return
*/
synchronized public Set<String> getVersions(String branch, Boolean allowRemote) {
Set<String> versions = new TreeSet<String>();
versions.addAll(getLocalVersions(branch));
if (allowRemote) {
versions.addAll(getRemoteVersions(branch));
}
if (versions.size() != possibleVersions.size()) {
possibleVersions = versions;
broadcastState();
}
return versions;
}
/**
* Get remote versions from jenkins
*
* @param branch
* @return
*/
public Set<String> getRemoteVersions(String branch) {
Set<String> versions = new TreeSet<String>();
try {
byte[] data = Http.get(String.format(REMOTE_BUILDS_URL_HOME + REMOTE_BUILDS_URL, branch));
if (data != null) {
CodecJson decoder = new CodecJson();
String json = new String(data);
WorkflowJob job = (WorkflowJob) decoder.decode(json, WorkflowJob.class);
if (job.builds != null) {
for (WorkflowRun build : job.builds) {
if ("SUCCESS".equals(build.result)) {
versions.add(versionPrefix + build.id);
}
}
}
}
} catch (Exception e) {
error(e);
}
return versions;
}
/**
* Checks in the branches directory for the latest version of desired "branch"
*
* @param branch
* @return
* @throws MrlException
*/
public String getLatestLocalVersion(String branch) throws MrlException {
Set<String> allLocal = getLocalVersions(branch);
String latest = null;
for (String version : allLocal) {
if (latest == null) {
latest = version;
continue;
}
if (isGreaterThan(version, latest)) {
latest = version;
}
}
return latest;
}
/**
* A version to be unique is both {branch}-{version}. This finds all currently
* available versions.
*
* @return
*/
public Set<String> getLocalVersions() {
Set<String> versions = new TreeSet<>();
// get local file system versions
File branchDir = new File(BRANCHES_ROOT);
// get local existing versions
File[] listOfFiles = branchDir.listFiles();
for (int i = 0; i < listOfFiles.length; ++i) {
File file = listOfFiles[i];
if (file.isDirectory()) {
// if (file.getName().startsWith(branch)) {
// String version = file.getName().substring(branch.length() + 1);//
// getFileVersion(file.getName());
// if (version != null) {
int pos = file.getName().lastIndexOf("-");
String branchAndVersion = file.getName().substring(0, pos - 1) + " " + file.getName().substring(pos + 1);
versions.add(branchAndVersion);
}
}
return versions;
}
/**
* Get the local versions available for the selected branch.
*
* @param branch
* @return
*/
public Set<String> getLocalVersions(String branch) {
Set<String> versions = new TreeSet<>();
// get local file system versions
File branchDir = new File(BRANCHES_ROOT);
// get local existing versions
File[] listOfFiles = branchDir.listFiles();
for (int i = 0; i < listOfFiles.length; ++i) {
File file = listOfFiles[i];
if (file.isDirectory()) {
if (file.getName().startsWith(branch)) {
String version = file.getName().substring(branch.length() + 1);// getFileVersion(file.getName());
if (version != null) {
versions.add(version);
}
}
}
}
return versions;
}
/**
* get a list of all the processes currently governed by this Agent
*
* @return hash map, int to process data
*/
public Map<String, ProcessData> getProcesses() {
return processes;
}
/**
* Kills requested process.
*
* @param id
* @return
*/
public String kill(String id) {
// FIXME !!! - "ask" all child processes to kindly Runtime.shutdown via msgs
if (processes.containsKey(id)) {
if (agent != null) {
agent.info("terminating %s", id);
}
ProcessData process = processes.get(id);
process.process.destroy();
process.state = ProcessData.stateType.stopped;
if (process.monitor != null) {
process.monitor.interrupt();
process.monitor = null;
}
// remove(processes.get(name));
if (agent != null) {
agent.info("%s haz beeen terminated", id);
agent.broadcastState();
}
return id;
}
error("kill unknown process id {}", id);
return null;
}
/**
* kill all processes
*/
public void killAll() {
// FIXME !!! - "ask" all child processes to kindly Runtime.shutdown via msgs
for (String id : processes.keySet()) {
kill(id);
}
log.info("no survivors sir...");
if (agent != null) {
agent.broadcastState();
}
}
/**
* kills and clears
*
* @param id
*/
public void killAndRemove(String id) {
if (processes.containsKey(id)) {
kill(id);
processes.remove(id);
if (agent != null) {
agent.broadcastState();
}
}
}
/**
* list processes
*
* @return lp ?
*/
public String[] lp() {
Object[] objs = processes.keySet().toArray();
String[] pd = new String[objs.length];
for (int i = 0; i < objs.length; ++i) {
String id = (String) objs[i];
ProcessData p = processes.get(id);
pd[i] = String.format("%s - %s [%s - %s]", id, p.options.id, p.options.branch, p.options.version);
}
return pd;
}
/**
* Publishing point when a process dies.
*
* @param id
* @return
*/
public String publishTerminated(String id) {
log.info("publishTerminated - terminated {} - restarting", id);
if (!processes.containsKey(id)) {
log.error("processes {} not found");
return id;
}
// if you don't fork with Agent allowed to
// exist without instances - then
if (!options.fork) {
// spin through instances - if I'm the only
// thing left - terminate
boolean processesStillRunning = false;
for (ProcessData pd : processes.values()) {
if (pd.isRunning() || pd.isRestarting()) {
processesStillRunning = true;
break;
}
}
if (!processesStillRunning) {
shutdown();
}
}
if (agent != null) {
agent.broadcastState();
}
return id;
}
/**
* Max complexity spawn - with all possible options - this will create a
* ProcessData object and send it to spawn. ProcessData contains all the
* unique data related to starting an instance.
*
* Convert command line parameter options into a ProcessData which can be
* spawned
*
* @param inOptions
* - cmd options
* @return a process
* @throws IOException
* @throws URISyntaxException
* @throws InterruptedException
*/
public Process spawn(CmdOptions inOptions) throws IOException, URISyntaxException, InterruptedException {
if (ProcessData.agent == null) {
ProcessData.agent = this;
}
// create a ProcessData then spawn it !
ProcessData pd = new ProcessData();
pd.options = inOptions;
CmdOptions options = pd.options;
if (options.id == null) {
options.id = NameGenerator.getName();
}
if (options.branch == null) {
options.branch = Platform.getLocalInstance().getBranch();
}
if (options.version == null) {
try {
options.version = getLatestVersion(options.branch, autoUpdate);
} catch (Exception e) {
log.error("getDir threw", e);
}
}
pd.jarPath = new File(getJarName(options.branch, options.version)).getAbsolutePath();
// javaExe
String fs = File.separator;
Platform platform = Platform.getLocalInstance();
String exeName = platform.isWindows() ? "javaw" : "java";
pd.javaExe = String.format("%s%sbin%s%s", System.getProperty("java.home"), fs, fs, exeName);
String jvmArgs = "-Djava.library.path=libraries/native -Djna.library.path=libraries/native -Dfile.encoding=UTF-8";
if (pd.options.memory != null) {
jvmArgs += String.format(" -Xms%s -Xmx%s ", pd.options.memory, pd.options.memory);
}
pd.jvm = jvmArgs.split(" ");
// user override
if (options.jvm != null) {
pd.jvm = options.jvm.split(" ");
}
if (options.services.size() == 0) {
options.services.add("log");
options.services.add("Log");
options.services.add("cli");
options.services.add("Cli");
options.services.add("gui");
options.services.add("SwingGui");
options.services.add("python");
options.services.add("Python");
}
return spawn(pd);
}
public String setBranch(String branch) {
currentBranch = branch;
return currentBranch;
}
static public Map<String, String> setEnv(Map<String, String> env) {
Platform platform = Platform.getLocalInstance();
String platformId = platform.getPlatformId();
if (platform.isLinux()) {
String ldPath = String.format("'pwd'/libraries/native:'pwd'/libraries/native/%s:${LD_LIBRARY_PATH}", platformId);
env.put("LD_LIBRARY_PATH", ldPath);
} else if (platform.isMac()) {
String dyPath = String.format("'pwd'/libraries/native:'pwd'/libraries/native/%s:${DYLD_LIBRARY_PATH}", platformId);
env.put("DYLD_LIBRARY_PATH", dyPath);
} else if (platform.isWindows()) {
// this just borks the path in Windows - additionally (unlike Linux)
// - i don't think you need native code on the PATH
// and Windows does not have a LD_LIBRARY_PATH
// String path =
// String.format("PATH=%%CD%%\\libraries\\native;PATH=%%CD%%\\libraries\\native\\%s;%%PATH%%",
// platformId);
// env.put("PATH", path);
// we need to sanitize against a non-ascii username
// work around for Jython bug in 2.7.0...
env.put("APPDATA", "%%CD%%");
} else {
log.error("unkown operating system");
}
return env;
}
/**
* Kills all connected processes, then shuts down itself. FIXME - should send
* shutdown to other processes instead of killing them
*/
public void shutdown() {
log.info("terminating others");
killAll();
log.info("terminating self ... goodbye...");
Runtime.shutdown();
}
/**
* Constructs a command line from a ProcessData object which can directly be
* run to spawn a new instance of mrl
*
* FIXME is this ProcessData.toString()
*
* @param pd
* @return
*/
public String[] buildCmdLine(ProcessData pd) {
// command line to be returned
List<String> cmd = new ArrayList<String>();
cmd.add(pd.javaExe);
if (pd.jvm != null) {
for (int i = 0; i < pd.jvm.length; ++i) {
cmd.add(pd.jvm[i]);
}
}
cmd.add("-cp");
// step 1 - get current env data
Platform platform = Platform.getLocalInstance();
/**
* The final spawn - all other data types as parameters make a ProcesData
* which is used by this method to start the process.
*
* @param pd
* @return
* @throws IOException
*/
public synchronized Process spawn(ProcessData pd) throws IOException {
log.info("============== spawn begin ==============");
// this needs cmdLine
String[] cmdLine = buildCmdLine(pd);
ProcessBuilder builder = new ProcessBuilder(cmdLine);
// handle stderr as a direct pass through to System.err
builder.redirectErrorStream(true);
// setting working directory to wherever the jar is...
String spawnDir = new File(pd.jarPath).getParent();
builder.directory(new File(spawnDir));
log.info("cd {}", spawnDir);
StringBuilder spawning = new StringBuilder();
for (String c : cmdLine) {
spawning.append(c);
spawning.append(" ");
}
log.info("SPAWNING ! --> [{}]", spawning);
// environment variables setup
setEnv(builder.environment());
Process process = builder.start();
pd.process = process;
pd.startTs = System.currentTimeMillis();
pd.monitor = new ProcessData.Monitor(pd);
pd.monitor.start();
pd.state = ProcessData.stateType.running;
if (pd.options.id == null) {
log.error("id should not be null!");
}
if (processes.containsKey(pd.options.id)) {
if (agent != null) {
agent.info("restarting %s", pd.options.id);
}
} else {
if (agent != null) {
agent.info("starting new %s", pd.options.id);
}
processes.put(pd.options.id, pd);
}
log.info("Agent finished spawn {}", formatter.format(new Date()));
if (agent != null) {
Cli cli = Runtime.getCli();
cli.add(pd.options.id, process.getInputStream(), process.getOutputStream());
cli.attach(pd.options.id);
agent.broadcastState();
}
return process;
}
/**
* DEPRECATE ? spawn should do this checking ?
*
* @param id
* i
* @throws IOException
* e
* @throws URISyntaxException
* e
* @throws InterruptedException
* e
*
*/
public void start(String id) throws IOException, URISyntaxException, InterruptedException {
if (!processes.containsKey(id)) {
log.error("start process %s can not start - process does not exist", id);
return;
}
ProcessData p = processes.get(id);
if (p.isRunning()) {
log.warn("process %s already started", id);
return;
}
spawn(p);
}
/**
* This static method returns all the details of the class without it having
* to be constructed. It has description, categories, dependencies, and peer
* definitions.
*
* @return ServiceType - returns all the data
*
*/
static public ServiceType getMetaData() {
ServiceType meta = new ServiceType(Agent.class.getCanonicalName());
meta.addDescription("responsible for spawning a MRL process. Agent can also terminate, respawn and control the spawned process");
meta.addCategory("framework");
meta.setSponsor("GroG");
meta.setLicenseApache();
meta.includeServiceInOneJar(true);
return meta;
}
/**
* First method JVM executes when myrobotlab.jar is in jar form.
*
* --agent "--logLevel DEBUG --service webgui WebGui"
*
* @param args
* args
*/
public static void main(String[] args) {
try {
options = new CmdOptions();
// for Callable version ...
// int exitCode = new CommandLine(options).execute(args);
new CommandLine(options).parseArgs(args);
if (options.help) {
Runtime.mainHelp();
return;
}
// String[] agentArgs = new String[] { "--id", "agent-" +
// NameGenerator.getName(), "-l", "WARN"};
List<String> agentArgs = new ArrayList<>();
if (options.agent != null) {
agentArgs.addAll(Arrays.asList(options.agent.split(" ")));
} else {
agentArgs.add("--id");
agentArgs.add("agent-" + NameGenerator.getName());
agentArgs.add("-s");
agentArgs.add("agent");
agentArgs.add("Agent");
agentArgs.add("cli");
agentArgs.add("Cli");
agentArgs.add("security");
agentArgs.add("Security");
agentArgs.add("--log-level");
agentArgs.add(options.logLevel);
// agentArgs.add("webgui"); FIXME - soon .. but not yet ...
// agentArgs.add("WebGui");
}
Process p = null;
if (!options.noBanner) {
System.out.println(banner);
System.out.println("");
}
log.info("user args {}", Arrays.toString(args));
log.info("agent args {}", Arrays.toString(agentArgs.toArray()));
Runtime.main(agentArgs.toArray(new String[agentArgs.size()]));
agent = (Agent) Runtime.getService("agent");
/*
* if (agent == null) { agent = (Agent) Runtime.start("agent", "Agent");
* agent.options = options; }
*/
if (options.listVersions) {
System.out.println("available local versions");
for (String bv : agent.getLocalVersions()) {
System.out.println(bv);
}
agent.shutdown();
}
if ("".equals(options.version)) {
Map<String, String> manifest = Platform.getManifest();
System.out.println("manifest");
for (String name : manifest.keySet()) {
System.out.println(String.format("%s=%s", name, manifest.get(name)));
}
agent.shutdown();
}
Platform platform = Platform.getLocalInstance();
if (options.branch == null) {
options.branch = platform.getBranch();
}
if (options.version == null) {
options.version = platform.getVersion();
}
agent.setBranch(options.branch);
agent.setVersion(options.version);
// FIXME - have a list versions ... command line !!!
// FIXME - the most common use case is the version of the spawned instance
// if that is the case its needed to determine what is the "proposed"
// branch & version if no
// special command parameters were given
// FIXME HELP !!!! :D
// if (cmdline.containsKey("-h") || cmdline.containsKey("--help")) {
// // FIXME - add all possible command descriptions ..
// System.out.println(String.format("%s branch %s version %s",
// platform.getBranch(), platform.getPlatformId(),
// platform.getVersion()));
// return;
if (options.webgui != null) {
agent.startWebGui(options.webgui);
}
// the user set auto-update to true
if (options.autoUpdate) {
// options.fork = true;
// lets check and get the latest jar if there is new one
if (options.src == null) {
// get the latest from Jenkins
agent.getLatestJar(agent.getBranch());
} else {
// get the latest from GitHub
agent.getLatestSrc(agent.getBranch());
}
// the "latest" should have been downloaded
options.version = agent.getLatestLocalVersion(agent.getBranch());
}
// FIXME - use wsclient for remote access
if (options.client != null) {
Runtime.start("cli", "Cli");
return;
}
// TODO - build command line ...
// FIXME - if another instances is spawned agent should wait for all
// instances to stop
// list of flags we want to by-pass spawning
if (options.fork && options.services.size() > 0 || !options.fork) {
p = agent.spawn(options); // <-- agent's is now in charge of first
}
// we start a timer to process future updates
if (options.autoUpdate) {
// if you update a single process
// it kills it and restarts - and this will kill the
// agent unless its forked
options.fork = true;
agent.autoUpdate(true);
}
if (options.install != null) {
// wait for mrl instance to finish installing
// then shutdown (addendum: check if supporting other processes)
p.waitFor();
agent.shutdown();
}
} catch (Exception e) {
log.error("unsuccessful spawn", e);
}
}
public String getLatestSrc(String branch) throws WrongRepositoryStateException, InvalidConfigurationException, DetachedHeadException, InvalidRemoteException, CanceledException, RefNotFoundException, NoHeadException, TransportException, IOException, GitAPIException {
Runtime.getInstance();
Agent agent = (Agent) Runtime.start("agent", "Agent");
RevCommit latestCommit = agent.gitPull(branch);
if (latestCommit != null) {
String version = agent.mvn(branch);
return version;
}
return null;
}
public String getBranch() {
return currentBranch;
}
public String getVersion() {
return currentVersion;
}
public String setVersion(String version) {
currentVersion = version;
return version;
}
public String mvn(String branch) {
return mvn(null, branch, null);
}
// mvn -DskipTests -Dbuild.number=71 -DGitBranch=develop clean package -o
public String mvn(String src, String branch, Long buildNumber) {
try {
if (src == null) {
src = branch + ".src";
}
if (buildNumber == null) {
// epoch minute build time number
buildNumber = System.currentTimeMillis() / 1000;
}
String version = versionPrefix + buildNumber;
Platform platform = Platform.getLocalInstance();
List<String> cmd = new ArrayList<>();
String pathToPom = src + File.separator + "pom.xml";
cmd.add((platform.isWindows()) ? "cmd" : "bash");
cmd.add((platform.isWindows()) ? "/c" : "-c");
cmd.add((platform.isWindows()) ? "mvn" : "mvn"); // huh .. thought it was
// mvn.bat
cmd.add("-DskipTests");
cmd.add("-Dbuild.number=" + buildNumber);
cmd.add("-DGitBranch=" + branch);
cmd.add("compile");
cmd.add("prepare-package");
cmd.add("package");
// cmd.add("-f");
// cmd.add(pathToPom);
// cmd.add("-o"); // offline
StringBuilder sb = new StringBuilder();
for (String c : cmd) {
sb.append(c);
sb.append(" ");
}
// src path ..
log.info("build [{}]", sb);
// ProcessBuilder pb = new
// ProcessBuilder("mvn","exec:java","-Dexec.mainClass="+"FunnyClass");
ProcessBuilder pb = new ProcessBuilder(cmd);
pb.directory(new File(src));
// handle stderr as a direct pass through to System.err
pb.redirectErrorStream(true);
// pb.environment().putAll(System.getenv());
pb.inheritIO().start().waitFor();
// FIXME LOOK FOR --> "BUILD FAILURE"
String newJar = src + File.separator + "target" + File.separator + "myrobotlab.jar";
String newJarLoc = getJarName(branch, version);
File p = new File(newJarLoc).getAbsoluteFile().getParentFile();
p.mkdirs();
Files.move(Paths.get(newJar), Paths.get(newJarLoc));
return buildNumber + "";
} catch (Exception e) {
log.error("mvn threw", e);
}
return null;
}
public RevCommit gitPull(String branch) throws WrongRepositoryStateException, InvalidConfigurationException, DetachedHeadException, InvalidRemoteException, CanceledException,
RefNotFoundException, NoHeadException, TransportException, IOException, GitAPIException {
return gitPull(null, branch);
}
public RevCommit gitPull(String src, String branch) throws IOException, WrongRepositoryStateException, InvalidConfigurationException, DetachedHeadException, InvalidRemoteException,
CanceledException, RefNotFoundException, NoHeadException, TransportException, GitAPIException {
if (branch == null) {
branch = currentBranch;
}
if (src == null) {
src = branch + ".src";
}
List<String> branches = new ArrayList<String>();
branches.add("refs/heads/" + branch);
File repoParentFolder = new File(src);
Git git = null;
TextProgressMonitor textmonitor = new TextProgressMonitor(new PrintWriter(System.out));
Repository repo = null;
if (!repoParentFolder.exists()) {
// String branch = "master";
git = Git.cloneRepository().setProgressMonitor(textmonitor).setURI("https://github.com/MyRobotLab/myrobotlab.git").setDirectory(new File(src)).setBranchesToClone(branches)
.setBranch("refs/heads/" + branch).call();
} else {
// Open an existing repository
String gitDir = repoParentFolder.getAbsolutePath() + "/.git";
repo = new FileRepositoryBuilder().setGitDir(new File(gitDir)).build();
git = new Git(repo);
}
repo = git.getRepository();
/**
* <pre>
* CheckoutCommand checkout = git.checkout().setCreateBranch(true).setName(branch).setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK).setStartPoint("origin/" + branch)
* .call();
* </pre>
*/
// git.pull().setCredentialsProvider(user).call();
// FIXME if currentBranch != branch - then checkout .. set current branch
if (!branch.equals(currentBranch)) {
git.branchCreate().setForce(true).setName(branch).setStartPoint("origin/" + branch).call();
git.checkout().setName(branch).call();
}
// FIXME - if auto-update or auto-fetch ie .. remote allowed and cache remote changes
git.fetch().setProgressMonitor(new TextProgressMonitor(new PrintWriter(System.out))).call();
List<RevCommit> localLogs = getLogs(git, "origin/" + branch, 1);
List<RevCommit> remoteLogs = getLogs(git, "remotes/origin/" + branch, 1);
BranchTrackingStatus status = BranchTrackingStatus.of(repo, branch);
RevCommit localCommit = localLogs.get(0);
RevCommit remoteCommit = remoteLogs.get(0);
// if (localCommit.getCommitTime() < remoteCommit.getCommitTime()) {
if (status.getBehindCount() > 0) {
log.info("local ts {}, remote {} - {} updating", localCommit.getCommitTime(), remoteCommit.getCommitTime(), remoteCommit.getFullMessage());
PullCommand pullCmd = git.pull();
pullCmd.setProgressMonitor(textmonitor);
pullCmd.call();
return remoteCommit;
}
return null;
}
private List<RevCommit> getLogs(Git git, String ref, int maxCount)
throws RevisionSyntaxException, NoHeadException, MissingObjectException, IncorrectObjectTypeException, AmbiguousObjectException, GitAPIException, IOException {
List<RevCommit> ret = new ArrayList<>();
Repository repository = git.getRepository();
Iterable<RevCommit> logs = git.log().setMaxCount(maxCount).add(repository.resolve(ref)).call();
int count = 0;
for (RevCommit rev : logs) {
System.out.println(
rev /*
* + ", name: " + rev.getName() + ", id: " + rev.getId().getName()
*/);
count++;
ret.add(rev);
}
System.out.println("Had " + count + " " + ref);
return ret;
}
/**
* Populate all the files to update, if the system should update.
*
* @throws GitAPIException
* @throws IOException
* @throws IncorrectObjectTypeException
* @throws AmbiguousObjectException
* @throws RevisionSyntaxException
*/
/*
* private List<DiffEntry> populateDiff(Git git) throws GitAPIException,
* RevisionSyntaxException, AmbiguousObjectException,
* IncorrectObjectTypeException, IOException {
*
* git.fetch().setProgressMonitor(new TextProgressMonitor(new
* PrintWriter(System.out))).call(); Repository repo = git.getRepository();
* ObjectId fetchHead = repo.resolve("FETCH_HEAD^{tree}"); ObjectId head =
* repo.resolve("HEAD^{tree}");
*
* ObjectReader reader = repo.newObjectReader(); CanonicalTreeParser
* oldTreeIter = new CanonicalTreeParser(); oldTreeIter.reset(reader, head);
* CanonicalTreeParser newTreeIter = new CanonicalTreeParser();
* newTreeIter.reset(reader, fetchHead); List<DiffEntry> diffs =
* git.diff().setShowNameAndStatusOnly(true) .setNewTree(newTreeIter)
* .setOldTree(oldTreeIter) .call();
*
* return diffs; }
*/
// FIXME - move to enums for status level !
public void updateLog(String level, String msg) {
if (updateLog.size() > 100) {
updateLog.remove(updateLog.size() - 1);
}
if ("info".equals(level)) {
updateLog.add(Status.info((new Date()).toString() + " " + msg));
} else if ("error".equals(level)) {
updateLog.add(Status.error((new Date()).toString() + " " + msg));
}
}
}
|
package com.ctrip.zeus.util;
import com.ctrip.zeus.model.entity.Group;
import com.ctrip.zeus.model.entity.Slb;
import com.ctrip.zeus.model.entity.VirtualServer;
import com.ctrip.zeus.queue.entity.GroupData;
import com.ctrip.zeus.queue.entity.SlbData;
import com.ctrip.zeus.queue.entity.SlbMessageData;
import com.ctrip.zeus.queue.entity.VsData;
import com.ctrip.zeus.queue.transform.DefaultJsonParser;
import com.ctrip.zeus.support.ObjectJsonParser;
import com.ctrip.zeus.support.ObjectJsonWriter;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
public class MessageUtil {
static Logger logger = LoggerFactory.getLogger(MessageUtil.class);
public static String getMessageData(HttpServletRequest request, Group[] groups, VirtualServer[] vses, Slb[] slbs, String[] ips, boolean success) {
SlbMessageData res = new SlbMessageData();
String query = request.getQueryString();
String description = getDescriptionFromQuery(query);
res.setQuery(query)
.setDescription(description)
.setUri(request.getRequestURI())
.setSuccess(success)
.setClientIp(getClientIP(request));
if (groups != null && groups.length > 0) {
for (Group group : groups) {
res.addGroupData(new GroupData().setId(group.getId()).setName(group.getName()).setVersion(group.getVersion()));
}
}
if (slbs != null && slbs.length > 0) {
for (Slb slb : slbs) {
res.addSlbData(new SlbData().setId(slb.getId()).setName(slb.getName()).setVersion(slb.getVersion()));
}
}
if (vses != null && vses.length > 0) {
for (VirtualServer vs : vses) {
res.addVsData(new VsData().setId(vs.getId()).setName(vs.getName()).setVersion(vs.getVersion()));
}
}
if (ips != null && ips.length > 0) {
for (String ip : ips) {
res.addIp(ip);
}
}
try {
return ObjectJsonWriter.write(res);
} catch (Exception e) {
logger.warn("Write Message Data Fail." + res.toString(), e);
return null;
}
}
public static String getDescriptionFromQuery(String query) {
if (query == null){
return null;
}
String[] qs = query.split("&");
String description = null;
for (String tmp : qs) {
if (tmp.startsWith("description=")) {
String[] l = tmp.split("=");
if (l.length == 2 && l[1] != null) {
try {
description = URLDecoder.decode(l[1], "utf-8");
} catch (UnsupportedEncodingException e) {
logger.warn("Get Description Failed. Description:" + l[1]);
}
}
}
}
if (description != null && description.length() > 512) {
description = description.substring(0, 512);
}
return description;
}
public static SlbMessageData parserSlbMessageData(String res) {
try {
if (res == null) return null;
return ObjectJsonParser.parse(res, SlbMessageData.class);
} catch (Exception e) {
logger.warn("Parser Slb Message Data Failed. Message:" + res, e);
return null;
}
}
public static String getClientIP(HttpServletRequest request) {
String ip = request.getHeader("X-Forwarded-For");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
}
|
package org.myrobotlab.service;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.PullCommand;
import org.eclipse.jgit.api.errors.CanceledException;
import org.eclipse.jgit.api.errors.DetachedHeadException;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.api.errors.InvalidConfigurationException;
import org.eclipse.jgit.api.errors.InvalidRemoteException;
import org.eclipse.jgit.api.errors.NoHeadException;
import org.eclipse.jgit.api.errors.RefNotFoundException;
import org.eclipse.jgit.api.errors.TransportException;
import org.eclipse.jgit.api.errors.WrongRepositoryStateException;
import org.eclipse.jgit.errors.AmbiguousObjectException;
import org.eclipse.jgit.errors.IncorrectObjectTypeException;
import org.eclipse.jgit.errors.MissingObjectException;
import org.eclipse.jgit.errors.RevisionSyntaxException;
import org.eclipse.jgit.lib.BranchTrackingStatus;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.lib.TextProgressMonitor;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.storage.file.FileRepositoryBuilder;
import org.myrobotlab.codec.CodecJson;
import org.myrobotlab.framework.MrlException;
import org.myrobotlab.framework.Platform;
import org.myrobotlab.framework.ProcessData;
import org.myrobotlab.framework.Service;
import org.myrobotlab.framework.ServiceType;
import org.myrobotlab.framework.Status;
import org.myrobotlab.lang.NameGenerator;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.net.Http;
import org.myrobotlab.service.Runtime.CmdOptions;
import org.slf4j.Logger;
import picocli.CommandLine;
/**
* <pre>
*
* Agent is responsible for managing running instances of myrobotlab. It
* can start, stop and update myrobotlab.
*
*
* FIXME - test switching branches and remaining on the branch for multiple updates
* FIXME - tes multiple instances on different branches
* FIXME - ws client connectivity and communication !!!
* FIXME - Cli client ws enabled !!
* FIXME - capability to update Agent from child
* FIXME - move CmdLine defintion to Runtime
* FIXME - convert Runtime's cmdline processing to CmdOptions Fixme - remove CmdLine
* FIXME !!! - remove stdin/stdout !!!! use sockets only
*
* FIXME - there are at least 3 different levels of updating
* 1. a global thread which only "checks" for updates
* 2. the possibility of just downloading an update (per instance)
* 3. the possibility of auto-restarting after a download is completed (per instance)
*
* FIXME - auto update log .. sparse log of only updates and their results ...
* FIXME - test changing version prefix .. e.g. 1.2.
* FIXME - testing test - without version test - remote unaccessable
* FIXME - spawn must be synchronized 2 threads (the timer and the user)
* FIXME - test naming an instance FIXME - test starting an old version
* FIXME - make hidden check latest version interval and make default interval check large
* FIXME - change Runtime's cli !!!
* FIXME - check user define services for Agent
*
* </pre>
*/
public class Agent extends Service {
private static final long serialVersionUID = 1L;
public final static Logger log = LoggerFactory.getLogger(Agent.class);
final Map<String, ProcessData> processes = new ConcurrentHashMap<String, ProcessData>();
transient static SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd.HHmmssSSS");
Platform platform = Platform.getLocalInstance();
transient WebGui webgui = null;
int port = 8887;
String address = "127.0.0.1";
String currentBranch;
String currentVersion;
/**
* auto update - automatically checks for updates and WILL update any running
* mrl instance automatically
*/
boolean autoUpdate = false;
/**
* autoCheckForUpdate - checks automatically checks for updates after some
* interval but does not automatically update - it publishes events of new
* availability of updates but does not update
*/
boolean autoCheckForUpdate = false;
Set<String> possibleVersions = new TreeSet<String>();
final static String REMOTE_BUILDS_URL_HOME = "http://build.myrobotlab.org:8080/job/myrobotlab-multibranch/";
// for more info -
// myrobotlab-multibranch/job/develop/api/json
// WARNING Jenkins url api format for multi-branch pipelines is different from
// maven builds !
final static String REMOTE_BUILDS_URL = "job/%s/api/json?tree=builds[number,status,timestamp,id,result]";
final static String REMOTE_JAR_URL = "job/%s/%s/artifact/target/myrobotlab.jar";
final static String REMOTE_MULTI_BRANCH_JOBS = "api/json";
boolean checkRemoteVersions = false;
/**
* command line options for the agent
*/
static CmdOptions globalOptions;
String versionPrefix = "1.1.";
static String banner = " _____ __________ ___. __ .____ ___. \n"
+ " / \\ ___.__.\\______ \\ ____\\_ |__ _____/ |_| | _____ \\_ |__ \n"
+ " / \\ / < | | | _
+ "/ Y \\___ | | | ( <_> ) \\_\\ ( <_> ) | | |___ / __ \\| \\_\\ \\\n" + "\\____|__ / ____| |____|_ /\\____/|___ /\\____/|__| |_______ (____ /___ /\n"
+ " \\/\\/ \\/ \\/ \\/ \\/ \\/ \n resistance is futile, we have cookies and robots ...";
/**
* singleton for security purposes
*/
transient static Agent agent;
/**
* development variable to force version "unknown" to be either greatest or
* smallest version for development
*/
private boolean unknownIsGreatest = false;
public static class WorkflowMultiBranchProject {
String name;
WorkflowJob[] jobs;
}
/**
* Jenkins data structure to describe jobs
*/
public static class WorkflowJob {
String name;
String url;
String color;
WorkflowRun lastSuccessfulBuild;
WorkflowRun[] builds;
}
/**
* Jenkins data structure to describe builds
*/
public static class WorkflowRun {
String id;
Integer number;
String result;
Long timestamp;
}
// FIXME - change this to hour for production ...
// long updateCheckIntervalMs = 60 * 60 * 1000; // every hour
long updateCheckIntervalMs = 60 * 1000; // every minute
List<Status> updateLog = new ArrayList<>();
/**
* Update thread - we cannot use addTask as a long update could pile up a
* large set of updates to process quickly in series. Instead, we have a
* simple single class which is always single threaded to process updates.
*
*/
class Updater implements Runnable {
transient Agent agent = null;
transient Thread thread = null;
ProcessData.stateType state = ProcessData.stateType.stopped;
public Updater(Agent agent) {
this.agent = agent;
}
@Override
public void run() {
state = ProcessData.stateType.running;
updateLog("info", "updater running");
autoUpdate = true;
broadcastState();
try {
while (true) {
state = ProcessData.stateType.sleeping;
updateLog("info", "updater sleeping");
Thread.sleep(updateCheckIntervalMs);
state = ProcessData.stateType.updating;
updateLog("info", "updater updating");
agent.update();
}
} catch (Exception e) {
log.info("updater threw", e);
}
log.info("updater stopping");
updateLog("info", "updater stopping");
autoUpdate = false;
state = ProcessData.stateType.stopped;
broadcastState();
}
synchronized public void start() {
if (state == ProcessData.stateType.stopped) {
thread = new Thread(this, getName() + ".updater");
thread.start();
updateLog("info", "updater starting");
} else {
log.warn("updater busy in state = {}", state);
}
}
synchronized public void stop() {
if (state != ProcessData.stateType.stopped) {
// we'll wait if its in the middle of an update
while (state == ProcessData.stateType.updating) {
log.warn("updater currently updating, waiting for 5 seconds...");
sleep(5000);
}
// most likely the thread is a sleeping state
// so, we wake it up quickly to die ;)
thread.interrupt();
}
}
}
public static String BRANCHES_ROOT = "branches";
Updater updater;
public Agent(String n) throws IOException {
super(n);
updater = new Updater(this);
currentBranch = Platform.getLocalInstance().getBranch();
currentVersion = Platform.getLocalInstance().getVersion();
log.info("Agent {} Pid {} is alive", n, Platform.getLocalInstance().getPid());
// basic setup - minimally we make a directory
// and instance folder of the same branch & version as the
// agent jar
setup();
// user has decided to look for updates ..
if (autoUpdate || checkRemoteVersions) {
invoke("getVersions", currentBranch);
}
}
public String getDir(String branch, String version) {
if (branch == null) {
branch = Platform.getLocalInstance().getBranch();
}
if (version == null) {
try {
version = getLatestVersion(branch, autoUpdate);
} catch (Exception e) {
log.error("getDir threw", e);
}
}
return BRANCHES_ROOT + File.separator + branch + "-" + version;
}
public String getJarName(String branch, String version) {
return getDir(branch, version) + File.separator + "myrobotlab.jar";
}
private void setup() throws IOException {
String agentBranch = Platform.getLocalInstance().getBranch();
String agentVersion = Platform.getLocalInstance().getVersion();
// location of the agent's branch (and version)
String agentVersionPath = getDir(agentBranch, agentVersion);
if (!new File(agentVersionPath).exists()) {
File branchDir = new File(agentVersionPath);
branchDir.mkdirs();
}
String agentMyRobotLabJar = getJarName(agentBranch, agentVersion);
if (!new File(agentMyRobotLabJar).exists()) {
String agentJar = new java.io.File(Agent.class.getProtectionDomain().getCodeSource().getLocation().getPath()).getName();
if (!new File(agentJar).exists() || !agentJar.endsWith(".jar")) {
// not operating in released runtime mode - probably operating in ide
String ideTargetJar = new File(System.getProperty("user.dir") + File.separator + "target" + File.separator + "myrobotlab.jar").getAbsolutePath();
if (!new File(ideTargetJar).exists()) {
error("no source agent jar can be found checked:\n%s\n%s\nare you using ide? please package a build (mvn package -DskipTest)", agentJar, ideTargetJar);
} else {
agentJar = ideTargetJar;
}
}
log.info("on branch {} copying agent's current jar to appropriate location {} -> {}", currentBranch, agentJar, agentMyRobotLabJar);
Files.copy(Paths.get(agentJar), Paths.get(agentMyRobotLabJar), StandardCopyOption.REPLACE_EXISTING);
}
}
public void startWebGui() {
startWebGui(null);
}
public void startWebGui(String addressPort) {
if (addressPort == null) {
startWebGui(null, null);
}
Integer port = null;
String address = null;
try {
port = Integer.parseInt(addressPort);
} catch (Exception e) {
}
try {
if (addressPort.contains(":")) {
String[] anp = addressPort.split(":");
port = Integer.parseInt(anp[1]);
addressPort = anp[0];
}
InetAddress ip = InetAddress.getByName(addressPort);
address = ip.getHostAddress();
} catch (Exception e2) {
}
startWebGui(address, port);
}
public void startWebGui(String address, Integer port) {
try {
if (webgui == null) {
if (address != null) {
this.address = address;
}
if (port != null) {
this.port = port;
} else {
port = 8887;
}
webgui = (WebGui) Runtime.create("webgui", "WebGui");
webgui.autoStartBrowser(false);
webgui.setPort(port);
webgui.setAddress(address);
webgui.startService();
} else {
log.info("webgui already started");
}
} catch (Exception e) {
log.error("startWebGui threw", e);
}
}
public void autoUpdate(boolean b) {
if (b) {
// addTask("update", 1000 * 60, 0, "update");
updater.start();
} else {
// purgeTask("update");
updater.stop();
}
}
/**
* FIXME !!! - i believe in task for these pipe up !!! NOT GOOD _ must have
* its own thread then !!
*
* called by the autoUpdate task which is scheduled every minute to look for
* updates from the build server
*/
public void update() {
for (String key : processes.keySet()) {
ProcessData process = processes.get(key);
if (!process.options.autoUpdate) {
log.info("not autoUpdate");
continue;
}
try {
// FIXME - if options.src != null GITHUB
if (globalOptions.src != null) {
log.info("checking for github updates on branch {}", process.options.branch);
String newVersion = getLatestSrc(process.options.branch);
if (newVersion != null && process.isRunning()) {
log.info("updating process [{}] from {} -to-> {}", process.options.id, process.options.version, newVersion);
// FIXME set currentVersion ???
currentVersion = newVersion;
process.options.version = newVersion;
process.jarPath = new File(getJarName(process.options.branch, process.options.version)).getAbsolutePath();
restart(process.options.id);
log.info("restarted");
}
} else {
log.info("checking for updates on jenkins");
// getRemoteVersions
log.info("getting version");
String version = getLatestVersion(process.options.branch, true);
if (version == null || version.equals(process.options.version)) {
log.info("same version {}", version);
continue;
}
// we have a possible update
log.info("WOOHOO ! updating to version {}", version);
process.options.version = version;
process.jarPath = new File(getJarName(process.options.branch, process.options.version)).getAbsolutePath();
getLatestJar(process.options.branch);
log.info("WOOHOO ! updated !");
if (process.isRunning()) {
log.info("its running - we should restart");
restart(process.options.id);
log.info("restarted");
}
}
} catch (Exception e) {
log.error("proccessing updates from scheduled task threw", e);
}
}
}
/**
* gets the latest jar if allowed to check remote ....
*
* @param branch
*/
public void getLatestJar(String branch) {
try {
// check for latest
String version = getLatestVersion(branch, true);
// check if branch and version exist locally
if (!existsLocally(branch, version)) {
log.info("found update - getting new jar {} {}", branch, version);
getJar(branch, version);
// download latest to the appropriate directory
// mkdirs
// download file
if (!verifyJar(branch, version)) {
}
log.info("successfully downloaded {} {}", branch, version);
}
} catch (Exception e) {
error(e);
}
}
// FIXME - implement :)
private boolean verifyJar(String branch, String version) {
return true;
}
synchronized public void getJar(String branch, String version) {
new File(getDir(branch, version)).mkdirs();
String build = getBuildId(version);
// this
Http.getSafePartFile(String.format(REMOTE_BUILDS_URL_HOME + REMOTE_JAR_URL, branch, build), getJarName(branch, version));
}
public String getBuildId(String version) {
String[] parts = version.split("\\.");
return parts[2];
}
public String getLatestVersion(String branch, Boolean allowRemote) throws MrlException {
Set<String> versions = getVersions(branch, allowRemote);
return getLatestVersion(versions);
}
public String getLatestVersion(Set<String> versions) throws MrlException {
String latest = null;
for (String version : versions) {
if (latest == null) {
latest = version;
continue;
}
if (isGreaterThan(version, latest)) {
latest = version;
}
}
return latest;
}
/**
* checks to see if a branch / version jar exists on the local filesystem
*
* @param branch
* @param version
* @return
*/
public boolean existsLocally(String branch, String version) {
return new File(getJarName(branch, version)).exists();
}
/**
* if there is a single instance - just restart it ...
*
* @throws IOException
* e
* @throws URISyntaxException
* e
* @throws InterruptedException
* e
*
*/
public synchronized void restart(String id) throws IOException, URISyntaxException, InterruptedException {
log.info("restarting process {}", id);
kill(id); // FIXME - kill should include prepare to shutdown ...
sleep(2000);
spawnId(id);
}
/**
* For respawning an existing ProcessData object
*
* @param id
*/
public void spawnId(String id) {
try {
if (processes.containsKey(id)) {
spawn(processes.get(id));
} else {
log.error("agent does not know about process id {}", id);
}
} catch (Exception e) {
log.error("spawn({}) threw ", id, e);
}
}
public Process spawn() throws IOException, URISyntaxException, InterruptedException, IllegalArgumentException, IllegalAccessException {
CmdOptions options = new CmdOptions();
new CommandLine(options).parseArgs(new String[] {});
return spawn(options);
}
public Process spawn(String args) throws IOException, URISyntaxException, InterruptedException, IllegalArgumentException, IllegalAccessException {
CmdOptions options = new CmdOptions();
new CommandLine(options).parseArgs(args.split(" "));
return spawn(options);
}
/**
* return a non-running process structure from an existing one with a new id
*
* @param id
* id
* @return process data
*
*/
public ProcessData copy(String id) {
if (!processes.containsKey(id)) {
log.error("cannot copy %s does not exist", id);
return null;
}
ProcessData pd = processes.get(id);
ProcessData pd2 = new ProcessData(pd);
pd2.startTs = null;
pd2.stopTs = null;
String[] parts = id.split("\\.");
if (parts.length == 4) {
try {
int instance = Integer.parseInt(parts[3]);
++instance;
} catch (Exception e) {
}
} else {
pd2.options.id = id + ".0";
}
processes.put(pd2.options.id, pd2);
if (agent != null) {
agent.broadcastState();
}
return pd2;
}
/**
* Copies an existing ProcessData, makes a new id and spawns it.
*
* @param id
* @throws IOException
*/
public void copyAndStart(String id) throws IOException {
// returns a non running copy with new process id
// on the processes list
ProcessData pd2 = copy(id);
spawn(pd2);
if (agent != null) {
agent.broadcastState();
}
}
/**
* get the current branches being built in a Jenkins multi-branch pipeline job
*
* @return
*/
static public Set<String> getBranches() {
Set<String> possibleBranches = new TreeSet<String>();
try {
byte[] r = Http.get(REMOTE_BUILDS_URL_HOME + REMOTE_MULTI_BRANCH_JOBS);
if (r != null) {
String json = new String(r);
CodecJson decoder = new CodecJson();
WorkflowMultiBranchProject project = (WorkflowMultiBranchProject) decoder.decode(json, WorkflowMultiBranchProject.class);
for (WorkflowJob job : project.jobs) {
possibleBranches.add(job.name);
}
}
} catch (Exception e) {
log.error("getRemoteBranches threw", e);
}
return possibleBranches;
}
/**
* Used to compare semantic versions
*
* @param version1
* @param version2
* @return
* @throws MrlException
*/
boolean isGreaterThan(String version1, String version2) throws MrlException {
if (version1 == null) {
return false;
}
if (version2 == null) {
return true;
}
// special development behavior
if (version1.equals("unknown")) {
return (unknownIsGreatest) ? true : false;
}
if (version2.equals("unknown")) {
return !((unknownIsGreatest) ? true : false);
}
String[] parts1 = version1.split("\\.");
String[] parts2 = version2.split("\\.");
if (parts1.length != 3 || parts2.length != 3) {
throw new MrlException("invalid version isGreaterThan(%s, %s)", version1, version2);
}
for (int i = 0; i < 3; ++i) {
int v1 = Integer.parseInt(parts1[i]);
int v2 = Integer.parseInt(parts2[i]);
if (v1 != v2) {
return v1 > v2;
}
}
throw new MrlException("invalid isGreaterThan(%s, %s)", version1, version2);
}
/**
* This method gets all the version on a particular branch, if allowed remote
* access it will ask the build server what successful builds exist
*
* @param branch
* @param allowRemote
* @return
*/
synchronized public Set<String> getVersions(String branch, Boolean allowRemote) {
Set<String> versions = new TreeSet<String>();
versions.addAll(getLocalVersions(branch));
if (allowRemote) {
versions.addAll(getRemoteVersions(branch));
}
if (versions.size() != possibleVersions.size()) {
possibleVersions = versions;
broadcastState();
}
return versions;
}
/**
* Get remote versions from jenkins
*
* @param branch
* @return
*/
public Set<String> getRemoteVersions(String branch) {
Set<String> versions = new TreeSet<String>();
try {
byte[] data = Http.get(String.format(REMOTE_BUILDS_URL_HOME + REMOTE_BUILDS_URL, branch));
if (data != null) {
CodecJson decoder = new CodecJson();
String json = new String(data);
WorkflowJob job = (WorkflowJob) decoder.decode(json, WorkflowJob.class);
if (job.builds != null) {
for (WorkflowRun build : job.builds) {
if ("SUCCESS".equals(build.result)) {
versions.add(versionPrefix + build.id);
}
}
}
}
} catch (Exception e) {
error(e);
}
return versions;
}
/**
* Checks in the branches directory for the latest version of desired "branch"
*
* @param branch
* @return
* @throws MrlException
*/
public String getLatestLocalVersion(String branch) throws MrlException {
Set<String> allLocal = getLocalVersions(branch);
String latest = null;
for (String version : allLocal) {
if (latest == null) {
latest = version;
continue;
}
if (isGreaterThan(version, latest)) {
latest = version;
}
}
return latest;
}
/**
* A version to be unique is both {branch}-{version}. This finds all currently
* available versions.
*
* @return
*/
public Set<String> getLocalVersions() {
Set<String> versions = new TreeSet<>();
// get local file system versions
File branchDir = new File(BRANCHES_ROOT);
// get local existing versions
File[] listOfFiles = branchDir.listFiles();
for (int i = 0; i < listOfFiles.length; ++i) {
File file = listOfFiles[i];
if (file.isDirectory()) {
// if (file.getName().startsWith(branch)) {
// String version = file.getName().substring(branch.length() + 1);//
// getFileVersion(file.getName());
// if (version != null) {
int pos = file.getName().lastIndexOf("-");
String branchAndVersion = file.getName().substring(0, pos - 1) + " " + file.getName().substring(pos + 1);
versions.add(branchAndVersion);
}
}
return versions;
}
/**
* Get the local versions available for the selected branch.
*
* @param branch
* @return
*/
public Set<String> getLocalVersions(String branch) {
Set<String> versions = new TreeSet<>();
// get local file system versions
File branchDir = new File(BRANCHES_ROOT);
// get local existing versions
File[] listOfFiles = branchDir.listFiles();
for (int i = 0; i < listOfFiles.length; ++i) {
File file = listOfFiles[i];
if (file.isDirectory()) {
if (file.getName().startsWith(branch)) {
String version = file.getName().substring(branch.length() + 1);// getFileVersion(file.getName());
if (version != null) {
versions.add(version);
}
}
}
}
return versions;
}
/**
* get a list of all the processes currently governed by this Agent
*
* @return hash map, int to process data
*/
public Map<String, ProcessData> getProcesses() {
return processes;
}
/**
* Kills requested process.
*
* @param id
* @return
*/
public String kill(String id) {
// FIXME !!! - "ask" all child processes to kindly Runtime.shutdown via msgs
if (processes.containsKey(id)) {
if (agent != null) {
agent.info("terminating %s", id);
}
ProcessData process = processes.get(id);
process.process.destroy();
process.state = ProcessData.stateType.stopped;
if (process.monitor != null) {
process.monitor.interrupt();
process.monitor = null;
}
// remove(processes.get(name));
if (agent != null) {
agent.info("%s haz beeen terminated", id);
agent.broadcastState();
}
return id;
}
error("kill unknown process id {}", id);
return null;
}
/**
* kill all processes
*/
public void killAll() {
// FIXME !!! - "ask" all child processes to kindly Runtime.shutdown via msgs
for (String id : processes.keySet()) {
kill(id);
}
log.info("no survivors sir...");
if (agent != null) {
agent.broadcastState();
}
}
/**
* kills and clears
*
* @param id
*/
public void killAndRemove(String id) {
if (processes.containsKey(id)) {
kill(id);
processes.remove(id);
if (agent != null) {
agent.broadcastState();
}
}
}
/**
* list processes
*
* @return lp ?
*/
public String[] lp() {
Object[] objs = processes.keySet().toArray();
String[] pd = new String[objs.length];
for (int i = 0; i < objs.length; ++i) {
String id = (String) objs[i];
ProcessData p = processes.get(id);
pd[i] = String.format("%s - %s [%s - %s]", id, p.options.id, p.options.branch, p.options.version);
}
return pd;
}
/**
* Publishing point when a process dies.
*
* @param id
* @return
*/
public String publishTerminated(String id) {
log.info("publishTerminated - terminated {} - restarting", id);
if (!processes.containsKey(id)) {
log.error("processes {} not found");
return id;
}
// if you don't fork with Agent allowed to
// exist without instances - then
if (!globalOptions.fork) {
// spin through instances - if I'm the only
// thing left - terminate
boolean processesStillRunning = false;
for (ProcessData pd : processes.values()) {
if (pd.isRunning() || pd.isRestarting()) {
processesStillRunning = true;
break;
}
}
if (!processesStillRunning) {
shutdown();
}
}
if (agent != null) {
agent.broadcastState();
}
return id;
}
public Process spawn(CmdOptions inOptions) throws IOException, URISyntaxException, InterruptedException, IllegalArgumentException, IllegalAccessException {
if (ProcessData.agent == null) {
ProcessData.agent = this;
}
// create a ProcessData then spawn it !
ProcessData pd = new ProcessData();
pd.options = new CmdOptions(inOptions);
CmdOptions options = pd.options;
if (options.id == null) {
options.id = NameGenerator.getName();
}
if (options.branch == null) {
options.branch = Platform.getLocalInstance().getBranch();
}
if (options.version == null) {
try {
options.version = getLatestVersion(options.branch, autoUpdate);
} catch (Exception e) {
log.error("getDir threw", e);
}
}
pd.jarPath = new File(getJarName(options.branch, options.version)).getAbsolutePath();
// javaExe
String fs = File.separator;
Platform platform = Platform.getLocalInstance();
String exeName = platform.isWindows() ? "javaw" : "java";
pd.javaExe = String.format("%s%sbin%s%s", System.getProperty("java.home"), fs, fs, exeName);
String jvmArgs = String.format("-Djava.library.path=%s/native -Djna.library.path=%s/native -Dfile.encoding=UTF-8", pd.options.libraries, pd.options.libraries);
if (platform.isWindows()) {
jvmArgs = jvmArgs.replace("/", "\\");
}
if (pd.options.memory != null) {
jvmArgs += String.format(" -Xms%s -Xmx%s ", pd.options.memory, pd.options.memory);
}
pd.jvm = jvmArgs.split(" ");
// user override
if (options.jvm != null) {
pd.jvm = options.jvm.split(" ");
}
if (options.services.size() == 0) {
options.services.add("log");
options.services.add("Log");
options.services.add("cli");
options.services.add("Cli");
options.services.add("gui");
options.services.add("SwingGui");
options.services.add("python");
options.services.add("Python");
}
return spawn(pd);
}
public String setBranch(String branch) {
currentBranch = branch;
return currentBranch;
}
static public Map<String, String> setEnv(ProcessData pd, Map<String, String> env) {
Platform platform = Platform.getLocalInstance();
String platformId = platform.getPlatformId();
if (platform.isLinux()) {
File f = new File(pd.options.libraries);
String ldPath = String.format("%s/native:%s/native/%s:${LD_LIBRARY_PATH}", pd.options.libraries, pd.options.libraries, platformId);
// String ldPath = String.format("'pwd'/libraries/native:'pwd'/libraries/native/%s:${LD_LIBRARY_PATH}", platformId);
env.put("LD_LIBRARY_PATH", ldPath);
} else if (platform.isMac()) {
// String dyPath = String.format("'pwd'/libraries/native:'pwd'/libraries/native/%s:${DYLD_LIBRARY_PATH}", platformId);
String dyPath = String.format("%s/native:%s/native/%s:${DYLD_LIBRARY_PATH}", pd.options.libraries, pd.options.libraries, platformId);
env.put("DYLD_LIBRARY_PATH", dyPath);
} else if (platform.isWindows()) {
// this just borks the path in Windows - additionally (unlike Linux)
// - i don't think you need native code on the PATH
// and Windows does not have a LD_LIBRARY_PATH
// String path =
// String.format("PATH=%%CD%%\\libraries\\native;PATH=%%CD%%\\libraries\\native\\%s;%%PATH%%",
// platformId);
// env.put("PATH", path);
// we need to sanitize against a non-ascii username
// work around for Jython bug in 2.7.0...
env.put("APPDATA", "%%CD%%");
} else {
log.error("unkown operating system");
}
return env;
}
/**
* Kills all connected processes, then shuts down itself. FIXME - should send
* shutdown to other processes instead of killing them
*/
public void shutdown() {
log.info("terminating others");
killAll();
log.info("terminating self ... goodbye...");
Runtime.shutdown();
}
/**
* Constructs a command line from a ProcessData object which can directly be
* run to spawn a new instance of mrl
*
* FIXME is this ProcessData.toString()
*
* @param pd
* @return
*/
public String[] buildCmdLine(ProcessData pd) {
// command line to be returned
List<String> cmd = new ArrayList<String>();
cmd.add(pd.javaExe);
if (pd.jvm != null) {
for (int i = 0; i < pd.jvm.length; ++i) {
cmd.add(pd.jvm[i]);
}
}
cmd.add("-cp");
// step 1 - get current env data
Platform platform = Platform.getLocalInstance();
File f = new File(pd.options.libraries);
String libraries = f.getAbsolutePath();
/**
* The final spawn - all other data types as parameters make a ProcesData
* which is used by this method to start the process.
*
* @param pd
* @return
* @throws IOException
*/
public synchronized Process spawn(ProcessData pd) throws IOException {
log.info("============== spawn begin ==============");
// this needs cmdLine
String[] cmdLine = buildCmdLine(pd);
ProcessBuilder builder = new ProcessBuilder(cmdLine);
// handle stderr as a direct pass through to System.err
builder.redirectErrorStream(true);
// setting working directory to wherever the jar is...
String spawnDir = new File(pd.jarPath).getParent();
builder.directory(new File(spawnDir));
log.info("cd {}", spawnDir);
StringBuilder spawning = new StringBuilder();
for (String c : cmdLine) {
spawning.append(c);
spawning.append(" ");
}
log.info("SPAWNING ! --> [{}]", spawning);
// environment variables setup
setEnv(pd, builder.environment());
Process process = builder.start();
pd.process = process;
pd.startTs = System.currentTimeMillis();
pd.monitor = new ProcessData.Monitor(pd);
pd.monitor.start();
pd.state = ProcessData.stateType.running;
if (pd.options.id == null) {
log.error("id cannot be null!");
}
if (processes.containsKey(pd.options.id)) {
if (agent != null) {
agent.info("restarting %s", pd.options.id);
}
} else {
if (agent != null) {
agent.info("starting new %s", pd.options.id);
}
processes.put(pd.options.id, pd);
}
log.info("Agent finished spawn {}", formatter.format(new Date()));
if (agent != null) {
Cli cli = Runtime.getCli();
cli.add(pd.options.id, process.getInputStream(), process.getOutputStream());
cli.attach(pd.options.id);
agent.broadcastState();
}
return process;
}
/**
* DEPRECATE ? spawn should do this checking ?
*
* @param id
* i
* @throws IOException
* e
* @throws URISyntaxException
* e
* @throws InterruptedException
* e
*
*/
public void start(String id) throws IOException, URISyntaxException, InterruptedException {
if (!processes.containsKey(id)) {
log.error("start process %s can not start - process does not exist", id);
return;
}
ProcessData p = processes.get(id);
if (p.isRunning()) {
log.warn("process %s already started", id);
return;
}
spawn(p);
}
/**
* This static method returns all the details of the class without it having
* to be constructed. It has description, categories, dependencies, and peer
* definitions.
*
* @return ServiceType - returns all the data
*
*/
static public ServiceType getMetaData() {
ServiceType meta = new ServiceType(Agent.class.getCanonicalName());
meta.addDescription("responsible for spawning a MRL process. Agent can also terminate, respawn and control the spawned process");
meta.addCategory("framework");
meta.setSponsor("GroG");
meta.setLicenseApache();
// meta.includeServiceInOneJar(true);
return meta;
}
/**
* First method JVM executes when myrobotlab.jar is in jar form.
*
* --agent "--logLevel DEBUG --service webgui WebGui"
*
* @param args
* args
*/
public static void main(String[] args) {
try {
globalOptions = new CmdOptions();
new CommandLine(globalOptions).parseArgs(args);
if (globalOptions.help) {
Runtime.mainHelp();
return;
}
List<String> agentArgs = new ArrayList<>();
if (globalOptions.agent != null) {
agentArgs.addAll(Arrays.asList(globalOptions.agent.split(" ")));
} else {
agentArgs.add("--id");
agentArgs.add("agent-" + NameGenerator.getName());
agentArgs.add("-s");
agentArgs.add("agent");
agentArgs.add("Agent");
agentArgs.add("cli");
agentArgs.add("Cli");
agentArgs.add("security");
agentArgs.add("Security");
agentArgs.add("--log-level");
agentArgs.add(globalOptions.logLevel);
// agentArgs.add("webgui"); FIXME - soon .. but not yet ...
// agentArgs.add("WebGui");
}
Process p = null;
if (!globalOptions.noBanner) {
System.out.println(banner);
System.out.println("");
}
log.info("user args {}", Arrays.toString(args));
log.info("agent args {}", Arrays.toString(agentArgs.toArray()));
Runtime.main(agentArgs.toArray(new String[agentArgs.size()]));
agent = (Agent) Runtime.getService("agent");
if (globalOptions.listVersions) {
System.out.println("available local versions");
for (String bv : agent.getLocalVersions()) {
System.out.println(bv);
}
agent.shutdown();
}
if ("".equals(globalOptions.version)) {
Map<String, String> manifest = Platform.getManifest();
System.out.println("manifest");
for (String name : manifest.keySet()) {
System.out.println(String.format("%s=%s", name, manifest.get(name)));
}
agent.shutdown();
}
Platform platform = Platform.getLocalInstance();
if (globalOptions.branch == null) {
globalOptions.branch = platform.getBranch();
}
if (globalOptions.version == null) {
globalOptions.version = platform.getVersion();
}
agent.setBranch(globalOptions.branch);
agent.setVersion(globalOptions.version);
// FIXME - have a list versions ... command line !!!
// FIXME - the most common use case is the version of the spawned instance
// if that is the case its needed to determine what is the "proposed"
// branch & version if no
// special command parameters were given
// FIXME HELP !!!! :D
// if (cmdline.containsKey("-h") || cmdline.containsKey("--help")) {
// // FIXME - add all possible command descriptions ..
// System.out.println(String.format("%s branch %s version %s",
// platform.getBranch(), platform.getPlatformId(),
// platform.getVersion()));
// return;
if (globalOptions.webgui != null) {
agent.startWebGui(globalOptions.webgui);
}
// the user set auto-update to true
if (globalOptions.autoUpdate) {
// options.fork = true;
// lets check and get the latest jar if there is new one
if (globalOptions.src == null) {
// get the latest from Jenkins
agent.getLatestJar(agent.getBranch());
} else {
// get the latest from GitHub
agent.getLatestSrc(agent.getBranch());
}
// the "latest" should have been downloaded
globalOptions.version = agent.getLatestLocalVersion(agent.getBranch());
}
// FIXME - use wsclient for remote access
if (globalOptions.client != null) {
Runtime.start("cli", "Cli");
return;
}
// TODO - build command line ...
// FIXME - if another instances is spawned agent should wait for all
// instances to stop
// list of flags we want to by-pass spawning
if (globalOptions.fork && globalOptions.services.size() > 0 || !globalOptions.fork) {
p = agent.spawn(globalOptions); // <-- agent's is now in charge of first
}
// we start a timer to process future updates
if (globalOptions.autoUpdate) {
// if you update a single process
// it kills it and restarts - and this will kill the
// agent unless its forked
globalOptions.fork = true;
agent.autoUpdate(true);
}
if (globalOptions.install != null) {
// wait for mrl instance to finish installing
// then shutdown (addendum: check if supporting other processes)
p.waitFor();
agent.shutdown();
// START AGAIN IF --install WAS SUPPLIED
if (globalOptions.autoUpdate) {
globalOptions.install = null;
p = agent.spawn(globalOptions);
}
}
} catch (Exception e) {
log.error("unsuccessful spawn", e);
}
}
public String getLatestSrc(String branch) throws WrongRepositoryStateException, InvalidConfigurationException, DetachedHeadException, InvalidRemoteException, CanceledException,
RefNotFoundException, NoHeadException, TransportException, IOException, GitAPIException {
Agent agent = (Agent) Runtime.getService("agent");
RevCommit latestCommit = agent.gitPull(branch);
if (latestCommit != null) {
log.info("latest {} - will attempt to build", latestCommit);
String version = agent.mvn(null, branch, (long) latestCommit.getCommitTime());
log.info("successfully build version {} - {}", latestCommit.getCommitTime(), latestCommit.getFullMessage());
return version;
}
return null;
}
public String getBranch() {
return currentBranch;
}
public String getVersion() {
return currentVersion;
}
public String setVersion(String version) {
currentVersion = version;
return version;
}
public String mvn(String branch) {
return mvn(null, branch, null);
}
// mvn -DskipTests -Dbuild.number=71 -DGitBranch=develop clean package -o
public String mvn(String src, String branch, Long buildNumber) {
try {
if (src == null) {
src = "data" + File.separator + branch + ".src";
}
if (buildNumber == null) {
// epoch minute build time number
buildNumber = System.currentTimeMillis() / 1000;
}
String version = versionPrefix + buildNumber;
Platform platform = Platform.getLocalInstance();
List<String> cmd = new ArrayList<>();
String pathToPom = src + File.separator + "pom.xml";
cmd.add((platform.isWindows()) ? "cmd" : "/bin/bash");
cmd.add((platform.isWindows()) ? "/c" : "-c");
// when you send a command to be interpreted by cmd or bash - you get more
// consistent results
// when you wrap the command in quotes - that's why we use a StringBuilder
StringBuilder sb = new StringBuilder();
sb.append((platform.isWindows()) ? "mvn" : "mvn"); // huh .. thought it
// was
sb.append(" "); // mvn.bat
sb.append("-DskipTests");
sb.append(" ");
sb.append("-Dbuild.number=" + buildNumber);
sb.append(" ");
sb.append("-DGitBranch=" + branch);
sb.append(" ");
sb.append("compile");
sb.append(" ");
sb.append("prepare-package");
sb.append(" ");
sb.append("package");
sb.append(" ");
// cmd.add("-f");
// cmd.add(pathToPom);
// cmd.add("-o"); // offline
// cmd.add("\"" + sb.toString() + "\"");
cmd.add(sb.toString());
StringBuilder sb1 = new StringBuilder();
for (String c : cmd) {
sb1.append(c);
sb1.append(" ");
}
// src path ..
log.info("build [{}]", sb1);
// ProcessBuilder pb = new
// ProcessBuilder("mvn","exec:java","-Dexec.mainClass="+"FunnyClass");
ProcessBuilder pb = new ProcessBuilder(cmd);
Map<String, String> envs = pb.environment();
log.info("PATH={}",envs.get("PATH"));
pb.directory(new File(src));
// handle stderr as a direct pass through to System.err
pb.redirectErrorStream(true);
// pb.environment().putAll(System.getenv());
pb.inheritIO().start().waitFor();
// FIXME LOOK FOR --> "BUILD FAILURE"
String newJar = src + File.separator + "target" + File.separator + "myrobotlab.jar";
String newJarLoc = getJarName(branch, version);
File p = new File(newJarLoc).getAbsoluteFile().getParentFile();
p.mkdirs();
Files.copy(Paths.get(newJar), Paths.get(newJarLoc), StandardCopyOption.REPLACE_EXISTING);
return versionPrefix + buildNumber + "";
} catch (Exception e) {
log.error("mvn threw ", e);
}
return null;
}
public RevCommit gitPull(String branch) throws WrongRepositoryStateException, InvalidConfigurationException, DetachedHeadException, InvalidRemoteException, CanceledException,
RefNotFoundException, NoHeadException, TransportException, IOException, GitAPIException {
return gitPull(null, branch);
}
public RevCommit gitPull(String src, String branch) throws IOException, WrongRepositoryStateException, InvalidConfigurationException, DetachedHeadException,
InvalidRemoteException, CanceledException, RefNotFoundException, NoHeadException, TransportException, GitAPIException {
if (branch == null) {
branch = currentBranch;
}
if (src == null) {
src = "data" + File.separator + branch + ".src";
}
List<String> branches = new ArrayList<String>();
branches.add("refs/heads/" + branch);
File repoParentFolder = new File(src);
Git git = null;
TextProgressMonitor textmonitor = new TextProgressMonitor(new PrintWriter(System.out));
Repository repo = null;
if (!repoParentFolder.exists()) {
// String branch = "master";
git = Git.cloneRepository().setProgressMonitor(textmonitor).setURI("https://github.com/MyRobotLab/myrobotlab.git").setDirectory(new File(src)).setBranchesToClone(branches)
.setBranch("refs/heads/" + branch).call();
} else {
// Open an existing repository
String gitDir = repoParentFolder.getAbsolutePath() + "/.git";
repo = new FileRepositoryBuilder().setGitDir(new File(gitDir)).build();
git = new Git(repo);
}
repo = git.getRepository();
/**
* <pre>
* CheckoutCommand checkout = git.checkout().setCreateBranch(true).setName(branch).setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK).setStartPoint("origin/" + branch)
* .call();
* </pre>
*/
// git.pull().setCredentialsProvider(user).call();
// FIXME if currentBranch != branch - then checkout .. set current branch
if (!branch.equals(currentBranch)) {
git.branchCreate().setForce(true).setName(branch).setStartPoint("origin/" + branch).call();
git.checkout().setName(branch).call();
}
// FIXME - if auto-update or auto-fetch ie .. remote allowed and cache
// remote changes
git.fetch().setProgressMonitor(new TextProgressMonitor(new PrintWriter(System.out))).call();
List<RevCommit> localLogs = getLogs(git, "origin/" + branch, 1);
List<RevCommit> remoteLogs = getLogs(git, "remotes/origin/" + branch, 1);
RevCommit localCommit = localLogs.get(0);
RevCommit remoteCommit = remoteLogs.get(0);
BranchTrackingStatus status = BranchTrackingStatus.of(repo, branch);
// if (localCommit.getCommitTime() < remoteCommit.getCommitTime()) {
if (status.getBehindCount() > 0) {
log.info("local ts {}, remote {} - {} updating", localCommit.getCommitTime(), remoteCommit.getCommitTime(), remoteCommit.getFullMessage());
PullCommand pullCmd = git.pull();
pullCmd.setProgressMonitor(textmonitor);
pullCmd.call();
return remoteCommit;
} else {
log.info("no new commits on branch {}", branch);
}
return null;
}
private List<RevCommit> getLogs(Git git, String ref, int maxCount)
throws RevisionSyntaxException, NoHeadException, MissingObjectException, IncorrectObjectTypeException, AmbiguousObjectException, GitAPIException, IOException {
List<RevCommit> ret = new ArrayList<>();
Repository repository = git.getRepository();
Iterable<RevCommit> logs = git.log().setMaxCount(maxCount).add(repository.resolve(ref)).call();
for (RevCommit rev : logs) {
ret.add(rev);
}
return ret;
}
// FIXME - move to enums for status level !
public void updateLog(String level, String msg) {
if (updateLog.size() > 100) {
updateLog.remove(updateLog.size() - 1);
}
if ("info".equals(level)) {
updateLog.add(Status.info((new Date()).toString() + " " + msg));
} else if ("error".equals(level)) {
updateLog.add(Status.error((new Date()).toString() + " " + msg));
}
}
}
|
package com.cube.storm;
import android.content.Context;
import android.net.Uri;
import com.cube.storm.language.data.Language;
import com.cube.storm.language.lib.manager.LanguageManager;
import com.cube.storm.util.lib.resolver.AssetsResolver;
import com.cube.storm.util.lib.resolver.FileResolver;
import com.cube.storm.util.lib.resolver.Resolver;
import java.util.LinkedHashMap;
import java.util.Map;
import lombok.Getter;
/**
* This is the entry point class of the library. To enable the use of the library, you must instantiate
* a new {@link com.cube.storm.LanguageSettings.Builder} object in your {@link android.app.Application} singleton class.
*
* This class should not be directly instantiated.
*
* @author Callum Taylor
* @project StormLanguage
*/
public class LanguageSettings
{
/**
* The singleton instance of the settings
*/
private static LanguageSettings instance;
public static LanguageSettings getInstance()
{
if (instance == null)
{
throw new IllegalAccessError("You must build the language settings object first using LanguageSettings$Builder");
}
return instance;
}
/**
* Default private constructor
*/
private LanguageSettings(){}
/**
* Language manager used to resolve
*/
@Getter private LanguageManager languageManager;
/**
* Uri resolver used to load a file based on it's protocol.
*/
@Getter private Map<String, Resolver> uriResolvers = new LinkedHashMap<String, Resolver>(2);
/**
* Default loaded language. This will default to what ever the device's locale currently is
*/
@Getter private Language defaultLanguage;
/**
* The fallback language to use if a key wasn't found in the default language, or if the default
* language was not loaded
*/
@Getter private Language fallbackLanguage;
/**
* The builder class for {@link com.cube.storm.LanguageSettings}. Use this to create a new {@link com.cube.storm.LanguageSettings} instance
* with the customised properties specific for your project.
*
* Call {@link #build()} to build the settings object.
*/
public static class Builder
{
/**
* The temporary instance of the {@link com.cube.storm.LanguageSettings} object.
*/
private LanguageSettings construct;
/**
* The context of the builder
*/
private Context context;
/**
* Temporary language Uris. Gets loaded when {@link #build()} is called
*/
private Uri defaultLanguage, fallbackLanguage;
/**
* Default constructor
*/
public Builder(Context context)
{
this.construct = new LanguageSettings();
this.context = context.getApplicationContext();
languageManager(LanguageManager.getInstance());
registerUriResolver("file", new FileResolver());
registerUriResolver("assets", new AssetsResolver(this.context));
defaultLanguage(Uri.parse("assets://languages/" + LanguageManager.getInstance().getLocale(context) + ".json"));
}
/**
* Sets the default language manager
*
* @param manager The language manager
*
* @return The {@link com.cube.storm.LanguageSettings.Builder} instance for chaining
*/
public Builder languageManager(LanguageManager manager)
{
construct.languageManager = manager;
return this;
}
/**
* Sets the default language uri to load
*
* @param languageUri The language Uri
*
* @return The {@link com.cube.storm.LanguageSettings.Builder} instance for chaining
*/
public Builder defaultLanguage(Uri languageUri)
{
this.defaultLanguage = languageUri;
return this;
}
/**
* Sets the fallback language uri to load
*
* @param languageUri The language Uri
*
* @return The {@link com.cube.storm.LanguageSettings.Builder} instance for chaining
*/
public Builder fallbackLanguage(Uri languageUri)
{
this.fallbackLanguage = languageUri;
return this;
}
/**
* Registers a uri resolver to use
*
* @param protocol The string protocol to register
* @param resolver The resolver to use for the registered protocol
*
* @return The {@link com.cube.storm.LanguageSettings.Builder} instance for chaining
*/
public Builder registerUriResolver(String protocol, Resolver resolver)
{
construct.uriResolvers.put(protocol, resolver);
return this;
}
/**
* Builds the final settings object and sets its instance. Use {@link #getInstance()} to retrieve the settings
* instance.
*
* The languages set by {@link #defaultLanguage(android.net.Uri)} and {@link #fallbackLanguage(android.net.Uri)} are
* loaded at this point.
*
* @return The newly set {@link com.cube.storm.LanguageSettings} instance
*/
public LanguageSettings build()
{
LanguageSettings.instance = construct;
construct.defaultLanguage = LanguageManager.getInstance().loadLanguage(context, defaultLanguage);
if (construct.fallbackLanguage != null)
{
construct.fallbackLanguage = LanguageManager.getInstance().loadLanguage(context, fallbackLanguage);
}
return LanguageSettings.instance;
}
}
}
|
package org.roi.itlab.cassandra;
import com.graphhopper.util.DistanceCalcEarth;
import org.apache.commons.math3.random.RandomGenerator;
import org.roi.itlab.cassandra.person.Person;
import org.roi.itlab.cassandra.random_attributes.IntensityNormalGenerator;
import org.roi.itlab.cassandra.random_attributes.NormalGenerator;
import org.roi.itlab.cassandra.random_attributes.PersonGenerator;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class City {
private static final String INTENSITY_FILENAME = "./target/intensity_map";
private static final String EDGES_FILENAME = "./target/edges_storage";
private static final int PREVIOUS_YEARS = 5;
private AccidentRate accidentRate;
private List<Person> drivers;
public City(int size, RandomGenerator rng) throws IOException, ClassNotFoundException {
PersonGenerator personGenerator = new PersonGenerator(rng);
//drivers = IntStream.range(0, size).parallel().mapToObj(i -> personGenerator.getResult()).collect(Collectors.toList());
drivers = IntStream.range(0, size).mapToObj(i -> personGenerator.getResult()).collect(Collectors.toList());
IntensityMap intensityMap = new IntensityMap();
Routing.loadEdgesStorage(EDGES_FILENAME);
intensityMap.load(INTENSITY_FILENAME);
accidentRate = new AccidentRate(intensityMap, rng);
}
public void simulate() {
drivers.parallelStream().forEach(person -> {
int previousAccidents = accidentRate.calculateAccidents(person, PREVIOUS_YEARS * 365);
int accidents = accidentRate.calculateAccidents(person, 365);
person.setAccidents(accidents);
person.setPreviousAccidents(previousAccidents);
});
}
public void save(String filename, int size) throws IOException {
Path path = FileSystems.getDefault().getPath(filename);
Files.deleteIfExists(path);
Files.createFile(path);
try (
OutputStream out = Files.newOutputStream(path, StandardOpenOption.WRITE);
OutputStreamWriter writer = new OutputStreamWriter(out, Charset.defaultCharset());) {
writer.write("Age,Experience,Skill,RushFactor,WorkStart,WorkDuration,WorkEnd,HomeLat,HomeLng,WorkLat,WorkLng,Distance,RouteDistance,PreviousAccidents,Probability,Accidents" + '\n');
DistanceCalcEarth earth = new DistanceCalcEarth();
for (int i = 0; i < size; i++) {
Person person = drivers.get(i);
double distance = earth.calcDist(person.getHome().getLatitude(), person.getHome().getLongitude(), person.getWork().getLatitude(), person.getWork().getLongitude());
writer.write(person.getAge() + "," + String.format(Locale.ROOT, "%.1f", person.getExperience()) + "," + String.format(Locale.ROOT, "%.3f", person.getSkill()) + "," + String.format(Locale.ROOT, "%.3f", person.getRushFactor()) + "," + person.getWorkStart().getHour() + "," + person.getWorkDuration().getHour() + "," + person.getWorkEnd().getHour() + "," + String.format(Locale.ROOT, "%.4f", person.getHome().getLatitude()) + "," + String.format(Locale.ROOT, "%.4f", person.getHome().getLongitude()) + "," + String.format(Locale.ROOT, "%.4f", person.getWork().getLatitude()) + "," + String.format(Locale.ROOT, "%.4f", person.getWork().getLongitude()) + "," + String.format(Locale.ROOT, "%.3f", distance) + "," + String.format(Locale.ROOT, "%.3f", person.getToWork().getDistance() + person.getToHome().getDistance()) + "," + person.getPreviousAccidents() + "," + String.format(Locale.ROOT, "%.6f", person.getProbability()) + "," + person.getAccidents() + '\n');
}
}
}
public void saveRoutes(String filename, int size) throws IOException {
Path path = FileSystems.getDefault().getPath(filename);
Files.deleteIfExists(path);
Files.createFile(path);
try (
OutputStream out = Files.newOutputStream(path, StandardOpenOption.WRITE);
OutputStreamWriter writer = new OutputStreamWriter(out, Charset.defaultCharset());) {
for (int i = 0; i < size; i++) {
Person person = drivers.get(i);
writer.write(person.getToWork().edgeIds() + ',' + person.getToHome().edgeIds() + '\n');
}
}
}
public void simulateAlter() {
drivers.stream().forEach(person -> {
int previousAccidents = accidentRate.calculateAccidentsAlter(person, PREVIOUS_YEARS * 365);
int accidents = accidentRate.calculateAccidents(person, 365);
person.setAccidents(accidents);
person.setPreviousAccidents(previousAccidents);
});
}
public void saveAlter(String filename, int size) throws IOException {
Path path = FileSystems.getDefault().getPath(filename);
Files.deleteIfExists(path);
Files.createFile(path);
try (
OutputStream out = Files.newOutputStream(path, StandardOpenOption.WRITE);
OutputStreamWriter writer = new OutputStreamWriter(out, Charset.defaultCharset());) {
writer.write("Age,Experience,Skill,RushFactor,TimeStartEdge,StartLat,StartLng,EndLat,EndLng," +
"Distance,Accidents" + '\n');
for (int i = 0; i < size; i++) {
Person person = drivers.get(i);
printEdges(person, person.getToWork(), person.getWorkStart(), writer);
printEdges(person, person.getToHome(), person.getWorkEnd(), writer);
}
}
}
private void printEdges(Person person, Route route, LocalTime localTime, OutputStreamWriter writer) throws IOException{
Edge[] edges = route.getEdges();
long time = localTime.toSecondOfDay()* 1000;
for(Edge edge: edges){
int accident = 0;
if(person.isAccidentOnEdge(edge))
accident = 1;
writer.write(person.getAge() + "," + String.format(Locale.ROOT, "%.1f", person.getExperience()) + "," +
String.format(Locale.ROOT, "%.3f", person.getSkill()) + "," +
String.format(Locale.ROOT, "%.3f", person.getRushFactor()) + "," +
(int) (time / 1000 / 60 % (60 * 24))/60 + "," +
String.format(Locale.ROOT, "%.4f",edge.getStart().getLat()) + "," +
String.format(Locale.ROOT, "%.4f", edge.getStart().getLon()) + "," +
String.format(Locale.ROOT, "%.4f", edge.getEnd().getLat()) + "," +
String.format(Locale.ROOT, "%.4f", edge.getEnd().getLon()) + "," +
String.format(Locale.ROOT, "%.4f",edge.getDistance()) + "," +
accident + "\n"); //+ "," + person.getPreviousAccidents()
time += edge.getTime();
}
}
}
|
package com.fishercoder.solutions;
import com.fishercoder.common.classes.TreeNode;
import java.util.LinkedList;
import java.util.Queue;
public class _1302 {
public static class Solution1 {
public int deepestLeavesSum(TreeNode root) {
int depth = maxDepth(root);
return bfs(root, depth);
}
private int bfs(TreeNode root, int depth) {
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int currentLevel = 0;
int sum = 0;
while (!queue.isEmpty()) {
int size = queue.size();
currentLevel++;
for (int i = 0; i < size; i++) {
TreeNode currNode = queue.poll();
if (currentLevel == depth) {
sum += currNode.val;
}
if (currNode.left != null) {
queue.offer(currNode.left);
}
if (currNode.right != null) {
queue.offer(currNode.right);
}
}
}
return sum;
}
private int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}
}
public static class Solution2 {
public int deepestLeavesSum(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int sum = 0;
while (!queue.isEmpty()) {
int size = queue.size();
sum = 0;
for (int i = 0; i < size; i++) {
TreeNode curr = queue.poll();
sum += curr.val;
if (curr.left != null) {
queue.offer(curr.left);
}
if (curr.right != null) {
queue.offer(curr.right);
}
}
}
return sum;
}
}
}
|
package org.udger.parser;
import org.sqlite.SQLiteConfig;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.lang.ref.SoftReference;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.sql.*;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Main parser's class handles parser requests for user agent or IP.
*/
public class UdgerParser implements Closeable {
private static final Logger LOG = Logger.getLogger(UdgerParser.class.getName());
private static final String DB_FILENAME = "udgerdb_v3.dat";
private static final String UDGER_UA_DEV_BRAND_LIST_URL = "https://udger.com/resources/ua-list/devices-brand-detail?brand=";
private static final String ID_CRAWLER = "crawler";
private static final Pattern PAT_UNPERLIZE = Pattern.compile("^/?(.*?)/si$");
private static class ClientInfo {
private Integer clientId;
private Integer classId;
}
private static class IdRegString {
int id;
int wordId1;
int wordId2;
Pattern pattern;
}
private static WordDetector clientWordDetector;
private static WordDetector deviceWordDetector;
private static WordDetector osWordDetector;
private static List<IdRegString> clientRegstringList;
private static List<IdRegString> osRegstringList;
private static List<IdRegString> deviceRegstringList;
private Connection connection;
private String dbFileName = DB_FILENAME;
private final Map<String, SoftReference<Pattern>> regexCache = new ConcurrentHashMap<>();
private Matcher lastPatternMatcher;
private Map<String, PreparedStatement> preparedStmtMap = new HashMap<>();
private LRUCache<String, UdgerUaResult> cache;
private boolean osParserEnabled = true;
private boolean deviceParserEnabled = true;
private boolean deviceBrandParserEnabled = true;
private boolean inMemoryEnabled = false;
/**
* Instantiates a new udger parser with LRU cache with capacity of 10.000 items
*
* @param dbFileName the udger database file name
*/
public UdgerParser(String dbFileName) {
this(dbFileName, 10000);
}
/**
* Instantiates a new udger parser. Parser must be prepared by prepare() method call before it is used.
*
* @param dbFileName the udger database file name
* @param cacheCapacity the LRU cache capacity
*/
public UdgerParser(String dbFileName, int cacheCapacity) {
this.dbFileName = dbFileName;
if (cacheCapacity > 0) {
cache = new LRUCache<>(cacheCapacity);
}
}
/**
* Instantiates a new udger parser with a in-memory SQLite DB if inMemoryEnabled is set to true.
*
* @param dbFileName the udger database file name
* @param inMemoryEnabled set true to enable in memory DB
* @param cacheCapacity the LRU cache capacity
*/
public UdgerParser(String dbFileName, boolean inMemoryEnabled, int cacheCapacity) {
this(dbFileName, cacheCapacity);
this.inMemoryEnabled = inMemoryEnabled;
}
@Override
public void close() throws IOException {
try {
for (PreparedStatement preparedStmt : preparedStmtMap.values()) {
preparedStmt.close();
}
preparedStmtMap.clear();
if (connection != null && !connection.isClosed()) {
connection.close();
connection = null;
}
if (cache != null) {
cache.clear();
}
regexCache.clear();
} catch (SQLException e) {
throw new IOException(e.getMessage());
}
}
/**
* Returns true if the sqlite DB connection has not been closed and is still valid.
*
* @param timeoutMillis the timeout millis
* @return true, if is valid
* @throws IOException Signals that an I/O exception has occurred.
*/
public boolean isValid(int timeoutMillis) throws IOException {
try {
return connection == null || connection.isValid(timeoutMillis);
} catch (SQLException e) {
throw new IOException("Failed to validate connection within " + timeoutMillis + " millis.", e);
}
}
/**
* Parses the user agent string and stores results of parsing in UdgerUaResult.
* If the parser was initialized to use an in memory DB, then the DB is not set to read only.
* This does not matter since the connection is internal to this client, as such there are
* no chance of external modifications.
*
* @param uaString the user agent string
* @return the intance of UdgerUaResult storing results of parsing
* @throws SQLException the SQL exception
*/
public UdgerUaResult parseUa(String uaString) throws SQLException {
UdgerUaResult ret;
if (cache != null) {
ret = cache.get(uaString);
if (ret != null) {
return ret;
}
}
ret = new UdgerUaResult(uaString);
prepare();
ClientInfo clientInfo = clientDetector(uaString, ret);
if (osParserEnabled) {
osDetector(uaString, ret, clientInfo);
}
if (deviceParserEnabled) {
deviceDetector(uaString, ret, clientInfo);
}
if (deviceBrandParserEnabled) {
if (ret.getOsFamilyCode() != null && !ret.getOsFamilyCode().isEmpty()) {
fetchDeviceBrand(uaString, ret);
}
}
if (cache != null) {
cache.put(uaString, ret);
}
return ret;
}
/**
* Parses the IP string and stores results of parsing in UdgerIpResult.
*
* @param ipString the IP string
* @return the instance of UdgerIpResult storing results of parsing
* @throws SQLException the SQL exception
* @throws UnknownHostException the unknown host exception
*/
public UdgerIpResult parseIp(String ipString) throws SQLException, UnknownHostException {
UdgerIpResult ret = new UdgerIpResult(ipString);
InetAddress addr = InetAddress.getByName(ipString);
Long ipv4int = null;
String normalizedIp = null;
if (addr instanceof Inet4Address) {
ipv4int = 0L;
for (byte b : addr.getAddress()) {
ipv4int = ipv4int << 8 | (b & 0xFF);
}
normalizedIp = addr.getHostAddress();
} else if (addr instanceof Inet6Address) {
normalizedIp = addr.getHostAddress().replaceAll("((?:(?:^|:)0+\\b){2,}):?(?!\\S*\\b\\1:0+\\b)(\\S*)", "::$2");
}
ret.setIpClassification("Unrecognized");
ret.setIpClassificationCode("unrecognized");
if (normalizedIp != null) {
prepare();
try (ResultSet ipRs = getFirstRow(UdgerSqlQuery.SQL_IP, normalizedIp)) {
if (ipRs != null && ipRs.next()) {
fetchUdgerIp(ipRs, ret);
if (!ID_CRAWLER.equals(ret.getIpClassificationCode())) {
ret.setCrawlerFamilyInfoUrl("");
}
}
}
if (ipv4int != null) {
ret.setIpVer(4);
ResultSet dataCenterRs = getFirstRow(UdgerSqlQuery.SQL_DATACENTER, ipv4int, ipv4int);
fetchDataCenterAndCloseRs(dataCenterRs, ret);
} else {
ret.setIpVer(6);
int[] ipArray = ip6ToArray((Inet6Address) addr);
ResultSet dataCenterRs = getFirstRow(UdgerSqlQuery.SQL_DATACENTER_RANGE6,
ipArray[0], ipArray[0],
ipArray[1], ipArray[1],
ipArray[2], ipArray[2],
ipArray[3], ipArray[3],
ipArray[4], ipArray[4],
ipArray[5], ipArray[5],
ipArray[6], ipArray[6],
ipArray[7], ipArray[7]
);
fetchDataCenterAndCloseRs(dataCenterRs, ret);
}
}
return ret;
}
private void fetchDataCenterAndCloseRs(ResultSet dataCenterRs, UdgerIpResult ret) throws SQLException {
if (dataCenterRs != null) {
try {
if (dataCenterRs.next()) {
fetchDataCenter(dataCenterRs, ret);
}
} finally {
dataCenterRs.close();
}
}
}
/**
* Checks if is OS parser enabled. OS parser is enabled by default
*
* @return true, if is OS parser enabled
*/
public boolean isOsParserEnabled() {
return osParserEnabled;
}
/**
* Enable/disable the OS parser. OS parser is enabled by default. If enabled following fields
* of UdgerUaResult are processed by the OS parser:
* <ul>
* <li>osFamily, osFamilyCode, OS, osCode, osHomePage, osIcon, osIconBig</li>
* <li>osFamilyVendor, osFamilyVendorCode, osFamilyVedorHomepage, osInfoUrl</li>
* </ul>
* <p>
* If the OSs fields are not necessary then disabling this feature can increase
* the parser's performance.
*
* @param osParserEnabled the true if os parser is to be enabled
*/
public void setOsParserEnabled(boolean osParserEnabled) {
this.osParserEnabled = osParserEnabled;
}
/**
* Checks if is device parser enabled. Device parser is enabled by default
*
* @return true, if device parser is enabled
*/
public boolean isDeviceParserEnabled() {
return deviceParserEnabled;
}
/**
* Enable/disable the device parser. Device parser is enabled by default. If enabled following fields
* of UdgerUaResult are filled by the device parser:
* <ul>
* <li>deviceClass, deviceClassCode, deviceClassIcon</li>
* <li>deviceClassIconBig, deviceClassInfoUrl</li>
* </ul>
* <p>
* If the DEVICEs fields are not necessary then disabling this feature can increase
* the parser's performance.
*
* @param deviceParserEnabled the true if device parser is to be enabled
*/
public void setDeviceParserEnabled(boolean deviceParserEnabled) {
this.deviceParserEnabled = deviceParserEnabled;
}
/**
* Checks if is device brand parser enabled. Device brand parser is enabled by default.
*
* @return true, if device brand parser is enabled
*/
public boolean isDeviceBrandParserEnabled() {
return deviceBrandParserEnabled;
}
/**
* Enable/disable the device brand parser. Device brand parser is enabled by default. If enabled following fields
* of UdgerUaResult are filled by the device brand parser:
* <ul>
* <li>deviceMarketname, deviceBrand, deviceBrandCode, deviceBrandHomepage</li>
* <li>deviceBrandIcon, deviceBrandIconBig, deviceBrandInfoUrl</li>
* </ul>
* <p>
* If the BRANDs fields are not necessary then disabling this feature can increase
* the parser's performance.
*
* @param deviceBrandParserEnabled the true if device brand parser is to be enabled
*/
public void setDeviceBrandParserEnabled(boolean deviceBrandParserEnabled) {
this.deviceBrandParserEnabled = deviceBrandParserEnabled;
}
private static synchronized void initStaticStructures(Connection connection) throws SQLException {
if (clientRegstringList == null) {
clientRegstringList = prepareRegexpStruct(connection, "udger_client_regex");
osRegstringList = prepareRegexpStruct(connection, "udger_os_regex");
deviceRegstringList = prepareRegexpStruct(connection, "udger_deviceclass_regex");
clientWordDetector = createWordDetector(connection, "udger_client_regex", "udger_client_regex_words");
deviceWordDetector = createWordDetector(connection, "udger_deviceclass_regex", "udger_deviceclass_regex_words");
osWordDetector = createWordDetector(connection, "udger_os_regex", "udger_os_regex_words");
}
}
private static WordDetector createWordDetector(Connection connection, String regexTableName, String wordTableName) throws SQLException {
Set<Integer> usedWords = new HashSet<>();
addUsedWords(usedWords, connection, regexTableName, "word_id");
addUsedWords(usedWords, connection, regexTableName, "word2_id");
WordDetector result = new WordDetector();
try (final Statement statement = connection.createStatement();
final ResultSet rs = statement.executeQuery("SELECT * FROM " + wordTableName)) {
if (rs != null) {
while (rs.next()) {
int id = rs.getInt("id");
if (usedWords.contains(id)) {
String word = rs.getString("word").toLowerCase();
result.addWord(id, word);
}
}
}
}
return result;
}
private static void addUsedWords(Set<Integer> usedWords, Connection connection, String regexTableName, String wordIdColumn) throws SQLException {
try (Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("SELECT " + wordIdColumn + " FROM " + regexTableName)) {
if (rs != null) {
while (rs.next()) {
usedWords.add(rs.getInt(wordIdColumn));
}
}
}
}
private int findIdFromList(String uaString, Set<Integer> foundClientWords, List<IdRegString> list) {
lastPatternMatcher = null;
for (IdRegString irs : list) {
if ((irs.wordId1 == 0 || foundClientWords.contains(irs.wordId1)) &&
(irs.wordId2 == 0 || foundClientWords.contains(irs.wordId2))) {
Matcher matcher = irs.pattern.matcher(uaString);
if (matcher.find()) {
lastPatternMatcher = matcher;
return irs.id;
}
}
}
return -1;
}
private int findIdFromListFullScan(String uaString, List<IdRegString> list) {
lastPatternMatcher = null;
for (IdRegString irs : list) {
Matcher matcher = irs.pattern.matcher(uaString);
if (matcher.find()) {
lastPatternMatcher = matcher;
return irs.id;
}
}
return -1;
}
private static List<IdRegString> prepareRegexpStruct(Connection connection, String regexpTableName) throws SQLException {
List<IdRegString> ret = new ArrayList<>();
try (Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("SELECT rowid, regstring, word_id, word2_id FROM " + regexpTableName + " ORDER BY sequence")) {
if (rs != null) {
while (rs.next()) {
IdRegString irs = new IdRegString();
irs.id = rs.getInt("rowid");
irs.wordId1 = rs.getInt("word_id");
irs.wordId2 = rs.getInt("word2_id");
String regex = rs.getString("regstring");
Matcher m = PAT_UNPERLIZE.matcher(regex);
if (m.matches()) {
regex = m.group(1);
}
irs.pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
ret.add(irs);
}
}
}
return ret;
}
private ClientInfo clientDetector(String uaString, UdgerUaResult ret) throws SQLException {
ClientInfo clientInfo = new ClientInfo();
try (ResultSet userAgentRs1 = getFirstRow(UdgerSqlQuery.SQL_CRAWLER, uaString)) {
if (userAgentRs1 != null && userAgentRs1.next()) {
fetchUserAgent(userAgentRs1, ret);
clientInfo.classId = 99;
clientInfo.clientId = -1;
} else {
int rowid = findIdFromList(uaString, clientWordDetector.findWords(uaString), clientRegstringList);
if (rowid != -1) {
try (ResultSet userAgentRs2 = getFirstRow(UdgerSqlQuery.SQL_CLIENT, rowid)) {
if (userAgentRs2 != null && userAgentRs2.next()) {
fetchUserAgent(userAgentRs2, ret);
clientInfo.classId = ret.getClassId();
clientInfo.clientId = ret.getClientId();
patchVersions(ret);
}
}
} else {
ret.setUaClass("Unrecognized");
ret.setUaClassCode("unrecognized");
}
}
}
return clientInfo;
}
private void osDetector(String uaString, UdgerUaResult ret, ClientInfo clientInfo) throws SQLException {
int rowid = findIdFromList(uaString, osWordDetector.findWords(uaString), osRegstringList);
if (rowid != -1) {
try (ResultSet opSysRs = getFirstRow(UdgerSqlQuery.SQL_OS, rowid)) {
if (opSysRs != null && opSysRs.next()) {
fetchOperatingSystem(opSysRs, ret);
}
}
} else {
if (clientInfo.clientId != null && clientInfo.clientId != 0) {
try (ResultSet opSysRs = getFirstRow(UdgerSqlQuery.SQL_CLIENT_OS, clientInfo.clientId.toString())) {
if (opSysRs != null && opSysRs.next()) {
fetchOperatingSystem(opSysRs, ret);
}
}
}
}
}
private void deviceDetector(String uaString, UdgerUaResult ret, ClientInfo clientInfo) throws SQLException {
int rowid = findIdFromListFullScan(uaString, deviceRegstringList);
if (rowid != -1) {
try (ResultSet devRs = getFirstRow(UdgerSqlQuery.SQL_DEVICE, rowid)) {
if (devRs != null && devRs.next()) {
fetchDevice(devRs, ret);
}
}
} else {
if (clientInfo.classId != null && clientInfo.classId != -1) {
try (ResultSet devRs = getFirstRow(UdgerSqlQuery.SQL_CLIENT_CLASS, clientInfo.classId.toString())) {
if (devRs != null && devRs.next()) {
fetchDevice(devRs, ret);
}
}
}
}
}
private void fetchDeviceBrand(String uaString, UdgerUaResult ret) throws SQLException {
PreparedStatement preparedStatement = preparedStmtMap.get(UdgerSqlQuery.SQL_DEVICE_REGEX);
if (preparedStatement == null) {
preparedStatement = connection.prepareStatement(UdgerSqlQuery.SQL_DEVICE_REGEX);
preparedStmtMap.put(UdgerSqlQuery.SQL_DEVICE_REGEX, preparedStatement);
}
preparedStatement.setObject(1, ret.getOsFamilyCode());
preparedStatement.setObject(2, ret.getOsCode());
try (ResultSet devRegexRs = preparedStatement.executeQuery()) {
if (devRegexRs != null) {
while (devRegexRs.next()) {
String devId = devRegexRs.getString("id");
String regex = devRegexRs.getString("regstring");
if (devId != null && regex != null) {
Pattern patRegex = getRegexFromCache(regex);
Matcher matcher = patRegex.matcher(uaString);
if (matcher.find()) {
try (ResultSet devNameListRs = getFirstRow(UdgerSqlQuery.SQL_DEVICE_NAME_LIST, devId, matcher.group(1))) {
if (devNameListRs != null && devNameListRs.next()) {
ret.setDeviceMarketname(devNameListRs.getString("marketname"));
ret.setDeviceBrand(devNameListRs.getString("brand"));
ret.setDeviceBrandCode(devNameListRs.getString("brand_code"));
ret.setDeviceBrandHomepage(devNameListRs.getString("brand_url"));
ret.setDeviceBrandIcon(devNameListRs.getString("icon"));
ret.setDeviceBrandIconBig(devNameListRs.getString("icon_big"));
ret.setDeviceBrandInfoUrl(UDGER_UA_DEV_BRAND_LIST_URL + devNameListRs.getString("brand_code"));
break;
}
}
}
}
}
}
}
}
private int[] ip6ToArray(Inet6Address addr) {
int ret[] = new int[8];
byte[] bytes = addr.getAddress();
for (int i = 0; i < 8; i++) {
ret[i] = ((bytes[i * 2] << 8) & 0xff00) | (bytes[i * 2 + 1] & 0xff);
}
return ret;
}
private void prepare() throws SQLException {
connect();
if (clientRegstringList == null) {
initStaticStructures(connection);
}
}
private void connect() throws SQLException {
if (connection == null) {
SQLiteConfig config = new SQLiteConfig();
config.setReadOnly(true);
if (inMemoryEnabled) {
// we cannot use read only for in memory DB since we need to populate this DB from the file.
connection = DriverManager.getConnection("jdbc:sqlite::memory:");
File dbfile = new File(dbFileName);
try (Statement statement = connection.createStatement()) {
statement.executeUpdate("restore from " + dbfile.getPath());
} catch (Exception e) {
LOG.warning("Error re-constructing in memory data base from Db file " + dbfile);
}
} else {
connection = DriverManager.getConnection("jdbc:sqlite:" + dbFileName, config.toProperties());
}
}
}
private Pattern getRegexFromCache(String regex) {
SoftReference<Pattern> patRegex = regexCache.get(regex);
if (patRegex == null || patRegex.get() == null) {
Matcher m = PAT_UNPERLIZE.matcher(regex);
if (m.matches()) {
regex = m.group(1);
}
patRegex = new SoftReference<>(Pattern.compile(regex, Pattern.CASE_INSENSITIVE | Pattern.DOTALL));
regexCache.put(regex, patRegex);
}
return patRegex.get();
}
private ResultSet getFirstRow(String query, Object... params) throws SQLException {
PreparedStatement preparedStatement = preparedStmtMap.get(query);
if (preparedStatement == null) {
preparedStatement = connection.prepareStatement(query);
preparedStmtMap.put(query, preparedStatement);
}
for (int i = 0; i < params.length; i++) {
preparedStatement.setObject(i + 1, params[i]);
}
preparedStatement.setMaxRows(1);
return preparedStatement.executeQuery();
}
private void fetchUserAgent(ResultSet rs, UdgerUaResult ret) throws SQLException {
ret.setClassId(rs.getInt("class_id"));
ret.setClientId(rs.getInt("client_id"));
ret.setCrawlerCategory(nvl(rs.getString("crawler_category")));
ret.setCrawlerCategoryCode(nvl(rs.getString("crawler_category_code")));
ret.setCrawlerLastSeen(nvl(rs.getString("crawler_last_seen")));
ret.setCrawlerRespectRobotstxt(nvl(rs.getString("crawler_respect_robotstxt")));
ret.setUa(nvl(rs.getString("ua")));
ret.setUaClass(nvl(rs.getString("ua_class")));
ret.setUaClassCode(nvl(rs.getString("ua_class_code")));
ret.setUaEngine(nvl(rs.getString("ua_engine")));
ret.setUaFamily(nvl(rs.getString("ua_family")));
ret.setUaFamilyCode(nvl(rs.getString("ua_family_code")));
ret.setUaFamilyHomepage(nvl(rs.getString("ua_family_homepage")));
ret.setUaFamilyIcon(nvl(rs.getString("ua_family_icon")));
ret.setUaFamilyIconBig(nvl(rs.getString("ua_family_icon_big")));
ret.setUaFamilyInfoUrl(nvl(rs.getString("ua_family_info_url")));
ret.setUaFamilyVendor(nvl(rs.getString("ua_family_vendor")));
ret.setUaFamilyVendorCode(nvl(rs.getString("ua_family_vendor_code")));
ret.setUaFamilyVendorHomepage(nvl(rs.getString("ua_family_vendor_homepage")));
ret.setUaUptodateCurrentVersion(nvl(rs.getString("ua_uptodate_current_version")));
ret.setUaVersion(nvl(rs.getString("ua_version")));
ret.setUaVersionMajor(nvl(rs.getString("ua_version_major")));
}
private void fetchOperatingSystem(ResultSet rs, UdgerUaResult ret) throws SQLException {
ret.setOsFamily(nvl(rs.getString("os_family")));
ret.setOs(nvl(rs.getString("os")));
ret.setOsCode(nvl(rs.getString("os_code")));
ret.setOsFamilyCode(nvl(rs.getString("os_family_code")));
ret.setOsFamilyVedorHomepage(nvl(rs.getString("os_family_vedor_homepage")));
ret.setOsFamilyVendor(nvl(rs.getString("os_family_vendor")));
ret.setOsFamilyVendorCode(nvl(rs.getString("os_family_vendor_code")));
ret.setOsHomePage(nvl(rs.getString("os_home_page")));
ret.setOsIcon(nvl(rs.getString("os_icon")));
ret.setOsIconBig(nvl(rs.getString("os_icon_big")));
ret.setOsInfoUrl(nvl(rs.getString("os_info_url")));
}
private void fetchDevice(ResultSet rs, UdgerUaResult ret) throws SQLException {
ret.setDeviceClass(nvl(rs.getString("device_class")));
ret.setDeviceClassCode(nvl(rs.getString("device_class_code")));
ret.setDeviceClassIcon(nvl(rs.getString("device_class_icon")));
ret.setDeviceClassIconBig(nvl(rs.getString("device_class_icon_big")));
ret.setDeviceClassInfoUrl(nvl(rs.getString("device_class_info_url")));
}
private void patchVersions(UdgerUaResult ret) {
if (lastPatternMatcher != null) {
String version = "";
if (lastPatternMatcher.groupCount() >= 1) {
version = lastPatternMatcher.group(1);
}
ret.setUaVersion(version);
ret.setUaVersionMajor(version.split("\\.")[0]);
ret.setUa((ret.getUa() != null ? ret.getUa() : "") + " " + version);
} else {
ret.setUaVersion("");
ret.setUaVersionMajor("");
}
}
private void fetchUdgerIp(ResultSet rs, UdgerIpResult ret) throws SQLException {
ret.setCrawlerCategory(nvl(rs.getString("crawler_category")));
ret.setCrawlerCategoryCode(nvl(rs.getString("crawler_category_code")));
ret.setCrawlerFamily(nvl(rs.getString("crawler_family")));
ret.setCrawlerFamilyCode(nvl(rs.getString("crawler_family_code")));
ret.setCrawlerFamilyHomepage(nvl(rs.getString("crawler_family_homepage")));
ret.setCrawlerFamilyIcon(nvl(rs.getString("crawler_family_icon")));
ret.setCrawlerFamilyInfoUrl(nvl(rs.getString("crawler_family_info_url")));
ret.setCrawlerFamilyVendor(nvl(rs.getString("crawler_family_vendor")));
ret.setCrawlerFamilyVendorCode(nvl(rs.getString("crawler_family_vendor_code")));
ret.setCrawlerFamilyVendorHomepage(nvl(rs.getString("crawler_family_vendor_homepage")));
ret.setCrawlerLastSeen(nvl(rs.getString("crawler_last_seen")));
ret.setCrawlerName(nvl(rs.getString("crawler_name")));
ret.setCrawlerRespectRobotstxt(nvl(rs.getString("crawler_respect_robotstxt")));
ret.setCrawlerVer(nvl(rs.getString("crawler_ver")));
ret.setCrawlerVerMajor(nvl(rs.getString("crawler_ver_major")));
ret.setIpCity(nvl(rs.getString("ip_city")));
ret.setIpClassification(nvl(rs.getString("ip_classification")));
ret.setIpClassificationCode(nvl(rs.getString("ip_classification_code")));
ret.setIpCountry(nvl(rs.getString("ip_country")));
ret.setIpCountryCode(nvl(rs.getString("ip_country_code")));
ret.setIpHostname(nvl(rs.getString("ip_hostname")));
ret.setIpLastSeen(nvl(rs.getString("ip_last_seen")));
}
private String nvl(String v) {
return v != null ? v : "";
}
private void fetchDataCenter(ResultSet rs, UdgerIpResult ret) throws SQLException {
ret.setDataCenterHomePage(nvl(rs.getString("datacenter_homepage")));
ret.setDataCenterName(nvl(rs.getString("datacenter_name")));
ret.setDataCenterNameCode(nvl(rs.getString("datacenter_name_code")));
}
}
|
package com.fishercoder.solutions;
import java.util.ArrayList;
import java.util.List;
public class _1314 {
public static class Solution1 {
public int[][] matrixBlockSum(int[][] mat, int K) {
int m = mat.length;
int n = mat[0].length;
int[][] answer = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
List<Integer> iRange = findRange(i, K, m);
List<Integer> jRange = findRange(j, K, n);
int sum = 0;
for (int ii = 0; ii < iRange.size(); ii++) {
for (int jj = 0; jj < jRange.size(); jj++) {
sum += mat[iRange.get(ii)][jRange.get(jj)];
}
}
answer[i][j] = sum;
}
}
return answer;
}
private List<Integer> findRange(int iOrJ, int k, int upper) {
int min = (iOrJ - k) < 0 ? 0 : (iOrJ - k);
int max = (iOrJ + k) >= upper ? (upper - 1) : (iOrJ + k);
List<Integer> range = new ArrayList<>();
for (int i = min; i <= max; i++) {
range.add(i);
}
return range;
}
}
}
|
package com.gmail.nossr50.skills;
import java.util.logging.Logger;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.getspout.spoutapi.SpoutManager;
import org.getspout.spoutapi.player.SpoutPlayer;
import com.gmail.nossr50.Leaderboard;
import com.gmail.nossr50.Users;
import com.gmail.nossr50.m;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.mcPermissions;
import com.gmail.nossr50.config.LoadProperties;
import com.gmail.nossr50.spout.SpoutStuff;
import com.gmail.nossr50.datatypes.AbilityType;
import com.gmail.nossr50.datatypes.PlayerProfile;
import com.gmail.nossr50.datatypes.PlayerStat;
import com.gmail.nossr50.datatypes.SkillType;
import com.gmail.nossr50.events.McMMOPlayerLevelUpEvent;
import com.gmail.nossr50.locale.mcLocale;
public class Skills
{
protected static final Logger log = Logger.getLogger("Minecraft");
public void updateSQLfromFile(Player player){
}
public static boolean cooldownOver(Player player, long oldTime, int cooldown){
long currentTime = System.currentTimeMillis();
if(currentTime - oldTime >= (cooldown * 1000)){
return true;
} else {
return false;
}
}
public boolean hasArrows(Player player){
for(ItemStack x : player.getInventory().getContents()){
if (x.getTypeId() == 262){
return true;
}
}
return false;
}
public void addArrows(Player player){
for(ItemStack x : player.getInventory().getContents()){
if (x.getTypeId() == 262){
x.setAmount(x.getAmount() + 1);
return;
}
}
}
public static int calculateTimeLeft(Player player, long deactivatedTimeStamp, int cooldown)
{
return (int) (((deactivatedTimeStamp + (cooldown * 1000)) - System.currentTimeMillis())/1000);
}
public static void watchCooldowns(Player player, PlayerProfile PP, long curTime){
if(!PP.getGreenTerraInformed() && curTime - (PP.getSkillDATS(AbilityType.GREEN_TERRA)*1000) >= (LoadProperties.greenTerraCooldown * 1000)){
PP.setGreenTerraInformed(true);
player.sendMessage(mcLocale.getString("Skills.YourGreenTerra"));
}
if(!PP.getTreeFellerInformed() && curTime - (PP.getSkillDATS(AbilityType.TREE_FELLER)*1000) >= (LoadProperties.treeFellerCooldown * 1000)){
PP.setTreeFellerInformed(true);
player.sendMessage(mcLocale.getString("Skills.YourTreeFeller"));
}
if(!PP.getSuperBreakerInformed() && curTime - (PP.getSkillDATS(AbilityType.SUPER_BREAKER)*1000) >= (LoadProperties.superBreakerCooldown * 1000)){
PP.setSuperBreakerInformed(true);
player.sendMessage(mcLocale.getString("Skills.YourSuperBreaker"));
}
if(!PP.getSerratedStrikesInformed() && curTime - (PP.getSkillDATS(AbilityType.SERRATED_STRIKES)*1000) >= (LoadProperties.serratedStrikeCooldown * 1000)){
PP.setSerratedStrikesInformed(true);
player.sendMessage(mcLocale.getString("Skills.YourSerratedStrikes"));
}
if(!PP.getBerserkInformed() && (curTime - (PP.getSkillDATS(AbilityType.BERSERK)*1000)) >= (LoadProperties.berserkCooldown * 1000)){
PP.setBerserkInformed(true);
player.sendMessage(mcLocale.getString("Skills.YourBerserk"));
}
if(!PP.getSkullSplitterInformed() && curTime - (PP.getSkillDATS(AbilityType.SKULL_SPLIITER)*1000) >= (LoadProperties.skullSplitterCooldown * 1000)){
PP.setSkullSplitterInformed(true);
player.sendMessage(mcLocale.getString("Skills.YourSkullSplitter"));
}
if(!PP.getGigaDrillBreakerInformed() && curTime - (PP.getSkillDATS(AbilityType.GIGA_DRILL_BREAKER)*1000) >= (LoadProperties.gigaDrillBreakerCooldown * 1000)){
PP.setGigaDrillBreakerInformed(true);
player.sendMessage(mcLocale.getString("Skills.YourGigaDrillBreaker"));
}
}
public static void hoeReadinessCheck(Player player)
{
if(LoadProperties.enableOnlyActivateWhenSneaking && !player.isSneaking())
return;
PlayerProfile PP = Users.getProfile(player);
if(mcPermissions.getInstance().herbalismAbility(player) && m.isHoe(player.getItemInHand()) && !PP.getHoePreparationMode()){
if(!PP.getGreenTerraMode() && !cooldownOver(player, (PP.getSkillDATS(AbilityType.GREEN_TERRA)*1000), LoadProperties.greenTerraCooldown)){
player.sendMessage(mcLocale.getString("Skills.TooTired")
+ChatColor.YELLOW+" ("+calculateTimeLeft(player, (PP.getSkillDATS(AbilityType.GREEN_TERRA)*1000), LoadProperties.greenTerraCooldown)+"s)");
return;
}
if(LoadProperties.enableAbilityMessages)
player.sendMessage(mcLocale.getString("Skills.ReadyHoe"));
PP.setHoePreparationATS(System.currentTimeMillis());
PP.setHoePreparationMode(true);
}
}
public static void monitorSkills(Player player, PlayerProfile PP, long curTime){
if(PP.getHoePreparationMode() && curTime - (PP.getHoePreparationATS()*1000) >= 4000){
PP.setHoePreparationMode(false);
player.sendMessage(mcLocale.getString("Skills.LowerHoe"));
}
if(PP.getAxePreparationMode() && curTime - (PP.getAxePreparationATS()*1000) >= 4000){
PP.setAxePreparationMode(false);
player.sendMessage(mcLocale.getString("Skills.LowerAxe"));
}
if(PP.getPickaxePreparationMode() && curTime - (PP.getPickaxePreparationATS()*1000) >= 4000){
PP.setPickaxePreparationMode(false);
player.sendMessage(mcLocale.getString("Skills.LowerPickAxe"));
}
if(PP.getSwordsPreparationMode() && curTime - (PP.getSwordsPreparationATS()*1000) >= 4000){
PP.setSwordsPreparationMode(false);
player.sendMessage(mcLocale.getString("Skills.LowerSword"));
}
if(PP.getFistsPreparationMode() && curTime - (PP.getFistsPreparationATS()*1000) >= 4000){
PP.setFistsPreparationMode(false);
player.sendMessage(mcLocale.getString("Skills.LowerFists"));
}
if(PP.getShovelPreparationMode() && curTime - (PP.getShovelPreparationATS()*1000) >= 4000){
PP.setShovelPreparationMode(false);
player.sendMessage(mcLocale.getString("Skills.LowerShovel"));
}
/*
* HERBALISM ABILITY
*/
if(mcPermissions.getInstance().herbalismAbility(player)){
if(PP.getGreenTerraMode() && (PP.getSkillDATS(AbilityType.GREEN_TERRA)*1000) <= curTime){
PP.setGreenTerraMode(false);
PP.setGreenTerraInformed(false);
player.sendMessage(mcLocale.getString("Skills.GreenTerraOff"));
}
}
/*
* AXES ABILITY
*/
if(mcPermissions.getInstance().axesAbility(player)){
if(PP.getSkullSplitterMode() && (PP.getSkillDATS(AbilityType.SKULL_SPLIITER)*1000) <= curTime){
PP.setSkullSplitterMode(false);
PP.setSkullSplitterInformed(false);
player.sendMessage(mcLocale.getString("Skills.SkullSplitterOff"));
}
}
/*
* WOODCUTTING ABILITY
*/
if(mcPermissions.getInstance().woodCuttingAbility(player)){
if(PP.getTreeFellerMode() && (PP.getSkillDATS(AbilityType.TREE_FELLER)*1000) <= curTime){
PP.setTreeFellerMode(false);
PP.setTreeFellerInformed(false);
player.sendMessage(mcLocale.getString("Skills.TreeFellerOff"));
}
}
/*
* MINING ABILITY
*/
if(mcPermissions.getInstance().miningAbility(player)){
if(PP.getSuperBreakerMode() && (PP.getSkillDATS(AbilityType.SUPER_BREAKER)*1000) <= curTime){
PP.setSuperBreakerMode(false);
PP.setSuperBreakerInformed(false);
player.sendMessage(mcLocale.getString("Skills.SuperBreakerOff"));
}
}
/*
* EXCAVATION ABILITY
*/
if(mcPermissions.getInstance().excavationAbility(player)){
if(PP.getGigaDrillBreakerMode() && (PP.getSkillDATS(AbilityType.GIGA_DRILL_BREAKER)*1000) <= curTime){
PP.setGigaDrillBreakerMode(false);
PP.setGigaDrillBreakerInformed(false);
player.sendMessage(mcLocale.getString("Skills.GigaDrillBreakerOff"));
}
}
/*
* SWORDS ABILITY
*/
if(mcPermissions.getInstance().swordsAbility(player)){
if(PP.getSerratedStrikesMode() && (PP.getSkillDATS(AbilityType.SERRATED_STRIKES)*1000) <= curTime){
PP.setSerratedStrikesMode(false);
PP.setSerratedStrikesInformed(false);
player.sendMessage(mcLocale.getString("Skills.SerratedStrikesOff"));
}
}
/*
* UNARMED ABILITY
*/
if(mcPermissions.getInstance().unarmedAbility(player)){
if(PP.getBerserkMode() && (PP.getSkillDATS(AbilityType.BERSERK)*1000) <= curTime){
PP.setBerserkMode(false);
PP.setBerserkInformed(false);
player.sendMessage(mcLocale.getString("Skills.BerserkOff"));
}
}
}
public static void abilityActivationCheck(Player player)
{
if(LoadProperties.enableOnlyActivateWhenSneaking && !player.isSneaking())
return;
PlayerProfile PP = Users.getProfile(player);
if(PP != null)
{
if(!PP.getAbilityUse() || PP.getSuperBreakerMode() || PP.getSerratedStrikesMode() || PP.getTreeFellerMode() || PP.getGreenTerraMode() || PP.getBerserkMode() || PP.getGigaDrillBreakerMode())
return;
if(mcPermissions.getInstance().miningAbility(player) && m.isMiningPick(player.getItemInHand()) && !PP.getPickaxePreparationMode())
{
if(!PP.getSuperBreakerMode() && !cooldownOver(player, (PP.getSkillDATS(AbilityType.SUPER_BREAKER)*1000), LoadProperties.superBreakerCooldown))
{
player.sendMessage(mcLocale.getString("Skills.TooTired")
+ChatColor.YELLOW+" ("+calculateTimeLeft(player, (PP.getSkillDATS(AbilityType.SUPER_BREAKER)*1000), LoadProperties.superBreakerCooldown)+"s)");
return;
}
if(LoadProperties.enableAbilityMessages)
player.sendMessage(mcLocale.getString("Skills.ReadyPickAxe"));
PP.setPickaxePreparationATS(System.currentTimeMillis());
PP.setPickaxePreparationMode(true);
}
if(mcPermissions.getInstance().excavationAbility(player) && m.isShovel(player.getItemInHand()) && !PP.getShovelPreparationMode())
{
if(!PP.getGigaDrillBreakerMode() && !cooldownOver(player, (PP.getSkillDATS(AbilityType.GIGA_DRILL_BREAKER)*1000), LoadProperties.gigaDrillBreakerCooldown))
{
player.sendMessage(mcLocale.getString("Skills.TooTired")
+ChatColor.YELLOW+" ("+calculateTimeLeft(player, (PP.getSkillDATS(AbilityType.GIGA_DRILL_BREAKER)*1000), LoadProperties.gigaDrillBreakerCooldown)+"s)");
return;
}
if(LoadProperties.enableAbilityMessages)
player.sendMessage(mcLocale.getString("Skills.ReadyShovel"));
PP.setShovelPreparationATS(System.currentTimeMillis());
PP.setShovelPreparationMode(true);
}
if(mcPermissions.getInstance().swordsAbility(player) && m.isSwords(player.getItemInHand()) && !PP.getSwordsPreparationMode())
{
if(!PP.getSerratedStrikesMode() && !cooldownOver(player, (PP.getSkillDATS(AbilityType.SERRATED_STRIKES)*1000), LoadProperties.serratedStrikeCooldown))
{
player.sendMessage(mcLocale.getString("Skills.TooTired")
+ChatColor.YELLOW+" ("+calculateTimeLeft(player, (PP.getSkillDATS(AbilityType.SERRATED_STRIKES)*1000), LoadProperties.serratedStrikeCooldown)+"s)");
return;
}
if(LoadProperties.enableAbilityMessages)
player.sendMessage(mcLocale.getString("Skills.ReadySword"));
PP.setSwordsPreparationATS(System.currentTimeMillis());
PP.setSwordsPreparationMode(true);
}
if(mcPermissions.getInstance().unarmedAbility(player) && player.getItemInHand().getTypeId() == 0 && !PP.getFistsPreparationMode())
{
if(!PP.getBerserkMode() && !cooldownOver(player, (PP.getSkillDATS(AbilityType.BERSERK)*1000), LoadProperties.berserkCooldown))
{
player.sendMessage(mcLocale.getString("Skills.TooTired")
+ChatColor.YELLOW+" ("+calculateTimeLeft(player, (PP.getSkillDATS(AbilityType.BERSERK)*1000), LoadProperties.berserkCooldown)+"s)");
return;
}
if(LoadProperties.enableAbilityMessages)
player.sendMessage(mcLocale.getString("Skills.ReadyFists"));
PP.setFistsPreparationATS(System.currentTimeMillis());
PP.setFistsPreparationMode(true);
}
if((mcPermissions.getInstance().axesAbility(player) || mcPermissions.getInstance().woodCuttingAbility(player)) && !PP.getAxePreparationMode())
{
if(m.isAxes(player.getItemInHand()))
{
if(LoadProperties.enableAbilityMessages)
player.sendMessage(mcLocale.getString("Skills.ReadyAxe"));
PP.setAxePreparationATS(System.currentTimeMillis());
PP.setAxePreparationMode(true);
}
}
}
}
public static void ProcessLeaderboardUpdate(SkillType skillType, Player player)
{
PlayerProfile PP = Users.getProfile(player);
PlayerStat ps = new PlayerStat();
if(skillType != SkillType.ALL)
ps.statVal = PP.getSkillLevel(skillType);
else
ps.statVal = m.getPowerLevel(player);
ps.name = player.getName();
Leaderboard.updateLeaderboard(ps, skillType);
}
public static void XpCheckSkill(SkillType skillType, Player player)
{
if(skillType == SkillType.ALL) {
XpCheckAll(player);
return;
}
PlayerProfile PP = Users.getProfile(player);
if(PP.getSkillXpLevel(skillType) >= PP.getXpToLevel(skillType))
{
int skillups = 0;
while(PP.getSkillXpLevel(skillType) >= PP.getXpToLevel(skillType))
{
if(getSkillMaxLevel(skillType) >= PP.getSkillLevel(skillType) + 1)
{
skillups++;
PP.removeXP(skillType, PP.getXpToLevel(skillType));
PP.skillUp(skillType, 1);
McMMOPlayerLevelUpEvent eventToFire = new McMMOPlayerLevelUpEvent(player, skillType);
Bukkit.getPluginManager().callEvent(eventToFire);
} else
{
PP.removeXP(skillType, PP.getXpToLevel(skillType));
}
}
if(!LoadProperties.useMySQL)
{
ProcessLeaderboardUpdate(skillType, player);
ProcessLeaderboardUpdate(SkillType.ALL, player);
}
String capitalized = m.getCapitalized(skillType.toString());
//Contrib stuff
if(LoadProperties.spoutEnabled && player instanceof SpoutPlayer)
{
SpoutPlayer sPlayer = SpoutManager.getPlayer(player);
if(sPlayer.isSpoutCraftEnabled())
{
SpoutStuff.levelUpNotification(skillType, sPlayer);
} else
{
player.sendMessage(mcLocale.getString("Skills."+capitalized+"Up", new Object[] {String.valueOf(skillups), PP.getSkillLevel(skillType)}));
}
}
else
player.sendMessage(mcLocale.getString("Skills."+capitalized+"Up", new Object[] {String.valueOf(skillups), PP.getSkillLevel(skillType)}));
}
if(LoadProperties.xpbar && LoadProperties.spoutEnabled)
{
SpoutPlayer sPlayer = SpoutManager.getPlayer(player);
if(sPlayer.isSpoutCraftEnabled())
{
SpoutStuff.updateXpBar(sPlayer);
}
}
}
public static void XpCheckAll(Player player)
{
for(SkillType x : SkillType.values())
{
//Don't want to do anything with this one
if(x == SkillType.ALL)
continue;
XpCheckSkill(x, player);
}
}
public static int getSkillMaxLevel(SkillType skillType) {
switch(skillType) {
case ACROBATICS:
return (LoadProperties.levelCapAcrobatics > 0) ? LoadProperties.levelCapAcrobatics : Integer.MAX_VALUE;
case ARCHERY:
return (LoadProperties.levelCapArchery > 0) ? LoadProperties.levelCapArchery : Integer.MAX_VALUE;
case AXES:
return (LoadProperties.levelCapAxes > 0) ? LoadProperties.levelCapAxes : Integer.MAX_VALUE;
case EXCAVATION:
return (LoadProperties.levelCapExcavation > 0) ? LoadProperties.levelCapExcavation : Integer.MAX_VALUE;
case FISHING:
return (LoadProperties.levelCapFishing > 0) ? LoadProperties.levelCapFishing : Integer.MAX_VALUE;
case HERBALISM:
return (LoadProperties.levelCapHerbalism > 0) ? LoadProperties.levelCapHerbalism : Integer.MAX_VALUE;
case MINING:
return (LoadProperties.levelCapMining > 0) ? LoadProperties.levelCapMining : Integer.MAX_VALUE;
case REPAIR:
return (LoadProperties.levelCapRepair > 0) ? LoadProperties.levelCapRepair : Integer.MAX_VALUE;
case SWORDS:
return (LoadProperties.levelCapSwords > 0) ? LoadProperties.levelCapSwords : Integer.MAX_VALUE;
case TAMING:
return (LoadProperties.levelCapTaming > 0) ? LoadProperties.levelCapTaming : Integer.MAX_VALUE;
case UNARMED:
return (LoadProperties.levelCapUnarmed > 0) ? LoadProperties.levelCapUnarmed : Integer.MAX_VALUE;
case WOODCUTTING:
return (LoadProperties.levelCapWoodcutting > 0) ? LoadProperties.levelCapWoodcutting : Integer.MAX_VALUE;
default:
return Integer.MAX_VALUE;
}
}
public static SkillType getSkillType(String skillName)
{
for(SkillType x : SkillType.values())
{
if(x.toString().equals(skillName.toUpperCase()))
return x;
}
return null;
}
public static boolean isSkill(String skillname){
skillname = skillname.toUpperCase();
for(SkillType x : SkillType.values())
{
if(x.toString().equals(skillname))
return true;
}
return false;
}
public static void arrowRetrievalCheck(Entity entity, mcMMO plugin)
{
if(plugin.misc.arrowTracker.containsKey(entity))
{
Integer x = 0;
while(x < plugin.misc.arrowTracker.get(entity))
{
m.mcDropItem(entity.getLocation(), 262);
x++;
}
}
plugin.misc.arrowTracker.remove(entity);
}
public static String getSkillStats(String skillname, Integer level, Integer XP, Integer XPToLevel)
{
ChatColor parColor = ChatColor.DARK_AQUA;
ChatColor xpColor = ChatColor.GRAY;
ChatColor LvlColor = ChatColor.GREEN;
ChatColor skillColor = ChatColor.YELLOW;
return skillColor+skillname+LvlColor+level+parColor+" XP"+"("+xpColor+XP+parColor+"/"+xpColor+XPToLevel+parColor+")";
}
public static boolean hasCombatSkills(Player player)
{
if(mcPermissions.getInstance().axes(player) || mcPermissions.getInstance().archery(player) || mcPermissions.getInstance().swords(player) || mcPermissions.getInstance().taming(player) || mcPermissions.getInstance().unarmed(player))
return true;
else
return false;
}
public static boolean hasGatheringSkills(Player player)
{
if(mcPermissions.getInstance().excavation(player) || mcPermissions.getInstance().herbalism(player) || mcPermissions.getInstance().mining(player) || mcPermissions.getInstance().woodcutting(player))
return true;
else
return false;
}
public static boolean hasMiscSkills(Player player)
{
if(mcPermissions.getInstance().acrobatics(player) || mcPermissions.getInstance().repair(player))
return true;
else
return false;
}
}
|
package se.kth.ansjobmarcular;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@SuppressWarnings("unchecked")
public class Keeper {
public static final int MAX_INDEX = 462;
private static Keeper[] keepers = new Keeper[MAX_INDEX];
private static List<Keeper>[] keepersM = (List<Keeper>[]) new List<?>[6];
private static Map<Keeper, Integer> indexes = new HashMap<Keeper, Integer>();
private byte count = 0;
private byte[] dice = new byte[6];
private Keeper() {
}
static {
for (int j = 0; j <keepersM.length; j++) {
keepersM[j] = new ArrayList<Keeper>(Hand.MAX_INDEX);
}
int i = 0;
for (byte a = 0; a <= 6; a++) {
for (byte b = a; b <= 6; b++) {
for (byte c = b; c <= 6; c++) {
for (byte d = c; d <= 6; d++) {
for (byte e = d; e <= 6; e++) {
Keeper k = new Keeper(a, b, c, d, e);
keepers[i] = k;
//Utils.debug("Generated keeper[%d]: %s\n", i, keepers[i]);
indexes.put(keepers[i], i);
keepersM[k.count].add(k);
i++;
}
}
}
}
}
}
public static List<Keeper> getKeepers(int cardinality) {
return keepersM[cardinality];
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + count;
result = prime * result + Arrays.hashCode(dice);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!(obj instanceof Keeper))
return false;
Keeper other = (Keeper) obj;
if (count != other.count)
return false;
if (!Arrays.equals(dice, other.dice))
return false;
return true;
}
public byte getMask(Hand hand) {
byte mask = 0;
byte[] h = hand.getDice();
byte local[] = Arrays.copyOf(dice, dice.length);
int i = 0;
int c = count;
int d = 0;
while (c > 0) {
/* Find the first die needed. */
while (local[d] == 0)
d++;
/* d is now the die needed. */
if (h[i] == (d+1)) {
mask |= (1 << (4-i));
c
local[d]
}
i++;
if (i == 5 && c > 0)
return -1;
}
return mask;
}
public Keeper add(int d) {
Keeper other = new Keeper();
other.count = (byte) (this.count + 1);
other.dice = Arrays.copyOf(this.dice, this.dice.length);
other.dice[d-1]++;
short idx = (short) other.getIndex();
other = null;
return Keeper.keepers[idx];
}
public int getCount() {
return count;
}
public byte[] getDice() {
return dice;
}
public int getIndex() {
return indexes.get(this);
}
public Hand getHand() {
if (count != 5) {
throw new IllegalArgumentException("Tried to do getHand when count was " + count);
}
byte[] hand = new byte[5];
byte c = count, i = 0, d = 1;
byte[] ldice = Arrays.copyOf(dice, dice.length);
while (c > 0) {
if (ldice[d-1] > 0) {
hand[i++] = (byte) (d);
ldice[d-1]
c
} else {
d++;
}
}
Hand h = new Hand(hand[0],hand[1], hand[2], hand[3], hand[4]);
short idx = (short) h.getIndex();
return Hand.getHand(idx);
}
public Keeper getKeeper(int index) {
return keepers[index];
}
public Keeper(Hand hand, int mask) {
byte[] tmp = hand.getDice();
for (byte i = 0; i < 5; i++) {
if ((mask & (1 << (4 - i))) != 0) {
dice[tmp[i]-1]++;
count++;
}
}
}
public Keeper(byte a, byte b, byte c, byte d, byte e) {
if (a != 0) {
count++;
dice[a-1]++;
}
if (b != 0) {
count++;
dice[b-1]++;
}
if (c != 0) {
count++;
dice[c-1]++;
}
if (d != 0) {
count++;
dice[d-1]++;
}
if (e != 0) {
count++;
dice[e-1]++;
}
}
@Override
public String toString() {
return Arrays.toString(dice);
}
}
|
package com.grosner.dbflow.sql;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;
import com.grosner.dbflow.ReflectionUtils;
import com.grosner.dbflow.config.FlowLog;
import com.grosner.dbflow.config.FlowManager;
import com.grosner.dbflow.converter.TypeConverter;
import com.grosner.dbflow.runtime.DBTransactionInfo;
import com.grosner.dbflow.runtime.TransactionManager;
import com.grosner.dbflow.runtime.observer.ModelObserver;
import com.grosner.dbflow.runtime.transaction.process.DeleteModelListTransaction;
import com.grosner.dbflow.runtime.transaction.process.ProcessModelInfo;
import com.grosner.dbflow.sql.builder.ConditionQueryBuilder;
import com.grosner.dbflow.sql.language.Select;
import com.grosner.dbflow.structure.Column;
import com.grosner.dbflow.structure.ForeignKeyReference;
import com.grosner.dbflow.structure.Model;
import com.grosner.dbflow.structure.StructureUtils;
import com.grosner.dbflow.structure.TableStructure;
import com.grosner.dbflow.structure.json.JSONModel;
import org.json.JSONObject;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
public class SqlUtils {
/**
* This marks the {@link #save(com.grosner.dbflow.config.FlowManager, com.grosner.dbflow.structure.Model, boolean, int)}
* operation as checking to see if the model exists before saving.
*/
public static final int SAVE_MODE_DEFAULT = 0;
/**
* This marks the {@link #save(com.grosner.dbflow.config.FlowManager, com.grosner.dbflow.structure.Model, boolean, int)}
* operation as updating only without checking for it to exist. This is when we know the data exists.
*/
public static final int SAVE_MODE_UPDATE = 1;
/**
* This marks the {@link #save(com.grosner.dbflow.config.FlowManager, com.grosner.dbflow.structure.Model, boolean, int)}
* operation as inserting only without checking for it to exist. This is for when we know the data is new.
*/
public static final int SAVE_MODE_INSERT = 2;
/**
* Queries the DB for a {@link android.database.Cursor} and converts it into a list.
*
* @param modelClass The class to construct the data from the DB into
* @param sql The SQL command to perform, must not be ; terminated.
* @param args You may include ?s in where clause in the query,
* which will be replaced by the values from selectionArgs. The
* values will be bound as Strings.
* @param <ModelClass> The class implements {@link com.grosner.dbflow.structure.Model}
* @return a list of {@link ModelClass}
*/
public static <ModelClass extends Model> List<ModelClass> queryList(Class<ModelClass> modelClass, String sql, String... args) {
FlowManager flowManager = FlowManager.getManagerForTable(modelClass);
Cursor cursor = flowManager.getWritableDatabase().rawQuery(sql, args);
List<ModelClass> list = convertToList(modelClass, cursor);
cursor.close();
return list;
}
/**
* Queries the DB and returns the first {@link com.grosner.dbflow.structure.Model} it finds. Note:
* this may return more than one object, but only will return the first item in the list.
*
* @param modelClass The class to construct the data from the DB into
* @param sql The SQL command to perform, must not be ; terminated.
* @param args You may include ?s in where clause in the query,
* which will be replaced by the values from selectionArgs. The
* values will be bound as Strings.
* @param <ModelClass> The class implements {@link com.grosner.dbflow.structure.Model}
* @return a single {@link ModelClass}
*/
public static <ModelClass extends Model> ModelClass querySingle(Class<ModelClass> modelClass, String sql, String... args) {
Cursor cursor = FlowManager.getManagerForTable(modelClass).getWritableDatabase().rawQuery(sql, args);
ModelClass retModel = convertToModel(false, modelClass, cursor);
cursor.close();
return retModel;
}
/**
* Checks whether the SQL query returns a {@link android.database.Cursor} with a count of at least 1. This
* means that the query was successful. It is commonly used when checking if a {@link com.grosner.dbflow.structure.Model} exists.
*
* @param flowManager The database manager that we run this query on
* @param sql The SQL command to perform, must not be ; terminated.
* @param args The optional string arguments when we use "?" in the sql
* @param <ModelClass> The class that implements {@link com.grosner.dbflow.structure.Model}
* @return
*/
public static <ModelClass extends Model> boolean hasData(Class<ModelClass> modelClass, String sql, String... args) {
FlowManager flowManager = FlowManager.getManagerForTable(modelClass);
Cursor cursor = flowManager.getWritableDatabase().rawQuery(sql, args);
boolean hasData = (cursor.getCount() > 0);
cursor.close();
return hasData;
}
/**
* Loops through a cursor and builds a list of {@link ModelClass} objects.
*
* @param table The model class that we convert the cursor data into.
* @param cursor The cursor from the DB
* @param <ModelClass>
* @return
*/
public static <ModelClass extends Model> List<ModelClass> convertToList(Class<ModelClass> table, Cursor cursor) {
final List<ModelClass> entities = new ArrayList<ModelClass>();
if (cursor.moveToFirst()) {
do {
entities.add(convertToModel(true, table, cursor));
}
while (cursor.moveToNext());
}
return entities;
}
/**
* Takes first {@link ModelClass} from the cursor
*
* @param isList If it's a list, do not reset the cursor
* @param table The model class that we convert the cursor data into.
* @param cursor The cursor from the DB
* @param <ModelClass>
* @return
*/
public static <ModelClass extends Model> ModelClass convertToModel(boolean isList, Class<ModelClass> table, Cursor cursor) {
ModelClass model = null;
try {
Constructor<ModelClass> entityConstructor = FlowManager.getManagerForTable(table).getStructure().getConstructorForModel(table);
if (isList || cursor.moveToFirst()) {
model = entityConstructor.newInstance();
model.load(cursor);
}
} catch (IllegalArgumentException i) {
throw new RuntimeException("Default constructor for: " + table.getName() + " was not found.");
} catch (NoSuchMethodException n) {
throw new RuntimeException("Default constructor for: " + table.getName() + " was not found.");
} catch (Exception e) {
FlowLog.log(FlowLog.Level.E, "Failed to process cursor.", e);
}
return model;
}
@SuppressWarnings("unchecked")
public static void putField(ContentValues values, FlowManager flowManager, Field field, String fieldName, Object value) {
Class<?> fieldType = field.getType();
// ignore foreign key conversions
if (value != null && !StructureUtils.isForeignKey(field)) {
final TypeConverter typeSerializer = flowManager.getTypeConverterForClass(fieldType);
if (typeSerializer != null) {
// serialize data
value = typeSerializer.getDBValue(value);
// set new object type
if (value != null) {
fieldType = value.getClass();
// check that the serializer returned what it promised
if (!fieldType.equals(typeSerializer.getDatabaseType())) {
FlowLog.log(FlowLog.Level.W, String.format(TypeConverter.class.getSimpleName() + " returned wrong type: expected a %s but got a %s",
typeSerializer.getDatabaseType(), fieldType));
}
}
}
}
// TODO: Find a smarter way to do this? This if block is necessary because we
// can't know the type until runtime.
if (value == null) {
values.putNull(fieldName);
} else if (fieldType.equals(Byte.class) || fieldType.equals(byte.class)) {
values.put(fieldName, (Byte) value);
} else if (fieldType.equals(Short.class) || fieldType.equals(short.class)) {
values.put(fieldName, (Short) value);
} else if (fieldType.equals(Integer.class) || fieldType.equals(int.class)) {
values.put(fieldName, (Integer) value);
} else if (fieldType.equals(Long.class) || fieldType.equals(long.class)) {
values.put(fieldName, (Long) value);
} else if (fieldType.equals(Float.class) || fieldType.equals(float.class)) {
values.put(fieldName, (Float) value);
} else if (fieldType.equals(Double.class) || fieldType.equals(double.class)) {
values.put(fieldName, (Double) value);
} else if (fieldType.equals(Boolean.class) || fieldType.equals(boolean.class)) {
values.put(fieldName, (Boolean) value);
} else if (fieldType.equals(Character.class) || fieldType.equals(char.class)) {
values.put(fieldName, value.toString());
} else if (fieldType.equals(String.class)) {
values.put(fieldName, value.toString());
} else if (fieldType.equals(Byte[].class) || fieldType.equals(byte[].class)) {
values.put(fieldName, (byte[]) value);
} else if (StructureUtils.isForeignKey(field) && ReflectionUtils.implementsModel(fieldType)) {
Column key = field.getAnnotation(Column.class);
Class<? extends Model> entityType = (Class<? extends Model>) fieldType;
// JSON backed model
if(value instanceof JSONObject) {
// save model first
JSONObject jsonObject = ((JSONObject) value);
JSONModel<? extends Model> jsonModel = new JSONModel<Model>(jsonObject, (Class<Model>) entityType);
jsonModel.save(false);
TableStructure tableStructure = flowManager.getStructure().getTableStructureForClass(entityType);
for (ForeignKeyReference foreignKeyReference : key.references()) {
Field foreignColumnField = tableStructure.getField(foreignKeyReference.foreignColumnName());
Object jsonValue = jsonObject.opt(foreignKeyReference.foreignColumnName());
field.setAccessible(true);
SqlUtils.putField(values, flowManager, foreignColumnField, foreignKeyReference.columnName(), jsonValue);
}
} else {
// save model first
try {
Model model = (Model) field.get(value);
model.save(false);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
TableStructure tableStructure = flowManager.getStructure().getTableStructureForClass(entityType);
for (ForeignKeyReference foreignKeyReference : key.references()) {
Field foreignColumnField = tableStructure.getField(foreignKeyReference.foreignColumnName());
foreignColumnField.setAccessible(true);
try {
putField(values, flowManager, foreignColumnField, foreignKeyReference.columnName(),
foreignColumnField.get(value));
} catch (IllegalAccessException e) {
FlowLog.logError(e);
}
}
}
} else if (ReflectionUtils.isSubclassOf(fieldType, Enum.class)) {
values.put(fieldName, ((Enum<?>) value).name());
}
}
/**
* Saves a model to the database.
*
* @param model The model to save
* @param async Whether it goes on the {@link com.grosner.dbflow.runtime.DBTransactionQueue} or done immediately.
* @param mode The save mode, can be {@link #SAVE_MODE_DEFAULT}, {@link #SAVE_MODE_INSERT}, {@link #SAVE_MODE_UPDATE}
* @param notify If we should notify all of our {@link com.grosner.dbflow.runtime.observer.ModelObserver}
* @param <ModelClass> The class that implements {@link com.grosner.dbflow.structure.Model}
*/
@SuppressWarnings("unchecked")
public static <ModelClass extends Model> void save(ModelClass model, boolean async, int mode, boolean notify) {
if (!async) {
FlowManager flowManager = FlowManager.getManagerForTable(model.getClass());
ConditionQueryBuilder<ModelClass> primaryConditionQueryBuilder =
flowManager.getStructure().getPrimaryWhereQuery((Class<ModelClass>) model.getClass());
final SQLiteDatabase db = flowManager.getWritableDatabase();
final ContentValues values = new ContentValues();
TableStructure<ModelClass> tableStructure = primaryConditionQueryBuilder.getTableStructure();
Set<Field> fields = tableStructure.getColumns();
for (Field field : fields) {
String fieldName = tableStructure.getColumnName(field);
field.setAccessible(true);
try {
putField(values, flowManager, field, fieldName, field.get(model));
} catch (IllegalArgumentException e) {
FlowLog.logError(e);
} catch (IllegalAccessException e) {
FlowLog.logError(e);
}
}
boolean exists = false;
if (mode == SAVE_MODE_DEFAULT) {
exists = exists(model);
} else if (mode == SAVE_MODE_UPDATE) {
exists = true;
}
if (exists) {
exists = (db.update(tableStructure.getTableName(), values,
ConditionQueryBuilder.getPrimaryModelWhere(primaryConditionQueryBuilder, model), null) != 0);
}
if (!exists) {
long id = db.insert(tableStructure.getTableName(), null, values);
Collection<Field> primaryFields = tableStructure.getPrimaryKeys();
for (Field field : primaryFields) {
if (StructureUtils.isPrimaryKeyAutoIncrement(field)) {
field.setAccessible(true);
try {
field.set(mode, id);
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
}
}
if (notify) {
// Notify any observers of this model change
FlowManager.getManagerForTable(model.getClass()).fireModelChanged(model, ModelObserver.Mode.fromData(mode, false));
}
} else {
TransactionManager.getInstance().save(ProcessModelInfo.withModels(model).info(DBTransactionInfo.create()));
}
}
/**
* Loads a {@link com.grosner.dbflow.structure.Model} from the DB cursor through reflection with the
* specified {@link com.grosner.dbflow.config.FlowManager}.
*
* @param model The model we load from the cursor
* @param cursor The cursor from the DB
* @param <ModelClass> The class that implements {@link com.grosner.dbflow.structure.Model}
*/
@SuppressWarnings("unchecked")
public static <ModelClass extends Model> void loadFromCursor(ModelClass model, Cursor cursor) {
TableStructure<ModelClass> tableStructure = FlowManager.getManagerForTable(model.getClass()).getTableStructureForClass((Class<ModelClass>) model.getClass());
Set<Field> fields = tableStructure.getColumns();
for (Field field : fields) {
try {
Object value = getModelValueFromCursor(cursor, tableStructure, field, tableStructure.getColumnName(field), field.getType());
// Set the field value
if (value != null) {
field.setAccessible(true);
field.set(model, value);
}
} catch (IllegalArgumentException e) {
FlowLog.logError(e);
} catch (IllegalAccessException e) {
FlowLog.logError(e);
} catch (SecurityException e) {
FlowLog.logError(e);
}
}
}
/**
* Converts the value from the database {@link android.database.Cursor} into the value that goes into a model from the
* specified {@link com.grosner.dbflow.structure.TableStructure} and {@link java.lang.reflect.Field}.
*
* @param cursor The cursor from the DB
* @param tableStructure The structure of the table we're on
* @param field The field from the {@link com.grosner.dbflow.structure.Model} class
* @return The value that should be set on the field from the {@link com.grosner.dbflow.structure.TableStructure}
*/
@SuppressWarnings("unchecked")
public static Object getModelValueFromCursor(Cursor cursor, TableStructure tableStructure, Field field, String columnName, Class<?> fieldType) {
int columnIndex = TextUtils.isEmpty(columnName) ? -1 : cursor.getColumnIndex(columnName);
Object value = null;
if (columnIndex >=0 || (StructureUtils.isForeignKey(field) && ReflectionUtils.implementsModel(fieldType))) {
boolean columnIsNull = cursor.isNull(columnIndex);
TypeConverter typeSerializer = tableStructure.getManager().getTypeConverterForClass(fieldType);
if (typeSerializer != null) {
fieldType = typeSerializer.getDatabaseType();
}
if (fieldType.equals(Byte.class) || fieldType.equals(byte.class)) {
value = cursor.getInt(columnIndex);
} else if (fieldType.equals(Short.class) || fieldType.equals(short.class)) {
value = cursor.getInt(columnIndex);
} else if (fieldType.equals(Integer.class) || fieldType.equals(int.class)) {
value = cursor.getInt(columnIndex);
} else if (fieldType.equals(Long.class) || fieldType.equals(long.class)) {
value = cursor.getLong(columnIndex);
} else if (fieldType.equals(Float.class) || fieldType.equals(float.class)) {
value = cursor.getFloat(columnIndex);
} else if (fieldType.equals(Double.class) || fieldType.equals(double.class)) {
value = cursor.getDouble(columnIndex);
} else if (fieldType.equals(Boolean.class) || fieldType.equals(boolean.class)) {
value = cursor.getInt(columnIndex) != 0;
} else if (fieldType.equals(Character.class) || fieldType.equals(char.class)) {
value = cursor.getString(columnIndex).charAt(0);
} else if (fieldType.equals(String.class)) {
value = cursor.getString(columnIndex);
} else if (fieldType.equals(Byte[].class) || fieldType.equals(byte[].class)) {
value = cursor.getBlob(columnIndex);
} else if (StructureUtils.isForeignKey(field) && ReflectionUtils.implementsModel(fieldType)) {
final Class<? extends Model> entityType = (Class<? extends Model>) fieldType;
Column foreignKey = field.getAnnotation(Column.class);
Object[] foreignColumns = new Object[foreignKey.references().length];
for(int i = 0; i < foreignColumns.length; i++) {
ForeignKeyReference foreignKeyReference = foreignKey.references()[i];
foreignColumns[i] = getModelValueFromCursor(cursor, tableStructure, null, foreignKeyReference.columnName(), foreignKeyReference.columnType());
}
// Build the primary key query using the converter and querybuilder
ConditionQueryBuilder conditionQueryBuilder = FlowManager.getPrimaryWhereQuery(entityType);
value = new Select().from(entityType).where()
.whereQuery(conditionQueryBuilder.replaceEmptyParams(foreignColumns))
.querySingle();
} else if (ReflectionUtils.isSubclassOf(fieldType, Enum.class)) {
@SuppressWarnings("rawtypes")
final Class<? extends Enum> enumType = (Class<? extends Enum>) fieldType;
value = Enum.valueOf(enumType, cursor.getString(columnIndex));
}
// Use a deserializer if one is available
if (typeSerializer != null && !columnIsNull) {
value = typeSerializer.getModelValue(value);
}
}
return value;
}
/**
* Deletes {@link com.grosner.dbflow.structure.Model} from the database using the specfied {@link com.grosner.dbflow.config.FlowManager}
*
* @param model The model to delete
* @param async Whether it goes on the {@link com.grosner.dbflow.runtime.DBTransactionQueue} or done immediately.
* @param <ModelClass> The class that implements {@link com.grosner.dbflow.structure.Model}
*/
@SuppressWarnings("unchecked")
public static <ModelClass extends Model> void delete(final ModelClass model, boolean async, boolean notify) {
if (!async) {
FlowManager flowManager = FlowManager.getManagerForTable(model.getClass());
TableStructure tableStructure = flowManager.getTableStructureForClass(model.getClass());
ConditionQueryBuilder<ModelClass> conditionQueryBuilder = flowManager.getStructure().getPrimaryWhereQuery((Class<ModelClass>) model.getClass());
flowManager.getWritableDatabase().delete(tableStructure.getTableName(), ConditionQueryBuilder.getPrimaryModelWhere(conditionQueryBuilder, model), null);
if (notify) {
// Notify any observers of this model change
FlowManager.getManagerForTable(model.getClass()).fireModelChanged(model, ModelObserver.Mode.fromData(0, true));
}
} else {
TransactionManager.getInstance().addTransaction(new DeleteModelListTransaction<ModelClass>(ProcessModelInfo.withModels(model).fetch()));
}
}
/**
* This is used to check if the specified {@link com.grosner.dbflow.structure.Model} exists within the specified
* {@link com.grosner.dbflow.config.FlowManager} DB.
*
* @param model The model to query
* @param <ModelClass> The class that implements {@link com.grosner.dbflow.structure.Model}
* @return If the model exists within the DB
*/
@SuppressWarnings("unchecked")
public static <ModelClass extends Model> boolean exists(ModelClass model) {
ConditionQueryBuilder<ModelClass> conditionQueryBuilder = (ConditionQueryBuilder<ModelClass>)
FlowManager.getPrimaryWhereQuery(model.getClass());
return new Select().from(model.getClass()).where(ConditionQueryBuilder.getPrimaryModelWhere(conditionQueryBuilder, model)).hasData();
}
}
|
package sociam.pybossa;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Random;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.json.JSONArray;
import org.json.JSONObject;
import sociam.pybossa.config.Config;
import sociam.pybossa.util.StringToImage;
import sociam.pybossa.util.TwitterAccount;
import twitter4j.StatusUpdate;
import twitter4j.Twitter;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.result.UpdateResult;
/**
*
* @author user Saud Aljaloud
* @author email sza1g10@ecs.soton.ac.uk
*
*/
public class TaskPerformer {
final static Logger logger = Logger.getLogger(TaskPerformer.class);
final static SimpleDateFormat MongoDBformatter = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
static Boolean wasPushed = false;
public static void main(String[] args) {
PropertyConfigurator.configure("log4j.properties");
logger.info("TaskPerformer will be repeated every "
+ Config.TaskCreatorTrigger + " ms");
try {
while (true) {
Config.reload();
run();
logger.info("Sleeping for " + Config.TaskPerformerTrigger
+ " ms");
Thread.sleep(Integer.valueOf(Config.TaskPerformerTrigger));
}
} catch (InterruptedException e) {
logger.error("Error ", e);
}
}
public static void run() {
try {
ArrayList<Document> tasksToBePushed = getReadyTasksFromMongoDB();
if (tasksToBePushed != null) {
logger.info("There are "
+ tasksToBePushed.size()
+ " tasks that need to be pushed into Twitter, then updating to MongoDB");
// randomly pick a task
// for (Document document : tasksToBePushed) {
HashSet<Integer> taskIDs = new HashSet<Integer>();
int seed = 200;
while (taskIDs.size() < tasksToBePushed.size()) {
Random random = new Random(seed);
seed++;
Integer genertatedTaskID = random.nextInt(tasksToBePushed
.size());
if (taskIDs.contains(genertatedTaskID)) {
continue;
} else {
taskIDs.add(genertatedTaskID);
}
Document document = tasksToBePushed.get(genertatedTaskID);
String task_status = document.getString("task_status");
String task_text = document.getString("task_text");
if (task_status.equals("pushed")) {
Date lastPushAt = document.getDate("lastPushAt");
if (!rePush(lastPushAt)) {
continue;
} else {
logger.debug("Repushing task " + task_text);
}
}
ObjectId _id = document.getObjectId("_id");
int pybossa_task_id = document
.getInteger("pybossa_task_id");
int project_id = document.getInteger("project_id");
String media_url = null;
if (document.containsKey("media_url")) {
media_url = document.getString("media_url");
}
JSONObject project = getProjectByID(project_id);
ArrayList<String> hashtags = new ArrayList<>();
if (project != null) {
JSONArray bin_id = project.getJSONArray("bin_ids");
for (Object object : bin_id) {
String binItem = (String) object;
hashtags.add("#" + binItem);
}
}
String taskTag = "#t" + pybossa_task_id;
int responseCode = sendTaskToTwitter(task_text, media_url,
taskTag, hashtags, 2);
if (responseCode == 1) {
if (updateTaskToPushedInMongoDB(_id, "pushed")) {
logger.info("Task with text " + task_text
+ " has been sucessfully pushed to Twitter");
wasPushed = true;
} else {
logger.error("Error with updating "
+ Config.taskCollection + " for the _id "
+ _id.toString());
}
} else if (responseCode == 0) {
if (updateTaskToPushedInMongoDB(_id, "notValied")) {
logger.debug("Tweeet is not valid because of length, but updated in Mongodb"
+ task_text);
}
logger.error("Couldn't update the task in MongoDB");
} else if (responseCode == 2) {
if (updateTaskToPushedInMongoDB(_id, "error")) {
logger.debug("pushing tweet has encountered an error, but has been updated into MongoDB "
+ task_text);
} else {
logger.error("Couldn't update the task in MongoDB");
}
}
// TODO: add lastPushAt when updating tasks
if (wasPushed) {
wasPushed = false;
logger.debug("waiting for "
+ Config.TaskPerformerPushRate
+ " ms before pushing another tweet");
Thread.sleep(Integer
.valueOf(Config.TaskPerformerPushRate));
}
}
}
} catch (Exception e) {
logger.error("Error ", e);
}
}
public static Boolean rePush(Date lastPushAt) {
try {
Calendar cal = Calendar.getInstance();
Date currentDate = new Date();
cal.setTime(lastPushAt);
cal.add(Calendar.HOUR, Integer.valueOf(Config.RePushTaskToTwitter));
Date convertedDate = cal.getTime();
return currentDate.before(convertedDate);
} catch (Exception e) {
logger.error("Error ", e);
return false;
}
}
public static Boolean updateTaskToPushedInMongoDB(ObjectId _id,
String task_status) {
MongoClient mongoClient = new MongoClient(Config.mongoHost,
Config.mongoPort);
try {
MongoDatabase database = mongoClient
.getDatabase(Config.projectsDatabaseName);
Date date = new Date();
String lastPushAt = MongoDBformatter.format(date);
UpdateResult result = database.getCollection(Config.taskCollection)
.updateOne(
new Document("_id", _id),
new Document().append("$set", new Document(
"task_status", task_status).append(
"lastPushAt", lastPushAt)));
logger.debug(result.toString());
if (result.wasAcknowledged()) {
if (result.getMatchedCount() > 0) {
logger.debug(Config.taskCollection
+ " Collection was updated where _id= "
+ _id.toString() + " to task_status=" + task_status);
mongoClient.close();
return true;
}
}
mongoClient.close();
return false;
} catch (Exception e) {
logger.error("Error ", e);
mongoClient.close();
return false;
}
}
/**
* This method send a task by a twitter account
*
* @param taskId
* The id of the task to be hashed within the tweet
* @param taskContent
* the content of the tweet to be published
*/
public static int sendTaskToTwitter(String taskContent, String media_url,
String taskTag, ArrayList<String> hashtags, int project_type) {
try {
Twitter twitter = TwitterAccount.setTwitterAccount(project_type);
// defualt
String question = "";
if (project_type == 2) {
question = Config.project_validation_question;
}
// combine hashtags and tasktag while maintaining the 140 length
String post = question;
for (String string : hashtags) {
if (post.length() == 0) {
post = string;
} else {
String tmpResult = post + " " + string + taskTag;
if (tmpResult.length() >= 140) {
break;
}
post = post + " " + string;
}
}
post = post + "?";
post = post + " " + taskTag;
// convert taskContent and question into an image
File image = null;
if (media_url != null) {
if (media_url.equals("")) {
image = StringToImage.convertStringToImage(taskContent);
} else {
image = StringToImage.combineTextWithImage(taskContent,
media_url);
}
} else {
image = StringToImage.convertStringToImage(taskContent);
}
if (post.length() < 140) {
// image must exist
if (image != null) {
// status = twitter.updateStatus(post);
StatusUpdate status = new StatusUpdate(post);
status.setMedia(image);
twitter.updateStatus(status);
logger.debug("Successfully posting a task '"
+ status.getStatus() + "'." + status.getPlaceId());
return 1;
} else {
logger.error("Image couldn't br generated");
return 0;
}
} else {
logger.error("Post \"" + post
+ "\" is longer than 140 characters. It has: "
+ (post.length()));
return 0;
}
} catch (Exception e) {
logger.error("Error", e);
return 2;
}
}
public static ArrayList<Document> getReadyTasksFromMongoDB() {
ArrayList<Document> NotPushedTasksjsons = new ArrayList<Document>();
MongoClient mongoClient = new MongoClient(Config.mongoHost,
Config.mongoPort);
try {
MongoDatabase database = mongoClient
.getDatabase(Config.projectsDatabaseName);
FindIterable<Document> iterable = database.getCollection(
Config.taskCollection).find(
new Document("task_status", "ready"));
if (iterable.first() != null) {
for (Document document : iterable) {
NotPushedTasksjsons.add(document);
}
}
mongoClient.close();
return NotPushedTasksjsons;
} catch (Exception e) {
logger.error("Error ", e);
mongoClient.close();
return null;
}
}
public static JSONObject getProjectByID(int project_id) {
logger.debug("getting project by project_id from "
+ Config.projectCollection + " collection");
MongoClient mongoClient = new MongoClient(Config.mongoHost,
Config.mongoPort);
try {
MongoDatabase database = mongoClient
.getDatabase(Config.projectsDatabaseName);
JSONObject json = null;
FindIterable<Document> iterable = database.getCollection(
Config.projectCollection).find(
new Document("project_id", project_id));
if (iterable.first() != null) {
Document document = iterable.first();
json = new JSONObject(document);
}
mongoClient.close();
return json;
} catch (Exception e) {
logger.error("Error ", e);
mongoClient.close();
return null;
}
}
}
|
package tachyon;
import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import org.apache.thrift.TException;
import org.apache.log4j.Logger;
import org.apache.commons.io.FileUtils;
import org.apache.hadoop.fs.Path;
import tachyon.thrift.Command;
import tachyon.thrift.FailedToCheckpointException;
import tachyon.thrift.FileDoesNotExistException;
import tachyon.thrift.NetAddress;
import tachyon.thrift.SuspectedFileSizeException;
import tachyon.thrift.WorkerService;
public class WorkerServiceHandler implements WorkerService.Iface {
// TODO The reason this is public is for DataServerMessage to access. Need to re-organize this.
public static final BlockingQueue<Integer> sDataAccessQueue =
new ArrayBlockingQueue<Integer>(Config.WORKER_DATA_ACCESS_QUEUE_SIZE);
private final Logger LOG = Logger.getLogger(Config.LOGGER_TYPE);
private volatile MasterClient mMasterClient;
private InetSocketAddress mMasterAddress;
private WorkerInfo mWorkerInfo;
// TODO Should merge these three structures, and make it more clean. Define NodeStroage class.
private Set<Integer> mMemoryData = new HashSet<Integer>();
private Map<Integer, Long> mLatestFileAccessTimeMs = new HashMap<Integer, Long>();
private Map<Integer, Set<Long>> mUsersPerLockedFile = new HashMap<Integer, Set<Long>>();
private Map<Long, Set<Integer>> mLockedFilesPerUser = new HashMap<Long, Set<Integer>>();
private Map<Integer, Long> mFileSizes = new HashMap<Integer, Long>();
private BlockingQueue<Integer> mRemovedFileList =
new ArrayBlockingQueue<Integer>(Config.WORKER_DATA_ACCESS_QUEUE_SIZE);
private BlockingQueue<Integer> mAddedFileList =
new ArrayBlockingQueue<Integer>(Config.WORKER_DATA_ACCESS_QUEUE_SIZE);
// Dependency related lock
private Object mDependencyLock = new Object();
private Set<Integer> mUncheckpointFiles = new HashSet<Integer>();
// From dependencyId to files in that set.
private Map<Integer, Set<Integer>> mDepIdToFiles = new HashMap<Integer, Set<Integer>>();
private List<Integer> mPriorityDependencies = new ArrayList<Integer>();
private File mDataFolder;
private File mUserFolder;
private Path mHdfsWorkerFolder;
private Path mHdfsWorkerDataFolder;
private HdfsClient mHdfsClient;
private Users mUsers;
private ArrayList<Thread> mCheckpointThreads =
new ArrayList<Thread>(Config.WORKER_CHECKPOINT_THREADS);
public class CheckpointThread implements Runnable {
private final Logger LOG = Logger.getLogger(Config.LOGGER_TYPE);
private final int ID;
private HdfsClient mLocalHdfsClient = null;
public CheckpointThread(int id) {
ID = id;
}
@Override
public void run() {
while (true) {
try {
int fileId = -1;
synchronized (mDependencyLock) {
fileId = getFileIdBasedOnPriorityDependency();
if (mPriorityDependencies.size() == 0) {
mPriorityDependencies = getSortedPriorityDependencyList();
if (!mPriorityDependencies.isEmpty()) {
LOG.info("Get new mPriorityDependencies " +
CommonUtils.listToString(mPriorityDependencies));
}
} else {
List<Integer> tList = getSortedPriorityDependencyList();
boolean equal = true;
if (mPriorityDependencies.size() != tList.size()) {
equal = false;
}
if (equal) {
for (int k = 0; k < tList.size(); k ++) {
if (tList.get(k) != mPriorityDependencies.get(k)) {
equal = false;
break;
}
}
}
if (!equal) {
mPriorityDependencies = tList;
}
}
fileId = getFileIdBasedOnPriorityDependency();
if (fileId == -1) {
fileId = getRandomUncheckpointedFile();
}
}
if (fileId == -1) {
LOG.debug("Thread " + ID + " has nothing to checkpoint. Sleep for 1 sec.");
CommonUtils.sleepMs(LOG, 1000);
continue;
}
//TODO checkpoint process. In future, move from midPath to dstPath should be done by
// master
String srcPath = mDataFolder + "/" + fileId;
long fileSize = (new File(srcPath)).length();
String midPath = mHdfsWorkerDataFolder + "/" + fileId;
String dstPath = Config.HDFS_ADDRESS + Config.HDFS_DATA_FOLDER + "/" + fileId;
LOG.info("Thread " + ID + " is checkpointing file " + fileId + " from " + srcPath +
" to " + midPath + " to " + dstPath);
if (mLocalHdfsClient == null) {
mLocalHdfsClient = new HdfsClient(midPath);
}
long startCopyTimeMs = System.currentTimeMillis();
mLocalHdfsClient.copyFromLocalFile(false, false, srcPath, midPath);
if (!mLocalHdfsClient.rename(midPath, dstPath)) {
LOG.error("Failed to rename from " + midPath + " to " + dstPath);
}
mMasterClient.addCheckpoint(mWorkerInfo.getId(), fileId, fileSize, dstPath);
long shouldTakeMs = (long)
(1000.0 * fileSize / Config.MB / Config.WORKER_PER_THREAD_CHECKPOINT_CAP_MB_SEC);
long currentTimeMs = System.currentTimeMillis();
if (startCopyTimeMs + shouldTakeMs > currentTimeMs) {
long shouldSleepMs = startCopyTimeMs + shouldTakeMs - currentTimeMs;
LOG.info("Checkpointed last file " + fileId + " took " +
(currentTimeMs - startCopyTimeMs) + " ms. Need to sleep " + shouldSleepMs + " ms.");
CommonUtils.sleepMs(LOG, shouldSleepMs);
}
unlockFile(fileId, Users.sCHECKPOINT_USER_ID);
} catch (FileDoesNotExistException e) {
LOG.warn(e);
} catch (SuspectedFileSizeException e) {
LOG.error(e);
} catch (TException e) {
LOG.warn(e);
}
}
}
private List<Integer> getSortedPriorityDependencyList() throws TException {
List<Integer> ret = mMasterClient.worker_getPriorityDependencyList();
for (int i = 0; i < ret.size(); i ++) {
for (int j = i + 1; j < ret.size(); j ++) {
if (ret.get(i) < ret.get(j)) {
int k = ret.get(i);
ret.set(i, ret.get(j));
ret.set(j, k);
}
}
}
return ret;
}
// This method assumes the mDependencyLock has been acquired.
private int getRandomUncheckpointedFile() throws TException {
if (mUncheckpointFiles.isEmpty()) {
return -1;
}
for (int depId: mDepIdToFiles.keySet()) {
int fileId = getFileIdFromOneDependency(depId);
if (fileId != -1) {
return fileId;
}
}
return -1;
}
// This method assumes the mDependencyLock has been acquired.
private int getFileIdBasedOnPriorityDependency() throws TException {
if (mPriorityDependencies.isEmpty()) {
return -1;
}
for (int depId : mPriorityDependencies) {
int fileId = getFileIdFromOneDependency(depId);
if (fileId != -1) {
return fileId;
}
}
return -1;
}
// This method assumes the mDependencyLock has been acquired.
private int getFileIdFromOneDependency(int depId) throws TException {
Set<Integer> fileIds = mDepIdToFiles.get(depId);
if (fileIds != null && !fileIds.isEmpty()) {
int fileId = fileIds.iterator().next();
lockFile(fileId, Users.sCHECKPOINT_USER_ID);
fileIds.remove(fileId);
mUncheckpointFiles.remove(fileId);
if (fileIds.isEmpty()) {
mDepIdToFiles.remove(depId);
}
return fileId;
}
return -1;
}
}
public WorkerServiceHandler(InetSocketAddress masterAddress, InetSocketAddress workerAddress,
String dataFolder, long spaceLimitBytes) {
mMasterAddress = masterAddress;
mMasterClient = new MasterClient(mMasterAddress);
long id = 0;
while (id == 0) {
try {
mMasterClient.open();
id = mMasterClient.worker_register(
new NetAddress(workerAddress.getHostName(), workerAddress.getPort()),
spaceLimitBytes, 0, new ArrayList<Integer>());
} catch (TException e) {
LOG.error(e.getMessage(), e);
id = 0;
CommonUtils.sleepMs(LOG, 1000);
}
}
mDataFolder = new File(dataFolder);
mUserFolder = new File(mDataFolder.toString(), Config.USER_TEMP_RELATIVE_FOLDER);
mWorkerInfo = new WorkerInfo(id, workerAddress, spaceLimitBytes);
mHdfsWorkerFolder = new Path(Config.HDFS_ADDRESS + "/" + Config.WORKER_HDFS_FOLDER + "/" + id);
mHdfsWorkerDataFolder = new Path(mHdfsWorkerFolder.toString() + "/data");
if (Config.USING_HDFS) {
mHdfsClient = new HdfsClient(Config.HDFS_ADDRESS);
}
mUsers = new Users(mUserFolder.toString(), mHdfsWorkerFolder.toString());
if (Config.USING_HDFS) {
for (int k = 0; k < Config.WORKER_CHECKPOINT_THREADS; k ++) {
Thread thread = new Thread(new CheckpointThread(k));
mCheckpointThreads.add(thread);
thread.start();
}
}
try {
initializeWorkerInfo();
} catch (FileDoesNotExistException e) {
CommonUtils.runtimeException(e);
} catch (SuspectedFileSizeException e) {
CommonUtils.runtimeException(e);
} catch (TException e) {
CommonUtils.runtimeException(e);
}
LOG.info("Current Worker Info: " + mWorkerInfo);
}
@Override
public void accessFile(int fileId) throws TException {
sDataAccessQueue.add(fileId);
}
@Override
public void addCheckpoint(long userId, int fileId)
throws FileDoesNotExistException, SuspectedFileSizeException,
FailedToCheckpointException, TException {
// TODO This part need to be changed.
String srcPath = getUserHdfsTempFolder(userId) + "/" + fileId;
String dstPath = Config.HDFS_ADDRESS + Config.HDFS_DATA_FOLDER + "/" + fileId;
if (!mHdfsClient.rename(srcPath, dstPath)) {
throw new FailedToCheckpointException("Failed to rename from " + srcPath + " to " + dstPath);
}
long fileSize = mHdfsClient.getFileSize(dstPath);
mMasterClient.addCheckpoint(mWorkerInfo.getId(), fileId, fileSize, dstPath);
}
private void addFoundPartition(int fileId, long fileSizeBytes)
throws FileDoesNotExistException, SuspectedFileSizeException, TException {
addId(fileId, fileSizeBytes);
mMasterClient.worker_cachedFile(mWorkerInfo.getId(), mWorkerInfo.getUsedBytes(), fileId,
fileSizeBytes);
}
private void addId(int fileId, long fileSizeBytes) {
mWorkerInfo.updateFile(true, fileId);
synchronized (mLatestFileAccessTimeMs) {
mLatestFileAccessTimeMs.put(fileId, System.currentTimeMillis());
mFileSizes.put(fileId, fileSizeBytes);
mMemoryData.add(fileId);
}
}
@Override
public void cacheFile(long userId, int fileId)
throws FileDoesNotExistException, SuspectedFileSizeException, TException {
File srcFile = new File(getUserTempFolder(userId) + "/" + fileId);
File dstFile = new File(mDataFolder + "/" + fileId);
long fileSizeBytes = srcFile.length();
if (!srcFile.exists()) {
throw new FileDoesNotExistException("File " + srcFile + " does not exist.");
}
if (!srcFile.renameTo(dstFile)) {
throw new FileDoesNotExistException("Failed to rename file from " + srcFile.getPath() +
" to " + dstFile.getPath());
}
addId(fileId, fileSizeBytes);
mUsers.addOwnBytes(userId, - fileSizeBytes);
int dependencyId = mMasterClient.worker_cachedFile(mWorkerInfo.getId(),
mWorkerInfo.getUsedBytes(), fileId, fileSizeBytes);
if (dependencyId != -1) {
synchronized (mDependencyLock) {
mUncheckpointFiles.add(fileId);
if (!mDepIdToFiles.containsKey(dependencyId)) {
mDepIdToFiles.put(dependencyId, new HashSet<Integer>());
}
mDepIdToFiles.get(dependencyId).add(fileId);
}
}
}
public void checkStatus() {
List<Long> removedUsers = mUsers.checkStatus(mWorkerInfo);
for (long userId : removedUsers) {
synchronized (mUsersPerLockedFile) {
Set<Integer> fileIds = mLockedFilesPerUser.get(userId);
mLockedFilesPerUser.remove(userId);
if (fileIds != null) {
for (int fileId : fileIds) {
try {
unlockFile(fileId, userId);
} catch (TException e) {
CommonUtils.runtimeException(e);
}
}
}
}
}
synchronized (mLatestFileAccessTimeMs) {
while (!sDataAccessQueue.isEmpty()) {
int fileId = sDataAccessQueue.poll();
mLatestFileAccessTimeMs.put(fileId, System.currentTimeMillis());
}
}
}
private void freeFile(int fileId) {
mWorkerInfo.returnUsedBytes(mFileSizes.get(fileId));
mWorkerInfo.removeFile(fileId);
File srcFile = new File(mDataFolder + "/" + fileId);
srcFile.delete();
synchronized (mLatestFileAccessTimeMs) {
mLatestFileAccessTimeMs.remove(fileId);
mFileSizes.remove(fileId);
mRemovedFileList.add(fileId);
mMemoryData.remove(fileId);
}
LOG.info("Removed Data " + fileId);
}
@Override
public String getDataFolder() throws TException {
return mDataFolder.toString();
}
@Override
public String getUserTempFolder(long userId) throws TException {
String ret = mUsers.getUserTempFolder(userId);
LOG.info("Return UserTempFolder for " + userId + " : " + ret);
return ret;
}
@Override
public String getUserHdfsTempFolder(long userId) throws TException {
String ret = mUsers.getUserHdfsTempFolder(userId);
LOG.info("Return UserHdfsTempFolder for " + userId + " : " + ret);
return ret;
}
public Command heartbeat() throws TException {
ArrayList<Integer> sendRemovedPartitionList = new ArrayList<Integer>();
while (mRemovedFileList.size() > 0) {
sendRemovedPartitionList.add(mRemovedFileList.poll());
}
return mMasterClient.worker_heartbeat(mWorkerInfo.getId(), mWorkerInfo.getUsedBytes(),
sendRemovedPartitionList);
}
private void initializeWorkerInfo()
throws FileDoesNotExistException, SuspectedFileSizeException, TException {
LOG.info("Initializing the worker info.");
if (!mDataFolder.exists()) {
LOG.info("Local folder " + mDataFolder.toString() + " does not exist. Creating a new one.");
mDataFolder.mkdir();
mUserFolder.mkdir();
return;
}
if (!mDataFolder.isDirectory()) {
String tmp = mDataFolder.toString() + " is not a folder!";
LOG.error(tmp);
throw new IllegalArgumentException(tmp);
}
int cnt = 0;
for (File tFile : mDataFolder.listFiles()) {
if (tFile.isFile()) {
cnt ++;
LOG.info("File " + cnt + ": " + tFile.getPath() + " with size " + tFile.length() + " Bs.");
int fileId = CommonUtils.getFileIdFromFileName(tFile.getName());
boolean success = mWorkerInfo.requestSpaceBytes(tFile.length());
addFoundPartition(fileId, tFile.length());
mAddedFileList.add(fileId);
if (!success) {
CommonUtils.runtimeException("Pre-existing files exceed the local memory capacity.");
}
}
}
if (mUserFolder.exists()) {
try {
FileUtils.deleteDirectory(mUserFolder);
} catch (IOException e) {
LOG.error(e.getMessage(), e);
}
}
mUserFolder.mkdir();
}
@Override
public void lockFile(int fileId, long userId) throws TException {
synchronized (mUsersPerLockedFile) {
if (!mUsersPerLockedFile.containsKey(fileId)) {
mUsersPerLockedFile.put(fileId, new HashSet<Long>());
}
mUsersPerLockedFile.get(fileId).add(userId);
if (!mLockedFilesPerUser.containsKey(userId)) {
mLockedFilesPerUser.put(userId, new HashSet<Integer>());
}
mLockedFilesPerUser.get(userId).add(fileId);
}
}
private boolean memoryEvictionLRU() {
long latestTimeMs = Long.MAX_VALUE;
int fileId = -1;
Set<Integer> pinList = new HashSet<Integer>();
// TODO Cache replacement policy should go through Master.
try {
pinList = mMasterClient.worker_getPinIdList();
} catch (TException e) {
LOG.error(e.getMessage());
pinList = new HashSet<Integer>();
}
synchronized (mLatestFileAccessTimeMs) {
synchronized (mUsersPerLockedFile) {
synchronized (mDependencyLock) {
for (Entry<Integer, Long> entry : mLatestFileAccessTimeMs.entrySet()) {
if (entry.getValue() < latestTimeMs && !pinList.contains(entry.getKey())) {
if(!mUsersPerLockedFile.containsKey(entry.getKey())
&& !mUncheckpointFiles.contains(entry.getKey())) {
fileId = entry.getKey();
latestTimeMs = entry.getValue();
}
}
}
if (fileId != -1) {
freeFile(fileId);
return true;
}
}
}
}
return false;
}
public void register() {
long id = 0;
while (id == 0) {
try {
mMasterClient.open();
id = mMasterClient.worker_register(
new NetAddress(mWorkerInfo.ADDRESS.getHostName(), mWorkerInfo.ADDRESS.getPort()),
mWorkerInfo.getCapacityBytes(), 0, new ArrayList<Integer>());
} catch (TException e) {
LOG.error(e.getMessage(), e);
id = 0;
CommonUtils.sleepMs(LOG, 1000);
}
}
mWorkerInfo.updateId(id);
}
@Override
public void returnSpace(long userId, long returnedBytes) throws TException {
LOG.info("returnSpace(" + userId + ", " + returnedBytes + ") : " +
mWorkerInfo.getAvailableBytes() + " returned: " + returnedBytes);
mWorkerInfo.returnUsedBytes(returnedBytes);
mUsers.addOwnBytes(userId, - returnedBytes);
LOG.info("user_returnSpace(): new available: " + mWorkerInfo.getAvailableBytes());
}
@Override
public boolean requestSpace(long userId, long requestBytes) throws TException {
LOG.info("requestSpace(" + userId + ", " + requestBytes + "): Current available: " +
mWorkerInfo.getAvailableBytes() + " requested: " + requestBytes);
if (mWorkerInfo.getCapacityBytes() < requestBytes) {
LOG.info("user_requestSpace(): requested memory size is larger than the total memory on" +
" the machine.");
return false;
}
while (!mWorkerInfo.requestSpaceBytes(requestBytes)) {
if (!memoryEvictionLRU()) {
return false;
}
}
mUsers.addOwnBytes(userId, requestBytes);
return true;
}
public void resetMasterClient() {
MasterClient tMasterClient = new MasterClient(mMasterAddress);
tMasterClient.open();
mMasterClient = tMasterClient;
}
@Override
public void unlockFile(int fileId, long userId) throws TException {
synchronized (mUsersPerLockedFile) {
if (mUsersPerLockedFile.containsKey(fileId)) {
mUsersPerLockedFile.get(fileId).remove(userId);
if (mUsersPerLockedFile.get(fileId).size() == 0) {
mUsersPerLockedFile.remove(fileId);
}
}
if (mLockedFilesPerUser.containsKey(userId)) {
mLockedFilesPerUser.get(userId).remove(fileId);
}
}
}
@Override
public void userHeartbeat(long userId) throws TException {
mUsers.userHeartbeat(userId);
}
}
|
//This software may be modified and distributed under the terms
package wyjs.io;
import java.io.*;
import java.util.*;
import wybs.lang.Build;
import wybs.lang.NameID;
import wybs.lang.NameResolver.ResolutionError;
import wybs.lang.SyntacticElement;
import static wybs.lang.SyntaxError.*;
import wyfs.lang.Path;
import static wyc.lang.WhileyFile.*;
import wyc.lang.WhileyFile;
import wyc.type.TypeSystem;
import wyc.util.ErrorMessages;
import wyc.util.SingleParameterVisitor;
/**
* Writes WYIL bytecodes in a textual from to a given file.
*
* <b>NOTE:</b> currently, this class is somewhat broken since it does not
* provide any way to specify the output directory. Rather, it simply puts the
* WYIL file in the same place as the Whiley file.
*
* @author David J. Pearce
*
*/
public final class JavaScriptFileWriter extends SingleParameterVisitor<JavaScriptFileWriter.Context> {
private final PrintWriter out;
/**
* The master project for identifying all resources available to the
* builder. This includes all modules declared in the project being verified
* and/or defined in external resources (e.g. jar files).
*/
private final Build.Project project;
/**
* The type system is useful for managing nominal types and converting them
* into their underlying types.
*/
protected final TypeSystem typeSystem;
private boolean verbose = false;
private boolean commentTypes = false;
private boolean commentSpecifications = false;
private WhileyFile wyilfile;
public JavaScriptFileWriter(Build.Project project, TypeSystem typeSystem, PrintWriter writer) {
this.project = project;
this.typeSystem = typeSystem;
this.out = writer;
}
public JavaScriptFileWriter(Build.Project project, TypeSystem typeSystem, OutputStream stream) {
this.project = project;
this.typeSystem = typeSystem;
this.out = new PrintWriter(new OutputStreamWriter(stream));
}
// Configuration Methods
public void setVerbose(boolean flag) {
this.verbose = flag;
}
// Apply Method
public void apply(WhileyFile module) {
Context context = new Context(0,new HashSet<>());
this.visitWhileyFile(module, context);
writeTypeTests(context.typeTests, new HashSet<>());
out.flush();
}
@Override
public void visitType(Decl.Type td, Context context) {
Decl.Variable vardecl = td.getVariableDeclaration();
out.print("function ");
out.print(td.getName());
out.print("$type(");
out.print(vardecl.getName());
out.println(") {");
Tuple<Expr> invariant = td.getInvariant();
if(invariant.size() == 0) {
tabIndent(1);
out.println("return true;");
} else if(invariant.size() == 1) {
tabIndent(1);
out.print("return ");
visitExpression(invariant.get(0), context);
out.println(";");
} else {
for(int i=0;i!=invariant.size();++i) {
tabIndent(1);
if(i == 0) {
out.print("var result = (");
} else {
out.print("result = result && (");
}
visitExpression(invariant.get(i), context);
out.println(");");
}
tabIndent(1);
out.println("return result;");
}
out.println("}");
out.println();
}
@Override
public void visitStaticVariable(Decl.StaticVariable cd, Context context) {
out.print("var " + cd.getName());
if (cd.hasInitialiser()) {
out.print(" = ");
visitExpression(cd.getInitialiser(), context);
}
out.println(";");
}
@Override
public void visitFunctionOrMethod(Decl.FunctionOrMethod method, Context context) {
// FIXME: what to do with private methods?
if (method.getModifiers().match(Modifier.Export.class) != null) {
writeExportTrampoline(method);
}
out.print("function ");
out.print(method.getName());
writeTypeMangle(method.getType());
visitVariables(method.getParameters(), context);
if(commentTypes) {
if (method.getReturns().size() > 0) {
out.print("
visitVariables(method.getReturns(), context);
out.println();
} else {
out.println();
}
} else {
out.print(" ");
}
if(commentSpecifications) {
for (Expr precondition : method.getRequires()) {
out.print("// requires ");
visitExpression(precondition, context);
}
for (Expr postcondition : method.getEnsures()) {
out.print("// ensures ");
visitExpression(postcondition, context);
out.println();
}
}
out.println("{");
writeInvariantCheck(method.getRequires(), context.indent());
if (method.getBody() != null) {
visitBlock(method.getBody(), context);
}
out.println("}");
}
@Override
public void visitProperty(Decl.Property method, Context context) {
out.print("function ");
out.print(method.getName());
writeTypeMangle(method.getType());
out.print("$property");
visitVariables(method.getParameters(), context);
if(commentTypes) {
if (method.getReturns().size() > 0) {
out.print("
visitVariables(method.getReturns(), context);
out.println();
} else {
out.println();
}
} else {
out.print(" ");
}
out.println("{");
writeInvariantCheck(method.getInvariant(), context.indent());
tabIndent(1);
out.println("return true;");
out.println("}");
}
@Override
public void visitVariables(Tuple<Decl.Variable> parameters, Context context) {
out.print("(");
for (int i = 0; i != parameters.size(); ++i) {
if (i != 0) {
out.print(", ");
}
Decl.Variable decl = parameters.get(i);
writeType(decl.getType());
out.print(decl.getName());
}
out.print(")");
}
@Override
public void visitVariable(Decl.Variable decl, Context context) {
out.print("var ");
writeType(decl.getType());
out.print(decl.getName());
if (decl.hasInitialiser()) {
out.print(" = ");
visitExpression(decl.getInitialiser(), context);
}
out.println(";");
}
@Override
public void visitLambda(Decl.Lambda expr, Context context) {
out.print("function(");
Tuple<Decl.Variable> parameters = expr.getParameters();
for (int i = 0; i != parameters.size(); ++i) {
Decl.Variable var = parameters.get(i);
if (i != 0) {
out.print(", ");
}
writeType(var.getType());
out.print(var.getName());
}
out.print(") { ");
out.print("return ");
visitExpression(expr.getBody(), context);
out.print("; }");
}
/**
* Create a trampoline for an exported function. This is simply a function
* without a name mangle which redirects to the same function with the name
* mangle.
*
* @param method
*/
private void writeExportTrampoline(Decl.FunctionOrMethod method) {
Type.Callable ft = method.getType();
Tuple<Decl.Variable> params = method.getParameters();
Tuple<Decl.Variable> returns = method.getReturns();
if (params.size() > 0) {
out.print("function ");
out.print(method.getName());
visitVariables(params, null);
out.println(" {");
tabIndent(1);
if (returns.size() > 0) {
out.print("return ");
}
out.print(method.getName());
writeTypeMangle(ft);
writeTrampolineArguments(params);
out.println("}");
out.println();
}
}
private void writeTrampolineArguments(Tuple<Decl.Variable> parameters) {
out.print("(");
for (int i = 0; i != parameters.size(); ++i) {
if (i != 0) {
out.print(", ");
}
Decl.Variable decl = parameters.get(i);
out.print(decl.getName());
}
out.println(");");
}
@Override public void visitStatement(Stmt stmt, Context context) {
tabIndent(context.indent+1);
super.visitStatement(stmt, context);
switch(stmt.getOpcode()) {
case EXPR_invoke:
case EXPR_indirectinvoke:
// Need as an invocation expression won't terminate itself.
out.println(";");
}
}
@Override public void visitAssert(Stmt.Assert c, Context context) {
out.print("Wy.assert(");
visitExpression(c.getCondition(), context);
out.println(");");
}
@Override public void visitAssume(Stmt.Assume c, Context context) {
out.print("Wy.assert(");
visitExpression(c.getCondition(), context);
out.println(");");
}
@Override
public void visitAssign(Stmt.Assign stmt, Context context) {
Tuple<LVal> lhs = stmt.getLeftHandSide();
Tuple<Expr> rhs = stmt.getRightHandSide();
if (lhs.size() == 1) {
// easy case
writeLVal(lhs.get(0), context);
out.print(" = ");
visitExpression(rhs.get(0), context);
out.println(";");
} else if (lhs.size() > 1) {
// FIXME: this is broken when multiple rhs expressions
out.print("var $ = ");
// Translate right-hand sides
visitExpression(rhs.get(0), context);
out.println(";");
// Translate left-hand sides
for (int i = 0; i != lhs.size(); ++i) {
tabIndent(context.indent + 1);
writeLVal(lhs.get(i), context);
out.println(" = $[" + i + "];");
}
}
}
@Override
public void visitBreak(Stmt.Break b, Context context) {
out.println("break;");
}
@Override
public void visitContinue(Stmt.Continue b, Context context) {
out.println("continue;");
}
@Override
public void visitDebug(Stmt.Debug b, Context context) {
}
@Override
public void visitDoWhile(Stmt.DoWhile b, Context context) {
out.println("do {");
visitBlock(b.getBody(), context.indent());
tabIndent(context.indent + 1);
// FIXME: write loop invariant if DEBUG mode
out.print("} while(");
visitExpression(b.getCondition(), context);
out.println(");");
}
@Override public void visitFail(Stmt.Fail c, Context context) {
out.println("fail");
}
@Override
public void visitIfElse(Stmt.IfElse b, Context context) {
out.print("if(");
visitExpression(b.getCondition(), context);
context = context.indent();
out.println(") {");
visitBlock(b.getTrueBranch(), context);
if (b.hasFalseBranch()) {
tabIndent(context.indent);
out.println("} else {");
visitBlock(b.getFalseBranch(), context);
}
tabIndent(context.indent);
out.println("}");
}
@Override
public void visitNamedBlock(Stmt.NamedBlock b, Context context) {
out.print(b.getName());
out.println(":");
visitBlock(b.getBlock(), context.indent());
}
@Override
public void visitWhile(Stmt.While b, Context context) {
out.print("while(");
visitExpression(b.getCondition(), context);
out.println(") {");
visitBlock(b.getBody(), context.indent());
tabIndent(context.indent + 1);
out.println("}");
}
@Override
public void visitReturn(Stmt.Return b, Context context) {
Tuple<Expr> operands = b.getReturns();
out.print("return");
if (operands.size() == 1) {
// easy case
out.print(" ");
visitExpression(operands.get(0), context);
} else if (operands.size() > 0) {
// harder case
out.print(" [");
for (int i = 0; i != operands.size(); ++i) {
if (i != 0) {
out.print(", ");
}
visitExpression(operands.get(i), context);
}
out.print("]");
}
out.println(";");
}
@Override
public void visitSkip(Stmt.Skip b, Context context) {
out.println("// skip");
}
@Override
public void visitSwitch(Stmt.Switch b, Context context) {
out.print("switch(");
visitExpression(b.getCondition(), context);
out.println(") {");
Tuple<Stmt.Case> cases = b.getCases();
for (int i = 0; i != cases.size(); ++i) {
// FIXME: ugly
Stmt.Case cAse = cases.get(i);
Tuple<Expr> values = cAse.getConditions();
if (values.size() == 0) {
tabIndent(context.indent + 1);
out.println("default:");
} else {
for (int j = 0; j != values.size(); ++j) {
tabIndent(context.indent + 1);
out.print("case ");
// FIXME: this needs to be fixed
out.print(values.get(j));
out.println(":");
}
}
visitBlock(cAse.getBlock(), context.indent());
tabIndent(context.indent + 2);
out.println("break;");
}
tabIndent(context.indent + 1);
out.println("}");
}
/**
* Write a bracketed operand if necessary. Any operand whose human-readable
* representation can contain whitespace must have brackets around it.
*
* @param operand
* @param enclosing
* @param out
*/
private void writeBracketedExpression(Expr expr, Context context) {
boolean needsBrackets = needsBrackets(expr);
if (needsBrackets) {
out.print("(");
}
visitExpression(expr, context);
if (needsBrackets) {
out.print(")");
}
}
@Override
public void visitCast(Expr.Cast expr, Context context) {
visitExpression(expr.getOperand(), context);
}
@Override
public void visitConstant(Expr.Constant expr, Context context) {
Value val = expr.getValue();
if (val instanceof Value.Byte) {
Value.Byte b = (Value.Byte) val;
// FIXME: support es6 binary literals
// out.print("0b");
out.print("parseInt('");
out.print(Integer.toBinaryString(b.get() & 0xFF));
out.print("',2)");
} else if (val instanceof Value.UTF8) {
Value.UTF8 s = (Value.UTF8) val;
byte[] bytes = s.get();
out.print("[");
for (int i = 0; i != bytes.length; ++i) {
if (i != 0) {
out.print(", ");
}
out.print(bytes[i]);
}
out.print("]");
} else {
out.print(val);
}
}
@Override
public void visitEqual(Expr.Equal expr, Context context) {
visitEqualityOperator(expr, context);
}
@Override
public void visitNotEqual(Expr.NotEqual expr, Context context) {
visitEqualityOperator(expr, context);
}
private void visitEqualityOperator(Expr.NaryOperator expr, Context context) {
Tuple<Expr> operands = expr.getOperands();
if (operands.size() > 2) {
throw new IllegalArgumentException();
}
// Extract the type information
Expr lhs = operands.get(0);
Expr rhs = operands.get(1);
// FIXME: put this back
Type lhsT = lhs.getType();
Type rhsT = rhs.getType();
if (isCopyable(lhsT, lhs) && isCopyable(rhsT, rhs)) {
writeInfixOperator(expr, context);
} else {
if (expr instanceof Expr.NotEqual) {
out.print("!");
}
out.print("Wy.equals(");
visitExpression(lhs, context);
out.print(", ");
visitExpression(rhs, context);
out.print(")");
}
}
@Override
public void visitIs(Expr.Is expr, Context context) {
Type t = expr.getTestType();
// Handle all non-trivial cases directly
if (t instanceof Type.Null) {
visitExpression(expr.getOperand(), context);
out.print(" === null");
} else if (t instanceof Type.Int) {
// FIXME: this will need to be updated when unbounded arithmetic is
// supported
out.print("typeof ");
visitExpression(expr.getOperand(), context);
out.print(" === \"number\"");
} else if (t instanceof Type.Bool) {
out.print("typeof ");
visitExpression(expr.getOperand(), context);
out.print(" === \"boolean\"");
} else {
// Fall back case
out.print("is$");
writeTypeMangle(t);
out.print("(");
visitExpression(expr.getOperand(), context);
out.print(")");
// Register this type test to be written out as an appropriately
// named function.
context.typeTests.add(t);
}
}
@Override
public void visitStaticVariableAccess(Expr.StaticVariableAccess expr, Context context) {
// FIXME: this is horrendously broken
out.print("Wy.copy(" + expr.getName() + ")");
}
@Override
public void visitVariableAccess(Expr.VariableAccess expr, Context context) {
Decl.Variable vd = expr.getVariableDeclaration();
// Variable move needs to be supported here
if (isCopyable(vd.getType(), expr)) {
out.print(vd.getName());
} else {
out.print("Wy.copy(" + vd.getName() + ")");
}
}
// Arrays
@Override
public void visitArrayLength(Expr.ArrayLength expr, Context context) {
visitExpression(expr.getOperand(), context);
out.print(".length");
}
@Override
public void visitArrayAccess(Expr.ArrayAccess expr, Context context) {
visitExpression(expr.getFirstOperand(), context);
out.print("[");
visitExpression(expr.getSecondOperand(), context);
out.print("]");
}
@Override
public void visitArrayInitialiser(Expr.ArrayInitialiser expr, Context context) {
Tuple<Expr> operands = expr.getOperands();
out.print("[");
for (int i = 0; i != operands.size(); ++i) {
if (i != 0) {
out.print(", ");
}
visitExpression(operands.get(i), context);
}
out.print("]");
}
@Override
public void visitArrayGenerator(Expr.ArrayGenerator expr, Context context) {
out.print("Wy.array(");
visitExpression(expr.getFirstOperand(), context);
out.print(", ");
visitExpression(expr.getSecondOperand(), context);
out.print(")");
}
// Bitwise
@Override
public void visitBitwiseAnd(Expr.BitwiseAnd expr, Context context) {
writeInfixOperator(expr,context);
}
@Override
public void visitBitwiseComplement(Expr.BitwiseComplement expr, Context context) {
// Prefix operators
out.print("((~");
writeBracketedExpression(expr.getOperand(), context);
out.print(") & 0xFF)");
}
@Override
public void visitBitwiseOr(Expr.BitwiseOr expr, Context context) {
writeInfixOperator(expr,context);
}
@Override
public void visitBitwiseShiftLeft(Expr.BitwiseShiftLeft expr, Context context) {
out.print("((");
writeBracketedExpression(expr.getFirstOperand(), context);
out.print(" << ");
writeBracketedExpression(expr.getSecondOperand(), context);
out.print(") & 0xFF)");
}
@Override
public void visitBitwiseShiftRight(Expr.BitwiseShiftRight expr, Context context) {
out.print("((");
writeBracketedExpression(expr.getFirstOperand(), context);
out.print(" >> ");
writeBracketedExpression(expr.getSecondOperand(), context);
out.print(") & 0xFF)");
}
@Override
public void visitBitwiseXor(Expr.BitwiseXor expr, Context context) {
writeInfixOperator(expr,context);
}
// Callables
@Override
public void visitIndirectInvoke(Expr.IndirectInvoke expr, Context context) {
visitExpression(expr.getSource(), context);
Tuple<Expr> arguments = expr.getArguments();
out.print("(");
for (int i = 0; i != arguments.size(); ++i) {
if (i != 0) {
out.print(", ");
}
visitExpression(arguments.get(i), context);
}
out.print(")");
}
@Override
public void visitInvoke(Expr.Invoke expr, Context context) {
Name name = expr.getName();
// FIXME: this doesn't work for imported function symbols!
out.print(name);
writeTypeMangle(expr.getSignature());
if(expr.getSignature() instanceof Type.Property) {
out.print("$property");
}
out.print("(");
Tuple<Expr> args = expr.getOperands();
for (int i = 0; i != args.size(); ++i) {
if (i != 0) {
out.print(", ");
}
visitExpression(args.get(i), context);
}
out.print(")");
}
@Override
public void visitLambdaAccess(Expr.LambdaAccess expr, Context context) {
// NOTE: the reason we use a function declaration here (i.e. instead of
// just assigning the name) is that it protects against potential name
// clashes with local variables.
Type.Callable ft = expr.getSignature();
Tuple<Type> params = ft.getParameters();
out.print("function(");
for (int i = 0; i != params.size(); ++i) {
if (i != 0) {
out.print(",");
}
out.print("p" + i);
}
out.print(") { return ");
out.print(expr.getName());
writeTypeMangle(ft);
out.print("(");
for (int i = 0; i != params.size(); ++i) {
if (i != 0) {
out.print(",");
}
out.print("p" + i);
}
out.print("); }");
}
// Integers
@Override
public void visitIntegerAddition(Expr.IntegerAddition expr, Context context) {
writeInfixOperator(expr,context);
}
@Override
public void visitIntegerDivision(Expr.IntegerDivision expr, Context context) {
out.print("Math.floor(");
writeInfixOperator(expr, context);
out.print(")");
}
@Override
public void visitIntegerRemainder(Expr.IntegerRemainder expr, Context context) {
writeInfixOperator(expr, context);
}
@Override
public void visitIntegerGreaterThan(Expr.IntegerGreaterThan expr, Context context) {
writeInfixOperator(expr,context);
}
@Override
public void visitIntegerGreaterThanOrEqual(Expr.IntegerGreaterThanOrEqual expr, Context context) {
writeInfixOperator(expr,context);
}
@Override
public void visitIntegerLessThan(Expr.IntegerLessThan expr, Context context) {
writeInfixOperator(expr,context);
}
@Override
public void visitIntegerLessThanOrEqual(Expr.IntegerLessThanOrEqual expr, Context context) {
writeInfixOperator(expr,context);
}
@Override
public void visitIntegerMultiplication(Expr.IntegerMultiplication expr, Context context) {
writeInfixOperator(expr,context);
}
@Override
public void visitIntegerNegation(Expr.IntegerNegation expr, Context context) {
// Prefix operators
out.print("-");
writeBracketedExpression(expr.getOperand(), context);
}
@Override
public void visitIntegerSubtraction(Expr.IntegerSubtraction expr, Context context) {
writeInfixOperator(expr,context);
}
// Logical
@Override
public void visitLogicalAnd(Expr.LogicalAnd expr, Context context) {
writeInfixOperator(expr,context);
}
@Override public void visitLogicalImplication(Expr.LogicalImplication expr, Context context) {
Tuple<Expr> operands = expr.getOperands();
if(operands.size() > 2) {
throw new IllegalArgumentException();
}
out.print("!");
writeBracketedExpression(operands.get(0), context);
out.print("||");
writeBracketedExpression(operands.get(1), context);
}
@Override public void visitLogicalIff(Expr.LogicalIff expr, Context context) {
Tuple<Expr> operands = expr.getOperands();
for(int i=0;i!=operands.size();++i) {
if(i != 0) {
out.print(" == ");
}
writeBracketedExpression(operands.get(i), context);
}
}
@Override
public void visitLogicalNot(Expr.LogicalNot expr, Context context) {
// Prefix operators
out.print("!");
writeBracketedExpression(expr.getOperand(), context);
}
@Override
public void visitLogicalOr(Expr.LogicalOr expr, Context context) {
writeInfixOperator(expr,context);
}
@Override
public void visitUniversalQuantifier(Expr.UniversalQuantifier expr, Context context) {
writeQuantifier(expr,context);
}
@Override
public void visitExistentialQuantifier(Expr.ExistentialQuantifier expr, Context context) {
writeQuantifier(expr,context);
}
public void writeQuantifier(Expr.Quantifier expr, Context context) {
out.print("Wy.");
out.print((expr instanceof Expr.UniversalQuantifier) ? "all" : "some");
out.print("(");
Tuple<Decl.Variable> params = expr.getParameters();
for (int i = 0; i != params.size(); ++i) {
Decl.Variable param = params.get(i);
if(i > 0) {
throw new RuntimeException("Need to support multiple operand groups");
}
// FIXME: for now assume initialiser must be an array range.
Expr.ArrayRange range = (Expr.ArrayRange) param.getInitialiser();
visitExpression(range.getFirstOperand(), context);
out.print(",");
visitExpression(range.getSecondOperand(), context);
}
out.print(",function(");
for (int i = 0; i != params.size(); ++i) {
Decl.Variable param = params.get(i);
out.print(param.getName());
}
out.print("){return ");
visitExpression(expr.getOperand(), context);
out.print(";})");
}
// Objects
@Override
public void visitNew(Expr.New expr, Context context) {
out.print("new Wy.Ref(");
visitExpression(expr.getOperand(), context);
out.print(")");
}
@Override
public void visitDereference(Expr.Dereference expr, Context context) {
out.print("Wy.deref(");
visitExpression(expr.getOperand(), context);
out.print(")");
}
// Records
@Override
public void visitRecordAccess(Expr.RecordAccess expr, Context context) {
writeBracketedExpression(expr.getOperand(), context);
out.print("." + expr.getField());
}
@Override
public void visitRecordInitialiser(Expr.RecordInitialiser expr, Context context) {
out.print("Wy.record({");
Tuple<Expr> operands = expr.getOperands();
Tuple<Identifier> fields = expr.getFields();
for (int i = 0; i != operands.size(); ++i) {
if (i != 0) {
out.print(", ");
}
out.print(fields.get(i));
out.print(": ");
visitExpression(operands.get(i), context);
}
out.print("})");
}
// Helpers
private void writeInvariantCheck(Tuple<Expr> invariant, Context context) {
for(int i=0;i!=invariant.size();++i) {
tabIndent(context.indent);
out.print("Wy.assert(");
visitExpression(invariant.get(i), context);
out.println(");");
}
}
private void writeInfixOperator(Expr.NaryOperator expr, Context context) {
Tuple<Expr> operands = expr.getOperands();
for (int i = 0; i != operands.size(); ++i) {
if (i != 0) {
out.print(" ");
out.print(opcode(expr.getOpcode()));
out.print(" ");
}
writeBracketedExpression(operands.get(i), context);
}
}
private void writeLVal(LVal lval, Context context) {
switch (lval.getOpcode()) {
case EXPR_aread:
writeArrayIndexLVal((Expr.ArrayAccess) lval, context);
break;
case EXPR_pread:
writeDereferenceLVal((Expr.Dereference) lval, context);
break;
case EXPR_rread:
writeFieldLoadLVal((Expr.RecordAccess) lval, context);
break;
case EXPR_varcopy:
case EXPR_varmove:
writeVariableAccessLVal((Expr.VariableAccess) lval, context);
break;
default:
throw new IllegalArgumentException("invalid lval: " + lval);
}
}
private void writeDereferenceLVal(Expr.Dereference expr, Context context) {
writeLVal((LVal) expr.getOperand(), context);
out.print(".$ref");
}
private void writeArrayIndexLVal(Expr.ArrayAccess expr, Context context) {
writeLVal((LVal) expr.getFirstOperand(), context);
out.print("[");
visitExpression(expr.getSecondOperand(), context);
out.print("]");
}
private void writeFieldLoadLVal(Expr.RecordAccess expr, Context context) {
writeLVal((LVal) expr.getOperand(), context);
out.print("." + expr.getField());
}
private void writeVariableAccessLVal(Expr.VariableAccess expr, Context context) {
Decl.Variable vd = expr.getVariableDeclaration();
out.print(vd.getName());
}
private void writeTypeTests(Set<Type> typeTests, Set<Type> allTests) {
HashSet<Type> deps = new HashSet<>();
for(Type type : typeTests) {
out.print("function is$");
writeTypeMangle(type);
out.print("(val) {");
writeTypeTest(type, deps);
out.println("}");
out.println();
}
deps.removeAll(allTests);
allTests.addAll(deps);
if(deps.size() > 0) {
writeTypeTests(deps,allTests);
}
}
private void writeTypeTest(Type test, Set<Type> deps) {
if(test instanceof Type.Any) {
writeTypeTestAny((Type.Primitive) test,deps);
} else if(test instanceof Type.Null) {
writeTypeTestNull((Type.Primitive) test,deps);
} else if(test instanceof Type.Bool) {
writeTypeTestBool((Type.Primitive) test,deps);
} else if(test instanceof Type.Byte) {
// FIXME: This is clear incorrect. However, there is no better
// alternative. The good news is that the byte type is slated to be
// removed in future versions of Whiley and, hence, this problem
// will go away.
writeTypeTestInt((Type.Primitive) test,deps);
} else if(test instanceof Type.Int) {
writeTypeTestInt((Type.Primitive) test,deps);
} else if(test instanceof Type.Nominal) {
writeTypeTestNominal((Type.Nominal) test,deps);
} else if(test instanceof Type.Array) {
writeTypeTestArray((Type.Array) test,deps);
} else if(test instanceof Type.Reference) {
writeTypeTestReference((Type.Reference) test,deps);
} else if(test instanceof Type.Record) {
writeTypeTestRecord((Type.Record) test,deps);
} else if(test instanceof Type.Callable) {
writeTypeTestFunctionOrMethod((Type.Callable) test,deps);
} else if(test instanceof Type.Negation) {
writeTypeTestNegation((Type.Negation) test,deps);
} else if(test instanceof Type.Union) {
writeTypeTestUnion((Type.Union) test,deps);
} else if(test instanceof Type.Intersection) {
writeTypeTestIntersection((Type.Intersection) test,deps);
} else {
throw new RuntimeException("unknown type encountered: " + test);
}
}
private void writeTypeTestAny(Type.Primitive test, Set<Type> deps) {
out.print(" return true; ");
}
private void writeTypeTestNull(Type.Primitive test, Set<Type> deps) {
out.print(" return val === null; ");
}
private void writeTypeTestBool(Type.Primitive test, Set<Type> deps) {
out.print(" return typeof val === \"boolean\"; ");
}
private void writeTypeTestInt(Type.Primitive test, Set<Type> deps) {
out.print(" return typeof val === \"number\"; ");
}
private void writeTypeTestNominal(Type.Nominal test, Set<Type> deps) {
// FIXME: this is so horrendously broken
Name name = test.getName();
try {
Decl.Type td = typeSystem.resolveExactly(name, Decl.Type.class);
out.print(" return is$");
writeTypeMangle(td.getVariableDeclaration().getType());
out.print("(val) && " + name.getLast() + "$type(val); ");
deps.add(td.getVariableDeclaration().getType());
} catch (ResolutionError e) {
throw new RuntimeException(e);
}
}
private static int variableIndex = 0;
private void writeTypeTestArray(Type.Array test, Set<Type> deps) {
out.println();
tabIndent(1);
out.println("if(val != null && val.constructor === Array) {");
tabIndent(2);
// FIXME: could optimise this in the case of element "any"
String var = "i" + (variableIndex++);
out.println("for(var x=0;x!=val.length;++x) {".replaceAll("x", var));
tabIndent(3);
out.print("if(!is$");
writeTypeMangle(test.getElement());
out.println("(val[" + var +"])) {");
tabIndent(4);
out.println("return false;");
tabIndent(3);
out.println("}");
tabIndent(2);
out.println("}");
tabIndent(2);
out.println("return true;");
tabIndent(1);
out.println("}");
tabIndent(1);
out.println("return false;");
// Add a follow-on dependency
deps.add(test.getElement());
}
private void writeTypeTestReference(Type.Reference test, Set<Type> deps) {
out.println();
tabIndent(1);
out.println("if(val != null && val.constructor === Wy.Ref) {");
tabIndent(2);
out.print(" return is$");
writeTypeMangle(test.getElement());
out.println("(Wy.deref(val));");
tabIndent(1);
out.println("}");
tabIndent(1);
out.println("return false;");
deps.add(test.getElement());
}
private void writeTypeTestRecord(Type.Record test, Set<Type> deps) {
out.println();
tabIndent(1);
out.print("if(val != null && typeof val === \"object\"");
Tuple<Decl.Variable> fields = test.getFields();
if (!test.isOpen()) {
out.print(" && Object.keys(val).length === " + fields.size());
}
out.println(") {");
for (int i = 0; i != fields.size(); ++i) {
Decl.Variable field = fields.get(i);
tabIndent(2);
out.print("if(val." + field.getName() + " === \"undefined\" || !is$");
writeTypeMangle(field.getType());
out.println("(val." + field.getName() + ")) { return false; }");
deps.add(field.getType());
}
tabIndent(2);
out.println("return true;");
tabIndent(1);
out.println("}");
tabIndent(1);
out.println("return false;");
}
/**
* Perform a runtime type test looking for a function or method of a given
* type. This is tricky in JavaScript since there is insufficient type
* information available. Specifically, <code>typeof f</code> (for some
* function f) returns only <code>"function"</code>.
*
* @param test
* @param deps
*/
private void writeTypeTestFunctionOrMethod(Type.Callable test, Set<Type> deps) {
out.println();
tabIndent(1);
out.println("if(val != null && typeof val === \"function\") {");
// FIXME: we need to do more here to distinguish functions. We could,
// for example, try to embed their signature string.
tabIndent(2);
out.println("return true;");
tabIndent(1);
out.println("}");
tabIndent(1);
out.println("return false;");
}
private void writeTypeTestNegation(Type.Negation test, Set<Type> deps) {
out.print(" return !(is$");
writeTypeMangle(test.getElement());
out.print("(val)); ");
deps.add(test.getElement());
}
private void writeTypeTestUnion(Type.Union test, Set<Type> deps) {
out.println();
for(int i=0;i!=test.size();++i) {
Type bound = test.get(i);
tabIndent(1);
out.print("if(is$");
writeTypeMangle(bound);
out.println("(val)) { return true; }");
deps.add(bound);
}
tabIndent(1);
out.print("return false;");
}
private void writeTypeTestIntersection(Type.Intersection test, Set<Type> deps) {
out.println();
for(int i=0;i!=test.size();++i) {
Type bound = test.get(i);
tabIndent(1);
out.print("if(!is$");
writeTypeMangle(bound);
out.println("(val)) { return false; }");
deps.add(bound);
}
tabIndent(1);
out.print("return true;");
}
private void writeTypeMangle(Type.Callable fmt) {
Tuple<Type> params = fmt.getParameters();
for (int i = 0; i != params.size(); ++i) {
if (i == 0) {
out.print("_");
}
writeTypeMangle(params.get(i));
}
}
private void writeTypeMangle(Type t) {
if (t instanceof Type.Any) {
out.print("T");
} else if (t instanceof Type.Null) {
out.print("N");
} else if (t instanceof Type.Bool) {
out.print("B");
} else if (t instanceof Type.Byte) {
out.print("U");
} else if (t instanceof Type.Int) {
out.print("I");
} else if (t instanceof Type.Array) {
writeTypeMangleArray((Type.Array) t);
} else if (t instanceof Type.Reference) {
writeTypeMangleReference((Type.Reference) t);
} else if (t instanceof Type.Record) {
writeTypeMangleRecord((Type.Record) t);
} else if (t instanceof Type.Nominal) {
writeTypeMangleNominal((Type.Nominal) t);
} else if (t instanceof Type.Callable) {
writeTypeMangleFunctionOrMethod((Type.Callable) t);
} else if (t instanceof Type.Negation) {
writeTypeMangleNegation((Type.Negation) t);
} else if (t instanceof Type.Union) {
writeTypeMangleUnion((Type.Union) t);
} else if (t instanceof Type.Intersection) {
writeTypeMangleIntersection((Type.Intersection) t);
} else {
throw new IllegalArgumentException("unknown type encountered: " + t);
}
}
private void writeTypeMangleArray(Type.Array t) {
out.print("a");
writeTypeMangle(t.getElement());
}
private void writeTypeMangleReference(Type.Reference t) {
out.print("p");
if (t.hasLifetime()) {
String lifetime = t.getLifetime().get();
if(lifetime.equals("*")) {
out.print("_");
} else {
out.print(lifetime.length());
out.print(lifetime);
}
} else {
out.print("0");
}
writeTypeMangle(t.getElement());
}
private void writeTypeMangleRecord(Type.Record rt) {
out.print("r");
Tuple<Decl.Variable> fields = rt.getFields();
out.print(fields.size());
for (int i = 0; i != fields.size(); ++i) {
Decl.Variable field = fields.get(i);
writeTypeMangle(field.getType());
String fieldName = field.getName().get();
out.print(fieldName.length());
out.print(fieldName);
}
}
private void writeTypeMangleNominal(Type.Nominal t) {
out.print("n");
// FIXME: need to figure out package
String name = t.getName().getLast().get();
out.print(name.length());
out.print(name);
}
private void writeTypeMangleFunctionOrMethod(Type.Callable t) {
if (t instanceof Type.Function) {
out.print("f");
} else {
out.print("m");
}
Tuple<Type> params = t.getParameters();
out.print(params.size());
for (int i = 0; i != params.size(); ++i) {
writeTypeMangle(params.get(i));
}
Tuple<Type> returns = t.getReturns();
out.print(returns.size());
for (int i = 0; i != returns.size(); ++i) {
writeTypeMangle(returns.get(i));
}
out.print("e");
}
private void writeTypeMangleNegation(Type.Negation t) {
out.print("n");
writeTypeMangle(t.getElement());
}
private void writeTypeMangleUnion(Type.Union t) {
out.print("u");
out.print(t.size());
for(int i=0;i!=t.size();++i) {
writeTypeMangle(t.get(i));
}
}
private void writeTypeMangleIntersection(Type.Intersection t) {
out.print("c");
out.print(t.size());
for(int i=0;i!=t.size();++i) {
writeTypeMangle(t.get(i));
}
}
private void writeType(Type t) {
if(commentTypes) {
out.print("/*");
out.print(t);
out.print("*/");
}
}
/**
* Return true if the type in question can be copied directly. More
* specifically, if a bitwise copy of the value is sufficient to fully copy
* it. In general, this is true for primitive data types in JavaScript. But,
* for array types or general class types, it is not true (since these are
* references into the heap). As an exception, class types which are known
* to be immutable can be safely considered as copyable.
*
* @param type
* @return
*/
private boolean isCopyable(Type type, SyntacticElement context) {
if(type instanceof Type.Any) {
return false;
} else if (type instanceof Type.Primitive) {
return true;
} else if (type instanceof Type.Callable) {
return true;
} else if (type instanceof Type.Reference) {
return true;
} else if (type instanceof Type.Nominal) {
Type.Nominal tn = (Type.Nominal) type;
try {
Decl.Type td = typeSystem.resolveExactly(tn.getName(), Decl.Type.class);
return isCopyable(td.getType(), context);
} catch (ResolutionError e) {
throw new RuntimeException(e);
}
} else {
return false;
}
}
private boolean needsBrackets(Expr e) {
switch(e.getOpcode()) {
case EXPR_cast:
case EXPR_iadd:
case EXPR_isub:
case EXPR_imul:
case EXPR_idiv:
case EXPR_irem:
case EXPR_eq:
case EXPR_neq:
case EXPR_ilt:
case EXPR_ile:
case EXPR_igt:
case EXPR_igteq:
case EXPR_land:
case EXPR_lor:
case EXPR_bor:
case EXPR_bxor:
case EXPR_band:
case EXPR_bshl:
case EXPR_bshr:
case EXPR_is:
case EXPR_pinit:
return true;
}
return false;
}
private static String opcode(int k) {
switch(k) {
case EXPR_ineg:
return "-";
case EXPR_lnot:
return "!";
case EXPR_bnot:
return "~";
case EXPR_pread:
return "*";
// Binary
case EXPR_iadd:
return "+";
case EXPR_isub:
return "-";
case EXPR_imul:
return "*";
case EXPR_idiv:
return "/";
case EXPR_irem:
return "%";
case EXPR_eq:
return "==";
case EXPR_neq:
return "!=";
case EXPR_ilt:
return "<";
case EXPR_ile:
return "<=";
case EXPR_igt:
return ">";
case EXPR_igteq:
return ">=";
case EXPR_land:
return "&&";
case EXPR_lor:
return "||";
case EXPR_bor:
return "|";
case EXPR_bxor:
return "^";
case EXPR_band:
return "&";
case EXPR_bshl:
return "<<";
case EXPR_bshr:
return ">>";
case EXPR_is:
return "is";
case EXPR_pinit:
return "new";
default:
throw new IllegalArgumentException("unknown operator kind : " + k);
}
}
private void tabIndent(int indent) {
indent = indent * 4;
for(int i=0;i<indent;++i) {
out.print(" ");
}
}
public static class Context {
public final int indent;
public final HashSet<Type> typeTests;
public Context(int indent, HashSet<Type> typeTests) {
this.indent = indent;
this.typeTests = typeTests;
}
public Context indent() {
return new Context(indent+1,typeTests);
}
}
}
|
package com.jarvis.core;
import com.jarvis.core.criteria.TermCriteria;
import org.apache.log4j.Logger;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.core.KeywordAnalyzer;
import org.apache.lucene.analysis.miscellaneous.PerFieldAnalyzerWrapper;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.*;
import org.apache.lucene.search.BooleanClause.Occur;
import org.apache.lucene.util.Version;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.apache.lucene.search.BooleanClause.Occur.SHOULD;
public class QueryScratchPad {
private static Logger logger = Logger.getLogger(QueryScratchPad.class);
private static final List<String> queries = new ArrayList<String>();
private static final Map<String, Analyzer> analyzerPerField = new HashMap<String, Analyzer>();
private static PerFieldAnalyzerWrapper analyzerWrapper = new PerFieldAnalyzerWrapper(new KeywordAnalyzer(), analyzerPerField);
static {
// description:iPhone
queries.add("iPhone");
// Microsoft AND Google
queries.add("Microsoft AND Google");
// "Perdue" AND "antibiotics"
queries.add("\"Perdue\" AND \"antibiotics\"");
// ("british columbia" OR BC) AND "wild within"
queries.add("(\"british columbia\" OR BC) AND \"wild within\"");
// "nwnatural" OR "nw natural" OR "northwest natural"
queries.add("\"nwnatural\" OR \"nw natural\" OR \"northwest natural\"");
// ( ( "dow" OR "chemical" ) AND ( "canada" ) ) AND NOT "dow jones"
queries.add("( ( \"dow\" OR \"chemical\" ) AND ( \"canada\" ) ) AND NOT \"dow jones\"");
// ( ( "Starbucks" OR "Tim Hortons" ) AND ( "coffee" ) ) AND NOT "tea"
queries.add("( ( \"Starbucks\" OR \"Tim Hortons\" ) AND ( \"coffee\" ) ) AND NOT \"tea\"");
queries.add("Medicare AND (\"Humana\" OR @Humana OR author:Humana OR author:Humana)");
// "#theNew10" OR "#theNewTen" OR "#new10" OR "#newTen" OR ("the new 10" AND "woman")
queries.add("\"#theNew10\" OR \"#theNewTen\" OR \"#new10\" OR \"#newTen\" OR (\"the new 10\" AND \"woman\")");
// NOT ("dow Jones" OR stock OR stocks OR download OR downloads OR price OR prices OR tick OR ticks OR investor OR investors OR job OR jobs OR point OR points OR poor OR poorer) AND (dow OR "dow chemical" OR "dow company") AND (innovation OR innovations OR "carbon dioxide" OR Carbon OR footprint OR "life cycle" OR chemistry)
queries.add("NOT (\"dow Jones\" OR stock OR stocks OR download OR downloads OR price OR prices OR tick OR ticks OR investor OR investors OR job OR jobs OR point OR points OR poor OR poorer) AND (dow OR \"dow chemical\" OR \"dow company\") AND (innovation OR innovations OR \"carbon dioxide\" OR Carbon OR footprint OR \"life cycle\" OR chemistry)");
// "@thegame OR (((\"the game\" OR game) AND (\"sexual assault\" OR accused OR \"sexually assaulting\" OR \"Priscilla Rainey\" OR rainey OR @shesgotgameVH1 OR VH1 OR TMZ)) OR (@shesgotgameVH1 OR \"rapper the game\" OR \"rapper, the game\" OR \"Jayceon Terrell Taylor\" OR \"Jayceon Taylor\" OR jayceonterrelltaylor OR jayceontaylor) AND (VH1 OR TMZ OR gross OR disgusting OR sued OR \"sexual assault\" OR accused OR \"sexually assaulting\" OR \"Priscilla Rainey\" OR rainey OR rapper OR 10million OR 10mill OR 10m OR contestant)) OR ((rapper OR #shesgotgame) AND (rainey OR @shesgotgameVH1 OR \"priscilla rainey\" OR VH1))"
queries.add("@thegame OR (((\"the game\" OR game) AND (\"sexual assault\" OR accused OR \"sexually assaulting\" OR \"Priscilla Rainey\" OR rainey OR @shesgotgameVH1 OR VH1 OR TMZ)) OR (@shesgotgameVH1 OR \"rapper the game\" OR \"rapper, the game\" OR \"Jayceon Terrell Taylor\" OR \"Jayceon Taylor\" OR jayceonterrelltaylor OR jayceontaylor) AND (VH1 OR TMZ OR gross OR disgusting OR sued OR \"sexual assault\" OR accused OR \"sexually assaulting\" OR \"Priscilla Rainey\" OR rainey OR rapper OR 10million OR 10mill OR 10m OR contestant)) OR ((rapper OR #shesgotgame) AND (rainey OR @shesgotgameVH1 OR \"priscilla rainey\" OR VH1))");
// description:(("nike" OR "shoes") AND ("sports" OR "win"))
queries.add("description:((\"nike\" OR \"shoes\") AND (\"sports\" OR \"win\"))");
// description:(("nike" "shoes") AND ("sports" "win"))
queries.add("description:((\"nike\" \"shoes\") AND (\"sports\" \"win\"))");
// description:(bike OR nike OR reebok OR adidas OR jordan OR "dc shoes" OR "New balance" OR "under armour" OR saucony)
queries.add("description:(bike OR nike OR reebok OR adidas OR jordan OR \"dc shoes\" OR \"New balance\" OR \"under armour\" OR saucony)");
}
private static final int maxQuery = 7;
public static void main(String[] args) throws ParseException {
buildCriteriaTree();
}
public static void buildCriteriaTree() throws ParseException {
List<TermCriteria> tcList = new ArrayList<TermCriteria>();
QueryParser luceneQP = new QueryParser(Version.LUCENE_44, "text", analyzerWrapper);
for(int i = 6; i < maxQuery; i++){
String qString = queries.get(i);
Query q = luceneQP.parse(qString);
buildCriteriaTree(qString, q, tcList);
}
displayCriteriaList(tcList);
}
private static void displayCriteriaList(List<TermCriteria> termCriteriaList){
for(TermCriteria termCriteria : termCriteriaList){
logger.info(String.format("TermCriteria Term:%-20s Fields: %s", termCriteria.getTerm(), termCriteria.getMustFields()));
}
}
public static void buildCriteriaTree(String qString, Query q, List<TermCriteria> tcList){
logger.info(String.format("Type:%-20s Original: %-25s Parsed: %s", q.getClass().getSimpleName(), qString, q));
if(q instanceof BooleanQuery){
BooleanQuery bq = (BooleanQuery) q;
for(BooleanClause bc : bq.clauses()) {
if(bc.getQuery() instanceof BooleanQuery) {
buildBQCriteria(0, bc, (BooleanQuery) bc.getQuery(), tcList);
} else {
buildNonBQCriteria(0, bc, bc.getQuery());
}
}
} else {
tcList.addAll(buildNonBQCriteria(0, q));
}
}
// Even the most wackiest nested queries couldn't cause problem with recursion.
public static void buildBQCriteria(int level, BooleanClause parentBC, BooleanQuery q, List<TermCriteria> tcList){
logger.info(String.format("%s%s %s {%s}", getPrintPrefix(level), parentBC.getOccur().name(), q.getClass().getSimpleName(), q));
level++;
for(BooleanClause bc : q.clauses()){
if(bc.getQuery() instanceof BooleanQuery) {
buildBQCriteria(level, bc, (BooleanQuery) bc.getQuery(), tcList);
} else {
buildNonBQCriteria(level, bc, bc.getQuery());
}
}
}
public static List<TermCriteria> buildNonBQCriteria(int level, Query q){
return buildNonBQCriteria(level, SHOULD, q);
}
public static List<TermCriteria> buildNonBQCriteria(int level, BooleanClause bc, Query q){
return buildNonBQCriteria(level, bc.getOccur(), q);
}
public static List<TermCriteria> buildNonBQCriteria(int level, Occur occur, Query q){
logger.info(String.format("%s%s %s {%s}", getPrintPrefix(level), occur.name(), q.getClass().getSimpleName(), q));
List<TermCriteria> termCriteriaList = new ArrayList<TermCriteria>(2);
if(q instanceof TermQuery){
termCriteriaList.add(createTermCriteria((TermQuery) q));
} else if(q instanceof PhraseQuery){
termCriteriaList.addAll(createTermCriteria((PhraseQuery) q));
}
return termCriteriaList;
}
private static TermCriteria createTermCriteria(TermQuery tq){
Term t = tq.getTerm();
return new TermCriteria(t.text(), t.field());
}
private static List<TermCriteria> createTermCriteria(PhraseQuery pq){
Term[] terms = pq.getTerms();
List<TermCriteria> tcList = new ArrayList<TermCriteria>(terms.length);
for(Term t : terms){
tcList.add(new TermCriteria(t.text(), t.field()));
}
return tcList;
}
private static final String prettyPrintPrefix = "
private static String getPrintPrefix(int level){
String prefix = "";
for(int i =0; i < level; i++) prefix += prettyPrintPrefix;
return String.format(" [%d] %s > ", level, prefix);
}
}
|
package edu.mit.streamjit.api;
/**
* The base interface of anything that can be put in a stream graph.
* @author Jeffrey Bosboom <jeffreybosboom@gmail.com>
* @since 11/7/2012
*/
public interface StreamElement<I, O> {
/**
* Initiates a visitation by the given visitor over the stream graph rooted
* at this element.
* @param v a visitor
*/
public void visit(StreamVisitor v);
}
|
package com.mes.msgboard;
import java.util.concurrent.Executor;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import com.google.common.base.Predicates;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@SpringBootApplication
@EnableSwagger2
@EnableAsync
@EnableResourceServer
@ComponentScan(basePackages = "com.*")
public class MesApplication {
public static void main(String[] args) {
SpringApplication.run(MesApplication.class, args);
}
@Bean
public Docket swaggerConfiguration() {
return new Docket(DocumentationType.SWAGGER_2).useDefaultResponseMessages(false).apiInfo(apiInfo()).select()
.paths(Predicates.not(PathSelectors.regex("/error.*")))
.paths(Predicates.not(PathSelectors.regex("/oauth.*"))).build();
}
@Bean(name = "threadPoolTaskExecutor")
public Executor threadPoolTaskExecutor() {
return new ThreadPoolTaskExecutor();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder().title("MES Api Documentation")
.description("Refer to the documentation below").description("Use the following curl command to get access token"
+ "\n\rAdd the token in Authorisation Header as \"Bearer {token}\""
+ "\n\r<strong>curl -X POST --user 'mes:secret' -d 'grant_type=password&username=johnd&password=1234' https://mes-beta.herokuapp.com/oauth/token</strong>"
+ "\n\r username <strong>johnd</strong> has ADMIN rights, and can create categories."
+ "\n\r username <strong>jacksond</strong> is a regular user. Both has same passwords")
.contact(new Contact("name", "url", "email")).version("1.0").build();
}
}
|
package com.ociweb.iot.maker;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ociweb.gl.api.Behavior;
import com.ociweb.gl.api.MsgCommandChannel;
import com.ociweb.gl.api.MsgRuntime;
import com.ociweb.gl.api.TelemetryConfig;
import com.ociweb.gl.impl.ChildClassScanner;
import com.ociweb.gl.impl.PrivateTopic;
import com.ociweb.gl.impl.schema.MessagePubSub;
import com.ociweb.gl.impl.schema.MessageSubscription;
import com.ociweb.gl.impl.schema.TrafficOrderSchema;
import com.ociweb.gl.impl.stage.ReactiveManagerPipeConsumer;
import com.ociweb.iot.hardware.HardwareImpl;
import com.ociweb.iot.hardware.impl.SerialInputSchema;
import com.ociweb.iot.hardware.impl.edison.GroveV3EdisonImpl;
import com.ociweb.iot.hardware.impl.grovepi.BeagleBoneModel;
import com.ociweb.iot.hardware.impl.grovepi.GrovePiHardwareImpl;
import com.ociweb.iot.hardware.impl.grovepi.LinuxDesktopModel;
import com.ociweb.iot.hardware.impl.grovepi.MacModel;
import com.ociweb.iot.hardware.impl.grovepi.PiModel;
import com.ociweb.iot.hardware.impl.grovepi.WindowsDesktopModel;
import com.ociweb.iot.hardware.impl.test.TestHardware;
import com.ociweb.pronghorn.iot.ReactiveIoTListenerStage;
import com.ociweb.pronghorn.iot.i2c.I2CBacking;
import com.ociweb.pronghorn.iot.schema.GroveRequestSchema;
import com.ociweb.pronghorn.iot.schema.GroveResponseSchema;
import com.ociweb.pronghorn.iot.schema.I2CCommandSchema;
import com.ociweb.pronghorn.iot.schema.I2CResponseSchema;
import com.ociweb.pronghorn.iot.schema.ImageSchema;
import com.ociweb.pronghorn.pipe.DataInputBlobReader;
import com.ociweb.pronghorn.pipe.Pipe;
import com.ociweb.pronghorn.pipe.PipeConfig;
import com.ociweb.pronghorn.pipe.PipeConfigManager;
import com.ociweb.pronghorn.stage.PronghornStage;
import com.ociweb.pronghorn.stage.scheduling.GraphManager;
import com.ociweb.pronghorn.stage.scheduling.ScriptedNonThreadScheduler;
public class FogRuntime extends MsgRuntime<HardwareImpl, ListenerFilterIoT> {
private static boolean isRunning = false;
public static final int I2C_WRITER = FogCommandChannel.I2C_WRITER;
public static final int PIN_WRITER = FogCommandChannel.PIN_WRITER;
public static final int SERIAL_WRITER = FogCommandChannel.SERIAL_WRITER;
public static final int BT_WRITER = FogCommandChannel.BT_WRITER;
private static final Logger logger = LoggerFactory.getLogger(FogRuntime.class);
private static final int i2cDefaultLength = 300;
private static final int i2cDefaultMaxPayload = 16;
private static final byte edI2C = 6;
static final String PROVIDED_HARDWARE_IMPL_NAME = "com.ociweb.iot.hardware.impl.ProvidedHardwareImpl";
private boolean disableHardwareDetection;
public FogRuntime() {
this(new String[0]);
}
public FogRuntime(String name) {
this(new String[0],name);
}
public FogRuntime(String[] args) {
super(args,null);
disableHardwareDetection = this.hasArgument("disableHardwareDetection", "--dhd");
}
public FogRuntime(String[] args, String name) {
super(args,name);
disableHardwareDetection = this.hasArgument("disableHardwareDetection", "--dhd");
}
public Hardware getHardware(){
if(this.builder==null){
if (!disableHardwareDetection) {
//setup system for binary binding in case Zulu is found on Arm
//must populate os.arch as "arm" instead of "aarch32" or "aarch64" in that case, JIFFI is dependent on this value.
if (System.getProperty("os.arch", "unknown").contains("aarch")) {
System.setProperty("os.arch", "arm"); //TODO: investigate if this a bug against jiffi or zulu and inform them
}
long startTime = System.currentTimeMillis();
// Detect provided hardware implementation.
// TODO: Should this ONLY occur on Android devices?
try {
Class.forName("android.app.Activity");
logger.trace("Detected Android environment. Searching for {}.", PROVIDED_HARDWARE_IMPL_NAME);
try {
Class<?> clazz = Class.forName(PROVIDED_HARDWARE_IMPL_NAME);
logger.trace("Detected {}.", PROVIDED_HARDWARE_IMPL_NAME);
try {
this.builder = (HardwareImpl) clazz.getConstructor(GraphManager.class).newInstance(gm);
return this.builder;
} catch (NoSuchMethodException e) {
logger.warn(
"{} does not provide a single argument constructor that accepts a GraphManager. Continuing native hardware detection.", PROVIDED_HARDWARE_IMPL_NAME);
} catch (Throwable e) {
logger.warn(
"Unable to instantiate {}. Continuing native hardware detection.", PROVIDED_HARDWARE_IMPL_NAME, e);
}
} catch (ClassNotFoundException e) {
logger.trace("No {} is present.", PROVIDED_HARDWARE_IMPL_NAME);
}
} catch (ClassNotFoundException ignored) { }
logger.info("android duration {} ",System.currentTimeMillis()-startTime);
//The best way to detect the pi or edison is to first check for the expected matching i2c implmentation
PiModel pm = null;
BeagleBoneModel bm = null;
I2CBacking i2cBacking = null;
// else if((bm = BeagleBoneModel.detect()) != BeagleBoneModel.Unknown) { //NOTE: this requres Super user to run
// this.builder = new TestHardware(gm, args);
// logger.info("Detected running on " + bm);
if ((pm = PiModel.detect()) != PiModel.Unknown){
logger.info("Detected running on " + pm);
this.builder = new GrovePiHardwareImpl(gm, args, pm.i2cBus());
}
else if(WindowsDesktopModel.detect() != WindowsDesktopModel.Unknown) {
this.builder = new TestHardware(gm, args);
logger.info("Detected running on Windows, test mock hardware will be used");
}
else if(LinuxDesktopModel.detect() != LinuxDesktopModel.Unknown) {
this.builder = new TestHardware(gm, args);
logger.info("Detected Running on Linux, test mock hardware will be used");
}
else if(MacModel.detect() != MacModel.Unknown) {
this.builder = new TestHardware(gm, args);
logger.info("Detected running on Mac, test mock hardware will be used");
}
else if (null != (this.builder = new GroveV3EdisonImpl(gm, args, edI2C)).getI2CBacking() ) {
logger.info("Detected running on Edison");
System.out.println("You are running on the Edison hardware.");
}
else {
this.builder = new TestHardware(gm, args);
logger.info("Unrecognized hardware, test mock hardware will be used");
}
} else
{
this.builder = new TestHardware(gm, args);
logger.info("Hardware detection disabled on the command line, now using mock hardware.");
}
}
return this.builder;
}
public FogCommandChannel newCommandChannel() {
int instance = -1;
PipeConfigManager pcm = buildPipeManager();
return this.builder.newCommandChannel(instance, pcm);
}
public FogCommandChannel newCommandChannel(int features) {
int instance = -1;
PipeConfigManager pcm = buildPipeManager();
return this.builder.newCommandChannel(features, instance, pcm);
}
protected PipeConfigManager buildPipeManager() {
PipeConfigManager pcm = super.buildPipeManager();
pcm.addConfig(new PipeConfig<GroveRequestSchema>(GroveRequestSchema.instance, defaultCommandChannelLength));
pcm.addConfig(new PipeConfig<I2CCommandSchema>(I2CCommandSchema.instance, i2cDefaultLength,i2cDefaultMaxPayload));
pcm.addConfig(defaultCommandChannelLength,0,TrafficOrderSchema.class );
return pcm;
}
public FogCommandChannel newCommandChannel(int features, int customChannelLength) {
int instance = -1;
PipeConfigManager pcm = new PipeConfigManager();
pcm.addConfig(customChannelLength,0,GroveRequestSchema.class);
pcm.addConfig(customChannelLength, defaultCommandChannelMaxPayload, I2CCommandSchema.class);
pcm.addConfig(customChannelLength, defaultCommandChannelMaxPayload, MessagePubSub.class );
pcm.addConfig(customChannelLength,0,TrafficOrderSchema.class);
return this.builder.newCommandChannel(features, instance, pcm);
}
public ListenerFilterIoT addRotaryListener(RotaryListener listener) {
return registerListener(listener);
}
public ListenerFilterIoT addAnalogListener(AnalogListener listener) {
return registerListener(listener);
}
public ListenerFilterIoT addDigitalListener(DigitalListener listener) {
return registerListener(listener);
}
public ListenerFilterIoT addSerialListener(SerialListener listener) {
return registerListener(listener);
}
public ListenerFilterIoT registerListener(Behavior listener) {
return registerListenerImpl(listener);
}
public ListenerFilterIoT addImageListener(ImageListener listener) {
switch (builder.getPlatformType()) {
case GROVE_PI:
return registerListener(listener);
default:
throw new UnsupportedOperationException("Image listeners are not supported for [" +
builder.getPlatformType() +
"] hardware");
}
}
public ListenerFilterIoT addI2CListener(I2CListener listener) {
return registerListenerImpl(listener);
}
public ListenerFilterIoT addRotaryListener(String id, RotaryListener listener) {
return registerListener(id, listener);
}
public ListenerFilterIoT addAnalogListener(String id, AnalogListener listener) {
return registerListener(id, listener);
}
public ListenerFilterIoT addDigitalListener(String id, DigitalListener listener) {
return registerListener(id, listener);
}
public ListenerFilterIoT addSerialListener(String id, SerialListener listener) {
return registerListener(id, listener);
}
public ListenerFilterIoT registerListener(String id, Behavior listener) {
return registerListenerImpl(id, listener);
}
public ListenerFilterIoT addImageListener(String id, ImageListener listener) {
switch (builder.getPlatformType()) {
case GROVE_PI:
return registerListener(id, listener);
default:
throw new UnsupportedOperationException("Image listeners are not supported for [" +
builder.getPlatformType() +
"] hardware");
}
}
public ListenerFilterIoT addI2CListener(String id, I2CListener listener) {
return registerListenerImpl(id, listener);
}
private ListenerFilterIoT registerListenerImpl(Behavior listener) {
return registerListenerImpl(null, listener);
}
private ListenerFilterIoT registerListenerImpl(String id, Behavior listener) {
outputPipes = new Pipe<?>[0];
ChildClassScanner.visitUsedByClass(listener, gatherPipesVisitor, MsgCommandChannel.class);//populates OutputPipes
//pre-count how many pipes will be needed so the array can be built to the right size
int pipesCount = 0;
if (this.builder.isListeningToI2C(listener) && this.builder.hasI2CInputs()) {
pipesCount++;
}
if (this.builder.isListeningToPins(listener) && this.builder.hasDigitalOrAnalogInputs()) {
pipesCount++;
}
if (this.builder.isListeningToSerial(listener)) {
pipesCount++;
}
if (this.builder.isListeningToCamera(listener)) {
pipesCount++;
}
pipesCount = addGreenPipesCount(listener, pipesCount);
Pipe<?>[] inputPipes = new Pipe<?>[pipesCount];
if (this.builder.isListeningToI2C(listener) && this.builder.hasI2CInputs()) {
inputPipes[--pipesCount] = new Pipe<I2CResponseSchema>(new PipeConfig<I2CResponseSchema>(I2CResponseSchema.instance, defaultCommandChannelLength, defaultCommandChannelMaxPayload).grow2x());
}
if (this.builder.isListeningToPins(listener) && this.builder.hasDigitalOrAnalogInputs()) {
inputPipes[--pipesCount] = new Pipe<GroveResponseSchema>(new PipeConfig<GroveResponseSchema>(GroveResponseSchema.instance, defaultCommandChannelLength).grow2x());
}
if (this.builder.isListeningToSerial(listener) ) {
inputPipes[--pipesCount] = newSerialInputPipe(new PipeConfig<SerialInputSchema>(SerialInputSchema.instance, defaultCommandChannelLength, defaultCommandChannelMaxPayload).grow2x());
}
if (this.builder.isListeningToCamera(listener)) {
inputPipes[--pipesCount] = new Pipe<ImageSchema>(new PipeConfig<ImageSchema>(ImageSchema.instance, defaultCommandChannelLength, defaultCommandChannelMaxPayload).grow2x());
}
final int httpClientPipeId = netResponsePipeIdx; //must be grabbed before populateGreenPipes
populateGreenPipes(listener, pipesCount, inputPipes);
//StartupListener is not driven by any response data and is called when the stage is started up. no pipe needed.
//TimeListener, time rate signals are sent from the stages its self and therefore does not need a pipe to consume.
//this is empty when transducerAutowiring is off
final ArrayList<ReactiveManagerPipeConsumer> consumers = new ArrayList<ReactiveManagerPipeConsumer>();
//extract this into common method to be called in GL and FL
if (transducerAutowiring) {
inputPipes = autoWireTransducers(listener, inputPipes, consumers);
}
if (null!=id) {
List<PrivateTopic> sourceTopics = builder.getPrivateTopicsFromSource(id);
int i = sourceTopics.size();
while (--i>=0) {
PrivateTopic privateTopic = sourceTopics.get(i);
outputPipes = PronghornStage.join(outputPipes, privateTopic.getPipe(parallelInstanceUnderActiveConstruction));
}
List<PrivateTopic> targetTopics = builder.getPrivateTopicsFromTarget(id);
int j = targetTopics.size();
while (--j>=0) {
PrivateTopic privateTopic = targetTopics.get(i);
inputPipes = PronghornStage.join(inputPipes, privateTopic.getPipe(parallelInstanceUnderActiveConstruction));
}
}
ReactiveIoTListenerStage reactiveListener = builder.createReactiveListener(
gm, listener,
inputPipes,
outputPipes,
consumers,
parallelInstanceUnderActiveConstruction, id);
configureStageRate(listener, reactiveListener);
//TODO: this is a new test adding this pipe.
if (httpClientPipeId != netResponsePipeIdx) {
//TODO: We need to add all the Sessions however we do not know this until later.
reactiveListener.configureHTTPClientResponseSupport(httpClientPipeId);
}
assert(checkPipeOrders(inputPipes));
return reactiveListener;
}
private boolean checkPipeOrders(Pipe<?>[] inputPipes) {
///only for assert
int testId = -1;
int i = inputPipes.length;
while (--i>=0) {
if (inputPipes[i]!=null
&& Pipe.isForSchema((Pipe<MessageSubscription>)inputPipes[i], MessageSubscription.class)) {
testId = inputPipes[i].id;
}
}
assert(-1==testId || GraphManager.allPipesOfType(gm, MessageSubscription.instance)[subscriptionPipeIdx-1].id==testId) : "GraphManager has returned the pipes out of the expected order";
return true;
}
private static Pipe<SerialInputSchema> newSerialInputPipe(PipeConfig<SerialInputSchema> config) {
return new Pipe<SerialInputSchema>(config) {
@SuppressWarnings("unchecked")
@Override
protected DataInputBlobReader<SerialInputSchema> createNewBlobReader() {
return new SerialReader(this);
}
};
}
@Deprecated
public static FogRuntime test(FogApp app) {
FogRuntime runtime = new FogRuntime();
test(app, runtime);
return runtime;
}
public static boolean testConcurrentUntilShutdownRequested(FogApp app, long timeoutMS) {
long limit = System.nanoTime() + (timeoutMS*1_000_000L);
MsgRuntime runtime = run(app);
while (!runtime.isShutdownComplete()) {
if (System.nanoTime() > limit) {
logger.warn("exit due to timeout");
return false;
}
try {
Thread.sleep(2);
} catch (InterruptedException e) {
return false;
}
}
return true;
}
public static boolean testUntilShutdownRequested(FogApp app, long timeoutMS) {
FogRuntime runtime = new FogRuntime(app.getClass().getSimpleName());
ScriptedNonThreadScheduler s = test(app, runtime);
long limit = System.nanoTime() + (timeoutMS*1_000_000L);
boolean result = true;
s.startup(true);
while (!ScriptedNonThreadScheduler.isShutdownRequested(s)) {
s.run();
if (System.nanoTime() > limit) {
result = false;
break;
}
}
s.shutdown();
return result;
}
public static ScriptedNonThreadScheduler test(FogApp app, FogRuntime runtime) {
//force hardware to TestHardware regardless of where or what platform its run on.
//this is done because this is the test() method and must behave the same everywhere.
runtime.builder = new TestHardware(runtime.gm, runtime.args);
TestHardware hardware = (TestHardware)runtime.getHardware();
hardware.isInUnitTest = true;
app.declareConfiguration(runtime.builder);
GraphManager.addDefaultNota(runtime.gm, GraphManager.SCHEDULE_RATE, runtime.builder.getDefaultSleepRateNS());
runtime.declareBehavior(app);
runtime.builder.coldSetup(); //TODO: should we add LCD init in the PI hardware code? How do we know when its used?
runtime.builder.buildStages(runtime);
runtime.logStageScheduleRates();
TelemetryConfig telemetryConfig = runtime.builder.getTelemetryConfig();
if (telemetryConfig != null) {
runtime.telemetryHost = runtime.gm.enableTelemetry(telemetryConfig.getHost(), telemetryConfig.getPort());
}
//exportGraphDotFile();
runtime.setScheduler(new ScriptedNonThreadScheduler(runtime.gm, null, false));
//= runtime.builder.createScheduler(runtime);
//for test we do not call startup and wait instead for this to be done by test.
return (ScriptedNonThreadScheduler)runtime.getScheduler();
}
public static FogRuntime run(FogApp app) {
return run(app,new String[0]);
}
public static FogRuntime run(FogApp app, String[] args) throws UnsupportedOperationException {
if (FogRuntime.isRunning){
throw new UnsupportedOperationException("An FogApp is already running!");
}
long lastTime;
long nowTime;
FogRuntime.isRunning = true;
FogRuntime runtime = new FogRuntime(args);
logger.info("{} ms startup", lastTime = System.currentTimeMillis());
Hardware hardware = runtime.getHardware();
//this default for Fog is slower due to the expected minimum hardware of iot devices
hardware.setDefaultRate(4_000_000); // 4 ms
app.declareConfiguration(hardware);
GraphManager.addDefaultNota(runtime.gm, GraphManager.SCHEDULE_RATE, runtime.builder.getDefaultSleepRateNS());
logger.info("{} ms duration {} ms finished declare configuration", nowTime = System.currentTimeMillis(), nowTime-lastTime);
lastTime = nowTime;
runtime.declareBehavior(app);
logger.info("{} ms duration {} ms finished declare behavior", nowTime = System.currentTimeMillis(), nowTime-lastTime);
lastTime = nowTime;
//TODO: at this point realize the stages in declare behavior
// all updates are done so create the reactors with the right pipes and names
// this change will let us move routes to part of the fluent API plus other benifits..
// move all reactor fields into object created early, shell is created here.
// register must hold list of all temp objects (linked list to preserve order?)
System.out.println("To exit app press Ctrl-C");
runtime.builder.coldSetup(); //TODO: should we add LCD init in the PI hardware code? How do we know when its used?
runtime.builder.buildStages(runtime);
runtime.logStageScheduleRates();
logger.info("{} ms duration {} ms finished building internal graph", nowTime = System.currentTimeMillis(), nowTime-lastTime);
lastTime = nowTime;
TelemetryConfig telemetryConfig = runtime.builder.getTelemetryConfig();
if (telemetryConfig != null) {
runtime.telemetryHost = runtime.gm.enableTelemetry(telemetryConfig.getHost(), telemetryConfig.getPort());
}
//exportGraphDotFile();
runtime.setScheduler(runtime.builder.createScheduler(runtime));
runtime.getScheduler().startup();
logger.info("{} ms duration {} ms finished graph startup", nowTime = System.currentTimeMillis(), nowTime-lastTime);
lastTime = nowTime;
return runtime;
}
}
|
package com.sdl.selenium.extjs6.tab;
import com.sdl.selenium.conditions.ConditionManager;
import com.sdl.selenium.conditions.RenderSuccessCondition;
import com.sdl.selenium.web.SearchType;
import com.sdl.selenium.web.WebLocator;
import com.sdl.selenium.web.XPathBuilder;
import com.sdl.selenium.web.link.WebLink;
import com.sdl.selenium.web.tab.ITab;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Tab extends WebLocator implements ITab {
private static final Logger LOGGER = LoggerFactory.getLogger(Tab.class);
public Tab() {
setClassName("TabPanel");
setBaseCls("x-tab-bar");
WebLink activeTab = new WebLink().setClasses("x-tab-active");
setTemplateTitle(new WebLocator(activeTab));
}
public Tab(String title) {
this();
setTitle(title, SearchType.EQUALS, SearchType.DEEP_CHILD_NODE);
}
public Tab(WebLocator container) {
this();
setContainer(container);
}
public Tab(WebLocator container, String title) {
this(title);
setContainer(container);
}
public WebLocator getTitleInactiveEl() {
WebLocator container = new WebLocator(getPathBuilder().getContainer()).setClasses(getPathBuilder().getBaseCls()).setTag(getPathBuilder().getTag());
return new WebLink(container).setText(getPathBuilder().getTitle(), SearchType.DEEP_CHILD_NODE, SearchType.EQUALS)
.setInfoMessage(getPathBuilder().getTitle() + " Tab");
}
/**
* this method return the path of the main Tab (that contains also this Tab/Panel)
*
* @return the path of the main TabPanel
*/
private String getBaseTabPanelPath() {
String selector = getPathBuilder().getBasePath();
return getPathBuilder().getRoot() + getPathBuilder().getTag() + "[" + selector + "]";
}
protected XPathBuilder createXPathBuilder() {
return new XPathBuilder() {
/**
* this method return the path of only one visible div from the main TabPanel
* @param disabled disabled
* @return the path of only one visible div from the main TabPanel
*/
@Override
public String getItemPath(boolean disabled) {
WebLocator body = new WebLocator().setTag("following-sibling::*").setClasses("x-panel-body");
WebLocator tab = new WebLocator(body).setRoot("/").setExcludeClasses("x-hidden-offsets").setClasses("x-tabpanel-child");
return getBaseTabPanelPath() + tab.getXPath();
}
};
}
/**
* After the tab is set to active
*
* @return true or false
*/
@Override
public boolean setActive() {
WebLocator inactiveTab = getTitleInactiveEl().setExcludeClasses("x-tab-active");
boolean activated = isActive() || inactiveTab.click();
if (activated) {
LOGGER.info("setActive : " + toString());
}
return activated;
}
@Override
public boolean isActive() {
return new ConditionManager(200).add(new RenderSuccessCondition(this)).execute().isSuccess();
}
public boolean isTabDisplayed() {
return getTitleInactiveEl().ready();
}
public boolean close() {
WebLocator titleEl = getTitleInactiveEl().setClasses("x-tab-active");
WebLocator closeEl = new WebLocator(titleEl).setClasses("x-tab-close-btn");
return closeEl.click();
}
}
|
package com.zakgof.db.velvet;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import com.zakgof.db.velvet.annotation.AutoKey;
import com.zakgof.db.velvet.annotation.Key;
import com.zakgof.db.velvet.annotation.Kind;
import com.zakgof.tools.generic.IFunction;
public class VelvetUtil {
public static Object keyOf(Object node) {
if (node == null)
return null;
try {
Class<?> clazz = node.getClass();
for (Field field : getAllFields(clazz)) {
field.setAccessible(true);
if (field.getAnnotation(Key.class) != null || field.getAnnotation(AutoKey.class) != null)
return field.get(node);
}
for (Method method : clazz.getDeclaredMethods()) {
method.setAccessible(true);
if (method.getAnnotation(Key.class) != null)
return method.invoke(node);
}
throw new RuntimeException("No key found for " + clazz);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static String keyFieldOf(Class<?> clazz) {
try {
for (Field field : getAllFields(clazz)) {
field.setAccessible(true);
if (field.getAnnotation(Key.class) != null || field.getAnnotation(AutoKey.class) != null)
return field.getName();
}
for (Method method : clazz.getDeclaredMethods()) {
method.setAccessible(true);
if (method.getAnnotation(Key.class) != null)
return method.getName();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
throw new RuntimeException("Not key field found for " + clazz);
}
public static Class<?> keyClassOf(Class<?> clazz) {
try {
for (Field field : getAllFields(clazz)) {
field.setAccessible(true);
if (field.getAnnotation(Key.class) != null || field.getAnnotation(AutoKey.class) != null)
return field.getType();
}
for (Method method : clazz.getDeclaredMethods()) {
method.setAccessible(true);
if (method.getAnnotation(Key.class) != null)
return method.getReturnType();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
throw new RuntimeException("Not key field found for " + clazz);
}
public static List<Field> getAllFields(Class<?> type) {
List<Field> fields = new ArrayList<Field>();
Field[] declaredFields = type.getDeclaredFields();
Arrays.sort(declaredFields, new Comparator<Field>() {
@Override
public int compare(Field f1, Field f2) {
return f1.getName().compareTo(f2.getName());
}
});
for (Field field : declaredFields)
fields.add(field);
if (type.getSuperclass() != null)
fields.addAll(getAllFields(type.getSuperclass()));
return fields;
}
public static String kindOf(Class<?> clazz) {
Kind annotation = clazz.getAnnotation(Kind.class);
if (annotation != null)
return annotation.value();
String kind = clazz.getSimpleName().toLowerCase(Locale.ENGLISH);
return kind;
}
public static boolean equals(Object node1, Object node2) {
return keyOf(node1).equals(keyOf(node2));
}
public static <T> List<T> getAll(IVelvet velvet, List<Object> keys, Class<T> clazz) {
List<T> nodes = new ArrayList<T>(keys.size());
for (Object key : keys) {
T node = velvet.get(clazz, key);
nodes.add(node);
}
return nodes;
}
public static <A, B> void upgrade(IVelvet velvet, Class<A> oldClass, Class<B> newClass, IFunction<A, B> convertor) {
String kind = kindOf(newClass);
if (!kind.equals(kindOf(oldClass)))
throw new RuntimeException("Upgrage impossible: kinds not match");
List<A> oldValues = velvet.allOf(oldClass);
for (A oldValue : oldValues) {
B newValue = convertor.get(oldValue);
if (!keyOf(newValue).equals(keyOf(oldValue)))
throw new RuntimeException("Upgrage error: keys not match");
velvet.put(newValue);
}
}
public static boolean isAutoKeyed(Class<?> clazz) {
try {
for (Field field : getAllFields(clazz)) {
field.setAccessible(true);
if (field.getAnnotation(AutoKey.class) != null)
return true;
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return false;
}
}
|
package de.lessvoid.nifty.screen;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import de.lessvoid.nifty.EndNotify;
import de.lessvoid.nifty.Nifty;
import de.lessvoid.nifty.NiftyStopwatch;
import de.lessvoid.nifty.controls.Controller;
import de.lessvoid.nifty.controls.FocusHandler;
import de.lessvoid.nifty.controls.NiftyControl;
import de.lessvoid.nifty.effects.EffectEventId;
import de.lessvoid.nifty.elements.Element;
import de.lessvoid.nifty.input.NiftyInputMapping;
import de.lessvoid.nifty.input.NiftyMouseInputEvent;
import de.lessvoid.nifty.input.keyboard.KeyboardInputEvent;
import de.lessvoid.nifty.render.NiftyRenderEngine;
import de.lessvoid.nifty.tools.NullObjectFactory;
import de.lessvoid.nifty.tools.StringHelper;
import de.lessvoid.nifty.tools.TimeProvider;
/**
* A single screen with elements and input focus.
* @author void
*/
public class Screen {
public int layoutLayersCallCount = 0;
private Logger log = Logger.getLogger(Screen.class.getName());
private String screenId;
private ScreenController screenController = new NullScreenController();
private boolean screenControllerBound = false;
private ArrayList < Element > layerElements = new ArrayList < Element >();
private LinkedList < Element > layerElementsToAdd = new LinkedList < Element >();
private LinkedList < Element > layerElementsToRemove = new LinkedList < Element >();
/**
* Popup layers are dynamic layers on top of the normal layers.
* They are treated as "normal" layers and are added to the layerElements variable. In the
* popupLayer variable we remember the pop ups additionally, so that we can send
* input events only to these elements when they are present.
*/
private ArrayList < Element > popupElements = new ArrayList < Element >();
private LinkedList < Element > popupElementsToAdd = new LinkedList < Element >();
private LinkedList<ElementWithEndNotify> popupElementsToRemove = new LinkedList < ElementWithEndNotify >();
private TimeProvider timeProvider;
private FocusHandler focusHandler;
private MouseOverHandler mouseOverHandler;
private Nifty nifty;
private List < InputHandlerWithMapping > postInputHandlers = new ArrayList < InputHandlerWithMapping >();
private List < InputHandlerWithMapping > preInputHandlers = new ArrayList < InputHandlerWithMapping >();
private Element rootElement;
private String defaultFocusElementId;
private boolean running = false;
private Set<String> registeredIds = new HashSet<String>();
private boolean bound;
public Screen(
final Nifty newNifty,
final String newId,
final ScreenController newScreenController,
final TimeProvider newTimeProvider) {
nifty = newNifty;
screenId = newId;
screenController = newScreenController;
if (screenController == null) {
log.info("Missing ScreenController for screen [" + newId + "] using DefaultScreenController() instead but this might not be what you want.");
screenController = new DefaultScreenController();
}
timeProvider = newTimeProvider;
focusHandler = new FocusHandler();
mouseOverHandler = new MouseOverHandler();
}
public void registerElementId(final String id) {
if (id != null && registeredIds.contains(id)) {
log.warning("Possible conflicting id [" + id + "] detected. Consider making all Ids unique or use #id in control-definitions.");
} else {
registeredIds.add(id);
}
}
public void unregisterElementId(final String id) {
registeredIds.remove(id);
}
public String getScreenId() {
return screenId;
}
public List<Element> getLayerElements() {
return layerElements;
}
public void addLayerElement(final Element layerElement) {
layerElementsToAdd.add(layerElement);
}
public void removeLayerElement(final Element layerElement) {
layerElementsToRemove.add(layerElement);
}
public void removeLayerElement(final String layerId) {
for (int i=0; i<layerElements.size(); i++) {
Element layer = layerElements.get(i);
if (layer.getId().equals(layerId)) {
removeLayerElement(layer);
return;
}
}
}
public void addPopup(final Element popup, final Element defaultFocusElement) {
// This enforced all mouse buttons to the released state when a new popup
// is about to be created. But I can't remember what that was for :)
// It made problems in the drop down example where the window controls have
// been used. Since drop down controls are temporarily moved to a popup layer
// so that they can be moved around above all other stuff this resetEvents()
// call had one odd side effect: If you would click on a window title bar (to
// move it around) - in this moment the control is being moved to the popup layer -
// and then you would release the button this release would never been detected
// by the window title bar (because the button has already been released by
// this call to resetEvents() in here). In this case the window got stuck in the
// popup until you'd press and release the mouse button again.
// Not calling resetEvents() in here fixes this issue but might break something
// else although I'm currently not sure what that might be :)
// nifty.resetEvents();
// create the callback
EndNotify localEndNotify = new EndNotify() {
public final void perform() {
for (int i=0; i<layerElements.size(); i++) {
Element w = layerElements.get(i);
if (w.isEffectActive(EffectEventId.onStartScreen)) {
return;
}
}
}
};
focusHandler.pushState();
// prepare pop up for display
popup.resetEffects();
popup.layoutElements();
popup.initControls();
popup.startEffect(EffectEventId.onStartScreen, localEndNotify);
popup.startEffect(EffectEventId.onActive);
popup.onStartScreen();
if (defaultFocusElement != null) {
defaultFocusElement.setFocus();
} else {
setDefaultFocus();
}
// add to layers and add as popup
addLayerElement(popup);
addPopupElement(popup);
}
void addPopupElement(final Element popup) {
popupElementsToAdd.add(popup);
}
public void closePopup(final Element popup, final EndNotify closeNotify) {
resetLayers();
removeLayerElement(popup);
schedulePopupElementRemoval(new ElementWithEndNotify(popup, closeNotify));
}
private void schedulePopupElementRemoval(final ElementWithEndNotify elementWithEndNotify) {
popupElementsToRemove.add(elementWithEndNotify);
}
public void startScreen() {
startScreen(null);
}
public void startScreen(final EndNotify startScreenEndNotify) {
NiftyStopwatch.start();
running = false;
focusHandler.resetFocusElements();
resetLayers();
layoutLayers();
bindControls();
// bind happens right BEFORE the onStartScreen
if (!screenControllerBound) {
screenController.bind(nifty, Screen.this);
screenControllerBound = true;
}
// activate the onActive event right now
activeEffectStart();
// onStartScreen
final StartScreenEndNotify endNotify = createScreenStartEndNotify(startScreenEndNotify);
startLayers(EffectEventId.onStartScreen, endNotify);
// default focus attribute has been set in onStartScreen
// event of the elements. so we have to set the default focus
// here after the onStartScreen is started.
setDefaultFocus();
NiftyStopwatch.stop("Screen.startScreen(" + layoutLayersCallCount + ")");
}
public void endScreen(final EndNotify callback) {
resetLayers();
final EndScreenEndNotify endNotify = createScreenEndNotify(callback);
startLayers(EffectEventId.onEndScreen, endNotify);
}
public void layoutLayers() {
NiftyStopwatch.start();
layoutLayersCallCount++;
for (int i=0; i<layerElements.size(); i++) {
Element w = layerElements.get(i);
w.layoutElements();
}
NiftyStopwatch.stop("Screen.layoutLayers()");
}
private void resetLayers() {
nifty.resetMouseInputEvents();
for (int i=0; i<layerElements.size(); i++) {
Element w = layerElements.get(i);
w.resetEffects();
}
}
private void startLayers(final EffectEventId effectEventId, final EndNotify endNotify) {
// create the callback
LocalEndNotify localEndNotify = new LocalEndNotify(effectEventId, endNotify);
// start the effect for all layers
for (int i=0; i<layerElements.size(); i++) {
Element w = layerElements.get(i);
w.startEffect(effectEventId, localEndNotify);
if (effectEventId == EffectEventId.onStartScreen) {
w.onStartScreen();
}
}
// just in case there was no effect activated, we'll check here, if we're already done
localEndNotify.enable();
localEndNotify.perform();
}
public void setDefaultFocus() {
if (focusHandler.getKeyboardFocusElement() != null) {
return;
}
if (defaultFocusElementId != null) {
Element defaultFocus = getFocusHandler().findElement(defaultFocusElementId);
if (defaultFocus != null) {
defaultFocus.setFocus();
return;
}
}
// fall back to first element
Element firstFocus = getFocusHandler().getFirstFocusElement();
if (firstFocus != null) {
firstFocus.setFocus();
}
}
/**
* Start the onActive effect.
*/
private void activeEffectStart() {
for (int i=0; i<layerElements.size(); i++) {
Element w = layerElements.get(i);
w.startEffect(EffectEventId.onActive, null);
// in case this element is disabled we will start the disabled effect right here.
if (!w.isEnabled()) {
w.startEffect(EffectEventId.onDisabled, null);
}
}
}
/**
* render all layers.
* @param renderDevice the renderDevice to use
*/
public final void renderLayers(final NiftyRenderEngine renderDevice) {
for (int i=0; i<layerElements.size(); i++) {
Element layer = layerElements.get(i);
layer.render(renderDevice);
}
}
public void resetLayout() {
for (int i=0; i<layerElements.size(); i++) {
Element layer = layerElements.get(i);
layer.resetLayout();
}
}
/**
* Handle Mouse Events for this screen. Forwards the event to the layers.
* @param inputEvent MouseInputEvent
* @return true when processed and false when not
*/
public boolean mouseEvent(final NiftyMouseInputEvent inputEvent) {
if (log.isLoggable(Level.FINE)) {
log.fine("screen mouseEvent: " + inputEvent.toString());
}
if (!popupElements.isEmpty()) {
return forwardMouseEventToLayers(popupElements, inputEvent);
} else {
return forwardMouseEventToLayers(layerElements, inputEvent);
}
}
/**
* forward mouse event to the given layer list.
* @param layerList layer list
* @param inputEvent TODO
* @return TODO
*/
private boolean forwardMouseEventToLayers(final List < Element > layerList, final NiftyMouseInputEvent inputEvent) {
mouseOverHandler.reset();
long eventTime = timeProvider.getMsTime();
for (int i=0; i<layerList.size(); i++) {
Element layer = layerList.get(i);
layer.buildMouseOverElements(inputEvent, eventTime, mouseOverHandler);
}
if (log.isLoggable(Level.FINE)) {
log.fine(mouseOverHandler.getInfoString());
}
mouseOverHandler.processMouseOverEvent(rootElement, inputEvent, eventTime);
mouseOverHandler.processMouseEvent(inputEvent, eventTime);
return mouseOverHandler.hitsElement();
}
/**
* find an element by name.
* @param name the id to find
* @return the element or null
*/
public Element findElementByName(final String name) {
for (int i=0; i<layerElements.size(); i++) {
Element layer = layerElements.get(i);
Element found = layer.findElementByName(name);
if (found != null) {
return found;
}
}
return null;
}
public < T extends Controller > T findControl(final String elementName, final Class < T > requestedControlClass) {
Element element = findElementByName(elementName);
if (element == null) {
return null;
}
return element.getControl(requestedControlClass);
}
public < T extends NiftyControl > T findNiftyControl(final String elementName, final Class < T > requestedControlClass) {
Element element = findElementByName(elementName);
if (element == null) {
log.warning("missing element/control with id [" + elementName + "] for requested control class [" + requestedControlClass.getName() + "]");
return NullObjectFactory.createNull(requestedControlClass);
}
return element.getNiftyControl(requestedControlClass);
}
/**
* set alternate key.
* @param alternateKey alternate key to set
*/
public void setAlternateKey(final String alternateKey) {
for (int i=0; i<layerElements.size(); i++) {
Element layer = layerElements.get(i);
layer.setAlternateKey(alternateKey);
}
}
/**
* keyboard event.
* @param inputEvent keyboard event
*/
public boolean keyEvent(final KeyboardInputEvent inputEvent) {
for (int i=0; i<preInputHandlers.size(); i++) {
InputHandlerWithMapping handler = preInputHandlers.get(i);
if (handler.process(inputEvent)) {
return true;
}
}
if (focusHandler.keyEvent(inputEvent)) {
return true;
}
for (int i=0; i<postInputHandlers.size(); i++) {
InputHandlerWithMapping handler = postInputHandlers.get(i);
if (handler.process(inputEvent)) {
return true;
}
}
return false;
}
/**
* add a keyboard input handler.
* @param mapping mapping
* @param handler new handler to add
*/
public void addKeyboardInputHandler(final NiftyInputMapping mapping, final KeyInputHandler handler) {
postInputHandlers.add(new InputHandlerWithMapping(mapping, handler));
}
public void removeKeyboardInputHandler(final KeyInputHandler handler) {
for (int i=0; i<postInputHandlers.size(); i++) {
if (postInputHandlers.get(i).getKeyInputHandler().equals(handler)) {
postInputHandlers.remove(i);
return;
}
}
}
/**
* add a keyboard input handler.
* @param mapping mapping
* @param handler new handler to add
*/
public void addPreKeyboardInputHandler(final NiftyInputMapping mapping, final KeyInputHandler handler) {
preInputHandlers.add(new InputHandlerWithMapping(mapping, handler));
}
public void removePreKeyboardInputHandler(final KeyInputHandler handler) {
for (int i=0; i<preInputHandlers.size(); i++) {
if (preInputHandlers.get(i).getKeyInputHandler().equals(handler)) {
preInputHandlers.remove(i);
return;
}
}
}
public String debugOutput() {
return debugOutput(".*", ".*");
}
public String debugOutput(final String regexpElement, final String regexpAttribute) {
StringBuffer result = new StringBuffer();
debugOutputLayerElements(regexpElement, regexpAttribute, result, layerElements);
debugOutputLayerElements(regexpElement, regexpAttribute, result, popupElements);
result.append(focusHandler.toString());
return result.toString();
}
private void debugOutputLayerElements(final String regexpElement, final String regexpAttribute, StringBuffer result, ArrayList<Element> layers) {
for (int i=0; i<layers.size(); i++) {
Element layer = layerElements.get(i);
String layerType = " +";
if (!layer.isVisible()) {
layerType = " -";
}
result.append(
"\n" + layerType + getIdText(layer) +
"\n" + StringHelper.whitespace(layerType.length()) + layer.getElementStateString(StringHelper.whitespace(layerType.length()), regexpAttribute));
result.append(outputElement(layer, " ", regexpElement, regexpAttribute));
}
}
public String outputElement(final Element w, final String offset, final String regexpElement, final String regexpAttribute) {
StringBuffer result = new StringBuffer();
List<Element> wwElements = w.getElements();
for (int i=0; i<wwElements.size(); i++) {
Element ww = wwElements.get(i);
String elementId = getIdText(ww);
if (elementId.matches(regexpElement)) {
result.append("\n" + offset + elementId + " " + ww.getElementType().getClass().getSimpleName() + " childLayout [" + ww.getElementType().getAttributes().get("childLayout") + "]");
result.append("\n" + StringHelper.whitespace(offset.length()) + ww.getElementStateString(StringHelper.whitespace(offset.length()), regexpAttribute));
result.append(outputElement(ww, offset + " ", ".*", regexpAttribute));
} else {
result.append(outputElement(ww, offset + " ", regexpElement, regexpAttribute));
}
}
return result.toString();
}
private String getIdText(final Element ww) {
String id = ww.getId();
if (id == null) {
return "[
} else {
return "[" + id + "]";
}
}
/**
* get current attached screen controller.
* @return ScreenController
*/
public ScreenController getScreenController() {
return screenController;
}
/**
* get the screens focus handler.
* @return focus handler
*/
public FocusHandler getFocusHandler() {
return focusHandler;
}
/**
* Get RootElement.
* @return root element
*/
public Element getRootElement() {
return rootElement;
}
/**
* Set RootElement.
* @param rootElementParam new root element
*/
public void setRootElement(final Element rootElementParam) {
rootElement = rootElementParam;
}
/**
* Do things when the current frame has ended.
*/
public void processAddAndRemoveLayerElements() {
// add/remove layer elements
layerElements.addAll(layerElementsToAdd);
layerElements.removeAll(layerElementsToRemove);
layerElementsToAdd.clear();
layerElementsToRemove.clear();
// add/remove popup elements
popupElements.addAll(popupElementsToAdd);
popupElementsToAdd.clear();
while (!popupElementsToRemove.isEmpty()) {
ElementWithEndNotify e = popupElementsToRemove.remove(0);
e.remove();
}
}
public boolean hasDynamicElements() {
if (!layerElementsToAdd.isEmpty() || !layerElementsToRemove.isEmpty() || !popupElementsToAdd.isEmpty() || !popupElementsToRemove.isEmpty()) {
return true;
}
return false;
}
public void setDefaultFocusElement(final String defaultFocusElementIdParam) {
defaultFocusElementId = defaultFocusElementIdParam;
}
public String getDefaultFocusElementId() {
return defaultFocusElementId;
}
private class LocalEndNotify implements EndNotify {
private boolean enabled = false;
private EffectEventId effectEventId = null;
private EndNotify endNotify = null;
public LocalEndNotify(final EffectEventId effectEventIdParam, final EndNotify endNotifyParam) {
effectEventId = effectEventIdParam;
endNotify = endNotifyParam;
}
public void enable() {
enabled = true;
}
public void perform() {
if (enabled) {
for (int i=0; i<layerElements.size(); i++) {
Element w = layerElements.get(i);
if (w.isEffectActive(effectEventId)) {
return;
}
}
if (endNotify != null) {
endNotify.perform();
}
}
}
}
StartScreenEndNotify createScreenStartEndNotify(final EndNotify startScreenEndNotify) {
return new StartScreenEndNotify(startScreenEndNotify);
}
class StartScreenEndNotify implements EndNotify {
private EndNotify additionalEndNotify;
public StartScreenEndNotify(final EndNotify additionalEndNotify) {
this.additionalEndNotify = additionalEndNotify;
}
public void perform() {
log.info("onStartScreen has ended");
if (additionalEndNotify != null) {
additionalEndNotify.perform();
}
onStartScreenHasEnded();
}
}
EndScreenEndNotify createScreenEndNotify(final EndNotify endScreenEndNotify) {
return new EndScreenEndNotify(endScreenEndNotify);
}
class EndScreenEndNotify implements EndNotify {
private EndNotify additionalEndNotify;
public EndScreenEndNotify(final EndNotify additionalEndNotify) {
this.additionalEndNotify = additionalEndNotify;
}
public void perform() {
Logger.getAnonymousLogger().info("onEndScreen has ended");
onEndScreenHasEnded();
if (additionalEndNotify != null) {
additionalEndNotify.perform();
}
}
}
/**
* InputMappingWithMapping helper.
* @author void
*/
public class InputHandlerWithMapping {
/**
* Mapping.
*/
private NiftyInputMapping mapping;
/**
* KeyInputHandler.
*/
private KeyInputHandler handler;
/**
* Create InputHandlerWithMapping.
* @param newMapping NiftyInputMapping
* @param newHandler KeyInputHandler
*/
public InputHandlerWithMapping(
final NiftyInputMapping newMapping,
final KeyInputHandler newHandler) {
mapping = newMapping;
handler = newHandler;
}
public KeyInputHandler getKeyInputHandler() {
return handler;
}
/**
* Process Keyboard InputEvent.
* @param inputEvent KeyboardInputEvent
* @return event has been processed or not
*/
public boolean process(final KeyboardInputEvent inputEvent) {
return handler.keyEvent(mapping.convert(inputEvent));
}
}
public boolean isRunning() {
return running;
}
public boolean isNull() {
return false;
}
void onStartScreenHasEnded() {
nifty.processAnnotations(screenController);
// onStartScreen has ENDED so call the event.
screenController.onStartScreen();
// add dynamic controls
nifty.addControls();
running = true;
}
void onEndScreenHasEnded() {
nifty.unsubscribe(screenId, screenController);
nifty.unsubscribeAll(this);
// onEndScreen has ENDED so call the event.
screenController.onEndScreen();
for (int i=0; i<layerElements.size(); i++) {
layerElements.get(i).onEndScreen(this);
}
}
public boolean isEffectActive(final EffectEventId effectEventId) {
if (!popupElements.isEmpty()) {
return isEffectActive(popupElements, effectEventId);
} else {
return isEffectActive(layerElements, effectEventId);
}
}
private boolean isEffectActive(final List < Element > elements, final EffectEventId effectEventId) {
for (int i=0; i<elements.size(); i++) {
Element element = elements.get(i);
if (element.isEffectActive(effectEventId)) {
return true;
}
}
return false;
}
public Element getTopMostPopup() {
if (popupElements.isEmpty()) {
return null;
}
return popupElements.get(popupElements.size() - 1);
}
public boolean isActivePopup(final String id) {
for (int i=0; i<popupElements.size(); i++) {
if (id.equals(popupElements.get(i).getId())) {
return true;
}
}
return false;
}
public boolean isActivePopup(final Element element) {
return popupElements.contains(element);
}
/**
* Checks if the mouse currently hovers any element that is able to handle mouse events.
*
* @return true if the mouse hovers an element that is visibleToMouse and
* false if the mouse would hit the background and not any element at all
*/
public boolean isMouseOverElement() {
return mouseOverHandler.hitsElement();
}
/**
* This returns an informational String containing all elements that Nifty is aware of that
* could handle mouse events with the ones currently hovering the mouse sorted from top to
* bottom.
* @return String for debug output purpose
*/
public String getMouseOverInfoString() {
return mouseOverHandler.getInfoString();
}
public class ElementWithEndNotify {
private Element element;
private EndNotify closeNotify;
public ElementWithEndNotify(final Element element, final EndNotify closeNotify) {
this.element = element;
this.closeNotify = closeNotify;
}
public void remove() {
popupElements.remove(element);
focusHandler.popState();
if (closeNotify != null) {
closeNotify.perform();
}
}
}
private void bindControls() {
bound = true;
for (int i=0; i<layerElements.size(); i++) {
layerElements.get(i).bindControls(this);
}
for (int i=0; i<layerElements.size(); i++) {
layerElements.get(i).initControls();
}
}
public boolean isBound() {
return bound;
}
public void resetMouseDown() {
for (Element layer : layerElements) {
layer.resetMouseDown();
}
}
}
|
package edu.uw.zookeeper.data;
import static com.google.common.base.Preconditions.checkArgument;
import java.util.Set;
import com.google.common.base.Joiner;
import com.google.common.base.Objects;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableSet;
import edu.uw.zookeeper.util.Singleton;
//TODO: check if unicode is handled correctly
public abstract class ZNodeName implements CharSequence {
public static final Character SLASH = '/';
public static class Component extends ZNodeName {
protected static final Set<String> ILLEGAL = ImmutableSet.of(".", "..");
public static enum Reserved implements Singleton<Component> {
ZOOKEEPER(new Component("zookeeper"));
private final Component value;
private Reserved(Component value) {
this.value = value;
}
public Component get() {
return value;
}
}
public static Component of(String name) {
String validated = validate(name);
return new Component(validated);
}
public static String validate(String name) {
checkArgument(name != null);
checkArgument(name.length() > 0);
checkArgument(! ILLEGAL.contains(name));
checkArgument(name.indexOf(SLASH) == -1);
// u0000,
// u0001 - u001F and u007F - u009F,
// ud800 - uF8FF and uFFF0 - uFFFF,
// uXFFFE - uXFFFF (where X is a digit 1 - E),
// uF0000 - uFFFFF.
return name;
}
private Component(String name) {
super(name);
}
public boolean isReserved() {
for (Reserved e: Reserved.values()) {
if (equals(e.get())) {
return true;
}
}
return false;
}
}
public static class Path extends ZNodeName {
public static Path root() {
return Reserved.ROOT.get();
}
public static Path of(String path) {
String canonicalized = canonicalize(path);
Path root = root();
if (root.toString().equals(canonicalized)) {
return root;
} else {
return new Path(canonicalized);
}
}
public static String validate(String path) {
checkArgument(path != null);
checkArgument(path.length() > 0);
checkArgument(path.indexOf(SLASH) >= 0);
if (root().toString().equals(path)) {
return path;
}
boolean first = true;
for (String name : splitter.split(path)) {
// the only empty component should be the first one
if (first) {
first = false;
if (SLASH.equals(path.charAt(0))) {
assert (name.length() == 0);
continue;
}
}
Component.validate(name);
}
return path;
}
public static String canonicalize(String path) {
path = validate(path);
// don't end in a slash
int length = path.length();
if ((length > 1) && SLASH.equals(path.charAt(length - 1))) {
path = path.substring(0, length - 2);
}
return path;
}
public static String join(Object...components) {
return joiner.appendTo(new StringBuilder(SLASH), components).toString();
}
public static enum Reserved implements Singleton<Path> {
ROOT(new Path(SLASH.toString())),
CONFIG(new Path(join(Component.Reserved.ZOOKEEPER.get().toString(),
"config")));
private final Path value;
private Reserved(Path value) {
this.value = value;
}
@Override
public Path get() {
return value;
}
}
protected static final Joiner joiner = Joiner.on(SLASH);
protected static final Splitter splitter = Splitter.on(SLASH);
private Path(String path) {
super(path);
}
public boolean isAbsolute() {
return SLASH.equals(toString().charAt(0));
}
public boolean isRoot() {
return equals(root());
}
public Path head() {
// TODO: memoize since we are immutable
if (isRoot()) {
return null;
}
int lastSlash = toString().lastIndexOf(SLASH);
// we are canonicalized
assert (lastSlash > 0) && (lastSlash < length() - 2) : toString();
return Path.of(toString().substring(0, lastSlash));
}
public Component tail() {
// TODO: memoize since we are immutable
if (isRoot()) {
return null;
}
int lastSlash = toString().lastIndexOf(SLASH);
// we are canonicalized
assert (lastSlash > 0) && (lastSlash < length() - 2) : toString();
return Component.of(toString().substring(lastSlash + 1));
}
public Path append(Component tail) {
return append(tail.toString());
}
public Path append(Path tail) {
return append(tail.toString());
}
public Path append(String tail) {
if (SLASH.equals(tail.charAt(0))) {
tail = tail.substring(1);
}
if (tail.length() == 0) {
return this;
} else {
return Path.of(joiner.join(toString(), tail));
}
}
}
protected final String value;
protected ZNodeName(String value) {
this.value = value;
}
@Override
public String toString() {
return value;
}
@Override
public int length() {
return toString().length();
}
@Override
public char charAt(int arg0) {
return toString().charAt(arg0);
}
@Override
public CharSequence subSequence(int arg0, int arg1) {
return toString().subSequence(arg0, arg1);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (obj.getClass() != getClass()) {
return false;
}
ZNodeName other = (ZNodeName) obj;
return (Objects.equal(toString(), other.toString()));
}
@Override
public int hashCode() {
return toString().hashCode();
}
}
|
package es.sandbox.spike.connectn;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.IntStream;
import static es.sandbox.spike.connectn.Position.position;
public class Board {
private final Dimensions dimensions;
private final GameResultCalculator gameResultCalculator;
private final Chip[][] chips;
private Color nextTurn;
/**
* @param dimensions
* @param chipsToWin
* @param startingColor
*/
public Board(Dimensions dimensions, int chipsToWin, Color startingColor) {
Objects.requireNonNull(dimensions, "Dimensions may not be null");
GameRules.validateChipsToWin(chipsToWin, dimensions);
Objects.requireNonNull(startingColor, "Starting color may not be null");
this.dimensions = dimensions;
this.chips = new Chip[dimensions.getColumns()][dimensions.getRows()];
this.gameResultCalculator = new GameResultCalculator(this, chipsToWin);
this.nextTurn = startingColor;
}
/**
* @param color
* @param column
* @return
* @throws ColumnOutOfRangeException
* @throws ColumnIsFullException
* @throws WrongTurnException
* @throws GameOverException
*/
public Result put(Color color, int column)
throws ColumnOutOfRangeException, ColumnIsFullException, WrongTurnException, GameOverException {
this.gameResultCalculator.assertThatGameIsOnGoing();
consumeTurnFor(color);
final Position position = findFirstEmptyPositionInColumn(column);
this.chips[position.column()][position.row()] = new Chip(color, position);
return calculateResultFor(position);
}
private void consumeTurnFor(Color color) {
if (this.nextTurn != color) {
throw new WrongTurnException(color);
}
this.nextTurn = color.rotate();
}
private Position findFirstEmptyPositionInColumn(int column) throws ColumnOutOfRangeException, ColumnIsFullException {
this.dimensions.validateColumn(column);
return IntStream.range(0, this.chips[column].length)
.filter(row -> this.chips[column][row] == null)
.mapToObj(row -> position(column, row))
.findFirst()
.orElseThrow(() -> new ColumnIsFullException(column));
}
private Result calculateResultFor(Position position) {
return this.gameResultCalculator.calculateFor(position);
}
/**
* @param position
* @return
*/
public Optional<Color> colorAt(Position position) {
Objects.requireNonNull(position, "Position must be non null");
return chipAt(position)
.map(Chip::color);
}
/**
* @param position
* @return
*/
public Optional<Chip> chipAt(Position position) {
Objects.requireNonNull(position, "Position must be non null");
if (this.dimensions.contains(position)) {
return Optional.ofNullable(this.chips[position.column()][position.row()]);
}
return Optional.empty();
}
}
|
package eu.over9000.skadi.ui;
import java.util.Optional;
import java.util.function.Predicate;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.binding.DoubleBinding;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.ReadOnlyDoubleProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.collections.transformation.FilteredList;
import javafx.collections.transformation.SortedList;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.TableColumn.SortType;
import javafx.scene.image.Image;
import javafx.scene.input.Dragboard;
import javafx.scene.input.MouseButton;
import javafx.scene.input.TransferMode;
import javafx.scene.layout.Border;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.StackPane;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.util.Duration;
import org.apache.commons.lang3.StringUtils;
import org.controlsfx.control.SegmentedButton;
import org.controlsfx.control.StatusBar;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import de.jensd.fx.glyphs.GlyphsDude;
import de.jensd.fx.glyphs.fontawesome.FontAwesomeIcon;
import eu.over9000.skadi.handler.ChatHandler;
import eu.over9000.skadi.handler.StreamHandler;
import eu.over9000.skadi.io.PersistenceHandler;
import eu.over9000.skadi.lock.LockWakeupReceiver;
import eu.over9000.skadi.lock.SingleInstanceLock;
import eu.over9000.skadi.model.Channel;
import eu.over9000.skadi.model.ChannelStore;
import eu.over9000.skadi.model.StateContainer;
import eu.over9000.skadi.model.StreamQuality;
import eu.over9000.skadi.service.ForcedChannelUpdateService;
import eu.over9000.skadi.service.ImportFollowedService;
import eu.over9000.skadi.service.LivestreamerVersionCheckService;
import eu.over9000.skadi.service.VersionCheckerService;
import eu.over9000.skadi.ui.cells.ChannelGridCell;
import eu.over9000.skadi.ui.cells.LiveCell;
import eu.over9000.skadi.ui.cells.RightAlignedCell;
import eu.over9000.skadi.ui.cells.UptimeCell;
import eu.over9000.skadi.ui.dialogs.SettingsDialog;
import eu.over9000.skadi.ui.tray.Tray;
import eu.over9000.skadi.util.ExecutorServiceAccess;
import eu.over9000.skadi.util.JavaFXUtil;
import eu.over9000.skadi.util.NotificationUtil;
import eu.over9000.skadi.util.StringUtil;
public class MainWindow extends Application implements LockWakeupReceiver {
public static final int TOOLBAR_HEIGHT = 32;
private static final Logger LOGGER = LoggerFactory.getLogger(MainWindow.class);
private final String darkCSS = getClass().getResource("/styles/dark.css").toExternalForm();
private ChannelStore channelStore;
private ChatHandler chatHandler;
private StreamHandler streamHandler;
private PersistenceHandler persistenceHandler;
private StateContainer currentState;
private ObjectProperty<Channel> detailChannel;
private SplitPane splitPane;
private StatusBar statusBar;
private ChannelDetailPane detailPane;
private TableView<Channel> table;
private ChannelGrid grid;
private TableColumn<Channel, Boolean> liveCol;
private TableColumn<Channel, String> nameCol;
private TableColumn<Channel, String> titleCol;
private TableColumn<Channel, String> gameCol;
private TableColumn<Channel, Integer> viewerCol;
private TableColumn<Channel, Long> uptimeCol;
private FilteredList<Channel> filteredChannelListTable;
private FilteredList<Channel> filteredChannelListGrid;
private Button add;
private TextField addName;
private Button details;
private Button remove;
private Button refresh;
private ToggleButton onlineOnly;
private ToolBar toolBarL;
private ToolBar toolBarR;
private TextField filterText;
private HandlerControlButton chatAndStreamButton;
private Stage stage;
private Tray tray;
private Scene scene;
private Channel lastSelected;
@Override
public void init() throws Exception {
persistenceHandler = new PersistenceHandler();
currentState = persistenceHandler.loadState();
channelStore = new ChannelStore(persistenceHandler);
chatHandler = new ChatHandler();
streamHandler = new StreamHandler(this, channelStore);
detailChannel = new SimpleObjectProperty<>();
}
@Override
public void start(final Stage stage) throws Exception {
Thread.currentThread().setUncaughtExceptionHandler((thread, throwable) -> {
LOGGER.error("Uncaught exception in JavaFX Application Thread: ", throwable);
LOGGER.error("Will exit");
try {
Thread.sleep(1000);
} catch (final InterruptedException e) {
e.printStackTrace();
}
Platform.exit();
});
Platform.setImplicitExit(false);
this.stage = stage;
detailPane = new ChannelDetailPane(this);
final BorderPane bp = new BorderPane();
splitPane = new SplitPane();
splitPane.setBorder(Border.EMPTY);
splitPane.setPadding(Insets.EMPTY);
final StackPane stackPane = new StackPane();
stackPane.setBorder(Border.EMPTY);
stackPane.setPadding(Insets.EMPTY);
statusBar = new StatusBar();
statusBar.setBorder(null);
setupTable();
setupGrid();
stackPane.getChildren().add(grid);
stackPane.getChildren().add(table);
setupToolbarLeft(stage);
setupToolbarRight();
splitPane.getItems().add(stackPane);
final BorderPane toolbarPane = new BorderPane();
toolbarPane.setCenter(toolBarL);
toolbarPane.setRight(toolBarR);
bp.setTop(toolbarPane);
bp.setCenter(splitPane);
bp.setBottom(statusBar);
scene = new Scene(bp, 1280, 720);
scene.getStylesheets().add(getClass().getResource("/styles/copyable-label.css").toExternalForm());
scene.getStylesheets().add(getClass().getResource("/styles/common.css").toExternalForm());
if (currentState.isUseDarkTheme()) {
scene.getStylesheets().add(darkCSS);
}
scene.setOnDragOver(event -> {
final Dragboard d = event.getDragboard();
if (d.hasUrl() || d.hasString()) {
event.acceptTransferModes(TransferMode.COPY);
} else {
event.consume();
}
});
scene.setOnDragDropped(event -> {
final Dragboard d = event.getDragboard();
boolean success = false;
if (d.hasUrl()) {
final String user = StringUtil.extractUsernameFromURL(d.getUrl());
if (user != null) {
success = channelStore.addChannel(user, statusBar);
} else {
statusBar.setText("dragged url is no twitch stream");
}
} else if (d.hasString()) {
success = channelStore.addChannel(d.getString(), statusBar);
}
event.setDropCompleted(success);
event.consume();
});
tray = new Tray(stage);
NotificationUtil.init();
stage.setTitle("Skadi");
stage.getIcons().add(new Image(getClass().getResourceAsStream("/icons/skadi.png")));
stage.setScene(scene);
stage.show();
stage.iconifiedProperty().addListener((obs, oldV, newV) -> {
if (currentState.isMinimizeToTray()) {
if (newV) {
stage.hide();
}
}
});
stage.setOnCloseRequest(event -> Platform.exit());
updateFilterPredicate();
updateLiveColumn();
bindColumnWidths();
final VersionCheckerService versionCheckerService = new VersionCheckerService(stage, statusBar);
versionCheckerService.start();
final LivestreamerVersionCheckService livestreamerVersionCheckService = new LivestreamerVersionCheckService(statusBar);
livestreamerVersionCheckService.start();
SingleInstanceLock.addReceiver(this);
}
private void setupGrid() {
grid = new ChannelGrid();
grid.setBorder(Border.EMPTY);
grid.setPadding(Insets.EMPTY);
grid.setCellFactory(gridView -> new ChannelGridCell(grid, this));
grid.setCellHeight(200);
grid.setCellWidth(200);
grid.setHorizontalCellSpacing(5);
grid.setVerticalCellSpacing(5);
filteredChannelListGrid = new FilteredList<>(channelStore.getChannels());
final SortedList<Channel> sortedChannelListGrid = new SortedList<>(filteredChannelListGrid);
sortedChannelListGrid.setComparator((channel1, channel2) -> Integer.compare(channel2.getViewer(), channel1.getViewer()));
grid.setItems(sortedChannelListGrid);
}
private void setupToolbarRight() {
final ToggleButton tbTable = GlyphsDude.createIconToggleButton(FontAwesomeIcon.TABLE, null, null, ContentDisplay.GRAPHIC_ONLY);
final ToggleButton tbGrid = GlyphsDude.createIconToggleButton(FontAwesomeIcon.TH, null, null, ContentDisplay.GRAPHIC_ONLY);
tbTable.setTooltip(new Tooltip("Table view"));
tbGrid.setTooltip(new Tooltip("Grid view"));
tbTable.setOnAction(event -> {
table.toFront();
currentState.setShowGrid(false);
persistenceHandler.saveState(currentState);
});
tbGrid.setOnAction(event -> {
grid.toFront();
currentState.setShowGrid(true);
persistenceHandler.saveState(currentState);
});
final SegmentedButton segmentedButton = new SegmentedButton(tbTable, tbGrid);
final PersistentButtonToggleGroup toggleGroup = new PersistentButtonToggleGroup();
segmentedButton.setToggleGroup(toggleGroup);
toolBarR = new ToolBar(new Separator(), segmentedButton);
toolBarR.setPrefHeight(TOOLBAR_HEIGHT);
toolBarR.setMinHeight(TOOLBAR_HEIGHT);
if (currentState.isShowGrid()) {
tbGrid.setSelected(true);
grid.toFront();
} else {
tbTable.setSelected(true);
table.toFront();
}
}
@Override
public void stop() throws Exception {
super.stop();
tray.onShutdown();
ExecutorServiceAccess.onShutdown();
NotificationUtil.onShutdown();
}
private void setupToolbarLeft(final Stage stage) {
add = GlyphsDude.createIconButton(FontAwesomeIcon.PLUS);
addName = new TextField();
addName.setOnAction(event -> add.fire());
add.setOnAction(event -> {
final String name = addName.getText().trim();
if (name.isEmpty()) {
return;
}
final String nameFromUrl = StringUtil.extractUsernameFromURL(name);
final boolean result;
if (nameFromUrl != null) {
result = channelStore.addChannel(nameFromUrl, statusBar);
} else {
result = channelStore.addChannel(name, statusBar);
}
if (result) {
addName.clear();
}
});
final Button imprt = GlyphsDude.createIconButton(FontAwesomeIcon.DOWNLOAD);
imprt.setOnAction(event -> {
final TextInputDialog dialog = new TextInputDialog();
dialog.initModality(Modality.APPLICATION_MODAL);
dialog.initOwner(stage);
dialog.setTitle("Import followed channels");
dialog.setHeaderText("Import followed channels from Twitch");
dialog.setGraphic(null);
dialog.setContentText("Twitch username:");
dialog.showAndWait().ifPresent(name -> {
final ImportFollowedService ifs = new ImportFollowedService(channelStore, name, statusBar);
ifs.start();
});
});
details = GlyphsDude.createIconButton(FontAwesomeIcon.INFO);
details.setDisable(true);
details.setOnAction(event -> openDetailPage(lastSelected));
details.setTooltip(new Tooltip("Show channel information"));
remove = GlyphsDude.createIconButton(FontAwesomeIcon.TRASH);
remove.setDisable(true);
remove.setOnAction(event -> {
final Channel candidate = lastSelected;
final Alert alert = new Alert(AlertType.CONFIRMATION);
alert.initModality(Modality.APPLICATION_MODAL);
alert.initOwner(stage);
alert.setTitle("Delete channel");
alert.setHeaderText("Delete " + candidate.getName());
alert.setContentText("Do you really want to delete " + candidate.getName() + "?");
final Optional<ButtonType> result = alert.showAndWait();
if (result.get() == ButtonType.OK) {
channelStore.getChannels().remove(candidate);
statusBar.setText("Removed channel " + candidate.getName());
}
});
refresh = GlyphsDude.createIconButton(FontAwesomeIcon.REFRESH);
refresh.setTooltip(new Tooltip("Refresh all channels"));
refresh.setOnAction(event -> {
refresh.setDisable(true);
final ForcedChannelUpdateService service = new ForcedChannelUpdateService(channelStore, statusBar, refresh);
service.start();
});
final Button settings = GlyphsDude.createIconButton(FontAwesomeIcon.COG);
settings.setTooltip(new Tooltip("Settings"));
settings.setOnAction(event -> {
final SettingsDialog dialog = new SettingsDialog();
dialog.initModality(Modality.APPLICATION_MODAL);
dialog.initOwner(stage);
final Optional<StateContainer> result = dialog.showAndWait();
if (result.isPresent()) {
persistenceHandler.saveState(result.get());
checkThemeChange();
}
});
onlineOnly = new ToggleButton(null, GlyphsDude.createIcon(FontAwesomeIcon.VIDEO_CAMERA));
onlineOnly.setSelected(currentState.isOnlineFilterActive());
onlineOnly.setTooltip(new Tooltip("Show only live channels"));
onlineOnly.setOnAction(event -> {
currentState.setOnlineFilterActive(onlineOnly.isSelected());
persistenceHandler.saveState(currentState);
updateFilterPredicate();
updateLiveColumn();
});
filterText = new TextField();
filterText.textProperty().addListener((obs, oldV, newV) -> updateFilterPredicate());
filterText.setTooltip(new Tooltip("Filter channels by name, status and game"));
toolBarL = new ToolBar();
toolBarL.getItems().addAll(addName, add, imprt, new Separator(), refresh, settings, new Separator(), onlineOnly, filterText, new Separator(), details, remove);
toolBarL.setPrefHeight(TOOLBAR_HEIGHT);
toolBarL.setMinHeight(TOOLBAR_HEIGHT);
chatAndStreamButton = new HandlerControlButton(chatHandler, streamHandler, toolBarL, statusBar);
}
private void updateLiveColumn() {
if (onlineOnly.isSelected()) {
table.getColumns().remove(liveCol);
table.getSortOrder().remove(liveCol);
} else {
table.getColumns().add(0, liveCol);
table.getSortOrder().add(0, liveCol);
}
}
private void checkThemeChange() {
final boolean useDark = currentState.isUseDarkTheme();
final boolean isPresent = scene.getStylesheets().contains(darkCSS);
if (useDark == isPresent) {
return;
}
if (useDark) {
scene.getStylesheets().add(darkCSS);
} else {
scene.getStylesheets().remove(darkCSS);
}
}
private void updateFilterPredicate() {
final Predicate<Channel> channelPredicate = channel -> {
boolean isOnlineResult;
boolean containsTextResult;
// isOnline returns a Boolean, can be null
isOnlineResult = !onlineOnly.isSelected() || Boolean.TRUE.equals(channel.isOnline());
final String filter = filterText.getText().trim();
if (filter.isEmpty()) {
containsTextResult = true;
} else {
final boolean nameContains = StringUtils.containsIgnoreCase(channel.getName(), filter);
final boolean gameContains = StringUtils.containsIgnoreCase(channel.getGame(), filter);
final boolean titleContains = StringUtils.containsIgnoreCase(channel.getTitle(), filter);
containsTextResult = nameContains || gameContains || titleContains;
}
return isOnlineResult && containsTextResult;
};
filteredChannelListTable.setPredicate(channelPredicate);
filteredChannelListGrid.setPredicate(channelPredicate);
}
private void setupTable() {
table = new TableView<>();
table.setBorder(Border.EMPTY);
table.setPadding(Insets.EMPTY);
liveCol = new TableColumn<>("Live");
liveCol.setCellValueFactory(p -> p.getValue().onlineProperty());
liveCol.setSortType(SortType.DESCENDING);
liveCol.setCellFactory(p -> new LiveCell());
nameCol = new TableColumn<>("Channel");
nameCol.setCellValueFactory(p -> p.getValue().nameProperty());
titleCol = new TableColumn<>("Status");
titleCol.setCellValueFactory(p -> p.getValue().titleProperty());
gameCol = new TableColumn<>("Game");
gameCol.setCellValueFactory(p -> p.getValue().gameProperty());
viewerCol = new TableColumn<>("Viewer");
viewerCol.setCellValueFactory(p -> p.getValue().viewerProperty().asObject());
viewerCol.setSortType(SortType.DESCENDING);
viewerCol.setCellFactory(p -> new RightAlignedCell<>());
uptimeCol = new TableColumn<>("Uptime");
uptimeCol.setCellValueFactory((p) -> p.getValue().uptimeProperty().asObject());
uptimeCol.setCellFactory(p -> new UptimeCell());
table.setPlaceholder(new Label("no channels added/matching the filters"));
//table.getColumns().add(liveCol);
table.getColumns().add(nameCol);
table.getColumns().add(titleCol);
table.getColumns().add(gameCol);
table.getColumns().add(viewerCol);
table.getColumns().add(uptimeCol);
//table.getSortOrder().add(liveCol);
table.getSortOrder().add(viewerCol);
table.getSortOrder().add(nameCol);
filteredChannelListTable = new FilteredList<>(channelStore.getChannels());
final SortedList<Channel> sortedChannelListTable = new SortedList<>(filteredChannelListTable);
sortedChannelListTable.comparatorProperty().bind(table.comparatorProperty());
table.setItems(sortedChannelListTable);
table.getSelectionModel().selectedItemProperty().addListener((obs, oldV, newV) -> {
onSelection(newV);
if ((newV == null) && splitPane.getItems().contains(detailPane)) {
doDetailSlide(false);
}
});
table.setOnMousePressed(event -> {
if (table.getSelectionModel().getSelectedItem() == null) {
return;
}
if (event.getButton() == MouseButton.MIDDLE) {
openStream(table.getSelectionModel().getSelectedItem());
} else if (event.getButton() == MouseButton.PRIMARY && event.getClickCount() == 2) {
openDetailPage(table.getSelectionModel().getSelectedItem());
}
});
}
public void onSelection(final Channel channel) {
details.setDisable(channel == null);
remove.setDisable(channel == null);
chatAndStreamButton.setDisable(channel == null);
chatAndStreamButton.updateCandidate(channel);
lastSelected = channel;
}
public void openDetailPage(final Channel channel) {
if (channel == null) {
return;
}
detailChannel.set(channel);
if (!splitPane.getItems().contains(detailPane)) {
splitPane.getItems().add(detailPane);
doDetailSlide(true);
}
}
private void bindColumnWidths() {
final ScrollBar tsb = JavaFXUtil.getVerticalScrollbar(table);
final ReadOnlyDoubleProperty sbw = tsb.widthProperty();
final DoubleBinding tcw = table.widthProperty().subtract(sbw);
liveCol.prefWidthProperty().bind(tcw.multiply(0.05));
nameCol.prefWidthProperty().bind(tcw.multiply(0.15));
titleCol.prefWidthProperty().bind(tcw.multiply(0.4));
gameCol.prefWidthProperty().bind(tcw.multiply(0.2));
viewerCol.prefWidthProperty().bind(tcw.multiply(0.075));
uptimeCol.prefWidthProperty().bind(tcw.multiply(0.125));
}
public void doDetailSlide(final boolean doOpen) {
final KeyValue positionKeyValue = new KeyValue(splitPane.getDividers().get(0).positionProperty(), doOpen ? 0.15 : 1);
final KeyValue opacityKeyValue = new KeyValue(detailPane.opacityProperty(), doOpen ? 1 : 0);
final KeyFrame keyFrame = new KeyFrame(Duration.seconds(0.1), positionKeyValue, opacityKeyValue);
final Timeline timeline = new Timeline(keyFrame);
timeline.setOnFinished(evt -> {
if (!doOpen) {
splitPane.getItems().remove(detailPane);
detailPane.setOpacity(1);
}
});
timeline.play();
}
public ObjectProperty<Channel> getDetailChannel() {
return detailChannel;
}
@Override
public void onWakeupReceived() {
Platform.runLater(() -> {
statusBar.setText("Wakeup received");
stage.show();
stage.setIconified(false);
stage.toFront();
});
}
public void updateStatusText(final String text) {
statusBar.setText(text);
}
public void openStream(final Channel item) {
if (item == null) {
return;
}
streamHandler.openStream(item, StreamQuality.getBestQuality());
}
}
|
package foodtruck.tld;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nullable;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
import com.google.common.html.HtmlEscapers;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import foodtruck.model.Location;
/**
* @author aviolette
* @since 12/18/12
*/
public class LocationFormatTag extends TagSupport {
private Location location;
private static final Logger log = Logger.getLogger(LocationFormatTag.class.getName());
private DateTime when;
private boolean admin;
private final DateTimeFormatter formatter = DateTimeFormat.forPattern("YYYYMMdd");
public void setAdmin(boolean admin) {
this.admin = admin;
}
public void setAt(DateTime dateTime) {
when = dateTime;
}
public DateTime getAt() {
return when;
}
public void setLocation(@Nullable Location location) {
this.location = location;
}
public Location getLocation() {
return this.location;
}
@Override public int doStartTag() throws JspException {
JspWriter out = pageContext.getOut();
String dateString = "";
if (when != null) {
dateString = "&date=" + formatter.print(when);
}
try {
if (location != null) {
String locationName = HtmlEscapers.htmlEscaper().escape(location.getName());
String aString = admin ? "/admin" : "";
if (location.getKey() != null) {
out.println("<a href='" + aString + "/locations/" + location.getKey() + dateString +"'>" + locationName + "</a>");
} else {
out.println("<a href='/locations?q=" + locationName + dateString + "'>" + locationName + "</a>");
}
}
} catch (Exception e) {
if (location != null) {
log.log(Level.INFO, "Error saving location: " + location.getName());
}
log.log(Level.INFO, e.getMessage(), e);
//throw Throwables.propagate(e);
}
return SKIP_BODY;
}
}
|
package graphql.language;
import graphql.Internal;
import graphql.PublicApi;
import graphql.util.TraversalControl;
import graphql.util.TraverserContext;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import static graphql.language.NodeChildrenContainer.newNodeChildrenContainer;
import static graphql.language.NodeUtil.directivesByName;
@PublicApi
public class InlineFragment extends AbstractNode<InlineFragment> implements Selection<InlineFragment>, SelectionSetContainer<InlineFragment>, DirectivesContainer<InlineFragment> {
private final TypeName typeCondition;
private final List<Directive> directives;
private final SelectionSet selectionSet;
public static final String CHILD_TYPE_CONDITION = "typeCondition";
public static final String CHILD_DIRECTIVES = "directives";
public static final String CHILD_SELECTION_SET = "selectionSet";
@Internal
protected InlineFragment(TypeName typeCondition,
List<Directive> directives,
SelectionSet selectionSet,
SourceLocation sourceLocation,
List<Comment> comments,
IgnoredChars ignoredChars) {
super(sourceLocation, comments, ignoredChars);
this.typeCondition = typeCondition;
this.directives = directives;
this.selectionSet = selectionSet;
}
/**
* alternative to using a Builder for convenience
*
* @param typeCondition the type condition of the inline fragment
*/
public InlineFragment(TypeName typeCondition) {
this(typeCondition, new ArrayList<>(), null, null, new ArrayList<>(), IgnoredChars.EMPTY);
}
/**
* alternative to using a Builder for convenience
*
* @param typeCondition the type condition of the inline fragment
* @param selectionSet of the inline fragment
*/
public InlineFragment(TypeName typeCondition, SelectionSet selectionSet) {
this(typeCondition, new ArrayList<>(), selectionSet, null, new ArrayList<>(), IgnoredChars.EMPTY);
}
public TypeName getTypeCondition() {
return typeCondition;
}
@Override
public String getName() {
return typeCondition == null ? null : typeCondition.getName();
}
public List<Directive> getDirectives() {
return new ArrayList<>(directives);
}
public Map<String, Directive> getDirectivesByName() {
return directivesByName(directives);
}
public Directive getDirective(String directiveName) {
return getDirectivesByName().get(directiveName);
}
@Override
public SelectionSet getSelectionSet() {
return selectionSet;
}
@Override
public List<Node> getChildren() {
List<Node> result = new ArrayList<>();
if (typeCondition != null) {
result.add(typeCondition);
}
result.addAll(directives);
result.add(selectionSet);
return result;
}
@Override
public NodeChildrenContainer getNamedChildren() {
return newNodeChildrenContainer()
.child(CHILD_TYPE_CONDITION, typeCondition)
.children(CHILD_DIRECTIVES, directives)
.child(CHILD_SELECTION_SET, selectionSet)
.build();
}
@Override
public InlineFragment withNewChildren(NodeChildrenContainer newChildren) {
return transform(builder -> builder
.typeCondition(newChildren.getChildOrNull(CHILD_TYPE_CONDITION))
.directives(newChildren.getChildren(CHILD_DIRECTIVES))
.selectionSet(newChildren.getChildOrNull(CHILD_SELECTION_SET))
);
}
@Override
public boolean isEqualTo(Node o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
return true;
}
@Override
public InlineFragment deepCopy() {
return new InlineFragment(
deepCopy(typeCondition),
deepCopy(directives),
deepCopy(selectionSet),
getSourceLocation(),
getComments(),
getIgnoredChars()
);
}
@Override
public String toString() {
return "InlineFragment{" +
"typeCondition='" + typeCondition + '\'' +
", directives=" + directives +
", selectionSet=" + selectionSet +
'}';
}
@Override
public TraversalControl accept(TraverserContext<Node> context, NodeVisitor visitor) {
return visitor.visitInlineFragment(this, context);
}
public static Builder newInlineFragment() {
return new Builder();
}
public InlineFragment transform(Consumer<Builder> builderConsumer) {
Builder builder = new Builder(this);
builderConsumer.accept(builder);
return builder.build();
}
public static final class Builder implements NodeBuilder {
private SourceLocation sourceLocation;
private List<Comment> comments = new ArrayList<>();
private TypeName typeCondition;
private List<Directive> directives = new ArrayList<>();
private SelectionSet selectionSet;
private IgnoredChars ignoredChars = IgnoredChars.EMPTY;
private Builder() {
}
private Builder(InlineFragment existing) {
this.sourceLocation = existing.getSourceLocation();
this.comments = existing.getComments();
this.typeCondition = existing.getTypeCondition();
this.directives = existing.getDirectives();
this.selectionSet = existing.getSelectionSet();
this.ignoredChars = existing.getIgnoredChars();
}
public Builder sourceLocation(SourceLocation sourceLocation) {
this.sourceLocation = sourceLocation;
return this;
}
public Builder comments(List<Comment> comments) {
this.comments = comments;
return this;
}
public Builder typeCondition(TypeName typeCondition) {
this.typeCondition = typeCondition;
return this;
}
public Builder directives(List<Directive> directives) {
this.directives = directives;
return this;
}
public Builder selectionSet(SelectionSet selectionSet) {
this.selectionSet = selectionSet;
return this;
}
public Builder ignoredChars(IgnoredChars ignoredChars) {
this.ignoredChars = ignoredChars;
return this;
}
public InlineFragment build() {
InlineFragment inlineFragment = new InlineFragment(typeCondition, directives, selectionSet, sourceLocation, comments, ignoredChars);
return inlineFragment;
}
}
}
|
package hudson.plugins.jira;
import hudson.plugins.jira.soap.JiraSoapService;
import hudson.plugins.jira.soap.RemoteComment;
import hudson.plugins.jira.soap.RemoteFieldValue;
import hudson.plugins.jira.soap.RemoteGroup;
import hudson.plugins.jira.soap.RemoteIssue;
import hudson.plugins.jira.soap.RemoteIssueType;
import hudson.plugins.jira.soap.RemoteNamedObject;
import hudson.plugins.jira.soap.RemoteProject;
import hudson.plugins.jira.soap.RemoteProjectRole;
import hudson.plugins.jira.soap.RemoteStatus;
import hudson.plugins.jira.soap.RemoteValidationException;
import hudson.plugins.jira.soap.RemoteVersion;
import java.rmi.RemoteException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Logger;
/**
* Connection to JIRA.
*
* <p>
* JIRA has a built-in timeout for a session, so after some inactive period the
* session will become invalid. The caller must make sure that this doesn't
* happen.
*
* @author Kohsuke Kawaguchi
*/
public class JiraSession {
public final JiraSoapService service;
/**
* This security token is used by the server to associate SOAP invocations
* with a specific user.
*/
public final String token;
/**
* Lazily computed list of project keys.
*/
private Set<String> projectKeys;
/**
* This session is created for this site.
*/
private final JiraSite site;
/* package */JiraSession(JiraSite site, JiraSoapService service,
String token) {
this.service = service;
this.token = token;
this.site = site;
}
/**
* Returns the set of project keys (like MNG, JENKINS, etc) that are
* available in this JIRA.
*
* Guarantees to return all project keys in upper case.
*/
public Set<String> getProjectKeys() throws RemoteException {
if (projectKeys == null) {
LOGGER.fine("Fetching remote project key list from "
+ site.getName());
RemoteProject[] remoteProjects = service
.getProjectsNoSchemes(token);
projectKeys = new HashSet<String>(remoteProjects.length);
for (RemoteProject p : remoteProjects) {
projectKeys.add(p.getKey().toUpperCase());
}
LOGGER.fine("Project list=" + projectKeys);
}
return projectKeys;
}
/**
* Adds a comment to the existing issue. Constrains the visibility of the
* comment the the supplied groupVisibility.
*
* @param groupVisibility
*/
public void addComment(String issueId, String comment,
String groupVisibility, String roleVisibility) throws RemoteException {
RemoteComment rc = new RemoteComment();
rc.setBody(comment);
try {
if (roleVisibility != null && roleVisibility.equals("") == false
&& getRole(roleVisibility) != null) {
rc.setRoleLevel(roleVisibility);
}
} catch (RemoteValidationException rve) {
LOGGER.throwing(this.getClass().toString(), "setRoleLevel", rve);
}
try {
if (groupVisibility != null && groupVisibility.equals("") == false
&& getGroup(groupVisibility) != null) {
rc.setGroupLevel(groupVisibility);
}
} catch (RemoteValidationException rve) {
LOGGER.throwing(this.getClass().toString(), "setGroupLevel", rve);
}
service.addComment(token, issueId, rc);
}
/**
* Gets the details of one issue.
*
* @param id
* Issue ID like "MNG-1235".
* @return null if no such issue exists.
*/
public RemoteIssue getIssue(String id) throws RemoteException {
if (existsIssue(id))
return service.getIssue(token, id);
else
return null;
}
/**
* Gets all issues that match the given JQL filter
*
* @param jqlSearch
* JQL query string to execute
* @return issues matching the JQL query
* @throws RemoteException
*/
public RemoteIssue[] getIssuesFromJqlSearch(final String jqlSearch)
throws RemoteException {
return service.getIssuesFromJqlSearch(token, jqlSearch, 50);
}
/**
* Gets the details of a group, given a groupId. Used for validating group
* visibility.
*
* @param Group
* ID like "Software Development"
* @return null if no such group exists
*/
public RemoteGroup getGroup(String groupId) throws RemoteException {
LOGGER.fine("Fetching groupInfo from " + groupId);
return service.getGroup(token, groupId);
}
/**
* Gets the details of a role, given a roleId. Used for validating role
* visibility.
*
* TODO: Cannot validate against the real project role the user have in the project,
* jira soap api has no such function!
*
* @param Role
* ID like "Software Development"
* @return null if no such role exists
*/
public RemoteProjectRole getRole(String roleId) throws RemoteException {
LOGGER.fine("Fetching roleInfo from " + roleId);
RemoteProjectRole[] roles= service.getProjectRoles(token);
if(roles != null && roles.length > 0) {
for(RemoteProjectRole role : roles) {
if(role != null && role.getName() != null && role.getName().equals(roleId)) {
return role;
}
}
}
LOGGER.info("Did not find role named " + roleId + ".");
return null;
}
/**
* Get all versions from the given project
*
* @param projectKey The key for the project
* @return An array of versions
* @throws RemoteException
*/
public RemoteVersion[] getVersions(String projectKey) throws RemoteException {
LOGGER.fine("Fetching versions from project: " + projectKey);
return service.getVersions(token, projectKey);
}
/**
* Get a version by its name
*
* @param projectKey The key for the project
* @param name The version name
* @return A RemoteVersion, or null if not found
* @throws RemoteException
*/
public RemoteVersion getVersionByName(String projectKey, String name) throws RemoteException {
LOGGER.fine("Fetching versions from project: " + projectKey);
RemoteVersion[] versions = getVersions(projectKey);
if(versions == null) return null;
for( RemoteVersion version : versions ) {
if( version.getName().equals(name) ) {
return version;
}
}
return null;
}
public RemoteIssue[] getIssuesWithFixVersion(String projectKey, String version) throws RemoteException {
return getIssuesWithFixVersion(projectKey, version, "");
}
public RemoteIssue[] getIssuesWithFixVersion(String projectKey, String version, String filter) throws RemoteException {
LOGGER.fine("Fetching versions from project: " + projectKey + " with fixVersion:" + version);
if( filter != null && !filter.isEmpty())
return service.getIssuesFromJqlSearch(token, String.format("project = \"%s\" and fixVersion = \"%s\" and " + filter,projectKey,version) , Integer.MAX_VALUE);
return service.getIssuesFromJqlSearch(token, String.format("project = \"%s\" and fixVersion = \"%s\"",projectKey,version) , Integer.MAX_VALUE);
}
/**
* Get all issue types
*
* @return An array of issue types
* @throws RemoteException
*/
public RemoteIssueType[] getIssueTypes() throws RemoteException {
LOGGER.fine("Fetching issue types");
return service.getIssueTypes(token);
}
public boolean existsIssue(String id) throws RemoteException {
return site.existsIssue(id);
}
private static final Logger LOGGER = Logger.getLogger(JiraSession.class
.getName());
public void releaseVersion(String projectKey, RemoteVersion version) throws RemoteException {
LOGGER.fine("Releaseing version: " + version.getName());
service.releaseVersion(token, projectKey, version);
}
/**
* Replaces the fix version list of all issues matching the JQL Query with the version specified.
*
* @param projectKey The JIRA Project key
* @param version The replacement version
* @param query The JQL Query
* @throws RemoteException
*/
public void migrateIssuesToFixVersion(String projectKey, String version, String query) throws RemoteException {
RemoteVersion newVersion = getVersionByName(projectKey,version);
if(newVersion == null ) return;
LOGGER.fine("Fetching versions with JQL:" + query);
RemoteIssue[] issues = service.getIssuesFromJqlSearch(token,query,Integer.MAX_VALUE);
if( issues == null ) return;
LOGGER.fine("Found issues: " + issues.length);
RemoteFieldValue value = new RemoteFieldValue("fixVersions", new String[] { newVersion.getId() } );
for( RemoteIssue issue : issues ) {
LOGGER.fine("Migrating issue: " + issue.getKey());
service.updateIssue(token, issue.getKey(), new RemoteFieldValue[] { value });
}
}
/**
* Replaces the given fromVersion with toVersion in all issues matching the JQL query.
*
* @param projectKey The JIRA Project
* @param fromVersion The name of the version to replace
* @param toVersion The name of the replacement version
* @param query The JQL Query
* @throws RemoteException
*/
public void replaceFixVersion(String projectKey, String fromVersion, String toVersion, String query) throws RemoteException {
RemoteVersion newVersion = getVersionByName(projectKey,toVersion);
if(newVersion == null ) return;
LOGGER.fine("Fetching versions with JQL:" + query);
RemoteIssue[] issues = service.getIssuesFromJqlSearch(token,query,Integer.MAX_VALUE);
if( issues == null ) return;
LOGGER.fine("Found issues: " + issues.length);
for( RemoteIssue issue : issues ) {
Set<String> newVersions = new HashSet<String>();
newVersions.add(newVersion.getId());
for( RemoteVersion currentVersion : issue.getFixVersions() ) {
if( !currentVersion.getName().equals(fromVersion) ) {
newVersions.add(currentVersion.getId());
}
}
RemoteFieldValue value = new RemoteFieldValue("fixVersions", newVersions.toArray(new String[0]) );
LOGGER.fine("Replaceing version in issue: " + issue.getKey());
service.updateIssue(token, issue.getKey(), new RemoteFieldValue[] { value });
}
}
/**
* Progresses the issue's workflow by performing the specified action. The issue's new status is returned.
*
* @param issueKey
* @param workflowActionName
* @param fields
* @return The new status
* @throws RemoteException
*/
public String progressWorkflowAction(String issueKey, String workflowActionName, RemoteFieldValue[] fields)
throws RemoteException {
LOGGER.fine("Progressing issue " + issueKey + " with workflow action: " + workflowActionName);
RemoteIssue issue = service.progressWorkflowAction(token, issueKey, workflowActionName, fields);
return getStatusById(issue.getStatus());
}
/**
* Returns the matching action id for a given action name.
*
* @param issueKey
* @param workflowAction
* @return The action id, or null if the action cannot be found.
* @throws RemoteException
*/
public String getActionIdForIssue(String issueKey, String workflowAction) throws RemoteException {
RemoteNamedObject[] actions = service.getAvailableActions(token, issueKey);
if (actions != null) {
for (RemoteNamedObject action : actions) {
if (workflowAction.equalsIgnoreCase(action.getName())) {
return action.getId();
}
}
}
return null;
}
/**
* Returns the status name by status id.
*
* @param statusId
* @return
* @throws RemoteException
*/
public String getStatusById(String statusId) throws RemoteException {
String status = getKnownStatuses().get(statusId);
if (status == null) {
LOGGER.warning("JIRA status could not be found: " + statusId + ". Checking JIRA for new status types.");
knownStatuses = null;
// Try again, just in case the admin has recently added a new status. This should be a rare condition.
status = getKnownStatuses().get(statusId);
}
return status;
}
private HashMap<String, String> knownStatuses = null;
/**
* Returns all known statuses.
*
* @return
* @throws RemoteException
*/
private HashMap<String,String> getKnownStatuses() throws RemoteException {
if (knownStatuses == null) {
RemoteStatus[] statuses = service.getStatuses(token);
knownStatuses = new HashMap<String, String>(statuses.length);
for (RemoteStatus status : statuses) {
knownStatuses.put(status.getId(), status.getName());
}
}
return knownStatuses;
}
public RemoteIssue createIssue(String projectKey) throws RemoteException{
RemoteIssue issue= new RemoteIssue();
issue.setProject(projectKey);
issue.setSummary("Test issue created by jenkins...");
RemoteIssue createissue;
createissue=service.createIssue(token,issue);
return createissue;
}
}
|
package idsrend.services;
import java.awt.Font;
import java.awt.Stroke;
import java.awt.font.FontRenderContext;
import java.awt.geom.AffineTransform;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletContext;
import cc.ccomponent_adjuster.ExpSequenceLookup;
import cc.ccomponent_adjuster.ExpSequenceLookup_byDB;
import cc.char_indexingtool.ChineseCharacterTypeSetter;
import cc.char_indexingtool.FontRefSettingTool;
import cc.layouttools.MergePieceAdjuster;
import cc.char_indexingtool.FontCorrespondTable;
import cc.char_indexingtool.CommonFontNoSearch;
import cc.char_indexingtool.CommonFontNoSearchbyDB;
import cc.stroke.FunctinoalBasicBolder;
import cc.stroketool.MkeSeparateMovableType_Bolder;
import cc.tool.database.PgsqlConnection;
import idsrend.CharComponentStructureAdjuster.IDSnormalizer;
import java.lang.System;
/**
*
*
* @author Ihc
*/
public class IDSrendServlet extends HttpServlet
{
private static final long serialVersionUID = 1224634082415129183L;
protected IDSrendService ;
protected IDSrendService ;
protected IDSrendService ;
protected IDSrendService ;
/** X11 */
// GraphicsConfiguration ;
protected PgsqlConnection ;
int ;
public IDSrendServlet()
{
// = GraphicsEnvironment.getLocalGraphicsEnvironment()
// .getDefaultScreenDevice().getDefaultConfiguration();
= new PgsqlConnection();
// TODO
ExpSequenceLookup = new ExpSequenceLookup_byDB();
// TODO ExpSequenceLookup_byDB() ExpSequenceNoLookup()
IDSnormalizer = new IDSnormalizer();
MergePieceAdjuster = new MergePieceAdjuster(
// new FunctinoalBasicBolder(new Stroke[] {}, 01),
1e-1, 5);
CommonFontNoSearch = new CommonFontNoSearchbyDB();
// TODO CommonFontNoSearchbyDB() NonLookingupCommonFontNo()
int = Font.BOLD;
int = 0;
= 200;
MkeSeparateMovableType_Bolder = new MkeSeparateMovableType_Bolder(
new FunctinoalBasicBolder(new Stroke[] {}, 01), 1e-1);
ChineseCharacterTypeSetter = new FontRefSettingTool(, FontCorrespondTable
.().(, ), new FontRenderContext(
new AffineTransform(),
java.awt.RenderingHints.VALUE_TEXT_ANTIALIAS_DEFAULT,
java.awt.RenderingHints.VALUE_FRACTIONALMETRICS_DEFAULT), );
= new IDSrendService(, , , , , , );
ChineseCharacterTypeSetter = new FontRefSettingTool(, FontCorrespondTable
.().(, ), new FontRenderContext(
new AffineTransform(),
java.awt.RenderingHints.VALUE_TEXT_ANTIALIAS_DEFAULT,
java.awt.RenderingHints.VALUE_FRACTIONALMETRICS_DEFAULT), );
= new IDSrendService(, , , , , , );
ChineseCharacterTypeSetter = new FontRefSettingTool(, FontCorrespondTable
.().(, ), new FontRenderContext(
new AffineTransform(),
java.awt.RenderingHints.VALUE_TEXT_ANTIALIAS_DEFAULT,
java.awt.RenderingHints.VALUE_FRACTIONALMETRICS_DEFAULT), );
= new IDSrendService(, , , , , , );
ChineseCharacterTypeSetter = new FontRefSettingTool(, FontCorrespondTable
.().(, ), new FontRenderContext(
new AffineTransform(),
java.awt.RenderingHints.VALUE_TEXT_ANTIALIAS_DEFAULT,
java.awt.RenderingHints.VALUE_FRACTIONALMETRICS_DEFAULT), );
= new IDSrendService(, , , , , , );
}
@Override
/**
*
* <code>//.</code>
* <code></code><code></code><code></code><code></code>
* <code>png</code>
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws IOException
{
response.setHeader("Cache-Control", "public, max-age=31536000");
response.setHeader("Server", "han3_ji7_tsoo1_kian3");
String = URLDecoder.decode(request.getPathInfo(), "UTF-8");//request.getRequestURI()servlet path
= .length() != 0 ? .substring(1): "";
if (())// TODO ==
{
String[] = .split("/", 2);
String = String.format("/%s?%s=%s",
URLEncoder.encode([1], "UTF-8"),
URLEncoder.encode("", "UTF-8"),
URLEncoder.encode([0], "UTF-8"));
response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
// response.setHeader("Location", response.encodeRedirectURL());
response.setHeader("Location", );
// response.sendRedirect(String.format("/%s?=%s", [2], [1]));
return;
}
IDSrendService = ;
//System.out.println("="+);
//System.out.println("uri="+request.getRequestURI());
//System.out.println(""+request.getParameter(""));
String = request.getParameter("");
switch ( != null ? : "")
{
case "":
= ;
break;
case "":
= ;
break;
case "":
= ;
break;
case "":
= ;
break;
default:
= ;
break;
}
// TODO index.html
int = .lastIndexOf('.');
if ( == -1)
{
response.sendError(HttpServletResponse.SC_NOT_FOUND, "Filename extension missing.");
return;
}
String = .substring(0, );
System.out.println("="+);
String = .substring( + 1);
if (.equalsIgnoreCase("svg"))
{
response.setHeader("Content-Type", "image/svg+xml;charset=utf-8");
.svg(, response.getOutputStream());
}
else // if (.equalsIgnoreCase("png")) // TODO pngsvgpng
{
response.setHeader("Content-Type", "image/png");
.png(, response.getOutputStream());
}
}
private boolean (String )
{
String[] = .split("/");
if (.length == 2)// TODO ==
{
switch ([0])
{
case "":
case "":
case "":
case "":
return true;
default:
return false;
}
}
return false;
}
}
|
package info.faceland.bolt;
import info.faceland.hilt.HiltItemStack;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.block.*;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.entity.ItemSpawnEvent;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryMoveItemEvent;
import org.bukkit.event.inventory.InventoryOpenEvent;
import org.bukkit.inventory.DoubleChestInventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import java.util.ArrayList;
import java.util.List;
public class BoltListener implements Listener {
private final BoltPlugin plugin;
public BoltListener(BoltPlugin plugin) {
this.plugin = plugin;
}
@EventHandler(priority = EventPriority.LOWEST)
public void onInventoryMoveItem(InventoryMoveItemEvent event) {
ItemStack is = event.getItem();
if (is == null || is.getType() != Material.PAPER) {
return;
}
HiltItemStack his = new HiltItemStack(event.getItem());
if (his.getName().startsWith(ChatColor.GOLD + "Chest Status:")) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onBlockPlace(BlockPlaceEvent event) {
Block b = event.getBlockPlaced();
if (event.getBlockPlaced().getState() instanceof Hopper) {
BlockFace[] check =
{BlockFace.UP, BlockFace.DOWN, BlockFace.NORTH, BlockFace.EAST, BlockFace.SOUTH, BlockFace.WEST};
for (BlockFace bf : check) {
if (b.getRelative(bf).getState() instanceof Chest) {
if (!BoltAPI.isChestOwner(((Chest) b.getRelative(bf).getState()).getInventory(),
event.getPlayer().getName())) {
event.setCancelled(true);
event.getPlayer().sendMessage(ChatColor.YELLOW +
"You cannot place hoppers next to chests you do not own.");
return;
}
} else if (b.getRelative(bf).getState() instanceof DoubleChest) {
if (!BoltAPI.isChestOwner(((DoubleChest) b.getRelative(bf).getState()).getInventory(),
event.getPlayer().getName())) {
event.setCancelled(true);
event.getPlayer().sendMessage(ChatColor.YELLOW +
"You cannot place hoppers next to chests you do not own.");
return;
}
}
}
} else if (event.getBlockPlaced().getState() instanceof Chest) {
BlockFace[] check =
{BlockFace.UP, BlockFace.DOWN, BlockFace.NORTH, BlockFace.EAST, BlockFace.SOUTH, BlockFace.WEST};
for (BlockFace bf : check) {
if (b.getRelative(bf).getState() instanceof Chest) {
if (!BoltAPI.isChestOwner(((Chest) b.getRelative(bf).getState()).getInventory(),
event.getPlayer().getName())) {
event.setCancelled(true);
event.getPlayer().sendMessage(ChatColor.YELLOW +
"You cannot place chests next to chests you do not own.");
return;
}
} else if (b.getRelative(bf).getState() instanceof DoubleChest) {
if (!BoltAPI.isChestOwner(((DoubleChest) b.getRelative(bf).getState()).getInventory(),
event.getPlayer().getName())) {
event.setCancelled(true);
event.getPlayer().sendMessage(ChatColor.YELLOW +
"You cannot place chests next to chests you do not own.");
return;
}
}
}
Chest chest = (Chest) event.getBlockPlaced().getState();
ItemStack old = chest.getInventory().getItem(chest.getInventory().getSize() / 2 - 1);
if (old != null && old.getType() == Material.PAPER) {
HiltItemStack his = new HiltItemStack(old);
if (his.getName().equals(ChatColor.GOLD + "Chest Status: " + ChatColor.RED + "Locked")) {
chest.getInventory().setItem(chest.getInventory().getSize() / 2 - 1, null);
} else if (his.getName().equals(ChatColor.GOLD + "Chest Status: " + ChatColor.GREEN + "Unlocked")) {
chest.getInventory().setItem(chest.getInventory().getSize() / 2 - 1, null);
}
}
HiltItemStack hiltItemStack = new HiltItemStack(Material.PAPER);
hiltItemStack.setName(ChatColor.GOLD + "Chest Status: " + ChatColor.RED + "Locked");
List<String> lore = new ArrayList<>();
lore.add(ChatColor.WHITE + "<Click to Toggle>");
lore.add(ChatColor.GOLD + "Owner: " + ChatColor.WHITE + event.getPlayer().getName());
List<String> allowedUsers = BoltAPI.getAllowedUsers(chest.getInventory());
if (allowedUsers.size() > 0) {
for (String s : allowedUsers) {
lore.add(ChatColor.GRAY + s);
}
} else {
lore.add(ChatColor.GRAY + "Type /add <playername> while looking at");
lore.add(ChatColor.GRAY + "this chest to allow people to use it.");
}
hiltItemStack.setLore(lore);
chest.getInventory().setItem(chest.getInventory().getSize() - 1, hiltItemStack);
} else if (event.getBlockPlaced().getState() instanceof DoubleChest) {
BlockFace[] check =
{BlockFace.UP, BlockFace.DOWN, BlockFace.NORTH, BlockFace.EAST, BlockFace.SOUTH, BlockFace.WEST};
for (BlockFace bf : check) {
if (b.getRelative(bf).getState() instanceof Chest) {
if (!BoltAPI.isChestOwner(((Chest) b.getRelative(bf).getState()).getInventory(),
event.getPlayer().getName())) {
event.setCancelled(true);
event.getPlayer().sendMessage(ChatColor.YELLOW +
"You cannot place chests next to chests you do not own.");
return;
}
} else if (b.getRelative(bf).getState() instanceof DoubleChest) {
if (!BoltAPI.isChestOwner(((DoubleChest) b.getRelative(bf).getState()).getInventory(),
event.getPlayer().getName())) {
event.setCancelled(true);
event.getPlayer().sendMessage(ChatColor.YELLOW +
"You cannot place chests next to chests you do not own.");
return;
}
}
}
DoubleChest chest = (DoubleChest) event.getBlockPlaced().getState();
ItemStack old = chest.getInventory().getItem(chest.getInventory().getSize() / 2 - 1);
if (old != null && old.getType() == Material.PAPER) {
HiltItemStack his = new HiltItemStack(old);
if (his.getName().equals(ChatColor.GOLD + "Chest Status: " + ChatColor.RED + "Locked")) {
chest.getInventory().setItem(chest.getInventory().getSize() / 2 - 1, null);
} else if (his.getName().equals(ChatColor.GOLD + "Chest Status: " + ChatColor.GREEN + "Unlocked")) {
chest.getInventory().setItem(chest.getInventory().getSize() / 2 - 1, null);
}
}
HiltItemStack hiltItemStack = new HiltItemStack(Material.PAPER);
hiltItemStack.setName(ChatColor.GOLD + "Chest Status: " + ChatColor.RED + "Locked");
List<String> lore = new ArrayList<>();
lore.add(ChatColor.WHITE + "<Click to Toggle>");
lore.add(ChatColor.GOLD + "Owner: " + ChatColor.WHITE + event.getPlayer().getName());
List<String> allowedUsers = BoltAPI.getAllowedUsers(chest.getInventory());
if (allowedUsers.size() > 0) {
for (String s : allowedUsers) {
lore.add(ChatColor.GRAY + s);
}
} else {
lore.add(ChatColor.GRAY + "Type /add <playername> while looking at");
lore.add(ChatColor.GRAY + "this chest to allow people to use it.");
}
hiltItemStack.setLore(lore);
chest.getInventory().setItem(chest.getInventory().getSize() - 1, hiltItemStack);
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onBlockBreakEvent(BlockBreakEvent event) {
if (!(event.getBlock().getState() instanceof Chest) && !(event.getBlock().getState() instanceof DoubleChest)) {
return;
}
if (!BoltAPI.isChestOwner(((InventoryHolder) event.getBlock().getState()).getInventory(),
event.getPlayer().getName())) {
event.setCancelled(true);
event.getPlayer().sendMessage(ChatColor.RED + "You cannot break this chest.");
return;
}
InventoryHolder holder = (InventoryHolder) event.getBlock().getState();
ItemStack itemStack = holder.getInventory().getItem(holder.getInventory().getSize() - 1);
if (itemStack == null) {
return;
}
HiltItemStack his = new HiltItemStack(itemStack);
if (!his.getName().startsWith(ChatColor.GOLD + "Chest Status:")) {
return;
}
if (holder.getInventory() instanceof DoubleChestInventory) {
if (holder.getInventory().getItem(holder.getInventory().getSize() / 2 - 1) != null) {
event.getBlock().getWorld().dropItemNaturally(event.getBlock().getLocation(),
holder.getInventory().getItem(
holder.getInventory().getSize() / 2 - 1));
}
HiltItemStack hiltItemStack = new HiltItemStack(Material.PAPER);
hiltItemStack.setName(ChatColor.GOLD + "Chest Status: " + ChatColor.RED + "Locked");
List<String> lore = new ArrayList<>();
lore.add(ChatColor.WHITE + "<Click to Toggle>");
lore.add(ChatColor.GOLD + "Owner: " + ChatColor.WHITE + event.getPlayer().getName());
List<String> allowedUsers = BoltAPI.getAllowedUsers(holder.getInventory());
if (allowedUsers.size() > 0) {
for (String s : allowedUsers) {
lore.add(ChatColor.GRAY + s);
}
} else {
lore.add(ChatColor.GRAY + "Type /add <playername> while looking at");
lore.add(ChatColor.GRAY + "this chest to allow people to use it.");
}
hiltItemStack.setLore(lore);
holder.getInventory().setItem(holder.getInventory().getSize() / 2 - 1, hiltItemStack);
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onInventoryOpen(InventoryOpenEvent event) {
if (!(event.getPlayer() instanceof Player)) {
return;
}
if (event.getInventory().getHolder() instanceof Chest) {
if (BoltAPI.isChestLocked(event.getInventory(), (Player) event.getPlayer())) {
event.setCancelled(true);
((Player) event.getPlayer()).sendMessage(ChatColor.YELLOW + "This chest is locked.");
}
} else if (event.getInventory().getHolder() instanceof DoubleChest) {
if (BoltAPI.isChestLocked(event.getInventory(), (Player) event.getPlayer())) {
event.setCancelled(true);
((Player) event.getPlayer()).sendMessage(ChatColor.YELLOW + "This chest is locked.");
}
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onInventoryClick(InventoryClickEvent event) {
if (!(event.getWhoClicked() instanceof Player)) {
return;
}
if (event.getInventory().getHolder() instanceof Chest) {
ItemStack itemStack = event.getCurrentItem();
if (itemStack == null || itemStack.getType() != Material.PAPER) {
return;
}
HiltItemStack his = new HiltItemStack(itemStack);
if (his.getName().equals(ChatColor.GOLD + "Chest Status: " + ChatColor.RED + "Locked")) {
event.setCancelled(true);
event.setResult(Event.Result.DENY);
} else if (his.getName().equals(ChatColor.GOLD + "Chest Status: " + ChatColor.GREEN + "Unlocked")) {
event.setCancelled(true);
event.setResult(Event.Result.DENY);
}
if (BoltAPI.isChestOwner(event.getInventory(), event.getWhoClicked().getName())) {
if (his.getName().equals(ChatColor.GOLD + "Chest Status: " + ChatColor.RED + "Locked")) {
his.setName(ChatColor.GOLD + "Chest Status: " + ChatColor.GREEN + "Unlocked");
event.setCurrentItem(his);
} else if (his.getName().equals(ChatColor.GOLD + "Chest Status: " + ChatColor.GREEN + "Unlocked")) {
his.setName(ChatColor.GOLD + "Chest Status: " + ChatColor.RED + "Locked");
event.setCurrentItem(his);
}
}
} else if (event.getInventory().getHolder() instanceof DoubleChest) {
ItemStack itemStack = event.getCurrentItem();
if (itemStack == null || itemStack.getType() != Material.PAPER) {
return;
}
HiltItemStack his = new HiltItemStack(itemStack);
if (his.getName().equals(ChatColor.GOLD + "Chest Status: " + ChatColor.RED + "Locked")) {
event.setCancelled(true);
event.setResult(Event.Result.DENY);
} else if (his.getName().equals(ChatColor.GOLD + "Chest Status: " + ChatColor.GREEN + "Unlocked")) {
event.setCancelled(true);
event.setResult(Event.Result.DENY);
}
if (BoltAPI.isChestOwner(event.getInventory(), event.getWhoClicked().getName())) {
if (his.getName().equals(ChatColor.GOLD + "Chest Status: " + ChatColor.RED + "Locked")) {
his.setName(ChatColor.GOLD + "Chest Status: " + ChatColor.GREEN + "Unlocked");
event.setCurrentItem(his);
} else if (his.getName().equals(ChatColor.GOLD + "Chest Status: " + ChatColor.GREEN + "Unlocked")) {
his.setName(ChatColor.GOLD + "Chest Status: " + ChatColor.RED + "Locked");
event.setCurrentItem(his);
}
}
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onItemSpawn(ItemSpawnEvent event) {
ItemStack itemStack = event.getEntity().getItemStack();
HiltItemStack his = new HiltItemStack(itemStack);
if (his.getName().equals(ChatColor.GOLD + "Chest Status: " + ChatColor.RED + "Locked")) {
event.setCancelled(true);
}
if (his.getName().equals(ChatColor.GOLD + "Chest Status: " + ChatColor.GREEN + "Unlocked")) {
event.setCancelled(true);
}
}
}
|
package io.gomint.taglib;
import lombok.EqualsAndHashCode;
import java.io.*;
import java.nio.ByteOrder;
import java.util.*;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
/**
* Represents a compound tag that may hold several children tags.
*
* @author BlackyPaw
* @version 1.0
*/
@EqualsAndHashCode()
public class NBTTagCompound implements Cloneable {
/**
* Reads the NBTTagCompound from the specified file. See {@link #readFrom(InputStream, boolean, ByteOrder)} for
* further details.
*
* @param file The file to read the NBTCompound from
* @param compressed Whether or not the input is compressed
* @return The compound tag that was read from the input source
* @throws IOException Thrown in case an I/O error occurs or invalid NBT data is encountered
*/
public static NBTTagCompound readFrom( File file, boolean compressed, ByteOrder byteOrder ) throws IOException {
try ( FileInputStream in = new FileInputStream( file ) ) {
return readFrom( in, compressed, byteOrder );
}
}
/**
* Reads the NBTTagCompound from the specified input stream. In case compressed is set to true
* the given input stream will be wrapped in a deflating stream. The implementation is guaranteed
* to wrap the entire stream in a BufferedInputStream so that no unbuffered I/O will ever occur.
* Therefore it is not necessary to wrap the input in a BufferedInputStream manually. The input
* stream is closed automatically.
*
* @param in The input stream to read from
* @param compressed Whether or not the input is compressed
* @return The compound tag that was read from the input source
* @throws IOException Thrown in case an I/O error occurs or invalid NBT data is encountered
*/
public static NBTTagCompound readFrom( InputStream in, boolean compressed, ByteOrder byteOrder ) throws IOException {
InputStream input = null;
try {
input = new BufferedInputStream( ( compressed ? new GZIPInputStream( in ) : in ) );
NBTReader reader = new NBTReader( input, byteOrder );
return reader.parse();
} finally {
if ( input != null ) {
try {
input.close();
} catch ( IOException e ) {
e.printStackTrace();
}
}
}
}
private String name;
private Map<String, Object> children;
/**
* Constructs a new NBTTagCompound given its name. If no name is specified, i.e. name == null,
* the NBTTagCompound is considered to be member of a list.
*
* @param name The name of the tag
*/
public NBTTagCompound( final String name ) {
super();
this.name = name;
this.children = new HashMap<>();
}
/**
* Gets the name of the tag. May be null if the tag belongs to a list.
*
* @return The name of the tag
*/
public String getName() {
return this.name;
}
/**
* Adds the specified value to the compound given the name used to store it.
*
* @param name The name of the value
* @param value The value to be stored
*/
public void addValue( String name, byte value ) {
this.children.put( name, value );
}
/**
* Adds the specified value to the compound given the name used to store it.
*
* @param name The name of the value
* @param value The value to be stored
*/
public void addValue( String name, short value ) {
this.children.put( name, value );
}
/**
* Adds the specified value to the compound given the name used to store it.
*
* @param name The name of the value
* @param value The value to be stored
*/
public void addValue( String name, int value ) {
this.children.put( name, value );
}
/**
* Adds the specified value to the compound given the name used to store it.
*
* @param name The name of the value
* @param value The value to be stored
*/
public void addValue( String name, long value ) {
this.children.put( name, value );
}
/**
* Adds the specified value to the compound given the name used to store it.
*
* @param name The name of the value
* @param value The value to be stored
*/
public void addValue( String name, float value ) {
this.children.put( name, value );
}
/**
* Adds the specified value to the compound given the name used to store it.
*
* @param name The name of the value
* @param value The value to be stored
*/
public void addValue( String name, byte[] value ) {
this.children.put( name, value );
}
/**
* Adds the specified value to the compound given the name used to store it.
*
* @param name The name of the value
* @param value The value to be stored
*/
public void addValue( String name, String value ) {
this.children.put( name, value );
}
/**
* Adds the specified value to the compound given the name used to store it.
*
* @param name The name of the value
* @param value The value to be stored
*/
public void addValue( String name, double value ) {
this.children.put( name, value );
}
/**
* Adds the specified value to the compound given the name used to store it.
*
* @param name The name of the value
* @param value The value to be stored
*/
public void addValue( String name, int[] value ) {
this.children.put( name, value );
}
/**
* Adds the specified value to the compound given the name used to store it.
*
* @param name The name of the value
* @param value The value to be stored
*/
public void addValue( String name, List value ) {
this.children.put( name, value );
}
/**
* Adds the specified value to the compound given the name used to store it.
*
* @param name The name of the value
* @param value The value to be stored
*/
public void addValue( String name, NBTTagCompound value ) {
if ( !name.equals( value.getName() ) ) {
throw new AssertionError( "Failed to add NBTTagCompound with name '" + value.getName() + "' given name '" + name + "'" );
}
this.children.put( name, value );
}
/**
* Adds the specified tag as a child tag of this compound. This method is effectively the
* same as calling {@link #addValue(String, NBTTagCompound)} and specified tag.getName()
* as the name.
*
* @param tag The tag to be added as a child
*/
public void addChild( NBTTagCompound tag ) {
this.children.put( tag.getName(), tag );
}
/**
* Gets the attribute with the specified name from the compound if it exists. If not it will
* return the default value instead.
*
* @param name The name of the attribute
* @param defaultValue The default value to return for non-existing attributes
* @return The value of the attribute
*/
public Byte getByte( String name, Byte defaultValue ) {
return ( this.children.containsKey( name ) ? (Byte) this.children.get( name ) : defaultValue );
}
/**
* Gets the attribute with the specified name from the compound if it exists. If not it will
* return the default value instead.
*
* @param name The name of the attribute
* @param defaultValue The default value to return for non-existing attributes
* @return The value of the attribute
*/
public Short getShort( String name, Short defaultValue ) {
return ( this.children.containsKey( name ) ? (Short) this.children.get( name ) : defaultValue );
}
/**
* Gets the attribute with the specified name from the compound if it exists. If not it will
* return the default value instead.
*
* @param name The name of the attribute
* @param defaultValue The default value to return for non-existing attributes
* @return The value of the attribute
*/
public Integer getInteger( String name, Integer defaultValue ) {
return ( this.children.containsKey( name ) ? (Integer) this.children.get( name ) : defaultValue );
}
/**
* Gets the attribute with the specified name from the compound if it exists. If not it will
* return the default value instead.
*
* @param name The name of the attribute
* @param defaultValue The default value to return for non-existing attributes
* @return The value of the attribute
*/
public Long getLong( String name, Long defaultValue ) {
return ( this.children.containsKey( name ) ? (Long) this.children.get( name ) : defaultValue );
}
/**
* Gets the attribute with the specified name from the compound if it exists. If not it will
* return the default value instead.
*
* @param name The name of the attribute
* @param defaultValue The default value to return for non-existing attributes
* @return The value of the attribute
*/
public Float getFloat( String name, Float defaultValue ) {
return ( this.children.containsKey( name ) ? (Float) this.children.get( name ) : defaultValue );
}
/**
* Gets the attribute with the specified name from the compound if it exists. If not it will
* return the default value instead.
*
* @param name The name of the attribute
* @param defaultValue The default value to return for non-existing attributes
* @return The value of the attribute
*/
public Double getDouble( String name, Double defaultValue ) {
return ( this.children.containsKey( name ) ? (Double) this.children.get( name ) : defaultValue );
}
/**
* Gets the attribute with the specified name from the compound if it exists. If not it will
* return the default value instead.
*
* @param name The name of the attribute
* @param defaultValue The default value to return for non-existing attributes
* @return The value of the attribute
*/
public String getString( String name, String defaultValue ) {
return ( this.children.containsKey( name ) ? (String) this.children.get( name ) : defaultValue );
}
/**
* Gets the attribute with the specified name from the compound if it exists. If not it will
* return the default value instead.
*
* @param name The name of the attribute
* @param defaultValue The default value to return for non-existing attributes
* @return The value of the attribute
*/
public byte[] getByteArray( String name, byte[] defaultValue ) {
return ( this.children.containsKey( name ) ? (byte[]) this.children.get( name ) : defaultValue );
}
/**
* Gets the attribute with the specified name from the compound if it exists. If not it will
* return the default value instead.
*
* @param name The name of the attribute
* @param defaultValue The default value to return for non-existing attributes
* @return The value of the attribute
*/
public int[] getIntegerArray( String name, int[] defaultValue ) {
return ( this.children.containsKey( name ) ? (int[]) this.children.get( name ) : defaultValue );
}
/**
* Gets the list stored under the specified name. In case the list does not exist and insert is set to
* true a new and empty list with the specified name will be created. If insert is set to false null
* will be returned instead.
*
* @param name The name of the list
* @param insert Whether or not to insert a new and empty list if the list does not exist
* @return The list or null
*/
@SuppressWarnings( "unchecked" )
public List<Object> getList( String name, boolean insert ) {
if ( this.children.containsKey( name ) ) {
return (List<Object>) this.children.get( name );
}
if ( insert ) {
List<Object> backingList = new ArrayList<>( 0 );
this.addValue( name, backingList );
return backingList;
} else {
return null;
}
}
/**
* Gets the compound stored under the specified name. In case the compound does not exist and insert is set to
* true a new and empty compound with the specified name will be created. If insert is set to false null
* will be returned instead.
*
* @param name The name of the compound
* @param insert Whether or not to insert a new and empty compound if the compound does not exist
* @return The compound or null
*/
public NBTTagCompound getCompound( String name, boolean insert ) {
if ( this.children.containsKey( name ) ) {
return (NBTTagCompound) this.children.get( name );
}
if ( insert ) {
NBTTagCompound compound = new NBTTagCompound( name );
this.addValue( name, compound );
return compound;
} else {
return null;
}
}
/**
* Writes the NBTTagCompound to the specified file. See {@link #writeTo(OutputStream, boolean, ByteOrder)} for
* further details.
*
* @param file The file to write the NBTCompound to
* @param compressed Whether or not the output should be compressed
* @param byteOrder The byteorder to use
* @throws IOException Thrown in case an I/O error occurs or invalid NBT data is encountered
*/
public void writeTo( File file, boolean compressed, ByteOrder byteOrder ) throws IOException {
try ( FileOutputStream out = new FileOutputStream( file ) ) {
this.writeTo( out, compressed, byteOrder );
}
}
/**
* Writes the NBTTagCompound to the specified output stream. In case compressed is set to true
* the given output stream will be wrapped in an inflating stream. The implementation is guaranteed
* to wrap the entire stream in a BufferedOutputStream so that no unbuffered I/O will ever occur.
* Therefore it is not necessary to wrap the output in a BufferedOutputStream manually. The output
* stream is closed automatically.
*
* @param out The output stream to write to
* @param compressed Whether or not the output is compressed
* @param byteOrder The byteorder to use
* @throws IOException Thrown in case an I/O error occurs or invalid NBT data is encountered
*/
public void writeTo( OutputStream out, boolean compressed, ByteOrder byteOrder ) throws IOException {
OutputStream output = null;
try {
output = new BufferedOutputStream( ( compressed ? new GZIPOutputStream( out ) : out ) );
NBTWriter writer = new NBTWriter( output, byteOrder );
writer.write( this );
} finally {
if ( output != null ) {
try {
output.close();
} catch ( IOException e ) {
e.printStackTrace();
}
}
}
}
/**
* Returns an iterable set of entries this tag compound holds.
*
* @return The set of entries the compound holds
*/
public Set<Map.Entry<String, Object>> entrySet() {
return this.children.entrySet();
}
/**
* Checks whether or not the compound contains a child tag with the specified name.
*
* @param key The name of the child tag
* @return Whether or not the compound contains a child tag with the specified name
*/
public boolean containsKey( String key ) {
return this.children.containsKey( key );
}
/**
* Removes given child
*
* @param key The name of the child tag
* @return The object which has been removed or null when nothing has been removed
*/
public Object remove( String key ) {
return this.children.remove( key );
}
/**
* Get the amount of children in this compound
*
* @return amount of children
*/
public int size() {
return this.children.size();
}
/**
* Clones the compound and all of its non-immutable elements recursively. This operation
* may be expensive so use it only if absolutely necessary.
*
* @param newName New name of the root compound
* @return The cloned tag compound.
*/
public NBTTagCompound deepClone( String newName ) {
NBTTagCompound compound = this.deepClone0();
compound.setName( newName );
return compound;
}
private NBTTagCompound deepClone0() {
NBTTagCompound compound = new NBTTagCompound();
compound.name = this.name;
compound.children = new HashMap<>( this.children.size() );
for ( Map.Entry<String, Object> child : this.children.entrySet() ) {
Object value = child.getValue();
if ( value instanceof byte[] ) {
byte[] data = (byte[]) value;
compound.addValue( child.getKey(), Arrays.copyOf( data, data.length ) );
} else if ( value instanceof List ) {
compound.addValue( child.getKey(), this.deepCloneList( (List) value ) );
} else if ( value instanceof int[] ) {
int[] data = (int[]) value;
compound.addValue( child.getKey(), Arrays.copyOf( data, data.length ) );
} else if ( value instanceof NBTTagCompound ) {
compound.addChild( ( (NBTTagCompound) value ).deepClone0() );
} else {
// Other supported types are immutable:
compound.children.put( child.getKey(), child.getValue() );
}
}
return compound;
}
private List deepCloneList( List input ) {
List output = new ArrayList( input.size() );
for ( Object value : input ) {
if ( value instanceof byte[] ) {
byte[] data = (byte[]) value;
output.add( Arrays.copyOf( data, data.length ) );
} else if ( value instanceof List ) {
output.add( this.deepCloneList( (List) value ) );
} else if ( value instanceof int[] ) {
int[] data = (int[]) value;
output.add( Arrays.copyOf( data, data.length ) );
} else if ( value instanceof NBTTagCompound ) {
output.add( ( (NBTTagCompound) value ).deepClone0() );
} else {
// Other supported types are immutable:
output.add( value );
}
}
return output;
}
NBTTagCompound() {
super();
this.name = null;
this.children = new HashMap<>();
}
/**
* @deprecated For internal use only!
*/
void setName( String name ) {
this.name = name;
}
}
|
package jacobi.core.spatial.sort;
import java.util.AbstractList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.stream.IntStream;
import jacobi.core.util.IntStack;
/**
* Implementation of spatial sorting in the order of a kd-tree.
*
* <p>Fractal sort utilize all of the dimensions which in turn generates good result,
* but it does not scale well with the number of dimensions (especially Hilbert sort).
* Only sorting in a few dimensions may miss out a lot of information from the missing
* dimensions. </p>
*
* <p>K-d sort is provided for sorting data in high dimension. As in a kd-tree, the spatial
* data are divided in half by a single dimension, then in turn sorting the two halves
* in other dimensions in the same manner.</p>
*
* @author Y.K. Chan
*
*/
public class KdSort implements SpatialSort {
@Override
public int[] sort(List<double[]> vectors) {
int[] order = IntStream.range(0, vectors.size()).toArray();
return order;
}
protected List<IntStack> groupBy(VectorList vectorList, int[] dims, double[] mean) {
if(dims.length > DEFAULT_MAX_DIM) {
throw new UnsupportedOperationException("Number of dimensions "
+ dims.length + " in a batch is too large.");
}
IntStack[] groups = new IntStack[1 << dims.length];
for(int i = vectorList.begin; i < vectorList.end; i++) {
int k = vectorList.order[i];
double[] vector = vectorList.vectors.get(k);
int parity = 0;
for(int j = 0; j < dims.length; j++) {
int dim = dims[j];
parity += vector[dim] < mean[dim] ? 0 : 1;
parity *= 2;
}
if(groups[parity] == null){
groups[parity] = new IntStack(4);
}
groups[parity].push(k);
}
return Arrays.asList(groups);
}
protected int[] chooseDims(List<double[]> vectors, double[] mean) {
double[] var = this.varFn.apply(vectors, mean);
double totalVar = 0.0;
int max0 = -1, max1 = -1, max2 = -1;
for(int i = 0; i < var.length; i++) {
totalVar += var[i];
if(max0 < 0 || var[max0] < var[i]){
max2 = max1; max1 = max0; max0 = i;
continue;
}
if(max1 < 0 || var[max1] < var[i]){
max2 = max1; max1 = i;
continue;
}
if(max2 < 0 || var[max2] < var[i]){
max2 = i;
}
}
if(var[max0] + var[max1] + var[max2] > this.rSquare * totalVar){
return new int[] {max0, max1, max2} ;
}
return new int[] {};
}
protected int[] chooseDims(double[] mean, double[] var) {
return null;
}
private Function<List<double[]>, double[]> meanFn;
private BiFunction<List<double[]>, double[], double[]> varFn;
private Function<int[], SpatialSort> lowDim;
private double rSquare;
protected static class VectorList {
public final List<double[]> vectors;
public final int begin, end;
public final int[] order;
public VectorList(List<double[]> vectors, int begin, int end, int[] order) {
this.vectors = vectors;
this.begin = begin;
this.end = end;
this.order = order;
}
public List<double[]> toList() {
return new AbstractList<double[]>() {
@Override
public double[] get(int index) {
return vectors.get(order[index + begin]);
}
@Override
public int size() {
return end - begin;
}
};
}
}
protected static final int DEFAULT_MAX_DIM = 8;
}
|
package javax.persistence;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaDelete;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.CriteriaUpdate;
import javax.persistence.metamodel.Metamodel;
import java.util.List;
import java.util.Map;
/**
* Interface used to interact with the persistence context.
*
* <p> An <code>EntityManager</code> instance is associated with
* a persistence context. A persistence context is a set of entity
* instances in which for any persistent entity identity there is
* a unique entity instance. Within the persistence context, the
* entity instances and their lifecycle are managed.
* The <code>EntityManager</code> API is used
* to create and remove persistent entity instances, to find entities
* by their primary key, and to query over entities.
*
* <p> The set of entities that can be managed by a given
* <code>EntityManager</code> instance is defined by a persistence
* unit. A persistence unit defines the set of all classes that are
* related or grouped by the application, and which must be
* colocated in their mapping to a single database.
*
* @see Query
* @see TypedQuery
* @see CriteriaQuery
* @see PersistenceContext
*
* @since Java Persistence 1.0
*/
public interface EntityManager {
public void persist(Object entity);
public <T> T merge(T entity);
public void remove(Object entity);
public <T> T find(Class<T> entityClass, Object primaryKey);
public <T> T find(Class<T> entityClass, Object primaryKey,
Map<String, Object> properties);
public <T> T find(Class<T> entityClass, Object primaryKey,
LockModeType lockMode);
public <T> T find(Class<T> entityClass, Object primaryKey,
LockModeType lockMode,
Map<String, Object> properties);
public <T> T getReference(Class<T> entityClass,
Object primaryKey);
/**
* Synchronize the persistence context to the
* underlying database.
* @throws TransactionRequiredException if there is
* no transaction
* @throws PersistenceException if the flush fails
*/
public void flush();
/**
* Set the flush mode that applies to all objects contained
* in the persistence context.
* @param flushMode flush mode
*/
public void setFlushMode(FlushModeType flushMode);
/**
* Get the flush mode that applies to all objects contained
* in the persistence context.
* @return flushMode
*/
public FlushModeType getFlushMode();
public void lock(Object entity, LockModeType lockMode);
public void lock(Object entity, LockModeType lockMode,
Map<String, Object> properties);
public void refresh(Object entity);
public void refresh(Object entity,
Map<String, Object> properties);
public void refresh(Object entity, LockModeType lockMode);
public void refresh(Object entity, LockModeType lockMode,
Map<String, Object> properties);
/**
* Clear the persistence context, causing all managed
* entities to become detached. Changes made to entities that
* have not been flushed to the database will not be
* persisted.
*/
public void clear();
public void detach(Object entity);
public boolean contains(Object entity);
public LockModeType getLockMode(Object entity);
public void setProperty(String propertyName, Object value);
/**
* Get the properties and hints and associated values that are in effect
* for the entity manager. Changing the contents of the map does
* not change the configuration in effect.
* @return map of properties and hints in effect for entity manager
* @since Java Persistence 2.0
*/
public Map<String, Object> getProperties();
public Query createQuery(String qlString);
public <T> TypedQuery<T> createQuery(CriteriaQuery<T> criteriaQuery);
public Query createQuery(CriteriaUpdate updateQuery);
public Query createQuery(CriteriaDelete deleteQuery);
public <T> TypedQuery<T> createQuery(String qlString, Class<T> resultClass);
public Query createNamedQuery(String name);
public <T> TypedQuery<T> createNamedQuery(String name, Class<T> resultClass);
/**
* Create an instance of <code>Query</code> for executing
* a native SQL statement, e.g., for update or delete.
* @param sqlString a native SQL query string
* @return the new query instance
*/
public Query createNativeQuery(String sqlString);
/**
* Create an instance of <code>Query</code> for executing
* a native SQL query.
* @param sqlString a native SQL query string
* @param resultClass the class of the resulting instance(s)
* @return the new query instance
*/
public Query createNativeQuery(String sqlString, Class resultClass);
/**
* Create an instance of <code>Query</code> for executing
* a native SQL query.
* @param sqlString a native SQL query string
* @param resultSetMapping the name of the result set mapping
* @return the new query instance
*/
public Query createNativeQuery(String sqlString, String resultSetMapping);
public StoredProcedureQuery createNamedStoredProcedureQuery(
String name);
public StoredProcedureQuery createStoredProcedureQuery(
String procedureName);
public StoredProcedureQuery createStoredProcedureQuery(
String procedureName, Class... resultClasses);
public StoredProcedureQuery createStoredProcedureQuery(
String procedureName, String... resultSetMappings);
/**
* Indicate to the entity manager that a JTA transaction is
* active. This method should be called on a JTA application
* managed entity manager that was created outside the scope
* of the active transaction to associate it with the current
* JTA transaction.
* @throws TransactionRequiredException if there is
* no transaction
*/
public void joinTransaction();
/**
* Determine whether the entity manager is joined to the
* current transaction. Returns false if the entity manager
* is not joined to the current transaction or if no
* transaction is active
* @return boolean
*/
public boolean isJoinedToTransaction();
/**
* Return an object of the specified type to allow access to the
* provider-specific API. If the provider's <code>EntityManager</code>
* implementation does not support the specified class, the
* <code>PersistenceException</code> is thrown.
* @param cls the class of the object to be returned. This is
* normally either the underlying <code>EntityManager</code> implementation
* class or an interface that it implements.
* @return an instance of the specified class
* @throws PersistenceException if the provider does not
* support the call
* @since Java Persistence 2.0
*/
public <T> T unwrap(Class<T> cls);
/**
* Return the underlying provider object for the <code>EntityManager</code>,
* if available. The result of this method is implementation
* specific. The <code>unwrap</code> method is to be preferred for new
* applications.
* @return underlying provider object for EntityManager
*/
public Object getDelegate();
public void close();
/**
* Determine whether the entity manager is open.
* @return true until the entity manager has been closed
*/
public boolean isOpen();
public EntityTransaction getTransaction();
public EntityManagerFactory getEntityManagerFactory();
public CriteriaBuilder getCriteriaBuilder();
public Metamodel getMetamodel();
/**
* Return a mutable EntityGraph that can be used to dynamically create an EntityGraph.
*
* @param rootType class of entity graph
*
* @return entity graph
*
* @since JPA 2.1
*/
public <T> EntityGraph<T> createEntityGraph(Class<T> rootType);
/**
* Return a mutable copy of the named EntityGraph. If there is no entity graph with the specified name, null
* is returned.
*
* @param graphName name of an entity graph
*
* @return entity graph
*
* @since JPA 2.1
*/
public EntityGraph<?> createEntityGraph(String graphName);
public EntityGraph<?> getEntityGraph(String graphName);
public <T> List<EntityGraph<? super T>> getEntityGraphs(Class<T> entityClass);
}
|
package kcsaba.image.viewer;
import java.awt.BorderLayout;
import java.awt.LayoutManager;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import javax.swing.ButtonGroup;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JComponent;
import javax.swing.JMenu;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JViewport;
public class ImageViewer {
private final LayeredImageView view;
private ImageComponent theImage;
private final JScrollPane scroller;
private JPanel panel;
private StatusBar statusBar;
private boolean statusBarVisible=false;
private PropertyChangeSupport propertyChangeSupport;
private JPopupMenu popup;
private MouseListener contextMenuListener = new MouseAdapter() {
private void showPopup(MouseEvent e) {
e.consume();
Point p = panel.getPopupLocation(e);
if (p == null) {
p = e.getPoint();
}
popup.show(e.getComponent(), p.x, p.y);
}
@Override
public void mousePressed(MouseEvent e) {
if (e.isPopupTrigger()) {
showPopup(e);
}
}
@Override
public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger()) {
showPopup(e);
}
}
};
/**
* Creates a new image viewer.
*/
public ImageViewer() {
this(null);
}
/**
* Creates a new image viewer displaying the specified image.
* @param image the image to display; if <code>null</code> then no image is displayed
* @see #setImage(BufferedImage)
*/
public ImageViewer(BufferedImage image) {
propertyChangeSupport=new PropertyChangeSupport(this);
panel=new JPanel(new BorderLayout());
theImage=new ImageComponent(propertyChangeSupport);
view=new LayeredImageView(theImage, propertyChangeSupport);
theImage.setImage(image);
scroller=new JScrollPane(view.getComponent()) {
@Override
protected JViewport createViewport() {
return new JViewport() {
@Override
protected LayoutManager createLayoutManager() {
return new CustomViewportLayout(ImageViewer.this);
}
};
}
@Override
public boolean isValidateRoot() {
return false;
}
};
panel.add(scroller, BorderLayout.CENTER);
setStatusBar(new DefaultStatusBar());
popup=createPopup(this);
theImage.addMouseListener(contextMenuListener);
}
private static JPopupMenu createPopup(final ImageViewer imageViewer) {
JPopupMenu popup = new JPopupMenu();
final JCheckBoxMenuItem toggleStatusBarItem = new JCheckBoxMenuItem("Status bar");
toggleStatusBarItem.setState(imageViewer.isStatusBarVisible());
imageViewer.addPropertyChangeListener("statusBarVisible", new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
toggleStatusBarItem.setState(imageViewer.isStatusBarVisible());
}
});
toggleStatusBarItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
imageViewer.setStatusBarVisible(!imageViewer.isStatusBarVisible());
}
});
popup.add(toggleStatusBarItem);
JMenu zoomMenu = new JMenu("Zoom");
final JRadioButtonMenuItem[] zoomButtons = new JRadioButtonMenuItem[2];
zoomButtons[0] = new JRadioButtonMenuItem("Original size", imageViewer.getResizeStrategy()==ResizeStrategy.NO_RESIZE);
zoomButtons[0].addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
imageViewer.setResizeStrategy(ResizeStrategy.NO_RESIZE);
}
});
zoomButtons[1] = new JRadioButtonMenuItem("Shrink to fit", imageViewer.getResizeStrategy()==ResizeStrategy.SHRINK_TO_FIT);
zoomButtons[1].addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
imageViewer.setResizeStrategy(ResizeStrategy.SHRINK_TO_FIT);
}
});
ButtonGroup group = new ButtonGroup();
for (JRadioButtonMenuItem i : zoomButtons) {
zoomMenu.add(i);
group.add(i);
}
imageViewer.addPropertyChangeListener("resizeStrategy", new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
zoomButtons[((ResizeStrategy)evt.getNewValue()).ordinal()].setSelected(true);
}
});
popup.add(zoomMenu);
return popup;
}
public void setStatusBar(StatusBar statusBar) {
if (statusBar==this.statusBar) return;
if (statusBar.getImageViewer()!=null)
throw new IllegalArgumentException("Status bar already added to an image viewer");
StatusBar oldStatusBar=this.statusBar;
if (oldStatusBar!=null) {
panel.remove(oldStatusBar.getComponent());
oldStatusBar.setImageViewer(null);
}
this.statusBar=statusBar;
if (this.statusBar!=null) {
this.statusBar.setImageViewer(this);
panel.add(this.statusBar.getComponent(), BorderLayout.SOUTH);
}
this.statusBar.getComponent().setVisible(statusBarVisible);
panel.revalidate();
panel.repaint();
propertyChangeSupport.firePropertyChange("statusBar", oldStatusBar, statusBar);
}
/**
* Sets whether the status bar is visible.
* @param statusBarVisible true, if the status bar should be visible; false otherwise
*/
public void setStatusBarVisible(boolean statusBarVisible) {
if (this.statusBarVisible == statusBarVisible) return;
if (statusBar!=null)
statusBar.getComponent().setVisible(statusBarVisible);
boolean prev = this.statusBarVisible;
this.statusBarVisible = statusBarVisible;
propertyChangeSupport.firePropertyChange("statusBarVisible", prev, statusBarVisible);
}
/**
* Returns whether the status bar is set to be visible.
* @return the statusBarVisible property
*/
public boolean isStatusBarVisible() {
return statusBarVisible;
}
/**
* Returns the image viewer component that can be displayed.
* @return the image viewer component
*/
public JComponent getComponent() {
return panel;
}
/**
* Sets the image displayed by the viewer.
* @param image the new image to display; if <code>null</code> then no image is displayed
*/
public void setImage(BufferedImage image) {
theImage.setImage(image);
}
/**
* Returns the currently displayed image.
* @return the current image, or <code>null</code> if no image is displayed
*/
public BufferedImage getImage() {
return theImage.getImage();
}
/**
* Sets the resize strategy this viewer should use.
* @param resizeStrategy the new resize strategy
*/
public void setResizeStrategy(ResizeStrategy resizeStrategy) {
theImage.setResizeStrategy(resizeStrategy);
}
/**
* Returns the current resize strategy.
* @return the current resize strategy
*/
public ResizeStrategy getResizeStrategy() {
return theImage.getResizeStrategy();
}
/**
* Returns the transformation that is applied to the image. Most commonly the
* transformation is the concatenation of a uniform scale and a translation.
* <p>
* The <code>AffineTransform</code>
* instance returned by this method should not be modified.
* @return the transformation applied to the image before painting
*/
public AffineTransform getImageTransform() {
return theImage.getImageTransform();
}
public void addOverlay(Overlay overlay, int layer) {
view.addOverlay(overlay, layer);
}
public void removeOverlay(Overlay overlay) {
view.removeOverlay(overlay);
}
/**
* Adds the specified mouse listener to receive mouse events from
* the image component of this image viewer. If listener <code>l</code>
* is <code>null</code>, no exception is thrown and no action is performed.
* @param l the mouse listener
*/
public void addMouseListener(MouseListener l) {
theImage.addMouseListener(l);
}
/**
* Removes the specified mouse listener so that it no longer receives
* mouse motion events from the image component of this image viewer. This method
* performs no function, nor does it throw an exception, if the listener specified
* by the argument was not previously added to this component. If listener
* <code>l</code> is <code>null</code>, no exception is thrown and no action is
* performed.
* @param l the mouse motion listener
*/
public void removeMouseListener(MouseListener l) {
theImage.removeMouseListener(l);
}
/**
* Adds the specified mouse motion listener to receive mouse events from
* the image component of this image viewer. If listener <code>l</code>
* is <code>null</code>, no exception is thrown and no action is performed.
* @param l the mouse listener
*/
public void addMouseMotionListener(MouseMotionListener l) {
theImage.addMouseMotionListener(l);
}
/**
* Removes the specified mouse motion listener so that it no longer receives
* mouse motion events from the image component of this image viewer. This method
* performs no function, nor does it throw an exception, if the listener specified
* by the argument was not previously added to this component. If listener
* <code>l</code> is <code>null</code>, no exception is thrown and no action is
* performed.
* @param l the mouse motion listener
*/
public void removeMouseMotionListener(MouseMotionListener l) {
theImage.removeMouseMotionListener(l);
}
public void addImageMouseMoveListener(ImageMouseMoveListener l) {
theImage.addImageMouseMoveListener(l);
}
public void removeImageMouseMoveListener(ImageMouseMoveListener l) {
theImage.removeImageMouseMoveListener(l);
}
public void addImageMouseClickListener(ImageMouseClickListener l) {
theImage.addImageMouseClickListener(l);
}
public void removeImageMouseClickListener(ImageMouseClickListener l) {
theImage.removeImageMouseClickListener(l);
}
public void addPropertyChangeListener(PropertyChangeListener l) {
propertyChangeSupport.addPropertyChangeListener(l);
}
public void removePropertyChangeListener(PropertyChangeListener l) {
propertyChangeSupport.removePropertyChangeListener(l);
}
public void addPropertyChangeListener(String name, PropertyChangeListener l) {
propertyChangeSupport.addPropertyChangeListener(name, l);
}
public void removePropertyChangeListener(String name, PropertyChangeListener l) {
propertyChangeSupport.removePropertyChangeListener(name, l);
}
/**
* Returns the scroll pane of the image viewer.
* @return the scroll pane
*/
JScrollPane getScrollPane() {
return scroller;
}
/**
* Adds a component to the trackSizeIfEmpty set. If this component has no image set
* but one of the tracked ones does, then the size of this component will be set to
* match the size of the image displayed in one of the tracked components. This
* method is useful if the scroll bars of image viewers are synchronized, because
* if a viewer has no image set, it can cause the scrolling of a viewer that has an
* image set not to work.
* <p>
* Tracking is symmetrical and transitive.
* @param c the component to track
*/
void trackSizeIfEmpty(ImageViewer c) {
theImage.trackSizeIfEmpty(c.theImage);
}
}
|
package kr.co.vcnc.haeinsa;
import static kr.co.vcnc.haeinsa.HaeinsaConstants.LOCK_FAMILY;
import static kr.co.vcnc.haeinsa.HaeinsaConstants.LOCK_QUALIFIER;
import static kr.co.vcnc.haeinsa.HaeinsaConstants.ROW_LOCK_TIMEOUT;
import static kr.co.vcnc.haeinsa.HaeinsaConstants.ROW_LOCK_VERSION;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NavigableMap;
import java.util.NavigableSet;
import java.util.Set;
import javax.annotation.Nullable;
import kr.co.vcnc.haeinsa.exception.ConflictException;
import kr.co.vcnc.haeinsa.thrift.TRowLocks;
import kr.co.vcnc.haeinsa.thrift.generated.TCellKey;
import kr.co.vcnc.haeinsa.thrift.generated.TKeyValue;
import kr.co.vcnc.haeinsa.thrift.generated.TMutation;
import kr.co.vcnc.haeinsa.thrift.generated.TRowKey;
import kr.co.vcnc.haeinsa.thrift.generated.TRowLock;
import kr.co.vcnc.haeinsa.thrift.generated.TRowLockState;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.KeyValue.Type;
import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.HTableInterface;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.filter.ColumnRangeFilter;
import org.apache.hadoop.hbase.util.Bytes;
import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.collect.Iterables;
import com.google.common.collect.Iterators;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
/**
* Implementation of {@link HaeinsaTableIface}. It works with
* {@link HaeinsaTransaction} to provide transaction on HBase.
*/
class HaeinsaTable implements HaeinsaTableIfaceInternal {
private final HTableInterface table;
public HaeinsaTable(HTableInterface table) {
this.table = table;
}
@Override
public byte[] getTableName() {
return table.getTableName();
}
@Override
public Configuration getConfiguration() {
return table.getConfiguration();
}
@Override
public HTableDescriptor getTableDescriptor() throws IOException {
return table.getTableDescriptor();
}
/**
* Get data from HBase without transaction.
* {@link HaeinsaTransaction#commit()} to check or mutate lock column of the row scanned by this method.
* This method can be used when read performance is important or strict consistency of the result is not matter.
*
* @param get
* @return
* @throws IOException
*/
private HaeinsaResult getWithoutTx(HaeinsaGet get) throws IOException {
Get hGet = new Get(get.getRow());
for (Entry<byte[], NavigableSet<byte[]>> entry : get.getFamilyMap().entrySet()) {
if (entry.getValue() == null) {
hGet.addFamily(entry.getKey());
} else {
for (byte[] qualifier : entry.getValue()) {
hGet.addColumn(entry.getKey(), qualifier);
}
}
}
Result result = table.get(hGet);
return new HaeinsaResult(result);
}
@Override
public HaeinsaResult get(@Nullable HaeinsaTransaction tx, HaeinsaGet get) throws IOException {
Preconditions.checkNotNull(get);
if (tx == null) {
return getWithoutTx(get);
}
byte[] row = get.getRow();
HaeinsaTableTransaction tableState = tx.createOrGetTableState(this.table.getTableName());
HaeinsaRowTransaction rowState = tableState.getRowStates().get(row);
boolean lockInclusive = false;
Get hGet = new Get(get.getRow());
for (Entry<byte[], NavigableSet<byte[]>> entry : get.getFamilyMap().entrySet()) {
if (entry.getValue() == null) {
hGet.addFamily(entry.getKey());
} else {
for (byte[] qualifier : entry.getValue()) {
hGet.addColumn(entry.getKey(), qualifier);
}
}
}
if (rowState == null) {
if (hGet.hasFamilies()) {
hGet.addColumn(LOCK_FAMILY, LOCK_QUALIFIER);
}
lockInclusive = true;
}
Result result = table.get(hGet);
List<HaeinsaKeyValueScanner> scanners = Lists.newArrayList();
if (rowState != null) {
scanners.addAll(rowState.getScanners());
}
scanners.add(new HBaseGetScanner(result, Long.MAX_VALUE));
HaeinsaResult hResult = null;
// Scanners at this moment is:
// union( muationScanners from RowTransaction, Scanner of get)
try (ClientScanner scanner = new ClientScanner(tx, scanners, get.getFamilyMap(), lockInclusive)) {
hResult = scanner.next();
}
if (hResult == null) {
/*
* if specific row is empty and there was no puts at all, initialize ClientScanner make empty scanners variable.
* There will be no rowState associated to the row, and transaction will not operate normally.
* Therefore, create rowState if there was no HBase operation accessed to the row before.
*/
rowState = tableState.createOrGetRowState(row);
if (rowState.getCurrent() == null) {
rowState.setCurrent(TRowLocks.deserialize(null));
}
List<HaeinsaKeyValue> emptyList = Collections.emptyList();
hResult = new HaeinsaResult(emptyList);
}
return hResult;
}
/**
* Scan data from HBase without transaction.
* {@link HaeinsaTransaction#commit()} to check or mutate lock column of the row scanned by this method.
* This method can be used when read performance is important or strict consistency of the result is not matter.
*
* @param scan
* @return
* @throws IOException IOException from HBase.
*/
private HaeinsaResultScanner getScannerWithoutTx(HaeinsaScan scan) throws IOException {
Scan hScan = new Scan(scan.getStartRow(), scan.getStopRow());
hScan.setCaching(scan.getCaching());
hScan.setCacheBlocks(scan.getCacheBlocks());
for (Entry<byte[], NavigableSet<byte[]>> entry : scan.getFamilyMap().entrySet()) {
if (entry.getValue() == null) {
hScan.addFamily(entry.getKey());
} else {
for (byte[] qualifier : entry.getValue()) {
hScan.addColumn(entry.getKey(), qualifier);
}
}
}
final ResultScanner scanner = table.getScanner(hScan);
return new SimpleClientScanner(scanner);
}
/**
* Scan data inside single row (intraScan) without transaction.
* {@link HaeinsaTransaction#commit()} to check or mutate lock column of the row scanned by this method.
* This method can be used when read performance is important or strict consistency of the result is not matter.
*
* @param intraScan
* @return
* @throws IOException IOException from HBase.
*/
private HaeinsaResultScanner getScannerWithoutTx(HaeinsaIntraScan intraScan) throws IOException {
Scan hScan = new Scan(intraScan.getRow(), Bytes.add(intraScan.getRow(), new byte[] { 0x00 }));
hScan.setBatch(intraScan.getBatch());
for (byte[] family : intraScan.getFamilies()) {
hScan.addFamily(family);
}
ColumnRangeFilter rangeFilter = new ColumnRangeFilter(
intraScan.getMinColumn(), intraScan.isMinColumnInclusive(),
intraScan.getMaxColumn(), intraScan.isMaxColumnInclusive());
hScan.setFilter(rangeFilter);
final ResultScanner scanner = table.getScanner(hScan);
return new SimpleClientScanner(scanner);
}
/**
* Haeinsa implementation of {@link Scan}.
* Scan range of row inside defined by {@link HaeinsaScan} in the context of transaction(tx).
* Return {@link #ClientScanner} which related to {@link HaeinsaTable} and {@link HaeinsaTransaction}.
* <p>
* Return {@link SimpleClientScanner} which do not support transaction if tx is null.
* User can use this feature if specific scan operation does not require strong consistency
* or high performance is crucial because scan too wide range of rows.
*/
@Override
public HaeinsaResultScanner getScanner(@Nullable HaeinsaTransaction tx, HaeinsaScan scan) throws IOException {
Preconditions.checkNotNull(scan);
if (tx == null) {
return getScannerWithoutTx(scan);
}
Scan hScan = new Scan(scan.getStartRow(), scan.getStopRow());
hScan.setCaching(scan.getCaching());
hScan.setCacheBlocks(scan.getCacheBlocks());
for (Entry<byte[], NavigableSet<byte[]>> entry : scan.getFamilyMap().entrySet()) {
if (entry.getValue() == null) {
hScan.addFamily(entry.getKey());
} else {
for (byte[] qualifier : entry.getValue()) {
hScan.addColumn(entry.getKey(), qualifier);
}
}
}
if (hScan.hasFamilies()) {
hScan.addColumn(LOCK_FAMILY, LOCK_QUALIFIER);
}
HaeinsaTableTransaction tableState = tx.createOrGetTableState(getTableName());
NavigableMap<byte[], HaeinsaRowTransaction> rows;
if (Bytes.equals(scan.getStartRow(), HConstants.EMPTY_START_ROW)) {
if (Bytes.equals(scan.getStopRow(), HConstants.EMPTY_END_ROW)) {
// null, null
rows = tableState.getRowStates();
} else {
// null, StopRow
rows = tableState.getRowStates().headMap(scan.getStopRow(), false);
}
} else {
if (Bytes.equals(scan.getStopRow(), HConstants.EMPTY_END_ROW)) {
// StartRow, null
rows = tableState.getRowStates().tailMap(scan.getStartRow(), true);
} else {
// StartRow, StopRow
rows = tableState.getRowStates().subMap(scan.getStartRow(), true, scan.getStopRow(), false);
}
}
List<HaeinsaKeyValueScanner> scanners = Lists.newArrayList();
for (HaeinsaRowTransaction rowTx : rows.values()) {
scanners.addAll(rowTx.getScanners());
}
scanners.add(new HBaseScanScanner(table.getScanner(hScan)));
// Scanners at this moment is:
// union( muationScanners from all RowTransactions, Scanner of scan )
return new ClientScanner(tx, scanners, scan.getFamilyMap(), true);
}
/**
* Haeinsa implementation of {@link ColumnRangeFilter}.
* Scan range of column inside single row defined by {@link HaeinsaIntraScan} in the context of transaction(tx).
* Return {@link #ClientScanner} which related to {@link HaeinsaTable} and {@link HaeinsaTransaction}.
* <p>
* Return {@link SimpleClientScanner} which do not support transaction if tx is null.
* User can use this feature if specific intra-scan operation does not require strong consistency.
* <p>
* Haeinsa does not support column-range scan over multiple row in this version.
*/
@Override
public HaeinsaResultScanner getScanner(@Nullable HaeinsaTransaction tx, HaeinsaIntraScan intraScan)
throws IOException {
Preconditions.checkNotNull(intraScan);
if (tx == null) {
return getScannerWithoutTx(intraScan);
}
// scan from startRow ( inclusive ) to startRow + 0x00 ( exclusive )
Scan hScan = new Scan(intraScan.getRow(), Bytes.add(intraScan.getRow(), new byte[] { 0x00 }));
hScan.setBatch(intraScan.getBatch());
for (byte[] family : intraScan.getFamilies()) {
hScan.addFamily(family);
}
ColumnRangeFilter rangeFilter = new ColumnRangeFilter(
intraScan.getMinColumn(), intraScan.isMinColumnInclusive(),
intraScan.getMaxColumn(), intraScan.isMaxColumnInclusive());
hScan.setFilter(rangeFilter);
HaeinsaTableTransaction tableState = tx.createOrGetTableState(getTableName());
HaeinsaRowTransaction rowState = tableState.getRowStates().get(intraScan.getRow());
if (rowState == null) {
rowState = checkOrRecoverLock(tx, intraScan.getRow(), tableState, rowState);
}
List<HaeinsaKeyValueScanner> scanners = Lists.newArrayList();
if (rowState != null) {
scanners.addAll(rowState.getScanners());
}
scanners.add(new HBaseScanScanner(table.getScanner(hScan)));
// scanners at this moment is:
// union( muationScanners from RowTransaction, Scanner of intraScan )
return new ClientScanner(tx, scanners, hScan.getFamilyMap(), intraScan, false);
}
@Override
public HaeinsaResultScanner getScanner(@Nullable HaeinsaTransaction tx, byte[] family) throws IOException {
Preconditions.checkNotNull(family);
HaeinsaScan scan = new HaeinsaScan();
scan.addFamily(family);
return getScanner(tx, scan);
}
@Override
public HaeinsaResultScanner getScanner(@Nullable HaeinsaTransaction tx, byte[] family, byte[] qualifier)
throws IOException {
Preconditions.checkNotNull(family);
Preconditions.checkNotNull(qualifier);
HaeinsaScan scan = new HaeinsaScan();
scan.addColumn(family, qualifier);
return getScanner(tx, scan);
}
/**
* Check whether specific row need recover by checking {@link TRowLock}.
* Return true only if rowLock is NOT in {@link TRowLockState#STABLE} state and lock is expired.
* Return false if rowLock is in {@link TRowLockState#STABLE} state.
* Throw {@link ConflictException} if rowLock is not in stable state and not expired yet.
*
* @param rowLock
* @return true - when lock is established but expired. / false - when there
* is no lock ( {@link TRowLockState#STABLE} )
* @throws IOException {@link ConflictException} if lock is established and
* not expired.
*/
private boolean checkAndIsShouldRecover(TRowLock rowLock) throws IOException {
if (rowLock.getState() != TRowLockState.STABLE) {
if (rowLock.isSetExpiry() && rowLock.getExpiry() < System.currentTimeMillis()) {
return true;
}
throw new ConflictException("this row is unstable and not expired yet.");
}
return false;
}
/**
* Call {@link HaeinsaTransaction#recover()}.
* Abort or recover when there is failed transaction on the row,
* throw {@link ConflictException} when there is ongoing transaction.
*
* @param tx
* @param row
* @throws IOException ConflictException, HBase IOException
*/
private void recover(HaeinsaTransaction tx, byte[] row) throws IOException {
HaeinsaTransaction previousTx = tx.getManager().getTransaction(getTableName(), row);
if (previousTx != null) {
// row Transaction
previousTx.recover();
}
}
@Override
public void put(HaeinsaTransaction tx, HaeinsaPut put) throws IOException {
Preconditions.checkNotNull(tx);
Preconditions.checkNotNull(put);
byte[] row = put.getRow();
HaeinsaTableTransaction tableState = tx.createOrGetTableState(this.table.getTableName());
HaeinsaRowTransaction rowState = tableState.getRowStates().get(row);
if (rowState == null) {
// TODO(improvement) : Should consider to get lock when commit() called.
rowState = checkOrRecoverLock(tx, row, tableState, rowState);
}
rowState.addMutation(put);
}
/**
* Check rowState and whether it contains {@link TRowLock} already, create one if not.
* <p>
* Get {@link TRowLock} of the row from HBase if rowState does not contains it.
* If lock is not in stable state, try to recover it first by {@link HaeinsaTrasaction#recover()}.
* <p>
* By calling this method proper time, {@link RowTransaction} inside {@link HaeinsaTransaction} can have
* {@link TRowLock} of the row when this method was called first time in the context of the transaction.
*
* @param tx
* @param row
* @param tableState
* @param rowState
* @return
* @throws IOException ConflictionException, HBase IOException
*/
private HaeinsaRowTransaction checkOrRecoverLock(HaeinsaTransaction tx,
byte[] row, HaeinsaTableTransaction tableState,
@Nullable HaeinsaRowTransaction rowState) throws IOException {
if (rowState != null && rowState.getCurrent() != null) {
// return rowState itself if rowState already exist and contains TRowLock
return rowState;
}
while (true) {
TRowLock currentRowLock = getRowLock(row);
if (checkAndIsShouldRecover(currentRowLock)) {
recover(tx, row);
} else {
rowState = tableState.createOrGetRowState(row);
rowState.setCurrent(currentRowLock);
break;
}
}
return rowState;
}
@Override
public void put(HaeinsaTransaction tx, List<HaeinsaPut> puts) throws IOException {
Preconditions.checkNotNull(tx);
Preconditions.checkNotNull(puts);
for (HaeinsaPut put : puts) {
put(tx, put);
}
}
@Override
public void delete(HaeinsaTransaction tx, HaeinsaDelete delete) throws IOException {
Preconditions.checkNotNull(tx);
Preconditions.checkNotNull(delete);
byte[] row = delete.getRow();
// Can't delete entire row in Haeinsa because of lock column. Please specify column families when needed.
Preconditions.checkArgument(delete.getFamilyMap().size() > 0, "can't delete an entire row.");
HaeinsaTableTransaction tableState = tx.createOrGetTableState(this.table.getTableName());
HaeinsaRowTransaction rowState = tableState.getRowStates().get(row);
if (rowState == null) {
// TODO(improvement) : Should consider to get lock when commit() called.
rowState = checkOrRecoverLock(tx, row, tableState, rowState);
}
rowState.addMutation(delete);
}
@Override
public void delete(HaeinsaTransaction tx, List<HaeinsaDelete> deletes) throws IOException {
Preconditions.checkNotNull(tx);
Preconditions.checkNotNull(deletes);
for (HaeinsaDelete delete : deletes) {
delete(tx, delete);
}
}
@Override
public void close() throws IOException {
table.close();
}
@Override
public void commitSingleRowPutOnly(HaeinsaRowTransaction rowState, byte[] row) throws IOException {
HaeinsaTransaction tx = rowState.getTableTransaction().getTransaction();
Put put = new Put(row);
HaeinsaPut haeinsaPut = (HaeinsaPut) rowState.getMutations().remove(0);
for (HaeinsaKeyValue kv : Iterables.concat(haeinsaPut.getFamilyMap().values())) {
put.add(kv.getFamily(), kv.getQualifier(), tx.getCommitTimestamp(), kv.getValue());
}
TRowLock newRowLock = new TRowLock(ROW_LOCK_VERSION, TRowLockState.STABLE, tx.getCommitTimestamp());
put.add(LOCK_FAMILY, LOCK_QUALIFIER, tx.getCommitTimestamp(), TRowLocks.serialize(newRowLock));
byte[] currentRowLockBytes = TRowLocks.serialize(rowState.getCurrent());
if (!table.checkAndPut(row, LOCK_FAMILY, LOCK_QUALIFIER, currentRowLockBytes, put)) {
throw new ConflictException("can't acquire row's lock, commitSingleRowPutOnly failed");
} else {
rowState.setCurrent(newRowLock);
}
}
/**
* Read {@link TRowLock} from HBase and compare that lock with prevRowLock.
* If TRowLock is changed, it means transaction is failed, so throw
* {@link ConflictException}.
*
* @param prevRowLock
* @param row
* @throws IOException ConflictException, HBase IOException.
* @throws NullPointException if oldLock is null (haven't read lock from
* HBase)
*/
@Override
public void checkSingleRowLock(HaeinsaRowTransaction rowState, byte[] row) throws IOException {
TRowLock currentRowLock = getRowLock(row);
if (!rowState.getCurrent().equals(currentRowLock)) {
throw new ConflictException("this row is modified, checkSingleRow failed");
}
}
@Override
public void prewrite(HaeinsaRowTransaction rowState, byte[] row, boolean isPrimary) throws IOException {
Put put = new Put(row);
Set<TCellKey> prewritten = Sets.newTreeSet();
// order of remaining as TRemove, TPut, TRemove, TPut, ...
List<TMutation> remaining = Lists.newArrayList();
HaeinsaTransaction tx = rowState.getTableTransaction().getTransaction();
if (rowState.getMutations().size() > 0) {
if (rowState.getMutations().get(0) instanceof HaeinsaPut) {
HaeinsaPut haeinsaPut = (HaeinsaPut) rowState.getMutations().remove(0);
for (HaeinsaKeyValue kv : Iterables.concat(haeinsaPut.getFamilyMap().values())) {
put.add(kv.getFamily(), kv.getQualifier(), tx.getPrewriteTimestamp(), kv.getValue());
TCellKey cellKey = new TCellKey();
cellKey.setFamily(kv.getFamily());
cellKey.setQualifier(kv.getQualifier());
prewritten.add(cellKey);
}
}
for (HaeinsaMutation mutation : rowState.getMutations()) {
remaining.add(mutation.toTMutation());
}
}
TRowLock newRowLock = new TRowLock(ROW_LOCK_VERSION, TRowLockState.PREWRITTEN,
tx.getCommitTimestamp()).setCurrentTimestmap(tx.getPrewriteTimestamp());
if (isPrimary) {
// for primary row
for (Entry<TRowKey, HaeinsaRowTransaction> rowStateEntry : tx.getMutationRowStates().entrySet()) {
TRowKey rowKey = rowStateEntry.getKey();
if (Bytes.equals(rowKey.getTableName(), getTableName()) && Bytes.equals(rowKey.getRow(), row)) {
// if this is primaryRow
continue;
}
newRowLock.addToSecondaries(new TRowKey().setTableName(rowKey.getTableName()).setRow(rowKey.getRow()));
}
} else {
// for secondary rows
newRowLock.setPrimary(tx.getPrimary());
}
newRowLock.setPrewritten(Lists.newArrayList(prewritten));
newRowLock.setMutations(remaining);
newRowLock.setExpiry(System.currentTimeMillis() + ROW_LOCK_TIMEOUT);
put.add(LOCK_FAMILY, LOCK_QUALIFIER, tx.getPrewriteTimestamp(), TRowLocks.serialize(newRowLock));
byte[] currentRowLockBytes = TRowLocks.serialize(rowState.getCurrent());
if (!table.checkAndPut(row, LOCK_FAMILY, LOCK_QUALIFIER, currentRowLockBytes, put)) {
// Consider as conflict because another transaction might acquire lock of this row.
tx.abort();
throw new ConflictException("can't acquire row's lock");
} else {
rowState.setCurrent(newRowLock);
}
}
@Override
public void applyMutations(HaeinsaRowTransaction rowTxState, byte[] row) throws IOException {
if (rowTxState.getCurrent().getMutationsSize() == 0) {
// If this row does not have any left mutations to apply.
return;
}
List<TMutation> remaining = Lists.newArrayList(rowTxState.getCurrent().getMutations());
long currentTimestamp = rowTxState.getCurrent().getCurrentTimestmap();
for (int i = 0; i < remaining.size(); i++) {
byte[] currentRowLockBytes = TRowLocks.serialize(rowTxState.getCurrent());
int mutationOffset = i + 1;
long mutationTimestamp = currentTimestamp + mutationOffset;
TMutation mutation = remaining.get(i);
switch (mutation.getType()) {
case PUT: {
TRowLock newRowLock = rowTxState.getCurrent().deepCopy();
newRowLock.setCurrentTimestmap(mutationTimestamp);
newRowLock.setMutations(remaining.subList(mutationOffset, remaining.size()));
// Maintain prewritten state and extend lock by ROW_LOCK_TIMEOUT
newRowLock.setExpiry(System.currentTimeMillis() + ROW_LOCK_TIMEOUT);
Put put = new Put(row);
put.add(LOCK_FAMILY, LOCK_QUALIFIER, newRowLock.getCurrentTimestmap(), TRowLocks.serialize(newRowLock));
for (TKeyValue kv : mutation.getPut().getValues()) {
put.add(kv.getKey().getFamily(), kv.getKey().getQualifier(), newRowLock.getCurrentTimestmap(), kv.getValue());
}
if (!table.checkAndPut(row, LOCK_FAMILY, LOCK_QUALIFIER, currentRowLockBytes, put)) {
// Consider as conflict because another transaction might acquire lock of this row.
throw new ConflictException("can't acquire row's lock");
} else {
rowTxState.setCurrent(newRowLock);
}
break;
}
case REMOVE: {
Delete delete = new Delete(row);
if (mutation.getRemove().getRemoveFamiliesSize() > 0) {
for (ByteBuffer removeFamily : mutation.getRemove().getRemoveFamilies()) {
delete.deleteFamily(removeFamily.array(), mutationTimestamp);
}
}
if (mutation.getRemove().getRemoveCellsSize() > 0) {
for (TCellKey removeCell : mutation.getRemove().getRemoveCells()) {
delete.deleteColumns(removeCell.getFamily(), removeCell.getQualifier(), mutationTimestamp);
}
}
if (!table.checkAndDelete(row, LOCK_FAMILY, LOCK_QUALIFIER, currentRowLockBytes, delete)) {
// Consider as conflict because another transaction might acquire lock of this row.
throw new ConflictException("can't acquire row's lock");
}
break;
}
default:
break;
}
}
}
@Override
public void makeStable(HaeinsaRowTransaction rowTxState, byte[] row) throws IOException {
byte[] currentRowLockBytes = TRowLocks.serialize(rowTxState.getCurrent());
HaeinsaTransaction transaction = rowTxState.getTableTransaction().getTransaction();
long commitTimestamp = transaction.getCommitTimestamp();
TRowLock newRowLock = new TRowLock(ROW_LOCK_VERSION, TRowLockState.STABLE, commitTimestamp);
byte[] newRowLockBytes = TRowLocks.serialize(newRowLock);
Put put = new Put(row);
put.add(LOCK_FAMILY, LOCK_QUALIFIER, commitTimestamp, newRowLockBytes);
if (!table.checkAndPut(row, LOCK_FAMILY, LOCK_QUALIFIER, currentRowLockBytes, put)) {
// Consider as success because another transaction might already stabilize this row.
} else {
rowTxState.setCurrent(newRowLock);
}
}
@Override
public void commitPrimary(HaeinsaRowTransaction rowTxState, byte[] row) throws IOException {
byte[] currentRowLockBytes = TRowLocks.serialize(rowTxState.getCurrent());
HaeinsaTransaction transaction = rowTxState.getTableTransaction().getTransaction();
long commitTimestamp = transaction.getCommitTimestamp();
TRowLock newRowLock = rowTxState.getCurrent().deepCopy();
newRowLock.setCommitTimestamp(commitTimestamp);
newRowLock.setState(TRowLockState.COMMITTED);
// make prewritten to null
newRowLock.setPrewrittenIsSet(false);
// extend expiry by ROW_LOCK_TIMEOUT
newRowLock.setExpiry(System.currentTimeMillis() + ROW_LOCK_TIMEOUT);
byte[] newRowLockBytes = TRowLocks.serialize(newRowLock);
Put put = new Put(row);
put.add(LOCK_FAMILY, LOCK_QUALIFIER, newRowLock.getCurrentTimestmap(), newRowLockBytes);
if (!table.checkAndPut(row, LOCK_FAMILY, LOCK_QUALIFIER, currentRowLockBytes, put)) {
transaction.abort();
// Consider as conflict because another transaction might acquire lock of primary row.
throw new ConflictException("can't acquire primary row's lock");
} else {
rowTxState.setCurrent(newRowLock);
}
}
@Override
public TRowLock getRowLock(byte[] row) throws IOException {
Get get = new Get(row);
get.addColumn(LOCK_FAMILY, LOCK_QUALIFIER);
Result result = table.get(get);
if (result.isEmpty()) {
return TRowLocks.deserialize(null);
} else {
byte[] rowLockBytes = result.getValue(LOCK_FAMILY, LOCK_QUALIFIER);
return TRowLocks.deserialize(rowLockBytes);
}
}
@Override
public void abortPrimary(HaeinsaRowTransaction rowTxState, byte[] row) throws IOException {
byte[] currentRowLockBytes = TRowLocks.serialize(rowTxState.getCurrent());
HaeinsaTransaction transaction = rowTxState.getTableTransaction().getTransaction();
long commitTimestamp = transaction.getCommitTimestamp();
TRowLock newRowLock = rowTxState.getCurrent().deepCopy();
newRowLock.setCommitTimestamp(commitTimestamp);
newRowLock.setState(TRowLockState.ABORTED);
newRowLock.setMutationsIsSet(false);
newRowLock.setExpiry(System.currentTimeMillis() + ROW_LOCK_TIMEOUT);
byte[] newRowLockBytes = TRowLocks.serialize(newRowLock);
Put put = new Put(row);
put.add(LOCK_FAMILY, LOCK_QUALIFIER, commitTimestamp, newRowLockBytes);
if (!table.checkAndPut(row, LOCK_FAMILY, LOCK_QUALIFIER, currentRowLockBytes, put)) {
// Consider as conflict because another transaction might acquire lock of primary row.
throw new ConflictException("can't acquire primary row's lock");
} else {
rowTxState.setCurrent(newRowLock);
}
}
@Override
public void deletePrewritten(HaeinsaRowTransaction rowTxState, byte[] row) throws IOException {
if (rowTxState.getCurrent().getPrewrittenSize() == 0) {
// nothing to do
return;
}
byte[] currentRowLockBytes = TRowLocks.serialize(rowTxState.getCurrent());
long prewriteTimestamp = rowTxState.getCurrent().getCurrentTimestmap();
Delete delete = new Delete(row);
for (TCellKey cellKey : rowTxState.getCurrent().getPrewritten()) {
delete.deleteColumn(cellKey.getFamily(), cellKey.getQualifier(), prewriteTimestamp);
}
if (!table.checkAndDelete(row, LOCK_FAMILY, LOCK_QUALIFIER, currentRowLockBytes, delete)) {
// Consider as conflict because another transaction might acquire lock of this row.
throw new ConflictException("can't acquire primary row's lock");
}
}
protected HTableInterface getHTable() {
return table;
}
/**
* Implementation of {@link HaeinsaReulstScanner} which is used when scan without transaction.
*/
private class SimpleClientScanner implements HaeinsaResultScanner {
private final ResultScanner scanner;
public SimpleClientScanner(ResultScanner scanner) {
this.scanner = scanner;
}
@Override
public Iterator<HaeinsaResult> iterator() {
return Iterators.transform(scanner.iterator(), new Function<Result, HaeinsaResult>() {
@Override
public HaeinsaResult apply(@Nullable Result result) {
return new HaeinsaResult(result);
}
});
}
@Override
public HaeinsaResult[] next(int nbRows) throws IOException {
Result[] resultArray = scanner.next(nbRows);
HaeinsaResult[] transformed = new HaeinsaResult[resultArray.length];
for (int i = 0; i < resultArray.length; i++) {
transformed[i] = new HaeinsaResult(resultArray[i]);
}
return transformed;
}
@Override
public HaeinsaResult next() throws IOException {
Result result = scanner.next();
if (result != null) {
return new HaeinsaResult(result);
} else {
return null;
}
}
@Override
public void close() {
scanner.close();
}
}
/**
* Contains scanners for single {@link HaeinsaTable} to help project puts/deletes to gets/scans in same transaction.
* <p>
* This projection of mutations is crucial to proper execution of transaction.
* For instance, consider single transaction such as T = {W1(X), R2(X), R3(Y), W4(X)}.
* Haeinsa does not write mutations on HBase until commit() is called.
* Therefore if R(X) get data only from HBase, R2(X) on transaction T cannot read data written by W1(X)
* and this is not expected behavior to programmers.
* Haeinsa resolves this problem by projecting buffered mutations in client to get/scan operations executed in same transaction.
*/
private class ClientScanner implements HaeinsaResultScanner {
private final HaeinsaTransaction tx;
private final HaeinsaTableTransaction tableState;
private boolean initialized;
private final NavigableSet<HaeinsaKeyValueScanner> scanners =
Sets.newTreeSet(HaeinsaKeyValueScanner.COMPARATOR);
private final List<HaeinsaKeyValueScanner> scannerList = Lists.newArrayList();
// tracking delete of one specific row.
private final HaeinsaDeleteTracker deleteTracker = new HaeinsaDeleteTracker();
private final HaeinsaColumnTracker columnTracker;
/**
* true if TRowLock inside scanners, false if TRowLock is already
* included inside tableState.getRowStates().get(row)
*/
private final boolean lockInclusive;
/**
* -1 if not used. ( Get / Scan )
*/
private final int batch;
private final Map<byte[], NavigableSet<byte[]>> familyMap;
private HaeinsaKeyValue prevKV;
private long maxSeqID = Long.MAX_VALUE;
/**
*
* @param tx
* @param scanners
* @param familyMap
* @param lockInclusive - whether scanners contains {@link TRowLock} inside.
* If not, should bring from {@link RowTransaction} or get from HBase directly.
*/
public ClientScanner(HaeinsaTransaction tx, Iterable<HaeinsaKeyValueScanner> scanners,
Map<byte[], NavigableSet<byte[]>> familyMap, boolean lockInclusive) {
this(tx, scanners, familyMap, null, lockInclusive);
}
/**
*
* @param tx
* @param scanners
* @param familyMap
* @param intraScan - To support to use {@link ColumnRangeFilter}
* @param lockInclusive - whether scanners contains {@link TRowLock} inside.
* If not, should bring from {@link RowTransaction} or get from HBase directly.
*/
public ClientScanner(HaeinsaTransaction tx, Iterable<HaeinsaKeyValueScanner> scanners,
Map<byte[], NavigableSet<byte[]>> familyMap, HaeinsaIntraScan intraScan, boolean lockInclusive) {
this.tx = tx;
this.tableState = tx.createOrGetTableState(getTableName());
for (HaeinsaKeyValueScanner kvScanner : scanners) {
scannerList.add(kvScanner);
}
if (intraScan == null) {
intraScan = new HaeinsaIntraScan(null, null, false, null, false);
intraScan.setBatch(-1);
}
this.columnTracker = new HaeinsaColumnTracker(familyMap,
intraScan.getMinColumn(), intraScan.isMinColumnInclusive(),
intraScan.getMaxColumn(), intraScan.isMaxColumnInclusive());
this.batch = intraScan.getBatch();
this.lockInclusive = lockInclusive;
this.familyMap = familyMap;
}
/**
* Method to generate {@link #scanners} from {@link #scannerList}.
* Only can be called one time for every ClientScanner.
* <p>
* The reason why there are different variables for {@link #scannerList} and {@link #scanners} is that
* the way {@link #nextScanner()} implemented is removing {@link HaeinsaKeyValueScanner} one by one form scanners.
* {@link #close()} method needs to close every {@link ClientScanner} when called,
* so some other variable should preserve every scanner when ClientScanner created.
*
* @throws IOException
*/
private void initialize() throws IOException {
try {
for (HaeinsaKeyValueScanner scanner : scannerList) {
HaeinsaKeyValue peeked = scanner.peek();
if (peeked != null) {
scanners.add(scanner);
}
}
initialized = true;
} catch (Exception e) {
throw new IOException(e.getMessage(), e);
}
}
/**
* Return iterator of {@link ClientScanner}. Use {@link #next()} inside.
*/
@Override
public Iterator<HaeinsaResult> iterator() {
return new Iterator<HaeinsaResult>() {
// if current is null, whether scan is not started or next() was
// called.
// if hasNext() is called, next data will be ready on current.
private HaeinsaResult current;
@Override
public void remove() {
throw new UnsupportedOperationException();
}
@Override
public HaeinsaResult next() {
if (current == null) {
hasNext();
}
HaeinsaResult result = current;
current = null;
return result;
}
@Override
public boolean hasNext() {
if (current != null) {
return true;
}
try {
current = ClientScanner.this.next();
if (current != null) {
return true;
}
} catch (IOException e) {
// because hasNext() cannot throw IOException, wrap it with RuntimeException.
throw new IllegalStateException(e.getMessage(), e);
}
return false;
}
};
}
/**
* Return {@link TRowLock} for specific row from {@link IOException#scanners}.
* Return null if there is no proper {@link TRowLock}.
* <p>
* If one of these {@link #scanners} has row key which is smaller than given row,
* that {@link HaeinsaKeyValueScanner} is not peeked by this method and return null.
* So proper operation is guaranteed only when every scanner in {@link #scanners} return
* smaller or equal row key when {@link HaeinsaKeyValueScanner#peek()} is called.
*
* @param row
* @return null if there is no TRowLock information inside scanners,
* return rowLock otherwise.
* @throws IOException
*/
private TRowLock peekLock(byte[] row) throws IOException {
for (HaeinsaKeyValueScanner scanner : scanners) {
HaeinsaKeyValue kv = scanner.peek();
if (!Bytes.equals(kv.getRow(), row)) {
break;
}
TRowLock rowLock = scanner.peekLock();
if (rowLock != null) {
return rowLock;
}
}
return null;
}
@Override
public HaeinsaResult next() throws IOException {
if (!initialized) {
// move scannerList -> scanners
initialize();
}
final List<HaeinsaKeyValue> sortedKVs = Lists.newArrayList();
while (true) {
if (scanners.isEmpty()) {
break;
}
HaeinsaKeyValueScanner currentScanner = scanners.first();
HaeinsaKeyValue currentKV = currentScanner.peek();
if (prevKV == null) {
// start new row, deal with TRowLock and Recover()
if (lockInclusive) {
// HaeinsaKeyValues from HBaseScanScanner or HBaseGetScanner contains TRowLock for this row.
TRowLock currentRowLock = peekLock(currentKV.getRow());
HaeinsaRowTransaction rowState = tableState.createOrGetRowState(currentKV.getRow());
if (rowState.getCurrent() == null) {
// So proper TRowLock value should be set.
if (currentRowLock == null) {
/*
* HBase do not have TRowLock for this row.
* This is the case when Haeinsa accesses to this row first time.
* (This can be because of lazy-migration from HBase-only code).
*
* HaeinsaRowTransaction can use TRowLock(ROW_LOCK_VERSION,
* TRowLockState.STABLE, Long.MIN_VALUE) as initial TRowLock value.
* This initial TRowLock will be override by proper value and applied to HBase
* when commit() method is called.
*/
currentRowLock = TRowLocks.deserialize(null);
rowState.setCurrent(currentRowLock);
}
if (checkAndIsShouldRecover(currentRowLock)) {
// when currentRowLock is not stable but
// expired.
rowState = checkOrRecoverLock(tx, currentKV.getRow(), tableState, rowState);
Get get = new Get(currentKV.getRow());
for (Entry<byte[], NavigableSet<byte[]>> entry : familyMap.entrySet()) {
if (entry.getValue() != null) {
for (byte[] qualifier : entry.getValue()) {
get.addColumn(entry.getKey(), qualifier);
}
} else {
get.addFamily(entry.getKey());
}
}
Result result = table.get(get);
maxSeqID
HBaseGetScanner getScanner = new HBaseGetScanner(result, maxSeqID);
scanners.add(getScanner);
continue;
} else {
// when currentRowLock is stable
rowState.setCurrent(currentRowLock);
}
} else {
// rowState is already exist, use current variable in rowState instead of TRowLock from scan or get
}
// At this point, TRowLock of currentKV.getRow() is saved in rowState.
}
prevKV = currentKV;
}
if (Bytes.equals(prevKV.getRow(), currentKV.getRow())) {
if (currentScanner.getSequenceID() > maxSeqID) {
// too old data, ignore
} else if (Bytes.equals(currentKV.getFamily(), LOCK_FAMILY)
&& Bytes.equals(currentKV.getQualifier(), LOCK_QUALIFIER)) {
// if currentKV is Lock, ignore
} else if (currentKV.getType() == Type.DeleteColumn || currentKV.getType() == Type.DeleteFamily) {
// if currentKV is delete
deleteTracker.add(currentKV, currentScanner.getSequenceID());
} else if (prevKV == currentKV
|| !(Bytes.equals(prevKV.getRow(), currentKV.getRow())
&& Bytes.equals(prevKV.getFamily(), currentKV.getFamily())
&& Bytes.equals(prevKV.getQualifier(), currentKV.getQualifier()))) {
// if reference of prevKV and currentKV is same, the currentKV have new row.
// Ignore when prevKV and currentKV is different but row, family, qualifier of currentKv and prevKv is all same. ( not likely )
if (!deleteTracker.isDeleted(currentKV, currentScanner.getSequenceID())
&& columnTracker.isMatched(currentKV)) {
// if currentKV is not deleted and inside scan range
sortedKVs.add(currentKV);
prevKV = currentKV;
}
}
nextScanner(currentScanner);
} else {
// currentKV is different row with prevKV, so reset
// deleteTracker & maxSeqID
deleteTracker.reset();
prevKV = null;
maxSeqID = Long.MAX_VALUE;
if (sortedKVs.size() > 0) {
// If currentKV moved to next row and there are more than one KV satisfy scan requirement,
// should return HaeinsaResult which aggregate HaeinsaKeyValue for previous row.
break;
}
}
if (batch > 0 && sortedKVs.size() >= batch) {
// if intraScan & sortedKVs have more elements than batch.
break;
}
}
if (sortedKVs.size() > 0) {
return new HaeinsaResult(sortedKVs);
} else {
// scanners are exhausted.
return null;
}
}
/**
* Moving index of scanner of currentScanner by one. If there is no more
* element at the scanner, remove currentScanner from scanners
* (NavigableSet)
*
* @param currentScanner
* @throws IOException
*/
private void nextScanner(HaeinsaKeyValueScanner currentScanner) throws IOException {
scanners.remove(currentScanner);
currentScanner.next();
HaeinsaKeyValue currentScannerNext = currentScanner.peek();
if (currentScannerNext != null) {
// if currentScanner is not exhausted.
scanners.add(currentScanner);
}
}
@Override
public HaeinsaResult[] next(int nbRows) throws IOException {
List<HaeinsaResult> result = Lists.newArrayList();
for (int i = 0; i < nbRows; i++) {
HaeinsaResult current = this.next();
if (current != null) {
result.add(current);
} else {
break;
}
}
HaeinsaResult[] array = new HaeinsaResult[result.size()];
return result.toArray(array);
}
@Override
public void close() {
for (HaeinsaKeyValueScanner scanner : scannerList) {
scanner.close();
}
}
}
/**
* Implementation of {@link HaeinsaKeyValueScanner} which provides scanner interface which wrap
* {@link KeyValue}s from {@link ResultScanner} by HBase {@link Scan} to {@link HaeinsaKeyValue}s.
* This class is used if there are {@link HaeinsaScan} or {@link HaeinsaIntraScan} inside transaction.
* <p>
* HBaseScanScanner can contain kev-values for single row like {@link ResultScanner},
* or key-values of multiple rows.
* <p>
* HBaseScanScanner does not need sequenceID control because it will use {@link HBaseGetScanner}
* if rows from scan do not have stable state, and put result from get to lower sequenceID.
* Therefore, {@link #getSequenceID()} always return Long.MAX_VALUE
*/
private static class HBaseScanScanner implements HaeinsaKeyValueScanner {
private final ResultScanner resultScanner;
/**
* current is null when scan is not started or next() is called last
* time.
*/
private HaeinsaKeyValue current;
/**
* currentResult is null when there is no more elements to scan in resultScanner or scan is not started.
* currentResult only contains result of single row.
*/
private Result currentResult;
/**
* current = currentResult[resultIndex - 1]
*/
private int resultIndex;
public HBaseScanScanner(ResultScanner resultScanner) {
this.resultScanner = resultScanner;
}
@Override
public HaeinsaKeyValue peek() {
try {
if (current != null) {
return current;
}
if (currentResult == null || (currentResult != null && resultIndex >= currentResult.size())) {
currentResult = resultScanner.next();
if (currentResult != null && currentResult.isEmpty()) {
currentResult = null;
}
resultIndex = 0;
}
if (currentResult == null) {
// if currentResult is still null at this point, that means
// there is no more KV to scan.
return null;
}
// First scan or next() was called last time so move
// resultIndex.
current = new HaeinsaKeyValue(currentResult.raw()[resultIndex]);
resultIndex++;
return current;
} catch (IOException e) {
// because peek() cannot throw IOException, wrap it with RuntimeException.
throw new IllegalStateException(e.getMessage(), e);
}
}
@Override
public HaeinsaKeyValue next() throws IOException {
HaeinsaKeyValue result = peek();
current = null;
return result;
}
@Override
public TRowLock peekLock() throws IOException {
peek();
if (currentResult != null) {
byte[] lock = currentResult.getValue(LOCK_FAMILY, LOCK_QUALIFIER);
if (lock != null) {
return TRowLocks.deserialize(lock);
}
}
return null;
}
@Override
public long getSequenceID() {
/*
* Scan always read data from HBase, so sequenceId should be biggest every time.
*/
return Long.MAX_VALUE;
}
@Override
public void close() {
resultScanner.close();
}
}
/**
* Implementation of {@link HaeinsaKeyValueScanner} which provide scanner interface which wrap
* {@link KeyValue}s from {@link ResultScanner} by HBase {@link Scan} to {@link HaeinsaKeyValue}s.
* This class is used there is {@link HaeinsaScan} or {@link HaeinsaIntraScan} inside transaction.
* <p>
* HBaseScanScanner can contain kev-values for single row like {@link ResultScanner},
* or key-values of multiple rows.
* <p>
* HBaseScanScanner does not need sequenceID control because it will use {@link HBaseGetScanner}
* if rows from scan do not have stable state, and put result from get to lower sequenceID.
* Therefore, {@link #getSequenceID()} always return Long.MAX_VALUE
*/
/**
* Implementation of {@link HaeinsaKeyValueScanner} which provides scanner interface which wrap
* {@link KeyValue}s from {@link Result} by HBase {@link Get} to {@link HaeinsaKeyValue}s.
* This class is used if there is {@link HaeinsaGet} inside transaction.
* <p>
* HBaseGetScanner can contain key-values for only single row link {@link Result}.
* So {@link #peek()} method or {@link #next()} method will return value from same row.
* <p>
* HBaseGetScanner is now used in two cases.
* First, inside {@link HaeinsaTable#get()}, {@link HaeinsaKeyValue}s returned by this class will
* always have sequenceId of Long.MAX_VALUE.
* Second is used inside {@link ClientScanner}. In this case, HBaseGetScanner recover failed transaction and
* get recovered data from HBase.
* Recovered {@link HaeinsaKeyValue} should have smaller sequenceId contained in ClientScanner so far
* because it is more recent value.
*/
private static class HBaseGetScanner implements HaeinsaKeyValueScanner {
private final long sequenceID;
private Result result;
private int resultIndex;
private HaeinsaKeyValue current;
public HBaseGetScanner(Result result, final long sequenceID) {
if (result != null && !result.isEmpty()) {
this.result = result;
} else {
// null if result is empty
this.result = null;
}
// bigger sequenceID is older one.
this.sequenceID = sequenceID;
}
@Override
public HaeinsaKeyValue peek() {
if (current != null) {
return current;
}
if (result != null && resultIndex >= result.size()) {
result = null;
}
if (result == null) {
return null;
}
current = new HaeinsaKeyValue(result.list().get(resultIndex));
resultIndex++;
return current;
}
@Override
public HaeinsaKeyValue next() throws IOException {
HaeinsaKeyValue result = peek();
current = null;
return result;
}
@Override
public TRowLock peekLock() throws IOException {
peek();
if (result != null) {
byte[] lock = result.getValue(LOCK_FAMILY, LOCK_QUALIFIER);
if (lock != null) {
return TRowLocks.deserialize(lock);
}
}
return null;
}
@Override
public long getSequenceID() {
return sequenceID;
}
@Override
public void close() {
}
}
}
|
package mho.haskellesque.math;
import mho.haskellesque.iterables.IterableUtils;
import mho.haskellesque.structures.Pair;
import java.math.BigInteger;
import java.util.Iterator;
import java.util.List;
import static mho.haskellesque.iterables.IterableUtils.*;
public class BasicMath {
public static int gcd(int x, int y) {
return positiveGcd(x < 0 ? -x : x, y < 0 ? -y : y);
}
private static int positiveGcd(int x, int y) {
return y == 0 ? x : positiveGcd(y, x % y);
}
public static BigInteger mod(BigInteger x, BigInteger y) {
if (x.signum() < 0) {
return y.subtract(x.negate()).mod(y);
} else {
return x.mod(y);
}
}
public static Iterable<Boolean> bits(final int n) {
return () -> new Iterator<Boolean>() {
private int remaining = n;
@Override
public boolean hasNext() {
return remaining != 0;
}
@Override
public Boolean next() {
boolean bit = (remaining & 1) == 1;
remaining >>= 1;
return bit;
}
};
}
public static Iterable<Boolean> bits(final BigInteger n) {
return () -> new Iterator<Boolean>() {
private BigInteger remaining = n;
@Override
public boolean hasNext() {
return !remaining.equals(BigInteger.ZERO);
}
@Override
public Boolean next() {
boolean bit = remaining.testBit(0);
remaining = remaining.shiftRight(1);
return bit;
}
};
}
public static Iterable<Boolean> bitsPadded(int length, int n) {
return pad(false, length, bits(n));
}
public static Iterable<Boolean> bitsPadded(BigInteger length, BigInteger n) {
return pad(false, length, bits(n));
}
public static Iterable<Boolean> bigEndianBits(final int n) {
return reverse(bits(n));
}
public static Iterable<Boolean> bigEndianBits(final BigInteger n) {
return reverse(bits(n));
}
public static Iterable<Boolean> bigEndianBitsPadded(int length, int n) {
return reverse(bitsPadded(length, n));
}
public static Iterable<Boolean> bigEndianBitsPadded(BigInteger length, BigInteger n) {
return reverse(bitsPadded(length, n));
}
public static BigInteger fromBigEndianBits(Iterable<Boolean> bits) {
BigInteger n = BigInteger.ZERO;
for (boolean bit : bits) {
n = n.shiftLeft(1);
if (bit) n = n.add(BigInteger.ONE);
}
return n;
}
public static BigInteger fromBits(Iterable<Boolean> bits) {
return fromBigEndianBits(reverse(bits));
}
public static Iterable<Integer> digits(int base, final int n) {
return () -> new Iterator<Integer>() {
private int remaining = n;
@Override
public boolean hasNext() {
return remaining != 0;
}
@Override
public Integer next() {
int digit = remaining % base;
remaining /= base;
return digit;
}
};
}
public static Iterable<BigInteger> digits(BigInteger base, final BigInteger n) {
return () -> new Iterator<BigInteger>() {
private BigInteger remaining = n;
@Override
public boolean hasNext() {
return !remaining.equals(BigInteger.ZERO);
}
@Override
public BigInteger next() {
BigInteger digit = remaining.mod(base);
remaining = remaining.divide(base);
return digit;
}
};
}
public static Iterable<Integer> digitsPadded(int length, int base, int n) {
return pad(0, length, digits(base, n));
}
public static Iterable<BigInteger> digitsPadded(BigInteger length, BigInteger base, BigInteger n) {
return pad(BigInteger.ZERO, length, digits(base, n));
}
public static List<Integer> bigEndianDigits(int base, final int n) {
return reverse(digits(base, n));
}
public static List<BigInteger> bigEndianDigits(BigInteger base, final BigInteger n) {
return reverse(digits(base, n));
}
public static Iterable<Integer> bigEndianDigitsPadded(int length, int base, int n) {
return reverse(digitsPadded(length, base, n));
}
public static Iterable<BigInteger> bigEndianDigitsPadded(BigInteger length, BigInteger base, BigInteger n) {
return reverse(digitsPadded(length, base, n));
}
public static BigInteger fromBigEndianDigits(int base, Iterable<Integer> digits) {
BigInteger n = BigInteger.ZERO;
for (int digit : digits) {
n = n.multiply(BigInteger.valueOf(base)).add(BigInteger.valueOf(digit));
}
return n;
}
public static BigInteger fromBigEndianDigits(BigInteger base, Iterable<BigInteger> digits) {
BigInteger n = BigInteger.ZERO;
for (BigInteger digit : digits) {
n = n.multiply(base).add(digit);
}
return n;
}
public static BigInteger fromDigits(int base, Iterable<Integer> digits) {
return fromBigEndianDigits(base, reverse(digits));
}
public static BigInteger fromDigits(BigInteger base, Iterable<BigInteger> digits) {
return fromBigEndianDigits(base, (Iterable<BigInteger>) reverse(digits));
}
public static Pair<BigInteger, BigInteger> logarithmicDemux(BigInteger n) {
n = n.add(BigInteger.ONE);
int exp = n.getLowestSetBit();
return new Pair<>(n.shiftRight(exp + 1), BigInteger.valueOf(exp));
}
public static List<BigInteger> demux(int lines, BigInteger n) {
if (n.equals(BigInteger.ZERO)) {
return toList(replicate(lines, BigInteger.ZERO));
}
return reverse(IterableUtils.map(BasicMath::fromBits, IterableUtils.demux(lines, bits(n))));
}
}
|
package net.glowstone.entity;
import com.flowpowered.networking.Message;
import com.google.common.base.Preconditions;
import net.glowstone.EventFactory;
import net.glowstone.GlowChunk;
import net.glowstone.GlowServer;
import net.glowstone.GlowWorld;
import net.glowstone.entity.meta.MetadataIndex;
import net.glowstone.entity.meta.MetadataMap;
import net.glowstone.entity.objects.GlowItemFrame;
import net.glowstone.entity.physics.BoundingBox;
import net.glowstone.entity.physics.EntityBoundingBox;
import net.glowstone.net.message.play.entity.*;
import net.glowstone.net.message.play.player.InteractEntityMessage;
import net.glowstone.util.Position;
import org.apache.commons.lang3.Validate;
import org.bukkit.*;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityPortalEnterEvent;
import org.bukkit.event.entity.EntityPortalEvent;
import org.bukkit.event.entity.EntityPortalExitEvent;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
import org.bukkit.metadata.MetadataStore;
import org.bukkit.metadata.MetadataStoreBase;
import org.bukkit.metadata.MetadataValue;
import org.bukkit.permissions.Permission;
import org.bukkit.permissions.PermissionAttachment;
import org.bukkit.permissions.PermissionAttachmentInfo;
import org.bukkit.plugin.Plugin;
import org.bukkit.util.Vector;
import org.spigotmc.event.entity.EntityDismountEvent;
import org.spigotmc.event.entity.EntityMountEvent;
import org.spigotmc.event.player.PlayerSpawnLocationEvent;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
/**
* Represents some entity in the world such as an item on the floor or a player.
*
* @author Graham Edgecombe
*/
public abstract class GlowEntity implements Entity {
/**
* The metadata store for entities.
*/
private static final MetadataStore<Entity> bukkitMetadata = new EntityMetadataStore();
/**
* The server this entity belongs to.
*/
protected final GlowServer server;
/**
* The entity's metadata.
*/
protected final MetadataMap metadata = new MetadataMap(getClass());
/**
* The current position.
*/
protected final Location location;
/**
* The position in the last cycle.
*/
protected final Location previousLocation;
/**
* The entity's velocity, applied each tick.
*/
protected final Vector velocity = new Vector();
/**
* The world this entity belongs to.
*/
protected GlowWorld world;
/**
* A flag indicating if this entity is currently active.
*/
protected boolean active = true;
/**
* This entity's current identifier for its world.
*/
protected int id;
/**
* Whether the entity should have its position resent as if teleported.
*/
protected boolean teleported = false;
/**
* Whether the entity should have its velocity resent.
*/
protected boolean velocityChanged = false;
/**
* A counter of how long this entity has existed
*/
protected int ticksLived = 0;
/**
* Vehicle
*/
protected GlowEntity vehicle;
protected boolean vehicleChanged;
/**
* This entity's unique id.
*/
private UUID uuid;
/**
* The entity's bounding box, or null if it has no physical presence.
*/
private EntityBoundingBox boundingBox;
/**
* An EntityDamageEvent representing the last damage cause on this entity.
*/
private EntityDamageEvent lastDamageCause;
/**
* A flag indicting if the entity is on the ground
*/
private boolean onGround = true;
/**
* The distance the entity is currently falling without touching the ground.
*/
private float fallDistance;
/**
* How long the entity has been on fire, or 0 if it is not.
*/
private int fireTicks = 0;
/**
* Passanger
*/
private GlowEntity passenger;
/**
* Creates an entity and adds it to the specified world.
*
* @param location The location of the entity.
*/
public GlowEntity(Location location) {
// this is so dirty I washed my hands after writing it.
if (this instanceof GlowPlayer) {
// spawn location event
location = EventFactory.callEvent(new PlayerSpawnLocationEvent((Player) this, location)).getSpawnLocation();
}
this.location = location.clone();
this.world = (GlowWorld) location.getWorld();
this.server = world.getServer();
server.getEntityIdManager().allocate(this);
world.getEntityManager().register(this);
previousLocation = location.clone();
}
@Override
public String toString() {
return getClass().getSimpleName();
}
@Override
public void sendMessage(String s) {
//To change body of implemented methods use File | Settings | File Templates.
}
// Command sender
@Override
public void sendMessage(String[] strings) {
//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public final GlowServer getServer() {
return server;
}
@Override
public String getName() {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public final GlowWorld getWorld() {
return world;
}
// Core properties
@Override
public final int getEntityId() {
return id;
}
@Override
public UUID getUniqueId() {
if (uuid == null) {
uuid = UUID.randomUUID();
}
return uuid;
}
public void setUniqueId(UUID uuid) {
Validate.notNull(uuid, "uuid must not be null");
if (this.uuid == null) {
this.uuid = uuid;
} else if (!this.uuid.equals(uuid)) {
// silently allow setting the same UUID, since
// it can't be checked with getUniqueId()
throw new IllegalStateException("UUID of " + this + " is already " + this.uuid);
}
}
@Override
public boolean isDead() {
return !active;
}
@Override
public boolean isValid() {
return world.getEntityManager().getEntity(id) == this;
}
// Location stuff
@Override
public Location getLocation() {
return location.clone();
}
@Override
public Location getLocation(Location loc) {
return Position.copyLocation(location, loc);
}
/**
* Get the direction (SOUTH, WEST, NORTH, or EAST) this entity is facing.
*
* @return The cardinal BlockFace of this entity.
*/
public BlockFace getDirection() {
double rot = getLocation().getYaw() % 360;
if (rot < 0) {
rot += 360.0;
}
if (0 <= rot && rot < 45) {
return BlockFace.SOUTH;
} else if (45 <= rot && rot < 135) {
return BlockFace.WEST;
} else if (135 <= rot && rot < 225) {
return BlockFace.NORTH;
} else if (225 <= rot && rot < 315) {
return BlockFace.EAST;
} else if (315 <= rot && rot < 360.0) {
return BlockFace.SOUTH;
} else {
return BlockFace.EAST;
}
}
/**
* Gets the full direction (including SOUTH_SOUTH_EAST etc) this entity is facing.
*
* @return The intercardinal BlockFace of this entity
*/
public BlockFace getFacing() {
long facing = Math.round(getLocation().getYaw() / 22.5) + 8;
return Position.getDirection((byte) (facing % 16));
}
@Override
public Vector getVelocity() {
return velocity.clone();
}
@Override
public void setVelocity(Vector velocity) {
this.velocity.copy(velocity);
velocityChanged = true;
}
@Override
public boolean teleport(Location location) {
Validate.notNull(location, "location cannot be null");
Validate.notNull(location.getWorld(), "location's world cannot be null");
if (location.getWorld() != world) {
world.getEntityManager().unregister(this);
world = (GlowWorld) location.getWorld();
world.getEntityManager().register(this);
}
setRawLocation(location, false);
teleported = true;
return true;
}
@Override
public boolean teleport(Entity destination) {
return teleport(destination.getLocation());
}
@Override
public boolean teleport(Location location, TeleportCause cause) {
return teleport(location);
}
@Override
public boolean teleport(Entity destination, TeleportCause cause) {
return teleport(destination.getLocation(), cause);
}
public boolean isTeleported() {
return teleported;
}
// Internals
/**
* Checks if this entity is within the visible radius of another.
*
* @param other The other entity.
* @return {@code true} if the entities can see each other, {@code false} if
* not.
*/
public boolean isWithinDistance(GlowEntity other) {
if (other instanceof GlowLivingEntity) {
return ((GlowLivingEntity) other).getDeathTicks() <= 20 && isWithinDistance(other.location);
} else return !other.isDead() && (isWithinDistance(other.location) || other instanceof GlowLightningStrike);
}
/**
* Checks if this entity is within the visible radius of a location.
*
* @param loc The location.
* @return {@code true} if the entities can see each other, {@code false} if
* not.
*/
public boolean isWithinDistance(Location loc) {
double dx = Math.abs(location.getX() - loc.getX());
double dz = Math.abs(location.getZ() - loc.getZ());
return loc.getWorld() == getWorld() && dx <= (server.getViewDistance() * GlowChunk.WIDTH) && dz <= (server.getViewDistance() * GlowChunk.HEIGHT);
}
/**
* Checks whether this entity should be saved as part of the world.
*
* @return True if the entity should be saved.
*/
public boolean shouldSave() {
return true;
}
/**
* Called every game cycle. Subclasses should implement this to implement
* periodic functionality e.g. mob AI.
*/
public void pulse() {
ticksLived++;
if (fireTicks > 0) {
--fireTicks;
}
metadata.setBit(MetadataIndex.STATUS, MetadataIndex.StatusFlags.ON_FIRE, fireTicks > 0);
// resend position if it's been a while, causes ItemFrames to disappear.
if (ticksLived % (30 * 20) == 0) {
if (!(this instanceof GlowItemFrame)) {
teleported = true;
}
}
pulsePhysics();
if (hasMoved()) {
Block currentBlock = location.getBlock();
if (currentBlock.getType() == Material.ENDER_PORTAL) {
EventFactory.callEvent(new EntityPortalEnterEvent(this, currentBlock.getLocation()));
if (server.getAllowEnd()) {
Location previousLocation = location.clone();
boolean success;
if (getWorld().getEnvironment() == World.Environment.THE_END) {
success = teleportToSpawn();
} else {
success = teleportToEnd();
}
if (success) {
EntityPortalExitEvent e = EventFactory.callEvent(new EntityPortalExitEvent(this, previousLocation, location.clone(), velocity.clone(), new Vector()));
if (!e.getAfter().equals(velocity)) {
setVelocity(e.getAfter());
}
}
}
}
}
}
/**
* Resets the previous location and other properties to their current value.
*/
public void reset() {
Position.copyLocation(location, previousLocation);
metadata.resetChanges();
teleported = false;
velocityChanged = false;
vehicleChanged = false;
}
/**
* Sets this entity's location.
*
* @param location The new location.
* @param fall Whether to calculate fall damage or not.
*/
public void setRawLocation(Location location, boolean fall) {
if (location.getWorld() != world) {
throw new IllegalArgumentException("Cannot setRawLocation to a different world (got " + location.getWorld() + ", expected " + world + ")");
}
if (location.equals(previousLocation)) {
return;
}
if (teleported) {
teleported = false;
}
Block block = location.getBlock();
if (!block.getType().hasGravity() && block.getType().isOccluding() && block.getType() != Material.SOUL_SAND && block.getType() != Material.SNOW && block.getType() != Material.DEAD_BUSH) {
teleport(location.add(0, 1, 0));
return;
}
world.getEntityManager().move(this, location);
Position.copyLocation(location, this.location);
if (!fall) {
fallDistance = 0;
return;
}
if (this instanceof GlowPlayer) {
if (((GlowPlayer) this).getGameMode() == GameMode.CREATIVE) {
return;
}
}
// check if the entity is climbing, or in a liquid
if (location.getBlock().getType() != Material.AIR) {
fallDistance = 0;
return;
}
if (location.getY() < previousLocation.getY()) {
fallDistance += previousLocation.getY() - location.getY();
// check if entity is on the ground and did not fall the sufficient amount
if (new Location(location.getWorld(), location.getX(), location.getY() - 1, location.getZ()).getBlock().getType().isSolid() && !(fallDistance > 3)) {
fallDistance = 0;
}
} else if (location.getY() > previousLocation.getY()) {
fallDistance = 0;
}
}
/**
* Sets this entity's location and applies fall damage calculations.
*
* @param location The new location.
*/
public void setRawLocation(Location location) {
setRawLocation(location, true);
}
/**
* Creates a {@link Message} which can be sent to a client to spawn this
* entity.
*
* @return A message which can spawn this entity.
*/
public abstract List<Message> createSpawnMessage();
/**
* Creates a {@link Message} which can be sent to a client to update this
* entity.
*
* @return A message which can update this entity.
*/
public List<Message> createUpdateMessage() {
boolean moved = hasMoved();
boolean rotated = hasRotated();
double x = location.getX();
double y = location.getY();
double z = location.getZ();
double dx = x * 32 - previousLocation.getX() * 32;
double dy = y * 32 - previousLocation.getY() * 32;
double dz = z * 32 - previousLocation.getZ() * 32;
dx *= 128;
dy *= 128;
dz *= 128;
boolean teleport = dx > Short.MAX_VALUE || dy > Short.MAX_VALUE || dz > Short.MAX_VALUE || dx < Short.MIN_VALUE || dy < Short.MIN_VALUE || dz < Short.MIN_VALUE;
int yaw = Position.getIntYaw(location);
int pitch = Position.getIntPitch(location);
List<Message> result = new LinkedList<>();
if (teleported || (moved && teleport)) {
result.add(new EntityTeleportMessage(id, x, y, z, yaw, pitch));
} else if (moved && rotated) {
result.add(new RelativeEntityPositionRotationMessage(id, (short) dx, (short) dy, (short) dz, yaw, pitch));
} else if (moved) {
result.add(new RelativeEntityPositionMessage(id, (short) dx, (short) dy, (short) dz));
} else if (rotated) {
result.add(new EntityRotationMessage(id, yaw, pitch));
}
// todo: handle head rotation as a separate value
if (rotated) {
result.add(new EntityHeadRotationMessage(id, yaw));
}
// send changed metadata
List<MetadataMap.Entry> changes = metadata.getChanges();
if (changes.size() > 0) {
result.add(new EntityMetadataMessage(id, changes));
}
// send velocity if needed
if (velocityChanged) {
result.add(new EntityVelocityMessage(id, velocity));
}
if (vehicleChanged) {
//this method will not call for this player, we don't need check SELF_ID
result.add(new AttachEntityMessage(getEntityId(), vehicle != null ? vehicle.getEntityId() : -1, false));
}
return result;
}
/**
* Checks if this entity has moved this cycle.
*
* @return {@code true} if so, {@code false} if not.
*/
public boolean hasMoved() {
return Position.hasMoved(location, previousLocation);
}
/**
* Checks if this entity has rotated this cycle.
*
* @return {@code true} if so, {@code false} if not.
*/
public boolean hasRotated() {
return Position.hasRotated(location, previousLocation);
}
/**
* Teleport this entity to the spawn point of the main world.
* This is used to teleport out of the End.
*
* @return {@code true} if the teleport was successful.
*/
protected boolean teleportToSpawn() {
Location target = server.getWorlds().get(0).getSpawnLocation();
EntityPortalEvent event = EventFactory.callEvent(new EntityPortalEvent(this, location.clone(), target, null));
if (event.isCancelled()) {
return false;
}
target = event.getTo();
teleport(target);
return true;
}
/**
* Teleport this entity to the End.
* If no End world is loaded this does nothing.
*
* @return {@code true} if the teleport was successful.
*/
protected boolean teleportToEnd() {
if (!server.getAllowEnd()) {
return false;
}
Location target = null;
for (World world : server.getWorlds()) {
if (world.getEnvironment() == World.Environment.THE_END) {
target = world.getSpawnLocation();
break;
}
}
if (target == null) {
return false;
}
EntityPortalEvent event = EventFactory.callEvent(new EntityPortalEvent(this, location.clone(), target, null));
if (event.isCancelled()) {
return false;
}
target = event.getTo();
teleport(target);
return true;
}
protected void setSize(float xz, float y) {
setBoundingBox(xz, y);
}
/**
* Determine if this entity is intersecting a block of the specified type.
* If the entity has a defined bounding box, that is used to check for
* intersection. Otherwise,
*
* @param material The material to check for.
* @return True if the entity is intersecting
*/
public boolean isTouchingMaterial(Material material) {
if (boundingBox == null) {
// less accurate calculation if no bounding box is present
for (BlockFace face : new BlockFace[]{BlockFace.EAST, BlockFace.WEST, BlockFace.SOUTH, BlockFace.NORTH, BlockFace.DOWN, BlockFace.SELF,
BlockFace.NORTH_EAST, BlockFace.NORTH_WEST, BlockFace.SOUTH_EAST, BlockFace.SOUTH_WEST}) {
if (getLocation().getBlock().getRelative(face).getType() == material) {
return true;
}
}
} else {
// bounding box-based calculation
Vector min = boundingBox.minCorner, max = boundingBox.maxCorner;
for (int x = min.getBlockX(); x <= max.getBlockX(); ++x) {
for (int y = min.getBlockY(); y <= max.getBlockY(); ++y) {
for (int z = min.getBlockZ(); z <= max.getBlockZ(); ++z) {
if (world.getBlockTypeIdAt(x, y, z) == material.getId()) {
return true;
}
}
}
}
}
return false;
}
protected final void setBoundingBox(double xz, double y) {
boundingBox = new EntityBoundingBox(xz, y);
}
// Physics stuff
public boolean intersects(BoundingBox box) {
return boundingBox != null && boundingBox.intersects(box);
}
protected void pulsePhysics() {
// todo: update location based on velocity,
// do gravity, all that other good stuff
// make sure bounding box is up to date
if (boundingBox != null) {
boundingBox.setCenter(location.getX(), location.getY(), location.getZ());
}
}
@Override
public int getFireTicks() {
return fireTicks;
}
// Various properties
@Override
public void setFireTicks(int ticks) {
fireTicks = ticks;
}
@Override
public int getMaxFireTicks() {
return 160; // this appears to be Minecraft's default value
}
@Override
public float getFallDistance() {
return fallDistance;
}
@Override
public void setFallDistance(float distance) {
fallDistance = Math.max(distance, 0);
}
@Override
public EntityDamageEvent getLastDamageCause() {
return lastDamageCause;
}
@Override
public void setLastDamageCause(EntityDamageEvent event) {
lastDamageCause = event;
}
@Override
public int getTicksLived() {
return ticksLived;
}
@Override
public void setTicksLived(int value) {
this.ticksLived = value;
}
@Override
public boolean isOnGround() {
return onGround;
}
public void setOnGround(boolean onGround) {
this.onGround = onGround;
}
@Override
public void remove() {
active = false;
world.getEntityManager().unregister(this);
server.getEntityIdManager().deallocate(this);
}
// Miscellaneous actions
@Override
public List<Entity> getNearbyEntities(double x, double y, double z) {
// This behavior is similar to CraftBukkit, where a call with args
// (0, 0, 0) finds any entities whose bounding boxes intersect that of
// this entity.
BoundingBox searchBox;
if (boundingBox == null) {
searchBox = BoundingBox.fromPositionAndSize(location.toVector(), new Vector(0, 0, 0));
} else {
searchBox = BoundingBox.copyOf(boundingBox);
}
Vector vec = new Vector(x, y, z);
searchBox.minCorner.subtract(vec);
searchBox.maxCorner.add(vec);
return world.getEntityManager().getEntitiesInside(searchBox, this);
}
@Override
public void playEffect(EntityEffect type) {
EntityStatusMessage message = new EntityStatusMessage(id, type);
world.getRawPlayers().stream().filter(player -> player.canSeeEntity(this)).forEach(player -> player.getSession().send(message));
}
@Override
public EntityType getType() {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public boolean isInsideVehicle() {
return getVehicle() != null;
}
// Entity stacking
@Override
public boolean leaveVehicle() {
return isInsideVehicle() && vehicle.setPassenger(null);
}
@Override
public Entity getVehicle() {
return vehicle;
}
@Override
public String getCustomName() {
String name = metadata.getString(MetadataIndex.NAME_TAG);
if (name == null || name.length() == 0) {
name = "";
}
return name;
}
// Custom name
@Override
public void setCustomName(String name) {
if (name == null) {
name = "";
}
if (name.length() > 64) {
name = name.substring(0, 64);
}
metadata.set(MetadataIndex.NAME_TAG, name); // remove ?
}
@Override
public boolean isCustomNameVisible() {
return metadata.getByte(MetadataIndex.SHOW_NAME_TAG) == 1;
}
@Override
public void setCustomNameVisible(boolean flag) {
metadata.set(MetadataIndex.SHOW_NAME_TAG, flag ? (byte) 1 : (byte) 0);
}
@Override
public Entity getPassenger() {
return passenger;
}
@Override
public boolean setPassenger(Entity bPassenger) {
Preconditions.checkArgument(bPassenger != this, "Entity cannot ride itself.");
if (this.passenger == bPassenger) return false; // nothing changed
if (bPassenger == null) {
EventFactory.callEvent(new EntityDismountEvent(this.passenger, this));
this.passenger.vehicleChanged = true;
this.passenger.vehicle = null;
this.passenger = null;
} else {
if (!(bPassenger instanceof GlowEntity)) {
return false;
}
GlowEntity passenger = (GlowEntity) bPassenger;
if (passenger.vehicle != null) {
EventFactory.callEvent(new EntityDismountEvent(passenger, passenger.vehicle));
passenger.vehicle.passenger = null;
passenger.vehicle = null;
}
EntityMountEvent event = new EntityMountEvent(passenger, this);
EventFactory.callEvent(event);
if (event.isCancelled()) {
return false;
}
if (this.passenger != null) {
EventFactory.callEvent(new EntityDismountEvent(this.passenger, this));
this.passenger.vehicleChanged = true;
this.passenger.vehicle = null;
}
this.passenger = passenger;
this.passenger.vehicle = this;
this.passenger.vehicleChanged = true;
}
return true;
}
@Override
public boolean isEmpty() {
return getPassenger() == null;
}
@Override
public boolean eject() {
return !isEmpty() && setPassenger(null);
}
@Override
public void setMetadata(String metadataKey, MetadataValue newMetadataValue) {
bukkitMetadata.setMetadata(this, metadataKey, newMetadataValue);
}
// Metadata
@Override
public List<MetadataValue> getMetadata(String metadataKey) {
return bukkitMetadata.getMetadata(this, metadataKey);
}
@Override
public boolean hasMetadata(String metadataKey) {
return bukkitMetadata.hasMetadata(this, metadataKey);
}
@Override
public void removeMetadata(String metadataKey, Plugin owningPlugin) {
bukkitMetadata.removeMetadata(this, metadataKey, owningPlugin);
}
@Override
public boolean isPermissionSet(String s) {
return false; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public boolean isPermissionSet(Permission permission) {
return false; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public boolean hasPermission(String s) {
return false; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public boolean hasPermission(Permission permission) {
return false; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public PermissionAttachment addAttachment(Plugin plugin, String s, boolean b) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public PermissionAttachment addAttachment(Plugin plugin) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public PermissionAttachment addAttachment(Plugin plugin, String s, boolean b, int i) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public PermissionAttachment addAttachment(Plugin plugin, int i) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void removeAttachment(PermissionAttachment permissionAttachment) {
//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void recalculatePermissions() {
//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public Set<PermissionAttachmentInfo> getEffectivePermissions() {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public boolean isOp() {
return false; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void setOp(boolean b) {
//To change body of implemented methods use File | Settings | File Templates.
}
public boolean entityInteract(GlowPlayer player, InteractEntityMessage message) {
// Override in subclasses to implement behavior
return false;
}
public Entity.Spigot spigot() {
return null; // TODO: support entity isInvulnerable() API
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
GlowEntity other = (GlowEntity) obj;
return id == other.id;
}
/**
* The metadata store class for entities.
*/
private static final class EntityMetadataStore extends MetadataStoreBase<Entity> implements MetadataStore<Entity> {
@Override
protected String disambiguate(Entity subject, String metadataKey) {
return subject.getUniqueId() + ":" + metadataKey;
}
}
}
|
package net.goldolphin.maria;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.SSLException;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpUtil;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
/**
* @author goldolphin
* 2016-04-04 20:45
*/
public class HttpClient {
private static final int DEFAULT_HTTP_PORT = 80;
private static final int DEFAULT_HTTPS_PORT = 443;
private static final int DEFAULT_MAX_CONTENT_LENGTH = 1024 * 1024;
private static final Duration DEFAULT_TIMEOUT = Duration.ofSeconds(10);
private static final SslContext SSL_CONTEXT;
private final EventLoopGroup workerGroup;
private final Bootstrap bootstrap;
private final AddressResolver addressResolver;
private final ChannelPool channelPool;
static {
SslContextBuilder builder = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE);
try {
SSL_CONTEXT = builder.build();
} catch (SSLException e) {
throw new IllegalStateException(e); // Should not occur.
}
}
public HttpClient() {
this(new NioEventLoopGroup());
}
public HttpClient(AddressResolver addressResolver) {
this(new NioEventLoopGroup(), addressResolver);
}
public HttpClient(EventLoopGroup workerGroup) {
this(workerGroup, AddressResolver.SYSTEM_DEFAULT);
}
public HttpClient(EventLoopGroup workerGroup, AddressResolver addressResolver) {
this(DEFAULT_MAX_CONTENT_LENGTH, workerGroup, addressResolver);
}
public HttpClient(int maxContentLength, EventLoopGroup workerGroup, AddressResolver addressResolver) {
this(maxContentLength, workerGroup, addressResolver, 20);
}
public HttpClient(int maxContentLength, EventLoopGroup workerGroup, AddressResolver addressResolver, int poolCapacity) {
this.workerGroup = workerGroup;
bootstrap = new Bootstrap();
bootstrap.group(workerGroup)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("codec", new HttpClientCodec());
pipeline.addLast("aggregator", new HttpObjectAggregator(maxContentLength));
}
});
this.addressResolver = addressResolver;
this.channelPool = new ChannelPool(poolCapacity);
}
public CompletableFuture<FullHttpResponse> execute(HttpRequest request) {
return execute(request, DEFAULT_TIMEOUT);
}
public CompletableFuture<FullHttpResponse> execute(HttpRequest request, Duration timeout) {
String host;
int port;
boolean isHttps;
try {
HttpUtil.setKeepAlive(request, true);
URI uri = new URI(request.uri());
host = uri.getHost();
String scheme = uri.getScheme().toLowerCase();
isHttps = scheme.equals("https");
port = uri.getPort();
if (port < 0) {
port = isHttps ? DEFAULT_HTTPS_PORT : DEFAULT_HTTP_PORT;
request.headers().set(HttpHeaderNames.HOST, host);
} else {
request.headers().set(HttpHeaderNames.HOST, host + ":" + port);
}
// Refactor the URI.
String rawPath = uri.getRawPath();
String rawQuery = uri.getRawQuery();
String rawFragment = uri.getRawFragment();
StringBuilder builder = new StringBuilder(rawPath);
if (rawQuery != null) {
builder.append("?").append(rawQuery);
}
if (rawFragment != null) {
builder.append("#").append(rawFragment);
}
request.setUri(builder.toString());
} catch (URISyntaxException e) {
CompletableFuture<FullHttpResponse> future = new CompletableFuture<>();
future.completeExceptionally(e);
return future;
}
// Do not throw exceptions in listeners, because they will all be swallowed by netty.
InetSocketAddress remoteAddress = addressResolver.resolve(host, port);
return connect(remoteAddress, isHttps, host, port).thenCompose(channel -> send(channel, request, timeout)
.whenComplete((r, ex) -> {
if (ex == null && HttpUtil.isKeepAlive(request)) {
channelPool.release(remoteAddress, channel);
} else {
channel.close();
}
}));
}
private CompletableFuture<FullHttpResponse> send(Channel channel, HttpRequest request, Duration timeout) {
CompletableFuture<FullHttpResponse> future = new CompletableFuture<>();
channel.pipeline().addLast("handler", new HttpClientHandler(future));
channel.writeAndFlush(request).addListener((ChannelFutureListener) f -> {
if (f.isSuccess()) {
if (timeout != null) {
f.channel().eventLoop().schedule(() -> {
future.completeExceptionally(new HttpTimeoutException("Time is out"));
}, timeout.toMillis(), TimeUnit.MILLISECONDS);
}
} else {
future.completeExceptionally(f.cause());
}
});
return future.thenApply(r -> {
channel.pipeline().remove("handler");
return r;
});
}
private CompletableFuture<Channel> connect(InetSocketAddress remoteAddress, boolean isHttps, String host, int port) {
Channel channel = channelPool.acquire(remoteAddress);
if (channel != null && channel.isActive()) {
return CompletableFuture.completedFuture(channel);
}
CompletableFuture<Channel> future = new CompletableFuture<>();
// Do not throw exceptions in listeners, because they will all be swallowed by netty.
bootstrap.connect(remoteAddress).addListener((ChannelFutureListener) f -> {
if (f.isSuccess()) {
Channel c = f.channel();
if (isHttps) {
c.pipeline().addFirst("ssl", SSL_CONTEXT.newHandler(c.alloc(), host, port));
}
future.complete(c);
} else {
future.completeExceptionally(f.cause());
}
});
return future;
}
public void close(boolean stopEventLoop) {
try {
channelPool.close();
} finally {
if (stopEventLoop) {
workerGroup.shutdownGracefully();
}
}
}
public EventLoopGroup getWorkerGroup() {
return workerGroup;
}
}
|
package org.apache.couchdb.lucene;
import static org.apache.couchdb.lucene.Utils.text;
import static org.apache.couchdb.lucene.Utils.token;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.LogByteSizeMergePolicy;
import org.apache.lucene.index.Term;
import org.apache.lucene.index.TermEnum;
import org.apache.lucene.index.IndexWriter.MaxFieldLength;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
/**
* High-level wrapper class over Lucene.
*/
public final class Index {
private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
private static final Database DB = new Database(Config.DB_URL);
private static final Tika TIKA = new Tika();
private static final Object MUTEX = new Object();
private static class Indexer implements Runnable {
private Directory dir;
private boolean running = true;
public void run() {
try {
this.dir = FSDirectory.getDirectory(Config.INDEX_DIR);
while (running) {
updateIndex();
waitForUpdateNotification();
}
} catch (final IOException e) {
Log.errlog(e);
}
}
private void updateIndex() throws IOException {
if (IndexWriter.isLocked(dir)) {
Log.errlog("Forcibly unlocking locked index at startup.");
IndexWriter.unlock(dir);
}
final String[] dbnames = DB.getAllDatabases();
Arrays.sort(dbnames);
Rhino rhino = null;
boolean commit = false;
boolean expunge = false;
final IndexWriter writer = newWriter();
Progress progress = null;
try {
// Delete all documents in non-extant databases.
final IndexReader reader = IndexReader.open(dir);
try {
final TermEnum terms = reader.terms(new Term(Config.DB, ""));
try {
while (terms.next()) {
final Term term = terms.term();
if (!term.field().equals(Config.DB))
break;
if (Arrays.binarySearch(dbnames, term.text()) < 0) {
Log.errlog("Database '%s' has been deleted," + " removing all documents from index.",
term.text());
delete(writer, term.text());
commit = true;
expunge = true;
}
}
} finally {
terms.close();
}
} finally {
reader.close();
}
// Update all extant databases.
progress = new Progress(dir);
progress.load();
for (final String dbname : dbnames) {
// Database might supply a transformation function.
final JSONObject designDoc = DB.getDoc(dbname, "_design/lucene");
if (designDoc != null && designDoc.containsKey("transform")) {
String transform = designDoc.getString("transform");
// Strip start and end double quotes.
transform = transform.replaceAll("^\"*", "");
transform = transform.replaceAll("\"*$", "");
rhino = new Rhino(transform);
} else {
rhino = null;
}
commit |= updateDatabase(writer, dbname, progress, rhino);
}
} catch (final Exception e) {
Log.errlog(e);
commit = false;
} finally {
if (commit) {
if (expunge) {
writer.expungeDeletes();
}
writer.close();
progress.save();
final IndexReader reader = IndexReader.open(dir);
try {
Log.errlog("Committed changes to index (%,d documents in index, %,d deletes).", reader
.numDocs(), reader.numDeletedDocs());
} finally {
reader.close();
}
} else {
writer.rollback();
}
}
}
private void waitForUpdateNotification() {
synchronized (MUTEX) {
try {
MUTEX.wait();
} catch (final InterruptedException e) {
running = false;
}
}
}
private IndexWriter newWriter() throws IOException {
final IndexWriter result = new IndexWriter(dir, Config.ANALYZER, MaxFieldLength.UNLIMITED);
// Customize merge policy.
final LogByteSizeMergePolicy mp = new LogByteSizeMergePolicy();
mp.setMergeFactor(5);
mp.setMaxMergeMB(1000);
result.setMergePolicy(mp);
// Customer other settings.
result.setUseCompoundFile(false);
result.setRAMBufferSizeMB(Config.RAM_BUF);
return result;
}
private boolean updateDatabase(final IndexWriter writer, final String dbname, final Progress progress,
final Rhino rhino) throws HttpException, IOException {
final JSONObject obj = DB.getAllDocsBySeq(dbname, progress.getProgress(dbname));
if (!obj.has("rows")) {
Log.errlog("no rows found (%s).", obj);
return false;
}
// Process all rows
final JSONArray rows = obj.getJSONArray("rows");
long update_seq = 0;
for (int i = 0, max = rows.size(); i < max; i++) {
final JSONObject row = rows.getJSONObject(i);
final JSONObject value = row.optJSONObject("value");
final JSONObject doc = row.optJSONObject("doc");
if (doc != null) {
updateDocument(writer, dbname, rows.getJSONObject(i), rhino);
}
if (value != null && value.optBoolean("deleted")) {
writer.deleteDocuments(new Term(Config.ID, row.getString("id")));
}
update_seq = row.getLong("key");
}
if (rows.isEmpty()) {
return false; // no change.
}
progress.setProgress(dbname, update_seq);
Log.errlog("%s: index caught up to %,d.", dbname, update_seq);
return true;
}
private void delete(final IndexWriter writer, final String dbname) throws IOException {
writer.deleteDocuments(new Term(Config.DB, dbname));
}
private void updateDocument(final IndexWriter writer, final String dbname, final JSONObject obj,
final Rhino rhino) throws IOException {
final Document doc = new Document();
JSONObject json = obj.getJSONObject("doc");
// Skip design documents.
if (json.getString(Config.ID).startsWith("_design")) {
return;
}
// Pass through user-defined transformation (if any).
if (rhino != null) {
json = JSONObject.fromObject(rhino.parse(json.toString()));
if (json.isNullObject())
return;
}
// Standard properties.
doc.add(token(Config.DB, dbname, false));
final String id = (String) json.remove(Config.ID);
// Discard _rev
json.remove("_rev");
// Index _id and _rev as tokens.
doc.add(token(Config.ID, id, true));
// Index all attributes.
add(doc, null, json, false);
// Attachments
if (json.has("_attachments")) {
final JSONObject attachments = json.getJSONObject("_attachments");
final Iterator it = attachments.keys();
while (it.hasNext()) {
final String name = (String) it.next();
final JSONObject att = attachments.getJSONObject(name);
final String url = DB.url(String.format("%s/%s/%s", dbname, DB.encode(id), DB.encode(name)));
final GetMethod get = new GetMethod(url);
try {
final int sc = Database.CLIENT.executeMethod(get);
if (sc == 200) {
TIKA.parse(get.getResponseBodyAsStream(), att.getString("content_type"), doc);
} else {
Log.errlog("Failed to retrieve attachment: %d", sc);
}
} finally {
get.releaseConnection();
}
}
}
// write it
writer.updateDocument(new Term(Config.ID, id), doc);
}
private void add(final Document out, final String key, final Object value, final boolean store) {
if (value instanceof JSONObject) {
final JSONObject json = (JSONObject) value;
for (final Object obj : json.keySet()) {
add(out, (String) obj, json.get(obj), store);
}
} else if (value instanceof String) {
try {
DATE_FORMAT.parse((String) value);
out.add(token(key, (String) value, store));
} catch (final java.text.ParseException e) {
out.add(text(key, (String) value, store));
}
} else if (value instanceof Number) {
out.add(token(key, value.toString(), store));
} else if (value instanceof Boolean) {
out.add(token(key, value.toString(), store));
} else if (value instanceof JSONArray) {
final JSONArray arr = (JSONArray) value;
for (int i = 0, max = arr.size(); i < max; i++) {
add(out, key, arr.get(i), store);
}
} else if (value == null) {
Log.errlog("%s was null.", key);
} else {
Log.errlog("Unsupported data type: %s.", value.getClass());
}
}
}
/**
* update notifications look like this;
*
* {"type":"updated","db":"cas"}
*
* type can be created, updated or deleted.
*/
public static void main(final String[] args) {
final Runnable indexer = new Indexer();
final Thread indexerThread = new Thread(indexer, "indexer");
indexerThread.setDaemon(true);
indexerThread.start();
final Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
final String line = scanner.nextLine();
final JSONObject obj = JSONObject.fromObject(line);
if (obj.has("type") && obj.has("db")) {
synchronized (MUTEX) {
MUTEX.notify();
}
}
}
}
}
|
package org.bricolages.streaming;
import lombok.Getter;
import lombok.Setter;
import org.bricolages.streaming.s3.ObjectMapper;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
@Component
@ConfigurationProperties(prefix = "bricolage")
public class Config {
@Getter
private final EventQueue eventQueue = new EventQueue();
@Getter
private final LogQueue logQueue = new LogQueue();
@Getter
private List<ObjectMapper.Entry> mappings = new ArrayList<>();
@Setter
static class EventQueue {
String url;
int visibilityTimeout;
int maxNumberOfMessages;
int waitTimeSeconds;
}
@Setter
static class LogQueue {
String url;
}
// preflight
@Getter
@Setter
private String srcDs;
@Getter
@Setter
private String destDs;
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.broad.igv.sam;
import org.apache.log4j.Logger;
import org.broad.igv.Globals;
import org.broad.igv.data.CoverageDataSource;
import org.broad.igv.event.RepaintEvent;
import org.broad.igv.feature.FeatureUtils;
import org.broad.igv.feature.LocusScore;
import org.broad.igv.feature.genome.Genome;
import org.broad.igv.goby.GobyCountArchiveDataSource;
import org.broad.igv.prefs.IGVPreferences;
import org.broad.igv.prefs.PreferencesManager;
import org.broad.igv.renderer.*;
import org.broad.igv.tdf.TDFDataSource;
import org.broad.igv.tdf.TDFReader;
import org.broad.igv.track.*;
import org.broad.igv.ui.DataRangeDialog;
import org.broad.igv.ui.IGV;
import org.broad.igv.ui.color.ColorUtilities;
import org.broad.igv.ui.panel.FrameManager;
import org.broad.igv.ui.panel.IGVPopupMenu;
import org.broad.igv.ui.panel.ReferenceFrame;
import org.broad.igv.ui.util.FileDialogUtils;
import org.broad.igv.ui.util.MessageUtils;
import org.broad.igv.ui.util.UIUtilities;
import org.broad.igv.util.ResourceLocator;
import org.broad.igv.util.StringUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import static org.broad.igv.prefs.Constants.*;
/**
* @author jrobinso
*/
public class CoverageTrack extends AbstractTrack implements ScalableTrack {
private static Logger log = Logger.getLogger(CoverageTrack.class);
public static final int TEN_MB = 10000000;
static DecimalFormat locationFormatter = new DecimalFormat();
char[] nucleotides = {'a', 'c', 'g', 't', 'n'};
public static Color lightBlue = new Color(0, 0, 150);
private static Color coverageGrey = new Color(175, 175, 175);
public static final Color negStrandColor = new Color(140, 140, 160);
public static final Color posStrandColor = new Color(160, 140, 140);
public static final boolean DEFAULT_AUTOSCALE = true;
public static final boolean DEFAULT_SHOW_REFERENCE = false;
private float snpThreshold;
private AlignmentTrack alignmentTrack;
private AlignmentDataManager dataManager;
private CoverageDataSource dataSource;
private DataRenderer dataSourceRenderer;
private IntervalRenderer intervalRenderer;
private IGVPreferences prefs;
private JMenuItem dataRangeItem;
private Genome genome;
private boolean removed = false;
IGV igv;
/**
* Whether to autoscale across all ReferenceFrames
* Default is true because we usually do, SashimiPlot does not
*/
private boolean globalAutoScale = true;
/**
* Copy constructor. Used for Sashimi plot.
*
* @param track
*/
public CoverageTrack(CoverageTrack track) {
this(track.getResourceLocator(), track.getName(), track.alignmentTrack, track.genome);
if (track.dataManager != null) this.setDataManager(track.dataManager);
if (track.dataSource != null) this.setDataSource(track.dataSource);
this.snpThreshold = track.snpThreshold;
this.prefs = track.prefs;
this.igv = IGV.hasInstance() ? IGV.getInstance() : null;
}
public CoverageTrack(ResourceLocator locator, String name, AlignmentTrack alignmentTrack, Genome genome) {
super(locator.getPath() + "_coverage", name, locator);
super.setDataRange(new DataRange(0, 0, 60));
this.alignmentTrack = alignmentTrack;
this.genome = genome;
intervalRenderer = new IntervalRenderer();
setMaximumHeight(40);
setColor(coverageGrey);
prefs = PreferencesManager.getPreferences();
snpThreshold = prefs.getAsFloat(SAM_ALLELE_THRESHOLD);
autoScale = DEFAULT_AUTOSCALE;
this.igv = IGV.hasInstance() ? IGV.getInstance(): null;
}
@Override
public String getSample() {
if (sampleId != null) {
return sampleId; // Explicitly set sample ID (e.g. from server load XML)
}
return alignmentTrack.getSample();
}
@Override
public boolean isNumeric() {
return true;
}
public void setDataManager(AlignmentDataManager dataManager) {
this.dataManager = dataManager;
this.dataManager.subscribe(this);
}
public void setDataSource(CoverageDataSource dataSource) {
this.dataSource = dataSource;
dataSourceRenderer = new BarChartRenderer();
setDataRange(new DataRange(0, 0, 1.5f * (float) dataSource.getDataMax()));
}
@Override
public boolean isReadyToPaint(ReferenceFrame frame) {
if (frame.getChrName().equals(Globals.CHR_ALL) || frame.getScale() > dataManager.getMinVisibleScale()) {
return true; // Nothing to paint
} else {
return dataManager.isLoaded(frame);
}
}
@Override
public void load(ReferenceFrame referenceFrame) {
dataManager.load(referenceFrame, alignmentTrack.renderOptions, true);
}
public void setSnpThreshold(float snpThreshold) {
this.snpThreshold = snpThreshold;
}
public float getSnpThreshold() {
return snpThreshold;
}
public boolean isRemoved() {
return removed;
}
@Override
public void dispose() {
super.dispose();
removed = true;
if (dataManager != null) {
dataManager.unsubscribe(this);
}
dataManager = null;
dataSource = null;
alignmentTrack = null;
setVisible(false);
}
public void render(RenderContext context, Rectangle rect) {
int viewWindowSize = context.getReferenceFrame().getCurrentRange().getLength();
if (viewWindowSize > dataManager.getVisibilityWindow() && dataSource == null) {
Rectangle visibleRect = context.getVisibleRect().intersection(rect);
Graphics2D g = context.getGraphic2DForColor(Color.gray);
GraphicUtils.drawCenteredText("Zoom in to see coverage.", visibleRect, g);
return;
}
drawData(context, rect);
drawBorder(context, rect);
if (dataSourceRenderer != null) {
dataSourceRenderer.renderBorder(this, context, rect);
dataSourceRenderer.renderAxis(this, context, rect);
} else {
DataRenderer.drawScale(this.getDataRange(), context, rect);
}
}
public void drawData(RenderContext context, Rectangle rect) {
int viewWindowSize = context.getReferenceFrame().getCurrentRange().getLength();
if (viewWindowSize < dataManager.getVisibilityWindow() && !context.getChr().equals(Globals.CHR_ALL)) {
//Show coverage calculated from intervals if zoomed in enough
AlignmentInterval interval = null;
if (dataManager != null) {
interval = dataManager.getLoadedInterval(context.getReferenceFrame());
}
if (interval != null) {
if (interval.contains(context.getChr(), (int) context.getOrigin(), (int) context.getEndLocation())) {
//if (autoScale) rescale(context.getReferenceFrame());
intervalRenderer.paint(context, rect, interval.getCounts());
return;
}
}
}
//Not rendered yet. Use precomputed scores, if available
List<LocusScore> scores = getInViewScores(context.getReferenceFrame());
if (scores != null) {
dataSourceRenderer.renderScores(this, scores, context, rect);
}
}
private List<LocusScore> getInViewScores(ReferenceFrame frame) {
List<LocusScore> inViewScores = null;
if (dataSource != null) {
String chr = frame.getChrName();
int start = (int) frame.getOrigin();
int end = (int) frame.getEnd();
int zoom = frame.getZoom();
inViewScores = dataSource.getSummaryScoresForRange(chr, start, end, zoom);
// Trim
// Trim scores
int startIdx = Math.max(0, FeatureUtils.getIndexBefore(start, inViewScores));
int endIdx = inViewScores.size() - 1; // Starting guess
int tmp = Math.max(0, FeatureUtils.getIndexBefore(end, inViewScores));
for (int i = tmp; i < inViewScores.size(); i++) {
if (inViewScores.get(i).getStart() > end) {
endIdx = i - 1;
break;
}
}
endIdx = Math.max(startIdx + 1, endIdx);
if (inViewScores.size() > 1) {
return startIdx == 0 && endIdx == inViewScores.size() - 1 ?
inViewScores :
inViewScores.subList(startIdx, endIdx);
} else {
return inViewScores;
}
}
return inViewScores;
}
@Override
public Range getInViewRange(ReferenceFrame frame) {
int viewWindowSize = frame.getCurrentRange().getLength();
if (dataManager == null || viewWindowSize > dataManager.getVisibilityWindow()) {
List<LocusScore> scores = getInViewScores(frame);
if (scores != null && scores.size() > 0) {
float min = scores.get(0).getScore();
float max = min;
for (int i = 1; i < scores.size(); i++) {
LocusScore score = scores.get(i);
float value = score.getScore();
min = Math.min(value, min);
max = Math.max(value, max);
}
return new Range(min, max);
} else {
return null;
}
} else {
AlignmentInterval interval = dataManager.getLoadedInterval(frame);
if (interval == null) return null;
int origin = (int) frame.getOrigin();
int end = (int) frame.getEnd() + 1;
int intervalMax = interval.getMaxCount(origin, end);
return new Range(0, Math.max(10, intervalMax));
}
}
/**
* Draw border and scale
*
* @param context
* @param rect
*/
private void drawBorder(RenderContext context, Rectangle rect) {
context.getGraphic2DForColor(Color.gray).drawLine(
rect.x, rect.y + rect.height,
rect.x + rect.width, rect.y + rect.height);
}
public void drawScale(RenderContext context, Rectangle rect) {
DataRenderer.drawScale(getDataRange(), context, rect);
}
public boolean isLogNormalized() {
return false;
}
public String getValueStringAt(String chr, double position, int mouseX, int mouseY, ReferenceFrame frame) {
float maxRange = PreferencesManager.getPreferences().getAsFloat(SAM_MAX_VISIBLE_RANGE);
float minVisibleScale = (maxRange * 1000) / 700;
StringBuffer buf = new StringBuffer();
if (!chr.equals("All")) {
String posString = chr + ":" + locationFormatter.format(Math.floor(position + 1));
buf.append(posString + "<br>");
buf.append("<hr>");
}
if (frame.getScale() < minVisibleScale) {
AlignmentInterval interval = dataManager.getLoadedInterval(frame);
if (interval != null && interval.contains(chr, (int) position, (int) position)) {
AlignmentCounts counts = interval.getCounts();
if (counts != null) {
buf.append(counts.getValueStringAt((int) position));
}
}
} else {
buf.append(getPrecomputedValueString(chr, position, frame));
}
return buf.toString();
}
public AlignmentCounts getCounts(String chr, double position, ReferenceFrame frame) {
AlignmentInterval interval = dataManager.getLoadedInterval(frame);
if (interval != null && interval.contains(chr, (int) position, (int) position)) {
return interval.getCounts();
} else {
return null;
}
}
private String getPrecomputedValueString(String chr, double position, ReferenceFrame frame) {
if (dataSource == null) {
return "";
}
int zoom = Math.max(0, frame.getZoom());
List<LocusScore> scores = dataSource.getSummaryScoresForRange(chr, (int) position - 10, (int) position + 10, zoom);
// give a 2 pixel window, otherwise very narrow features will be missed.
double bpPerPixel = frame.getScale();
double minWidth = 2 * bpPerPixel;
if (scores == null) {
return "";
} else {
LocusScore score = (LocusScore) FeatureUtils.getFeatureAt(position, 0, scores);
return score == null ? "" : "Mean count: " + score.getScore();
}
}
public float getRegionScore(String chr, int start, int end, int zoom, RegionScoreType type, String frameName) {
return 0;
}
public void rescale(ReferenceFrame iframe) {
List<ReferenceFrame> frameList = new ArrayList<ReferenceFrame>();
if (iframe != null) frameList.add(iframe);
if (globalAutoScale) {
frameList.addAll(FrameManager.getFrames());
}
if (autoScale && dataManager != null) {
int max = 10;
for (ReferenceFrame frame : frameList) {
AlignmentInterval interval = dataManager.getLoadedInterval(frame);
if (interval == null) continue;
int origin = (int) frame.getOrigin();
int end = (int) frame.getEnd() + 1;
int intervalMax = interval.getMaxCount(origin, end);
max = intervalMax > max ? intervalMax : max;
}
DataRange newRange = new DataRange(0, max);
newRange.setType(getDataRange().getType());
super.setDataRange(newRange);
}
}
/**
* Class to render coverage track, including mismatches.
* <p/>
* NOTE: This class has been extensively optimized with the aid of a profiler, attempts to "clean up" this code
* should be done with frequent profiling, or it will likely have detrimental performance impacts.
*/
class IntervalRenderer {
private void paint(RenderContext context, Rectangle rect, AlignmentCounts alignmentCounts) {
Color color = getColor();
Graphics2D graphics = context.getGraphic2DForColor(color);
DataRange range = getDataRange();
double maxRange = range.isLog() ? Math.log10(range.getMaximum() + 1) : range.getMaximum();
final double rectX = rect.getX();
final double rectMaxX = rect.getMaxX();
final double rectY = rect.getY();
final double rectMaxY = rect.getMaxY();
final double rectHeight = rect.getHeight();
final double origin = context.getOrigin();
final double colorScaleMax = getColorScale().getMaximum();
final double scale = context.getScale();
boolean bisulfiteMode = alignmentTrack.renderOptions.getColorOption() == AlignmentTrack.ColorOption.BISULFITE;
// First pass, coverage
int lastpX = -1;
int start = alignmentCounts.getStart();
int step = alignmentCounts.getBucketSize();
int nPoints = alignmentCounts.getNumberOfPoints();
boolean isSparse = alignmentCounts instanceof SparseAlignmentCounts;
for (int idx = 0; idx < nPoints; idx++) {
int pos = isSparse ? ((SparseAlignmentCounts) alignmentCounts).getPosition(idx) : start + idx * step;
int pX = (int) (rectX + (pos - origin) / scale);
if (pX > rectMaxX) {
break; // We're done, data is position sorted so we're beyond the right-side of the view
}
int dX = (int) (rectX + (pos + step - origin) / scale) - pX;
dX = dX < 1 ? 1 : dX;
// if (pX + dX > lastpX) {
int pY = (int) rectMaxY - 1;
int totalCount = alignmentCounts.getTotalCount(pos);
double tmp = range.isLog() ? Math.log10(totalCount + 1) / maxRange : totalCount / maxRange;
int height = (int) (tmp * rectHeight);
height = Math.min(height, rect.height - 1);
int topY = (pY - height);
if (dX > 3) {
dX--; // Create a little space between bars when there is room.
}
if (height > 0) {
graphics.fillRect(pX, topY, dX, height);
}
lastpX = pX + dX;
}
// Second pass - mark mismatches
if (alignmentCounts.hasBaseCounts()) {
lastpX = -1;
BisulfiteCounts bisulfiteCounts = alignmentCounts.getBisulfiteCounts();
final int intervalEnd = alignmentCounts.getEnd();
final int intervalStart = alignmentCounts.getStart();
byte[] refBases = null;
// Dont try to compute mismatches for intervals > 10 MB
if ((intervalEnd - intervalStart) < TEN_MB) {
refBases = genome.getSequence(context.getChr(), intervalStart, intervalEnd);
}
start = alignmentCounts.getStart();
nPoints = alignmentCounts.getNumberOfPoints();
isSparse = alignmentCounts instanceof SparseAlignmentCounts;
for (int idx = 0; idx < nPoints; idx++) {
int pos = isSparse ? ((SparseAlignmentCounts) alignmentCounts).getPosition(idx) : start + idx;
BisulfiteCounts.Count bc = null;
if (bisulfiteMode && bisulfiteCounts != null) {
bc = bisulfiteCounts.getCount(pos);
}
int pX = (int) (rectX + (pos - origin) / scale);
if (pX > rectMaxX) {
break; // We're done, data is position sorted so we're beyond the right-side of the view
}
int dX = (int) (rectX + (pos + 1 - origin) / scale) - pX;
dX = dX < 1 ? 1 : dX;
if (pX + dX > lastpX) {
// Test to see if any single nucleotide mismatch (nucleotide other than the reference)
// has a quality weight > 20% of the total
boolean mismatch = false;
if (refBases != null) {
int refIdx = pos - intervalStart;
if (refIdx >= 0 && refIdx < refBases.length) {
if (bisulfiteMode) {
mismatch = (bc != null && (bc.methylatedCount + bc.unmethylatedCount) > 0);
} else {
byte ref = refBases[refIdx];
mismatch = alignmentCounts.isConsensusMismatch(pos, ref, context.getChr(), snpThreshold);
}
}
}
if (!mismatch) {
continue;
}
int pY = (int) rectMaxY - 1;
int totalCount = alignmentCounts.getTotalCount(pos);
double tmp = range.isLog() ? Math.log10(totalCount + 1) / maxRange : totalCount / maxRange;
int height = (int) (tmp * rectHeight);
height = Math.min(height, rect.height - 1);
if (dX > 3) {
dX--; // Create a little space between bars when there is room.
}
if (height > 0) {
if (bisulfiteMode) {
if (bc != null) {
drawBarBisulfite(context, pos, rect, totalCount, maxRange,
pY, pX, dX, bc, range.isLog());
}
} else {
drawBar(context, pos, rect, totalCount, maxRange,
pY, pX, dX, alignmentCounts, range.isLog());
}
}
lastpX = pX + dX;
}
}
}
}
}
/**
* Draw a colored bar to represent a mismatch to the reference. The height is proportional to the % of
* reads with respect to the total. If "showAllSnps == true" the bar is shaded by avg read quality.
*
* @param context
* @param pos
* @param rect
* @param max
* @param pY
* @param pX
* @param dX
* @param interval
* @return
*/
int drawBar(RenderContext context,
int pos,
Rectangle rect,
double totalCount,
double max,
int pY,
int pX,
int dX,
AlignmentCounts interval,
boolean isLog) {
for (char nucleotide : nucleotides) {
int count = interval.getCount(pos, (byte) nucleotide);
Color c = SequenceRenderer.nucleotideColors.get(nucleotide);
Graphics2D tGraphics = context.getGraphic2DForColor(c);
double tmp = isLog ?
(count / totalCount) * Math.log10(totalCount + 1) / max :
count / max;
int height = (int) (tmp * rect.getHeight());
height = Math.min(pY - rect.y, height);
int baseY = pY - height;
if (height > 0) {
tGraphics.fillRect(pX, baseY, dX, height);
}
pY = baseY;
}
return pX + dX;
}
int drawBarBisulfite(RenderContext context,
int pos,
Rectangle rect,
double totalCount,
double maxRange,
int pY,
int pX0,
int dX,
BisulfiteCounts.Count count,
boolean isLog) {
// If bisulfite mode, we expand the rectangle to make it more visible. This code is copied from
// AlignmentRenderer
int pX = pX0;
if (dX < 3) {
int expansion = dX;
pX -= expansion;
dX += (2 * expansion);
}
double nMethylated = count.methylatedCount;
double unMethylated = count.unmethylatedCount;
Color c = Color.red;
Graphics2D tGraphics = context.getGraphic2DForColor(c);
//Not all reads at a position are informative, color by % of informative reads
// double totalInformative = count.methylatedCount + count.unmethylatedCount;
// double mult = totalCount / totalInformative;
// nMethylated *= mult;
// unMethylated *= mult;
double tmp = isLog ?
(nMethylated / totalCount) * Math.log10(totalCount + 1) / maxRange :
nMethylated / maxRange;
int height = (int) (tmp * rect.getHeight());
height = Math.min(pY - rect.y, height);
int baseY = pY - height;
if (height > 0) {
tGraphics.fillRect(pX, baseY, dX, height);
}
pY = baseY;
c = Color.blue;
tGraphics = context.getGraphic2DForColor(c);
tmp = isLog ?
(unMethylated / totalCount) * Math.log10(totalCount + 1) / maxRange :
unMethylated / maxRange;
height = (int) (tmp * rect.getHeight());
height = Math.min(pY - rect.y, height);
baseY = pY - height;
if (height > 0) {
tGraphics.fillRect(pX, baseY, dX, height);
}
return pX + dX;
}
/**
* Strand-specific
*
* @param context
* @param pos
* @param rect
* @param maxCount
* @param pY
* @param pX
* @param dX
* @param isPositive
* @param interval
* @return
*/
void drawStrandBar(RenderContext context,
int pos,
Rectangle rect,
double maxCount,
int pY,
int pX,
int dX,
boolean isPositive,
AlignmentCounts interval) {
for (char nucleotide : nucleotides) {
Color c = SequenceRenderer.nucleotideColors.get(nucleotide);
Graphics2D tGraphics = context.getGraphic2DForColor(c);
int count = isPositive ? interval.getPosCount(pos, (byte) nucleotide) :
interval.getNegCount(pos, (byte) nucleotide);
int height = (int) Math.round(count * rect.getHeight() / maxCount);
height = isPositive ? Math.min(pY - rect.y, height) :
Math.min(rect.y + rect.height - pY, height);
int baseY = (int) (isPositive ? (pY - height) : pY);
if (height > 0) {
tGraphics.fillRect(pX, baseY, dX, height);
}
pY = isPositive ? baseY : baseY + height;
}
}
static float[] colorComps = new float[3];
private Color getShadedColor(int qual, Color backgroundColor, Color color) {
float alpha = 0;
int minQ = prefs.getAsInt(SAM_BASE_QUALITY_MIN);
ColorUtilities.getRGBColorComponents(color);
if (qual < minQ) {
alpha = 0.1f;
} else {
int maxQ = prefs.getAsInt(SAM_BASE_QUALITY_MAX);
alpha = Math.max(0.1f, Math.min(1.0f, 0.1f + 0.9f * (qual - minQ) / (maxQ - minQ)));
}
// Round alpha to nearest 0.1, for effeciency;
alpha = ((int) (alpha * 10 + 0.5f)) / 10.0f;
if (alpha >= 1) {
return color;
} else {
return ColorUtilities.getCompositeColor(backgroundColor, color, alpha);
}
}
/**
* Override to return a specialized popup menu
*
* @return
*/
@Override
public IGVPopupMenu getPopupMenu(TrackClickEvent te) {
Collection<Track> tmp = new ArrayList<Track>();
tmp.add(this);
IGVPopupMenu popupMenu = TrackMenuUtils.getPopupMenu(tmp, getName(), te);
popupMenu.addSeparator();
this.addSnpTresholdItem(popupMenu);
popupMenu.addSeparator();
addLoadCoverageDataItem(popupMenu);
popupMenu.addSeparator();
addCopyDetailsItem(popupMenu, te);
popupMenu.addSeparator();
addShowItems(popupMenu);
return popupMenu;
}
private void addCopyDetailsItem(IGVPopupMenu popupMenu, TrackClickEvent te) {
JMenuItem copyDetails = new JMenuItem("Copy Details to Clipboard");
copyDetails.setEnabled(false);
if (te.getFrame() != null) {
final String details = getValueStringAt(te.getFrame().getChrName(), te.getChromosomePosition(), te.getMouseEvent().getX(), te.getMouseEvent().getY(), te.getFrame());
copyDetails.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (details != null) {
String deets = details.replace("<br>", System.getProperty("line.separator"));
StringUtils.copyTextToClipboard(deets);
}
}
});
copyDetails.setEnabled(details != null);
}
popupMenu.add(copyDetails);
}
public static JMenuItem addDataRangeItem(final Frame parentFrame, JPopupMenu menu, final Collection<? extends Track> selectedTracks) {
JMenuItem maxValItem = new JMenuItem("Set Data Range");
maxValItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (selectedTracks.size() > 0) {
DataRange prevAxisDefinition = selectedTracks.iterator().next().getDataRange();
DataRangeDialog dlg = new DataRangeDialog(parentFrame, prevAxisDefinition);
dlg.setHideMid(true);
dlg.setVisible(true);
if (!dlg.isCanceled()) {
float min = Math.min(dlg.getMin(), dlg.getMax());
float max = Math.max(dlg.getMin(), dlg.getMax());
float mid = dlg.getBase();
if (mid < min) mid = min;
else if (mid > max) mid = max;
DataRange dataRange = new DataRange(min, mid, max);
dataRange.setType(dlg.getDataRangeType());
for (Track track : selectedTracks) {
track.setDataRange(dataRange);
track.setAutoScale(false);
}
parentFrame.repaint();
}
}
}
});
if (menu != null) menu.add(maxValItem);
return maxValItem;
}
public JMenuItem addSnpTresholdItem(JPopupMenu menu) {
JMenuItem maxValItem = new JMenuItem("Set allele frequency threshold...");
maxValItem.addActionListener(e -> {
String value = JOptionPane.showInputDialog("Allele frequency threshold: ", Float.valueOf(snpThreshold));
if (value == null) {
return;
}
try {
float tmp = Float.parseFloat(value);
snpThreshold = tmp;
if(igv != null) igv.postEvent(new RepaintEvent(CoverageTrack.this));
} catch (Exception exc) {
//log
}
});
menu.add(maxValItem);
return maxValItem;
}
public void addShowItems(JPopupMenu menu) {
if (alignmentTrack != null) {
final JMenuItem alignmentItem = new JCheckBoxMenuItem("Show Alignment Track");
alignmentItem.setSelected(alignmentTrack.isVisible());
alignmentItem.setEnabled(!alignmentTrack.isRemoved());
alignmentItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
alignmentTrack.setVisible(alignmentItem.isSelected());
}
});
menu.add(alignmentItem);
final SpliceJunctionTrack spliceJunctionTrack = alignmentTrack.getSpliceJunctionTrack();
if (spliceJunctionTrack != null) {
final JMenuItem junctionItem = new JCheckBoxMenuItem("Show Splice Junction Track");
junctionItem.setSelected(spliceJunctionTrack.isVisible());
junctionItem.setEnabled(!spliceJunctionTrack.isRemoved());
junctionItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
spliceJunctionTrack.setVisible(junctionItem.isSelected());
}
});
menu.add(junctionItem);
}
final JMenuItem coverageItem = new JMenuItem("Hide Coverage Track");
coverageItem.setEnabled(!isRemoved());
coverageItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
UIUtilities.invokeOnEventThread(new Runnable() {
public void run() {
setVisible(false);
if (IGV.hasInstance()) IGV.getInstance().getMainPanel().revalidate();
}
});
}
});
menu.add(coverageItem);
}
}
public void addLoadCoverageDataItem(JPopupMenu menu) {
// Change track height by attribute
final JMenuItem item = new JCheckBoxMenuItem("Load pre-computed coverage data...");
item.addActionListener(e -> {
final IGVPreferences prefs = PreferencesManager.getPreferences();
File initDirectory = prefs.getLastTrackDirectory();
File file = FileDialogUtils.chooseFile("Select coverage file", initDirectory, FileDialog.LOAD);
if (file != null) {
prefs.setLastTrackDirectory(file.getParentFile());
String path = file.getAbsolutePath();
if (path.endsWith(".tdf") || path.endsWith(".tdf")) {
TDFReader reader = TDFReader.getReader(file.getAbsolutePath());
TDFDataSource ds = new TDFDataSource(reader, 0, getName() + " coverage", genome);
setDataSource(ds);
if(igv != null) igv.postEvent(new RepaintEvent(CoverageTrack.this));
} else if (path.endsWith(".counts")) {
CoverageDataSource ds = new GobyCountArchiveDataSource(file);
setDataSource(ds);
igv.postEvent(new RepaintEvent(CoverageTrack.this));
} else {
if(igv != null) MessageUtils.showMessage("Coverage data must be in .tdf format");
}
}
});
item.setEnabled(dataSource == null);
menu.add(item);
}
public void setGlobalAutoScale(boolean globalAutoScale) {
this.globalAutoScale = globalAutoScale;
}
@Override
public void marshalXML(Document document, Element element) {
super.marshalXML(document, element);
element.setAttribute("snpThreshold", String.valueOf(snpThreshold));
}
@Override
public void unmarshalXML(Element element, Integer version) {
super.unmarshalXML(element, version);
if (element.hasAttribute("snpThreshold")) {
snpThreshold = Float.parseFloat(element.getAttribute("snpThreshold"));
}
}
}
|
package org.cactoos.text;
import java.io.IOException;
import org.cactoos.Text;
/**
* Normalize (replace sequences of whitespace characters by a single space)
* a Text.
*
* @author Fabricio Cabral (fabriciofx@gmail.com)
* @version $Id$
* @since 0.9
*/
public final class NormalizedText implements Text {
/**
* The text.
*/
private final Text origin;
/**
* Ctor.
* @param text A Text
*/
public NormalizedText(final String text) {
this(new TextOf(text));
}
/**
* Ctor.
* @param text A Text
*/
public NormalizedText(final Text text) {
this.origin = text;
}
@Override
public String asString() throws IOException {
return new ReplacedText(
new TrimmedText(this.origin),
"\\s+",
" "
).asString();
}
}
|
package org.kohsuke.github;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.infradna.tool.bridge_method_injector.WithBridgeMethods;
import org.apache.commons.lang.StringUtils;
import javax.xml.bind.DatatypeConverter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.InterruptedIOException;
import java.io.Reader;
import java.net.URL;
import java.util.*;
import static java.util.Arrays.asList;
/**
* A repository on GitHub.
*
* @author Kohsuke Kawaguchi
*/
@SuppressWarnings({"UnusedDeclaration"})
public class GHRepository extends GHObject {
/*package almost final*/ GitHub root;
private String description, homepage, name, full_name;
private String html_url; // this is the UI
private String git_url, ssh_url, clone_url, svn_url;
private GHUser owner; // not fully populated. beware.
private boolean has_issues, has_wiki, fork, has_downloads;
@JsonProperty("private")
private boolean _private;
private int watchers,forks,open_issues,size,network_count,subscribers_count;
private String pushed_at;
private Map<Integer,GHMilestone> milestones = new HashMap<Integer, GHMilestone>();
private String default_branch,language;
private Map<String,GHCommit> commits = new HashMap<String, GHCommit>();
private GHRepoPermission permissions;
private GHRepository source;
public GHDeploymentBuilder createDeployment(String ref) {
return new GHDeploymentBuilder(this,ref);
}
public PagedIterable<GHDeploymentStatus> getDeploymentStatuses(final int id) {
return new PagedIterable<GHDeploymentStatus>() {
public PagedIterator<GHDeploymentStatus> iterator() {
return new PagedIterator<GHDeploymentStatus>(root.retrieve().asIterator(getApiTailUrl("deployments")+"/"+id+"/statuses", GHDeploymentStatus[].class)) {
@Override
protected void wrapUp(GHDeploymentStatus[] page) {
for (GHDeploymentStatus c : page)
c.wrap(GHRepository.this);
}
};
}
};
}
public PagedIterable<GHDeployment> listDeployments(String sha,String ref,String task,String environment){
List<String> params = Arrays.asList(getParam("sha", sha), getParam("ref", ref), getParam("task", task), getParam("environment", environment));
final String deploymentsUrl = getApiTailUrl("deployments") + "?"+ join(params,"&");
return new PagedIterable<GHDeployment>() {
public PagedIterator<GHDeployment> iterator() {
return new PagedIterator<GHDeployment>(root.retrieve().asIterator(deploymentsUrl, GHDeployment[].class)) {
@Override
protected void wrapUp(GHDeployment[] page) {
for (GHDeployment c : page)
c.wrap(GHRepository.this);
}
};
}
};
}
private String join(List<String> params, String joinStr) {
StringBuilder output = new StringBuilder();
for(String param: params){
if(param != null){
output.append(param+joinStr);
}
}
return output.toString();
}
private String getParam(String name, String value) {
return StringUtils.trimToNull(value)== null? null: name+"="+value;
}
public GHDeploymentStatusBuilder createDeployStatus(int deploymentId, GHDeploymentState ghDeploymentState) {
return new GHDeploymentStatusBuilder(this,deploymentId,ghDeploymentState);
}
private static class GHRepoPermission {
boolean pull,push,admin;
}
public String getDescription() {
return description;
}
public String getHomepage() {
return homepage;
}
/**
* Gets the git:// URL to this repository, such as "git://github.com/kohsuke/jenkins.git"
* This URL is read-only.
*/
public String getGitTransportUrl() {
return git_url;
}
public String gitHttpTransportUrl() {
return clone_url;
}
public String getSvnUrl() {
return svn_url;
}
/**
* Gets the SSH URL to access this repository, such as git@github.com:rails/rails.git
*/
public String getSshUrl() {
return ssh_url;
}
public String getName() {
return name;
}
public String getFullName() {
return full_name;
}
public boolean hasPullAccess() {
return permissions!=null && permissions.pull;
}
public boolean hasPushAccess() {
return permissions!=null && permissions.push;
}
public boolean hasAdminAccess() {
return permissions!=null && permissions.admin;
}
/**
* Gets the primary programming language.
*/
public String getLanguage() {
return language;
}
public GHUser getOwner() throws IOException {
return root.getUser(owner.login); // because 'owner' isn't fully populated
}
public GHIssue getIssue(int id) throws IOException {
return root.retrieve().to(getApiTailUrl("issues/" + id), GHIssue.class).wrap(this);
}
public GHIssueBuilder createIssue(String title) {
return new GHIssueBuilder(this,title);
}
public List<GHIssue> getIssues(GHIssueState state) throws IOException {
return listIssues(state).asList();
}
public List<GHIssue> getIssues(GHIssueState state, GHMilestone milestone) throws IOException {
return Arrays.asList(GHIssue.wrap(root.retrieve()
.to(getApiTailUrl(String.format("issues?state=%s&milestone=%s",
state.toString().toLowerCase(), milestone == null ? "none" : "" + milestone.getNumber())),
GHIssue[].class
), this));
}
/**
* Lists up all the issues in this repository.
*/
public PagedIterable<GHIssue> listIssues(final GHIssueState state) {
return new PagedIterable<GHIssue>() {
public PagedIterator<GHIssue> iterator() {
return new PagedIterator<GHIssue>(root.retrieve().asIterator(getApiTailUrl("issues?state="+state.toString().toLowerCase(Locale.ENGLISH)), GHIssue[].class)) {
@Override
protected void wrapUp(GHIssue[] page) {
for (GHIssue c : page)
c.wrap(GHRepository.this);
}
};
}
};
}
public GHReleaseBuilder createRelease(String tag) {
return new GHReleaseBuilder(this,tag);
}
/**
* Creates a named ref, such as tag, branch, etc.
*
* @param name
* The name of the fully qualified reference (ie: refs/heads/master).
* If it doesn't start with 'refs' and have at least two slashes, it will be rejected.
* @param sha
* The SHA1 value to set this reference to
*/
public GHRef createRef(String name, String sha) throws IOException {
return new Requester(root)
.with("ref", name).with("sha", sha).method("POST").to(getApiTailUrl("git/refs"), GHRef.class).wrap(root);
}
/**
* @deprecated
* use {@link #listReleases()}
*/
public List<GHRelease> getReleases() throws IOException {
return listReleases().asList();
}
public PagedIterable<GHRelease> listReleases() throws IOException {
return new PagedIterable<GHRelease>() {
public PagedIterator<GHRelease> iterator() {
return new PagedIterator<GHRelease>(root.retrieve().asIterator(getApiTailUrl("releases"), GHRelease[].class)) {
@Override
protected void wrapUp(GHRelease[] page) {
for (GHRelease c : page)
c.wrap(GHRepository.this);
}
};
}
};
}
public PagedIterable<GHTag> listTags() throws IOException {
return new PagedIterable<GHTag>() {
public PagedIterator<GHTag> iterator() {
return new PagedIterator<GHTag>(root.retrieve().asIterator(getApiTailUrl("tags"), GHTag[].class)) {
@Override
protected void wrapUp(GHTag[] page) {
for (GHTag c : page)
c.wrap(GHRepository.this);
}
};
}
};
}
/**
* List languages for the specified repository.
* The value on the right of a language is the number of bytes of code written in that language.
* {
"C": 78769,
"Python": 7769
}
*/
public Map<String,Long> listLanguages() throws IOException {
return root.retrieve().to(getApiTailUrl("languages"), HashMap.class);
}
public String getOwnerName() {
return owner.login;
}
public boolean hasIssues() {
return has_issues;
}
public boolean hasWiki() {
return has_wiki;
}
public boolean isFork() {
return fork;
}
public int getForks() {
return forks;
}
public boolean isPrivate() {
return _private;
}
public boolean hasDownloads() {
return has_downloads;
}
public int getWatchers() {
return watchers;
}
public int getOpenIssueCount() {
return open_issues;
}
public int getNetworkCount() {
return network_count;
}
public int getSubscribersCount() {
return subscribers_count;
}
/**
*
* @return
* null if the repository was never pushed at.
*/
public Date getPushedAt() {
return GitHub.parseDate(pushed_at);
}
/**
* Returns the primary branch you'll configure in the "Admin > Options" config page.
*
* @return
* This field is null until the user explicitly configures the master branch.
*/
public String getMasterBranch() {
return default_branch;
}
public int getSize() {
return size;
}
/**
* Gets the collaborators on this repository.
* This set always appear to include the owner.
*/
@WithBridgeMethods(Set.class)
public GHPersonSet<GHUser> getCollaborators() throws IOException {
return new GHPersonSet<GHUser>(listCollaborators().asList());
}
/**
* Lists up the collaborators on this repository.
*
* @return Users
* @throws IOException
*/
public PagedIterable<GHUser> listCollaborators() throws IOException {
return new PagedIterable<GHUser>() {
public PagedIterator<GHUser> iterator() {
return new PagedIterator<GHUser>(root.retrieve().asIterator(getApiTailUrl("collaborators"), GHUser[].class)) {
@Override
protected void wrapUp(GHUser[] users) {
for (GHUser user : users) {
user.wrapUp(root);
}
}
};
}
};
}
/**
* Gets the names of the collaborators on this repository.
* This method deviates from the principle of this library but it works a lot faster than {@link #getCollaborators()}.
*/
public Set<String> getCollaboratorNames() throws IOException {
Set<String> r = new HashSet<String>();
for (GHUser u : GHUser.wrap(root.retrieve().to(getApiTailUrl("collaborators"), GHUser[].class),root))
r.add(u.login);
return r;
}
/**
* If this repository belongs to an organization, return a set of teams.
*/
public Set<GHTeam> getTeams() throws IOException {
return Collections.unmodifiableSet(new HashSet<GHTeam>(Arrays.asList(GHTeam.wrapUp(root.retrieve().to(getApiTailUrl("teams"), GHTeam[].class), root.getOrganization(owner.login)))));
}
public void addCollaborators(GHUser... users) throws IOException {
addCollaborators(asList(users));
}
public void addCollaborators(Collection<GHUser> users) throws IOException {
modifyCollaborators(users, "PUT");
}
public void removeCollaborators(GHUser... users) throws IOException {
removeCollaborators(asList(users));
}
public void removeCollaborators(Collection<GHUser> users) throws IOException {
modifyCollaborators(users, "DELETE");
}
private void modifyCollaborators(Collection<GHUser> users, String method) throws IOException {
verifyMine();
for (GHUser user : users) {
new Requester(root).method(method).to(getApiTailUrl("collaborators/" + user.getLogin()));
}
}
public void setEmailServiceHook(String address) throws IOException {
Map<String, String> config = new HashMap<String, String>();
config.put("address", address);
new Requester(root).method("POST").with("name", "email").with("config", config).with("active", "true")
.to(getApiTailUrl("hooks"));
}
private void edit(String key, String value) throws IOException {
Requester requester = new Requester(root);
if (!key.equals("name"))
requester.with("name", name); // even when we don't change the name, we need to send it in
requester.with(key, value).method("PATCH").to(getApiTailUrl(""));
}
/**
* Enables or disables the issue tracker for this repository.
*/
public void enableIssueTracker(boolean v) throws IOException {
edit("has_issues", String.valueOf(v));
}
/**
* Enables or disables Wiki for this repository.
*/
public void enableWiki(boolean v) throws IOException {
edit("has_wiki", String.valueOf(v));
}
public void enableDownloads(boolean v) throws IOException {
edit("has_downloads",String.valueOf(v));
}
/**
* Rename this repository.
*/
public void renameTo(String name) throws IOException {
edit("name",name);
}
public void setDescription(String value) throws IOException {
edit("description",value);
}
public void setHomepage(String value) throws IOException {
edit("homepage",value);
}
/**
* Deletes this repository.
*/
public void delete() throws IOException {
try {
new Requester(root).method("DELETE").to(getApiTailUrl(""));
} catch (FileNotFoundException x) {
throw (FileNotFoundException) new FileNotFoundException("Failed to delete " + owner.login + "/" + name + "; might not exist, or you might need the delete_repo scope in your token: http://stackoverflow.com/a/19327004/12916").initCause(x);
}
}
/**
* Forks this repository as your repository.
*
* @return
* Newly forked repository that belong to you.
*/
public GHRepository fork() throws IOException {
return new Requester(root).method("POST").to(getApiTailUrl("forks"), GHRepository.class).wrap(root);
}
/**
* Forks this repository into an organization.
*
* @return
* Newly forked repository that belong to you.
*/
public GHRepository forkTo(GHOrganization org) throws IOException {
new Requester(root).to(getApiTailUrl("forks?org="+org.getLogin()));
// this API is asynchronous. we need to wait for a bit
for (int i=0; i<10; i++) {
GHRepository r = org.getRepository(name);
if (r!=null) return r;
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
throw (IOException)new InterruptedIOException().initCause(e);
}
}
throw new IOException(this+" was forked into "+org.getLogin()+" but can't find the new repository");
}
/**
* Retrieves a specified pull request.
*/
public GHPullRequest getPullRequest(int i) throws IOException {
return root.retrieve().to(getApiTailUrl("pulls/" + i), GHPullRequest.class).wrapUp(this);
}
/**
* Retrieves all the pull requests of a particular state.
*
* @see #listPullRequests(GHIssueState)
*/
public List<GHPullRequest> getPullRequests(GHIssueState state) throws IOException {
return listPullRequests(state).asList();
}
/**
* Retrieves all the pull requests of a particular state.
*/
public PagedIterable<GHPullRequest> listPullRequests(final GHIssueState state) {
return new PagedIterable<GHPullRequest>() {
public PagedIterator<GHPullRequest> iterator() {
return new PagedIterator<GHPullRequest>(root.retrieve().asIterator(getApiTailUrl("pulls?state="+state.name().toLowerCase(Locale.ENGLISH)), GHPullRequest[].class)) {
@Override
protected void wrapUp(GHPullRequest[] page) {
for (GHPullRequest pr : page)
pr.wrapUp(GHRepository.this);
}
};
}
};
}
/**
* Creates a new pull request.
*
* @param title
* Required. The title of the pull request.
* @param head
* Required. The name of the branch where your changes are implemented.
* For cross-repository pull requests in the same network,
* namespace head with a user like this: username:branch.
* @param base
* Required. The name of the branch you want your changes pulled into.
* This should be an existing branch on the current repository.
* @param body
* The contents of the pull request. This is the markdown description
* of a pull request.
*/
public GHPullRequest createPullRequest(String title, String head, String base, String body) throws IOException {
return new Requester(root).with("title",title)
.with("head",head)
.with("base",base)
.with("body",body).to(getApiTailUrl("pulls"),GHPullRequest.class).wrapUp(this);
}
/**
* Retrieves the currently configured hooks.
*/
public List<GHHook> getHooks() throws IOException {
List<GHHook> list = new ArrayList<GHHook>(Arrays.asList(
root.retrieve().to(getApiTailUrl("hooks"), GHHook[].class)));
for (GHHook h : list)
h.wrap(this);
return list;
}
public GHHook getHook(int id) throws IOException {
return root.retrieve().to(getApiTailUrl("hooks/" + id), GHHook.class).wrap(this);
}
/**
* Gets a comparison between 2 points in the repository. This would be similar
* to calling <tt>git log id1...id2</tt> against a local repository.
* @param id1 an identifier for the first point to compare from, this can be a sha1 ID (for a commit, tag etc) or a direct tag name
* @param id2 an identifier for the second point to compare to. Can be the same as the first point.
* @return the comparison output
* @throws IOException on failure communicating with GitHub
*/
public GHCompare getCompare(String id1, String id2) throws IOException {
GHCompare compare = root.retrieve().to(getApiTailUrl(String.format("compare/%s...%s", id1, id2)), GHCompare.class);
return compare.wrap(this);
}
public GHCompare getCompare(GHCommit id1, GHCommit id2) throws IOException {
return getCompare(id1.getSHA1(), id2.getSHA1());
}
public GHCompare getCompare(GHBranch id1, GHBranch id2) throws IOException {
return getCompare(id1.getName(),id2.getName());
}
/**
* Retrieves all refs for the github repository.
* @return an array of GHRef elements coresponding with the refs in the remote repository.
* @throws IOException on failure communicating with GitHub
*/
public GHRef[] getRefs() throws IOException {
return GHRef.wrap(root.retrieve().to(String.format("/repos/%s/%s/git/refs", owner.login, name), GHRef[].class),root);
}
/**
* Retrieves all refs of the given type for the current GitHub repository.
* @param refType the type of reg to search for e.g. <tt>tags</tt> or <tt>commits</tt>
* @return an array of all refs matching the request type
* @throws IOException on failure communicating with GitHub, potentially due to an invalid ref type being requested
*/
public GHRef[] getRefs(String refType) throws IOException {
return GHRef.wrap(root.retrieve().to(String.format("/repos/%s/%s/git/refs/%s", owner.login, name, refType), GHRef[].class),root);
}
/**
* Retrive a ref of the given type for the current GitHub repository.
*
* @param refName
* eg: heads/branch
* @return refs matching the request type
* @throws IOException
* on failure communicating with GitHub, potentially due to an
* invalid ref type being requested
*/
public GHRef getRef(String refName) throws IOException {
return root.retrieve().to(String.format("/repos/%s/%s/git/refs/%s", owner.login, name, refName), GHRef.class).wrap(root);
}
/**
* Retrive a tree of the given type for the current GitHub repository.
*
* @param sha - sha number or branch name ex: "master"
* @return refs matching the request type
* @throws IOException
* on failure communicating with GitHub, potentially due to an
* invalid tree type being requested
*/
public GHTree getTree(String sha) throws IOException {
String url = String.format("/repos/%s/%s/git/trees/%s", owner.login, name, sha);
return root.retrieve().to(url, GHTree.class).wrap(root);
}
public GHTree getTreeRecursive(String sha, int recursive) throws IOException {
String url = String.format("/repos/%s/%s/git/trees/%s?recursive=%d", owner.login, name, sha, recursive);
return root.retrieve().to(url, GHTree.class).wrap(root);
}
/**
* Gets a commit object in this repository.
*/
public GHCommit getCommit(String sha1) throws IOException {
GHCommit c = commits.get(sha1);
if (c==null) {
c = root.retrieve().to(String.format("/repos/%s/%s/commits/%s", owner.login, name, sha1), GHCommit.class).wrapUp(this);
commits.put(sha1,c);
}
return c;
}
/**
* Lists all the commits.
*/
public PagedIterable<GHCommit> listCommits() {
return new PagedIterable<GHCommit>() {
public PagedIterator<GHCommit> iterator() {
return new PagedIterator<GHCommit>(root.retrieve().asIterator(String.format("/repos/%s/%s/commits", owner.login, name), GHCommit[].class)) {
protected void wrapUp(GHCommit[] page) {
for (GHCommit c : page)
c.wrapUp(GHRepository.this);
}
};
}
};
}
/**
* Search commits by specifying filters through a builder pattern.
*/
public GHCommitQueryBuilder queryCommits() {
return new GHCommitQueryBuilder(this);
}
/**
* Lists up all the commit comments in this repository.
*/
public PagedIterable<GHCommitComment> listCommitComments() {
return new PagedIterable<GHCommitComment>() {
public PagedIterator<GHCommitComment> iterator() {
return new PagedIterator<GHCommitComment>(root.retrieve().asIterator(String.format("/repos/%s/%s/comments", owner.login, name), GHCommitComment[].class)) {
@Override
protected void wrapUp(GHCommitComment[] page) {
for (GHCommitComment c : page)
c.wrap(GHRepository.this);
}
};
}
};
}
/**
* Lists all the commit statues attached to the given commit, newer ones first.
*/
public PagedIterable<GHCommitStatus> listCommitStatuses(final String sha1) throws IOException {
return new PagedIterable<GHCommitStatus>() {
public PagedIterator<GHCommitStatus> iterator() {
return new PagedIterator<GHCommitStatus>(root.retrieve().asIterator(String.format("/repos/%s/%s/statuses/%s", owner.login, name, sha1), GHCommitStatus[].class)) {
@Override
protected void wrapUp(GHCommitStatus[] page) {
for (GHCommitStatus c : page)
c.wrapUp(root);
}
};
}
};
}
/**
* Gets the last status of this commit, which is what gets shown in the UI.
*/
public GHCommitStatus getLastCommitStatus(String sha1) throws IOException {
List<GHCommitStatus> v = listCommitStatuses(sha1).asList();
return v.isEmpty() ? null : v.get(0);
}
/**
* Creates a commit status
*
* @param targetUrl
* Optional parameter that points to the URL that has more details.
* @param description
* Optional short description.
* @param context
* Optinal commit status context.
*/
public GHCommitStatus createCommitStatus(String sha1, GHCommitState state, String targetUrl, String description, String context) throws IOException {
return new Requester(root)
.with("state", state.name().toLowerCase(Locale.ENGLISH))
.with("target_url", targetUrl)
.with("description", description)
.with("context", context)
.to(String.format("/repos/%s/%s/statuses/%s",owner.login,this.name,sha1),GHCommitStatus.class).wrapUp(root);
}
/**
* @see {@link #createCommitStatus(String, GHCommitState,String,String,String) createCommitStatus}
*/
public GHCommitStatus createCommitStatus(String sha1, GHCommitState state, String targetUrl, String description) throws IOException {
return createCommitStatus(sha1, state, targetUrl, description,null);
}
/**
* Lists repository events.
*/
public PagedIterable<GHEventInfo> listEvents() throws IOException {
return new PagedIterable<GHEventInfo>() {
public PagedIterator<GHEventInfo> iterator() {
return new PagedIterator<GHEventInfo>(root.retrieve().asIterator(String.format("/repos/%s/%s/events", owner.login, name), GHEventInfo[].class)) {
@Override
protected void wrapUp(GHEventInfo[] page) {
for (GHEventInfo c : page)
c.wrapUp(root);
}
};
}
};
}
public PagedIterable<GHLabel> listLabels() throws IOException {
return new PagedIterable<GHLabel>() {
public PagedIterator<GHLabel> iterator() {
return new PagedIterator<GHLabel>(root.retrieve().asIterator(getApiTailUrl("labels"), GHLabel[].class)) {
@Override
protected void wrapUp(GHLabel[] page) {
for (GHLabel c : page)
c.wrapUp(GHRepository.this);
}
};
}
};
}
public GHLabel getLabel(String name) throws IOException {
return root.retrieve().to(getApiTailUrl("labels/"+name), GHLabel.class).wrapUp(this);
}
public GHLabel createLabel(String name, String color) throws IOException {
return root.retrieve().method("POST")
.with("name",name)
.with("color",color)
.to(getApiTailUrl("labels"), GHLabel.class).wrapUp(this);
}
public PagedIterable<GHUser> listSubscribers() {
return new PagedIterable<GHUser>() {
public PagedIterator<GHUser> iterator() {
return new PagedIterator<GHUser>(root.retrieve().asIterator(getApiTailUrl("subscribers"), GHUser[].class)) {
protected void wrapUp(GHUser[] page) {
for (GHUser c : page)
c.wrapUp(root);
}
};
}
};
}
public GHHook createHook(String name, Map<String,String> config, Collection<GHEvent> events, boolean active) throws IOException {
List<String> ea = null;
if (events!=null) {
ea = new ArrayList<String>();
for (GHEvent e : events)
ea.add(e.name().toLowerCase(Locale.ENGLISH));
}
return new Requester(root)
.with("name", name)
.with("active", active)
._with("config", config)
._with("events",ea)
.to(String.format("/repos/%s/%s/hooks",owner.login,this.name),GHHook.class).wrap(this);
}
public GHHook createWebHook(URL url, Collection<GHEvent> events) throws IOException {
return createHook("web",Collections.singletonMap("url",url.toExternalForm()),events,true);
}
public GHHook createWebHook(URL url) throws IOException {
return createWebHook(url,null);
}
// this is no different from getPullRequests(OPEN)
// /**
// * Retrieves all the pull requests.
// */
// public List<GHPullRequest> getPullRequests() throws IOException {
// return root.retrieveWithAuth("/pulls/"+owner+'/'+name,JsonPullRequests.class).wrap(root);
private void verifyMine() throws IOException {
if (!root.login.equals(owner.login))
throw new IOException("Operation not applicable to a repository owned by someone else: "+owner.login);
}
/**
* Returns a set that represents the post-commit hook URLs.
* The returned set is live, and changes made to them are reflected to GitHub.
*
* @deprecated
* Use {@link #getHooks()} and {@link #createHook(String, Map, Collection, boolean)}
*/
public Set<URL> getPostCommitHooks() {
return postCommitHooks;
}
/**
* Live set view of the post-commit hook.
*/
private final Set<URL> postCommitHooks = new AbstractSet<URL>() {
private List<URL> getPostCommitHooks() {
try {
List<URL> r = new ArrayList<URL>();
for (GHHook h : getHooks()) {
if (h.getName().equals("web")) {
r.add(new URL(h.getConfig().get("url")));
}
}
return r;
} catch (IOException e) {
throw new GHException("Failed to retrieve post-commit hooks",e);
}
}
@Override
public Iterator<URL> iterator() {
return getPostCommitHooks().iterator();
}
@Override
public int size() {
return getPostCommitHooks().size();
}
@Override
public boolean add(URL url) {
try {
createWebHook(url);
return true;
} catch (IOException e) {
throw new GHException("Failed to update post-commit hooks",e);
}
}
@Override
public boolean remove(Object url) {
try {
String _url = ((URL)url).toExternalForm();
for (GHHook h : getHooks()) {
if (h.getName().equals("web") && h.getConfig().get("url").equals(_url)) {
h.delete();
return true;
}
}
return false;
} catch (IOException e) {
throw new GHException("Failed to update post-commit hooks",e);
}
}
};
/*package*/ GHRepository wrap(GitHub root) {
this.root = root;
return this;
}
/**
* Gets branches by {@linkplain GHBranch#getName() their names}.
*/
public Map<String,GHBranch> getBranches() throws IOException {
Map<String,GHBranch> r = new TreeMap<String,GHBranch>();
for (GHBranch p : root.retrieve().to(getApiTailUrl("branches"), GHBranch[].class)) {
p.wrap(this);
r.put(p.getName(),p);
}
return r;
}
/**
* @deprecated
* Use {@link #listMilestones(GHIssueState)}
*/
public Map<Integer, GHMilestone> getMilestones() throws IOException {
Map<Integer,GHMilestone> milestones = new TreeMap<Integer, GHMilestone>();
for (GHMilestone m : listMilestones(GHIssueState.OPEN)) {
milestones.put(m.getNumber(), m);
}
return milestones;
}
/**
* Lists up all the milestones in this repository.
*/
public PagedIterable<GHMilestone> listMilestones(final GHIssueState state) {
return new PagedIterable<GHMilestone>() {
public PagedIterator<GHMilestone> iterator() {
return new PagedIterator<GHMilestone>(root.retrieve().asIterator(getApiTailUrl("milestones?state="+state.toString().toLowerCase(Locale.ENGLISH)), GHMilestone[].class)) {
@Override
protected void wrapUp(GHMilestone[] page) {
for (GHMilestone c : page)
c.wrap(GHRepository.this);
}
};
}
};
}
public GHMilestone getMilestone(int number) throws IOException {
GHMilestone m = milestones.get(number);
if (m == null) {
m = root.retrieve().to(getApiTailUrl("milestones/" + number), GHMilestone.class);
m.owner = this;
m.root = root;
milestones.put(m.getNumber(), m);
}
return m;
}
public GHContent getFileContent(String path) throws IOException {
return getFileContent(path, null);
}
public GHContent getFileContent(String path, String ref) throws IOException {
Requester requester = root.retrieve();
String target = getApiTailUrl("contents/" + path);
return requester.with("ref",ref).to(target, GHContent.class).wrap(this);
}
public List<GHContent> getDirectoryContent(String path) throws IOException {
return getDirectoryContent(path, null);
}
public List<GHContent> getDirectoryContent(String path, String ref) throws IOException {
Requester requester = root.retrieve();
String target = getApiTailUrl("contents/" + path);
GHContent[] files = requester.with("ref",ref).to(target, GHContent[].class);
GHContent.wrap(files, this);
return Arrays.asList(files);
}
public GHContent getReadme() throws IOException {
Requester requester = root.retrieve();
return requester.to(getApiTailUrl("readme"), GHContent.class).wrap(this);
}
public GHContentUpdateResponse createContent(String content, String commitMessage, String path) throws IOException {
return createContent(content.getBytes(), commitMessage, path, null);
}
public GHContentUpdateResponse createContent(String content, String commitMessage, String path, String branch) throws IOException {
return createContent(content.getBytes(), commitMessage, path, branch);
}
public GHContentUpdateResponse createContent(byte[] contentBytes, String commitMessage, String path) throws IOException {
return createContent(contentBytes, commitMessage, path, null);
}
public GHContentUpdateResponse createContent(byte[] contentBytes, String commitMessage, String path, String branch) throws IOException {
Requester requester = new Requester(root)
.with("path", path)
.with("message", commitMessage)
.with("content", DatatypeConverter.printBase64Binary(contentBytes))
.method("PUT");
if (branch != null) {
requester.with("branch", branch);
}
GHContentUpdateResponse response = requester.to(getApiTailUrl("contents/" + path), GHContentUpdateResponse.class);
response.getContent().wrap(this);
response.getCommit().wrapUp(this);
return response;
}
public GHMilestone createMilestone(String title, String description) throws IOException {
return new Requester(root)
.with("title", title).with("description", description).method("POST").to(getApiTailUrl("milestones"), GHMilestone.class).wrap(this);
}
public GHDeployKey addDeployKey(String title,String key) throws IOException {
return new Requester(root)
.with("title", title).with("key", key).method("POST").to(getApiTailUrl("keys"), GHDeployKey.class).wrap(this);
}
public List<GHDeployKey> getDeployKeys() throws IOException{
List<GHDeployKey> list = new ArrayList<GHDeployKey>(Arrays.asList(
root.retrieve().to(getApiTailUrl("keys"), GHDeployKey[].class)));
for (GHDeployKey h : list)
h.wrap(this);
return list;
}
/**
* Forked repositories have a 'source' attribute that specifies the repository they were forked
* from.
* @return The GHRepository instance from the fork source, or null if this
* GHRepository isn't a fork.
*/
public GHRepository getSource() {
return source;
}
/**
* Subscribes to this repository to get notifications.
*/
public GHSubscription subscribe(boolean subscribed, boolean ignored) throws IOException {
return new Requester(root)
.with("subscribed", subscribed)
.with("ignored", ignored)
.method("PUT").to(getApiTailUrl("subscription"), GHSubscription.class).wrapUp(this);
}
/**
* Returns the current subscription.
*
* @return null if no subscription exists.
*/
public GHSubscription getSubscription() throws IOException {
try {
return new Requester(root).to(getApiTailUrl("subscription"), GHSubscription.class).wrapUp(this);
} catch (FileNotFoundException e) {
return null;
}
}
public PagedIterable<Contributor> listContributors() throws IOException {
return new PagedIterable<Contributor>() {
public PagedIterator<Contributor> iterator() {
return new PagedIterator<Contributor>(root.retrieve().asIterator(getApiTailUrl("contributors"), Contributor[].class)) {
@Override
protected void wrapUp(Contributor[] page) {
for (Contributor c : page)
c.wrapUp(root);
}
};
}
};
}
public static class Contributor extends GHUser {
private int contributions;
public int getContributions() {
return contributions;
}
}
/**
* Render a Markdown document.
*
* In {@linkplain MarkdownMode#GFM GFM mode}, issue numbers and user mentions
* are linked accordingly.
*
* @see GitHub#renderMarkdown(String)
*/
public Reader renderMarkdown(String text, MarkdownMode mode) throws IOException {
return new InputStreamReader(
new Requester(root)
.with("text", text)
.with("mode",mode==null?null:mode.toString())
.with("context", getFullName())
.asStream("/markdown"),
"UTF-8");
}
/**
* List all the notifications in a repository for the current user.
*/
public GHNotificationStream listNotifications() {
return new GHNotificationStream(root,getApiTailUrl("/notifications"));
}
@Override
public String toString() {
return "Repository:"+owner.login+":"+name;
}
@Override
public int hashCode() {
return toString().hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj instanceof GHRepository) {
GHRepository that = (GHRepository) obj;
return this.owner.login.equals(that.owner.login)
&& this.name.equals(that.name);
}
return false;
}
String getApiTailUrl(String tail) {
if (tail.length()>0 && !tail.startsWith("/")) tail='/'+tail;
return "/repos/" + owner.login + "/" + name +tail;
}
}
|
package org.lightmare.deploy.fs;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchEvent.Kind;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.log4j.Logger;
import org.lightmare.cache.ConnectionContainer;
import org.lightmare.cache.DeploymentDirectory;
import org.lightmare.cache.MetaContainer;
import org.lightmare.cache.RestContainer;
import org.lightmare.config.Configuration;
import org.lightmare.jpa.datasource.FileParsers;
import org.lightmare.jpa.datasource.Initializer;
import org.lightmare.rest.providers.RestProvider;
import org.lightmare.utils.CollectionUtils;
import org.lightmare.utils.LogUtils;
import org.lightmare.utils.ObjectUtils;
import org.lightmare.utils.concurrent.ThreadFactoryUtil;
import org.lightmare.utils.fs.WatchUtils;
/**
* Deployment manager, {@link Watcher#deployFile(URL)},
* {@link Watcher#undeployFile(URL)}, {@link Watcher#listDeployments()} and
* {@link File} modification event handler for deployments if java version is
* 1.7 or above
*
* @author levan
* @since 0.0.45-SNAPSHOT
*/
public class Watcher implements Runnable {
private static final String DEPLOY_THREAD_NAME = "watch_thread";
private static final int DEPLOY_POOL_PRIORITY = Thread.MAX_PRIORITY - 5;
private static final long SLEEP_TIME = 5500L;
private static final ExecutorService DEPLOY_POOL = Executors
.newSingleThreadExecutor(new ThreadFactoryUtil(DEPLOY_THREAD_NAME,
DEPLOY_POOL_PRIORITY));
private Set<DeploymentDirectory> deployments;
private Set<String> dataSources;
private static final Logger LOG = Logger.getLogger(Watcher.class);
/**
* Defines file types for watch service
*
* @author Levan
* @since 0.0.45-SNAPSHOT
*/
private static enum WatchFileType {
DATA_SOURCE, DEPLOYMENT, NONE;
}
/**
* To filter only deployed sub files from directory
*
* @author levan
* @since 0.0.45-SNAPSHOT
*/
private static class DeployFiletr implements FileFilter {
@Override
public boolean accept(File file) {
boolean accept;
try {
URL url = file.toURI().toURL();
url = WatchUtils.clearURL(url);
accept = MetaContainer.chackDeployment(url);
} catch (MalformedURLException ex) {
LOG.error(ex.getMessage(), ex);
accept = false;
} catch (IOException ex) {
LOG.error(ex.getMessage(), ex);
accept = false;
}
return accept;
}
}
private Watcher() {
deployments = getDeployDirectories();
dataSources = getDataSourcePaths();
}
/**
* Clears and gets file {@link URL} by file name
*
* @param fileName
* @return {@link URL}
* @throws IOException
*/
private static URL getAppropriateURL(String fileName) throws IOException {
File file = new File(fileName);
URL url = file.toURI().toURL();
url = WatchUtils.clearURL(url);
return url;
}
/**
* Gets {@link Set} of {@link DeploymentDirectory} instances from
* configuration
*
* @return {@link Set}<code><DeploymentDirectory></code>
*/
private static Set<DeploymentDirectory> getDeployDirectories() {
Collection<Configuration> configs = MetaContainer.CONFIGS.values();
Set<DeploymentDirectory> deploymetDirss = new HashSet<DeploymentDirectory>();
Set<DeploymentDirectory> deploymetDirssCurrent;
for (Configuration config : configs) {
deploymetDirssCurrent = config.getDeploymentPath();
if (config.isWatchStatus()
&& CollectionUtils.valid(deploymetDirssCurrent)) {
deploymetDirss.addAll(deploymetDirssCurrent);
}
}
return deploymetDirss;
}
/**
* Gets {@link Set} of data source paths from configuration
*
* @return {@link Set}<code><String></code>
*/
private static Set<String> getDataSourcePaths() {
Collection<Configuration> configs = MetaContainer.CONFIGS.values();
Set<String> paths = new HashSet<String>();
Set<String> pathsCurrent;
for (Configuration config : configs) {
pathsCurrent = config.getDataSourcePath();
if (config.isWatchStatus() && CollectionUtils.valid(pathsCurrent)) {
paths.addAll(pathsCurrent);
}
}
return paths;
}
/**
* Checks and gets appropriated {@link WatchFileType} by passed file name
*
* @param fileName
* @return {@link WatchFileType}
*/
private static WatchFileType checkType(String fileName) {
WatchFileType type;
File file = new File(fileName);
String path = file.getPath();
String filePath = WatchUtils.clearPath(path);
path = file.getParent();
String parentPath = WatchUtils.clearPath(path);
Set<DeploymentDirectory> apps = getDeployDirectories();
Set<String> dss = getDataSourcePaths();
if (CollectionUtils.valid(apps)) {
String deploymantPath;
Iterator<DeploymentDirectory> iterator = apps.iterator();
boolean notDeployment = Boolean.TRUE;
DeploymentDirectory deployment;
while (iterator.hasNext() && notDeployment) {
deployment = iterator.next();
deploymantPath = deployment.getPath();
notDeployment = ObjectUtils.notEquals(deploymantPath,
parentPath);
}
if (notDeployment) {
type = WatchFileType.NONE;
} else {
type = WatchFileType.DEPLOYMENT;
}
} else if (CollectionUtils.valid(dss) && dss.contains(filePath)) {
type = WatchFileType.DATA_SOURCE;
} else {
type = WatchFileType.NONE;
}
return type;
}
private static void fillFileList(File[] files, List<File> list) {
if (CollectionUtils.valid(files)) {
for (File file : files) {
list.add(file);
}
}
}
/**
* Lists all deployed {@link File}s
*
* @return {@link List}<File>
*/
public static List<File> listDeployments() {
Collection<Configuration> configs = MetaContainer.CONFIGS.values();
Set<DeploymentDirectory> deploymetDirss = new HashSet<DeploymentDirectory>();
Set<DeploymentDirectory> deploymetDirssCurrent;
for (Configuration config : configs) {
deploymetDirssCurrent = config.getDeploymentPath();
if (CollectionUtils.valid(deploymetDirssCurrent)) {
deploymetDirss.addAll(deploymetDirssCurrent);
}
}
File[] files;
List<File> list = new ArrayList<File>();
if (CollectionUtils.valid(deploymetDirss)) {
String path;
DeployFiletr filter = new DeployFiletr();
for (DeploymentDirectory deployment : deploymetDirss) {
path = deployment.getPath();
files = new File(path).listFiles(filter);
fillFileList(files, list);
}
}
return list;
}
/**
* Lists all data source {@link File}s
*
* @return {@link List}<File>
*/
public static List<File> listDataSources() {
Collection<Configuration> configs = MetaContainer.CONFIGS.values();
Set<String> paths = new HashSet<String>();
Set<String> pathsCurrent;
for (Configuration config : configs) {
pathsCurrent = config.getDataSourcePath();
if (CollectionUtils.valid(pathsCurrent)) {
paths.addAll(pathsCurrent);
}
}
File file;
List<File> list = new ArrayList<File>();
if (CollectionUtils.valid(paths)) {
for (String path : paths) {
file = new File(path);
list.add(file);
}
}
return list;
}
/**
* Deploys application or data source file by passed file name
*
* @param fileName
* @throws IOException
*/
public static void deployFile(String fileName) throws IOException {
WatchFileType type = checkType(fileName);
if (type.equals(WatchFileType.DATA_SOURCE)) {
FileParsers fileParsers = new FileParsers();
fileParsers.parseStandaloneXml(fileName);
} else if (type.equals(WatchFileType.DEPLOYMENT)) {
URL url = getAppropriateURL(fileName);
deployFile(url);
}
}
/**
* Deploys application or data source file by passed {@link URL} instance
*
* @param url
* @throws IOException
*/
public static void deployFile(URL url) throws IOException {
URL[] archives = { url };
MetaContainer.getCreator().scanForBeans(archives);
}
/**
* Removes from deployments application or data source file by passed
* {@link URL} instance
*
* @param url
* @throws IOException
*/
public static void undeployFile(URL url) throws IOException {
boolean valid = MetaContainer.undeploy(url);
if (valid && RestContainer.hasRest()) {
RestProvider.reload();
}
}
/**
* Removes from deployments application or data source file by passed file
* name
*
* @param fileName
* @throws IOException
*/
public static void undeployFile(String fileName) throws IOException {
WatchFileType type = checkType(fileName);
if (type.equals(WatchFileType.DATA_SOURCE)) {
Initializer.undeploy(fileName);
} else if (type.equals(WatchFileType.DEPLOYMENT)) {
URL url = getAppropriateURL(fileName);
undeployFile(url);
}
}
/**
* Removes from deployments and deploys again application or data source
* file by passed file name
*
* @param fileName
* @throws IOException
*/
public static void redeployFile(String fileName) throws IOException {
undeployFile(fileName);
deployFile(fileName);
}
/**
* Handles file change event
*
* @param dir
* @param currentEvent
* @throws IOException
*/
private void handleEvent(Path dir, WatchEvent<Path> currentEvent)
throws IOException {
if (ObjectUtils.notNull(currentEvent)) {
Path prePath = currentEvent.context();
Path path = dir.resolve(prePath);
String fileName = path.toString();
int count = currentEvent.count();
Kind<?> kind = currentEvent.kind();
if (kind == StandardWatchEventKinds.ENTRY_MODIFY) {
LogUtils.info(LOG, "Modify: %s, count: %s\n", fileName, count);
redeployFile(fileName);
} else if (kind == StandardWatchEventKinds.ENTRY_DELETE) {
LogUtils.info(LOG, "Delete: %s, count: %s\n", fileName, count);
undeployFile(fileName);
} else if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
LogUtils.info(LOG, "Create: %s, count: %s\n", fileName, count);
redeployFile(fileName);
}
}
}
/**
* Runs file watch service
*
* @param watch
* @throws IOException
*/
private void runService(WatchService watch) throws IOException {
Path dir;
boolean toRun = true;
boolean valid;
while (toRun) {
try {
WatchKey key;
key = watch.take();
List<WatchEvent<?>> events = key.pollEvents();
WatchEvent<?> currentEvent = null;
WatchEvent<Path> typedCurrentEvent;
int times = 0;
dir = (Path) key.watchable();
for (WatchEvent<?> event : events) {
if (event.kind() == StandardWatchEventKinds.OVERFLOW) {
continue;
}
if (times == 0 || event.count() > currentEvent.count()) {
currentEvent = event;
}
times++;
valid = key.reset();
toRun = valid && key.isValid();
if (toRun) {
Thread.sleep(SLEEP_TIME);
typedCurrentEvent = ObjectUtils.cast(currentEvent);
handleEvent(dir, typedCurrentEvent);
}
}
} catch (InterruptedException ex) {
throw new IOException(ex);
}
}
}
private void registerPath(FileSystem fs, String path, WatchService watch)
throws IOException {
Path deployPath = fs.getPath(path);
deployPath.register(watch, StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_MODIFY,
StandardWatchEventKinds.OVERFLOW,
StandardWatchEventKinds.ENTRY_DELETE);
runService(watch);
}
private void registerPaths(File[] files, FileSystem fs, WatchService watch)
throws IOException {
String path;
for (File file : files) {
path = file.getPath();
registerPath(fs, path, watch);
}
}
private void registerPaths(Collection<DeploymentDirectory> deploymentDirss,
FileSystem fs, WatchService watch) throws IOException {
String path;
boolean scan;
File directory;
File[] files;
for (DeploymentDirectory deployment : deploymentDirss) {
path = deployment.getPath();
scan = deployment.isScan();
if (scan) {
directory = new File(path);
files = directory.listFiles();
if (CollectionUtils.valid(files)) {
registerPaths(files, fs, watch);
}
} else {
registerPath(fs, path, watch);
}
}
}
private void registerDsPaths(Collection<String> paths, FileSystem fs,
WatchService watch) throws IOException {
for (String path : paths) {
registerPath(fs, path, watch);
}
}
@Override
public void run() {
try {
FileSystem fs = FileSystems.getDefault();
WatchService watch = null;
try {
watch = fs.newWatchService();
} catch (IOException ex) {
LOG.error(ex.getMessage(), ex);
throw ex;
}
if (CollectionUtils.valid(deployments)) {
registerPaths(deployments, fs, watch);
}
if (CollectionUtils.valid(dataSources)) {
registerDsPaths(dataSources, fs, watch);
}
} catch (IOException ex) {
LOG.fatal(ex.getMessage(), ex);
LOG.fatal("system going to shut down cause of hot deployment");
try {
ConnectionContainer.closeConnections();
} catch (IOException iex) {
LOG.fatal(iex.getMessage(), iex);
}
System.exit(-1);
} finally {
DEPLOY_POOL.shutdown();
}
}
/**
* Starts watch service for application and data source files
*/
public static void startWatch() {
Watcher watcher = new Watcher();
DEPLOY_POOL.submit(watcher);
}
}
|
package org.lightmare.utils;
import org.lightmare.config.Configuration;
/**
* Utility class for JNDI names
*
* @author levan
*
*/
public class NamingUtils {
public static final String USER_TRANSACTION_NAME = "java:comp/UserTransaction";
public static final String CONNECTION_NAME_PREF = "java:comp/env/";
public static final String EJB_NAME_PREF = "ejb:";
private static final String DS_JNDI_FREFIX = "java:/";
/**
* Descriptor class which contains EJB bean class name and its interface
* class name
*
* @author levan
*
*/
public static class BeanDescriptor {
private String beanName;
private String interfaceName;
public BeanDescriptor(String beanName, String interfaceName) {
this.beanName = beanName;
this.interfaceName = interfaceName;
}
public String getBeanName() {
return beanName;
}
public void setBeanName(String beanName) {
this.beanName = beanName;
}
public String getInterfaceName() {
return interfaceName;
}
public void setInterfaceName(String interfaceName) {
this.interfaceName = interfaceName;
}
}
/**
* Creates JNDI name prefixes for EJB objects
*
* @param jndiName
* @return
*/
public static String createJpaJndiName(String jndiName) {
return String.format("%s%s", Configuration.JPA_NAME, jndiName);
}
/**
* Converts passed JNDI name to JPA name
*
* @param jndiName
* @return {@link String}
*/
public static String formatJpaJndiName(String jndiName) {
String name = jndiName.replace(Configuration.JPA_NAME, "");
return name;
}
/**
* Creates EJB names from passed JNDI name
*
* @param jndiName
* @return {@link String}
*/
public static String createEjbJndiName(String jndiName) {
return String.format("%s%s", Configuration.EJB_NAME, jndiName);
}
/**
* Converts passed JNDI name to bean name
*
* @param jndiName
* @return {@link String}
*/
public static String formatEjbJndiName(String jndiName) {
String name = jndiName.replace(Configuration.EJB_NAME, "");
return name;
}
/**
* Clears JNDI prefix "java:/" for data source name
*
* @param jndiName
* @return {@link String}
*/
public static String clearDataSourceName(String jndiName) {
String clearName;
if (ObjectUtils.available(jndiName)
&& jndiName.startsWith(DS_JNDI_FREFIX)) {
clearName = jndiName.replace(DS_JNDI_FREFIX,
ObjectUtils.EMPTY_STRING);
} else {
clearName = jndiName;
}
return clearName;
}
/**
* Adds JNDI prefix "java:/" to data source name
*
* @param clearName
* @return {@link String}
*/
public static String toJndiDataSourceName(String clearName) {
String jndiName;
if (ObjectUtils.available(clearName)
&& ObjectUtils.notTrue(clearName.contains(DS_JNDI_FREFIX))) {
jndiName = new StringBuilder().append(DS_JNDI_FREFIX)
.append(clearName).toString();
} else {
jndiName = clearName;
}
return jndiName;
}
/**
* Parses bean JNDI name for lookup bean
*
* @param jndiName
* @return {@link BeanDescriptor}
*/
public static BeanDescriptor parseEjbJndiName(String jndiName) {
String pureName = jndiName.substring(Configuration.EJB_NAME_LENGTH);
String[] formatedNames = pureName.split("\\");
String beanNames = formatedNames[1];
String[] beanDescriptors = beanNames.split("!");
String interfaceName = beanDescriptors[0];
String beanName = beanDescriptors[1];
BeanDescriptor descriptor = new BeanDescriptor(beanName, interfaceName);
return descriptor;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.